Thanks to visit codestin.com
Credit goes to doxygen.postgresql.org

PostgreSQL Source Code git master
varlena.c File Reference
#include "postgres.h"
#include <ctype.h>
#include <limits.h>
#include "access/detoast.h"
#include "access/toast_compression.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_type.h"
#include "common/hashfn.h"
#include "common/int.h"
#include "common/unicode_category.h"
#include "common/unicode_norm.h"
#include "common/unicode_version.h"
#include "funcapi.h"
#include "lib/hyperloglog.h"
#include "libpq/pqformat.h"
#include "miscadmin.h"
#include "nodes/execnodes.h"
#include "parser/scansup.h"
#include "port/pg_bswap.h"
#include "regex/regex.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/pg_locale.h"
#include "utils/sortsupport.h"
#include "utils/varlena.h"
#include "levenshtein.c"
Include dependency graph for varlena.c:

Go to the source code of this file.

Data Structures

struct  TextPositionState
 
struct  VarStringSortSupport
 
struct  SplitTextOutputData
 

Macros

#define TEXTBUFLEN   1024
 
#define DatumGetVarStringP(X)   ((VarString *) PG_DETOAST_DATUM(X))
 
#define DatumGetVarStringPP(X)   ((VarString *) PG_DETOAST_DATUM_PACKED(X))
 
#define CmpCall(cmpfunc)
 
#define TEXT_FORMAT_FLAG_MINUS   0x0001 /* is minus flag present? */
 
#define ADVANCE_PARSE_POINTER(ptr, end_ptr)
 
#define LEVENSHTEIN_LESS_EQUAL
 

Typedefs

typedef struct varlena VarString
 

Functions

static int varstrfastcmp_c (Datum x, Datum y, SortSupport ssup)
 
static int bpcharfastcmp_c (Datum x, Datum y, SortSupport ssup)
 
static int namefastcmp_c (Datum x, Datum y, SortSupport ssup)
 
static int varlenafastcmp_locale (Datum x, Datum y, SortSupport ssup)
 
static int namefastcmp_locale (Datum x, Datum y, SortSupport ssup)
 
static int varstrfastcmp_locale (char *a1p, int len1, char *a2p, int len2, SortSupport ssup)
 
static Datum varstr_abbrev_convert (Datum original, SortSupport ssup)
 
static bool varstr_abbrev_abort (int memtupcount, SortSupport ssup)
 
static int32 text_length (Datum str)
 
static texttext_catenate (text *t1, text *t2)
 
static texttext_substring (Datum str, int32 start, int32 length, bool length_not_specified)
 
static texttext_overlay (text *t1, text *t2, int sp, int sl)
 
static int text_position (text *t1, text *t2, Oid collid)
 
static void text_position_setup (text *t1, text *t2, Oid collid, TextPositionState *state)
 
static bool text_position_next (TextPositionState *state)
 
static char * text_position_next_internal (char *start_ptr, TextPositionState *state)
 
static char * text_position_get_match_ptr (TextPositionState *state)
 
static int text_position_get_match_pos (TextPositionState *state)
 
static void text_position_cleanup (TextPositionState *state)
 
static void check_collation_set (Oid collid)
 
static int text_cmp (text *arg1, text *arg2, Oid collid)
 
static void appendStringInfoText (StringInfo str, const text *t)
 
static bool split_text (FunctionCallInfo fcinfo, SplitTextOutputData *tstate)
 
static void split_text_accum_result (SplitTextOutputData *tstate, text *field_value, text *null_string, Oid collation)
 
static textarray_to_text_internal (FunctionCallInfo fcinfo, ArrayType *v, const char *fldsep, const char *null_string)
 
static StringInfo makeStringAggState (FunctionCallInfo fcinfo)
 
static bool text_format_parse_digits (const char **ptr, const char *end_ptr, int *value)
 
static const char * text_format_parse_format (const char *start_ptr, const char *end_ptr, int *argpos, int *widthpos, int *flags, int *width)
 
static void text_format_string_conversion (StringInfo buf, char conversion, FmgrInfo *typOutputInfo, Datum value, bool isNull, int flags, int width)
 
static void text_format_append_string (StringInfo buf, const char *str, int flags, int width)
 
textcstring_to_text (const char *s)
 
textcstring_to_text_with_len (const char *s, int len)
 
char * text_to_cstring (const text *t)
 
void text_to_cstring_buffer (const text *src, char *dst, size_t dst_len)
 
Datum textin (PG_FUNCTION_ARGS)
 
Datum textout (PG_FUNCTION_ARGS)
 
Datum textrecv (PG_FUNCTION_ARGS)
 
Datum textsend (PG_FUNCTION_ARGS)
 
Datum unknownin (PG_FUNCTION_ARGS)
 
Datum unknownout (PG_FUNCTION_ARGS)
 
Datum unknownrecv (PG_FUNCTION_ARGS)
 
Datum unknownsend (PG_FUNCTION_ARGS)
 
Datum textlen (PG_FUNCTION_ARGS)
 
Datum textoctetlen (PG_FUNCTION_ARGS)
 
Datum textcat (PG_FUNCTION_ARGS)
 
static int charlen_to_bytelen (const char *p, int n)
 
Datum text_substr (PG_FUNCTION_ARGS)
 
Datum text_substr_no_len (PG_FUNCTION_ARGS)
 
Datum textoverlay (PG_FUNCTION_ARGS)
 
Datum textoverlay_no_len (PG_FUNCTION_ARGS)
 
Datum textpos (PG_FUNCTION_ARGS)
 
static void text_position_reset (TextPositionState *state)
 
int varstr_cmp (const char *arg1, int len1, const char *arg2, int len2, Oid collid)
 
Datum texteq (PG_FUNCTION_ARGS)
 
Datum textne (PG_FUNCTION_ARGS)
 
Datum text_lt (PG_FUNCTION_ARGS)
 
Datum text_le (PG_FUNCTION_ARGS)
 
Datum text_gt (PG_FUNCTION_ARGS)
 
Datum text_ge (PG_FUNCTION_ARGS)
 
Datum text_starts_with (PG_FUNCTION_ARGS)
 
Datum bttextcmp (PG_FUNCTION_ARGS)
 
Datum bttextsortsupport (PG_FUNCTION_ARGS)
 
void varstr_sortsupport (SortSupport ssup, Oid typid, Oid collid)
 
Datum btvarstrequalimage (PG_FUNCTION_ARGS)
 
Datum text_larger (PG_FUNCTION_ARGS)
 
Datum text_smaller (PG_FUNCTION_ARGS)
 
Datum nameeqtext (PG_FUNCTION_ARGS)
 
Datum texteqname (PG_FUNCTION_ARGS)
 
Datum namenetext (PG_FUNCTION_ARGS)
 
Datum textnename (PG_FUNCTION_ARGS)
 
Datum btnametextcmp (PG_FUNCTION_ARGS)
 
Datum bttextnamecmp (PG_FUNCTION_ARGS)
 
Datum namelttext (PG_FUNCTION_ARGS)
 
Datum nameletext (PG_FUNCTION_ARGS)
 
Datum namegttext (PG_FUNCTION_ARGS)
 
Datum namegetext (PG_FUNCTION_ARGS)
 
Datum textltname (PG_FUNCTION_ARGS)
 
Datum textlename (PG_FUNCTION_ARGS)
 
Datum textgtname (PG_FUNCTION_ARGS)
 
Datum textgename (PG_FUNCTION_ARGS)
 
static int internal_text_pattern_compare (text *arg1, text *arg2)
 
Datum text_pattern_lt (PG_FUNCTION_ARGS)
 
Datum text_pattern_le (PG_FUNCTION_ARGS)
 
Datum text_pattern_ge (PG_FUNCTION_ARGS)
 
Datum text_pattern_gt (PG_FUNCTION_ARGS)
 
Datum bttext_pattern_cmp (PG_FUNCTION_ARGS)
 
Datum bttext_pattern_sortsupport (PG_FUNCTION_ARGS)
 
Datum text_name (PG_FUNCTION_ARGS)
 
Datum name_text (PG_FUNCTION_ARGS)
 
ListtextToQualifiedNameList (text *textval)
 
bool SplitIdentifierString (char *rawstring, char separator, List **namelist)
 
bool SplitDirectoriesString (char *rawstring, char separator, List **namelist)
 
bool SplitGUCList (char *rawstring, char separator, List **namelist)
 
Datum replace_text (PG_FUNCTION_ARGS)
 
static int check_replace_text_has_escape (const text *replace_text)
 
static void appendStringInfoRegexpSubstr (StringInfo str, text *replace_text, regmatch_t *pmatch, char *start_ptr, int data_pos)
 
textreplace_text_regexp (text *src_text, text *pattern_text, text *replace_text, int cflags, Oid collation, int search_start, int n)
 
Datum split_part (PG_FUNCTION_ARGS)
 
static bool text_isequal (text *txt1, text *txt2, Oid collid)
 
Datum text_to_array (PG_FUNCTION_ARGS)
 
Datum text_to_array_null (PG_FUNCTION_ARGS)
 
Datum text_to_table (PG_FUNCTION_ARGS)
 
Datum text_to_table_null (PG_FUNCTION_ARGS)
 
Datum array_to_text (PG_FUNCTION_ARGS)
 
Datum array_to_text_null (PG_FUNCTION_ARGS)
 
static textconvert_to_base (uint64 value, int base)
 
Datum to_bin32 (PG_FUNCTION_ARGS)
 
Datum to_bin64 (PG_FUNCTION_ARGS)
 
Datum to_oct32 (PG_FUNCTION_ARGS)
 
Datum to_oct64 (PG_FUNCTION_ARGS)
 
Datum to_hex32 (PG_FUNCTION_ARGS)
 
Datum to_hex64 (PG_FUNCTION_ARGS)
 
Datum pg_column_size (PG_FUNCTION_ARGS)
 
Datum pg_column_compression (PG_FUNCTION_ARGS)
 
Datum pg_column_toast_chunk_id (PG_FUNCTION_ARGS)
 
Datum string_agg_transfn (PG_FUNCTION_ARGS)
 
Datum string_agg_combine (PG_FUNCTION_ARGS)
 
Datum string_agg_serialize (PG_FUNCTION_ARGS)
 
Datum string_agg_deserialize (PG_FUNCTION_ARGS)
 
Datum string_agg_finalfn (PG_FUNCTION_ARGS)
 
static FmgrInfobuild_concat_foutcache (FunctionCallInfo fcinfo, int argidx)
 
static textconcat_internal (const char *sepstr, int argidx, FunctionCallInfo fcinfo)
 
Datum text_concat (PG_FUNCTION_ARGS)
 
Datum text_concat_ws (PG_FUNCTION_ARGS)
 
Datum text_left (PG_FUNCTION_ARGS)
 
Datum text_right (PG_FUNCTION_ARGS)
 
Datum text_reverse (PG_FUNCTION_ARGS)
 
Datum text_format (PG_FUNCTION_ARGS)
 
Datum text_format_nv (PG_FUNCTION_ARGS)
 
static bool rest_of_char_same (const char *s1, const char *s2, int len)
 
void initClosestMatch (ClosestMatchState *state, const char *source, int max_d)
 
void updateClosestMatch (ClosestMatchState *state, const char *candidate)
 
const char * getClosestMatch (ClosestMatchState *state)
 
static UnicodeNormalizationForm unicode_norm_form_from_string (const char *formstr)
 
Datum unicode_version (PG_FUNCTION_ARGS)
 
Datum icu_unicode_version (PG_FUNCTION_ARGS)
 
Datum unicode_assigned (PG_FUNCTION_ARGS)
 
Datum unicode_normalize_func (PG_FUNCTION_ARGS)
 
Datum unicode_is_normalized (PG_FUNCTION_ARGS)
 
static bool isxdigits_n (const char *instr, size_t n)
 
static unsigned int hexval (unsigned char c)
 
static unsigned int hexval_n (const char *instr, size_t n)
 
Datum unistr (PG_FUNCTION_ARGS)
 

Macro Definition Documentation

◆ ADVANCE_PARSE_POINTER

#define ADVANCE_PARSE_POINTER (   ptr,
  end_ptr 
)
Value:
do { \
if (++(ptr) >= (end_ptr)) \
ereport(ERROR, \
(errcode(ERRCODE_INVALID_PARAMETER_VALUE), \
errmsg("unterminated format() type specifier"), \
errhint("For a single \"%%\" use \"%%%%\"."))); \
} while (0)
int errhint(const char *fmt,...)
Definition: elog.c:1321
int errcode(int sqlerrcode)
Definition: elog.c:854
int errmsg(const char *fmt,...)
Definition: elog.c:1071
#define ERROR
Definition: elog.h:39

Definition at line 4721 of file varlena.c.

◆ CmpCall

#define CmpCall (   cmpfunc)
Value:
Datum DirectFunctionCall2Coll(PGFunction func, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:812
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:268
#define PG_GET_COLLATION()
Definition: fmgr.h:198
static int32 DatumGetInt32(Datum X)
Definition: postgres.h:212

Definition at line 2458 of file varlena.c.

◆ DatumGetVarStringP

#define DatumGetVarStringP (   X)    ((VarString *) PG_DETOAST_DATUM(X))

Definition at line 119 of file varlena.c.

◆ DatumGetVarStringPP

#define DatumGetVarStringPP (   X)    ((VarString *) PG_DETOAST_DATUM_PACKED(X))

Definition at line 120 of file varlena.c.

◆ LEVENSHTEIN_LESS_EQUAL

#define LEVENSHTEIN_LESS_EQUAL

Definition at line 5261 of file varlena.c.

◆ TEXT_FORMAT_FLAG_MINUS

#define TEXT_FORMAT_FLAG_MINUS   0x0001 /* is minus flag present? */

Definition at line 4719 of file varlena.c.

◆ TEXTBUFLEN

#define TEXTBUFLEN   1024

Definition at line 117 of file varlena.c.

Typedef Documentation

◆ VarString

typedef struct varlena VarString

Definition at line 45 of file varlena.c.

Function Documentation

◆ appendStringInfoRegexpSubstr()

static void appendStringInfoRegexpSubstr ( StringInfo  str,
text replace_text,
regmatch_t pmatch,
char *  start_ptr,
int  data_pos 
)
static

Definition at line 3202 of file varlena.c.

3205{
3206 const char *p = VARDATA_ANY(replace_text);
3207 const char *p_end = p + VARSIZE_ANY_EXHDR(replace_text);
3208
3209 while (p < p_end)
3210 {
3211 const char *chunk_start = p;
3212 int so;
3213 int eo;
3214
3215 /* Find next escape char, if any. */
3216 p = memchr(p, '\\', p_end - p);
3217 if (p == NULL)
3218 p = p_end;
3219
3220 /* Copy the text we just scanned over, if any. */
3221 if (p > chunk_start)
3222 appendBinaryStringInfo(str, chunk_start, p - chunk_start);
3223
3224 /* Done if at end of string, else advance over escape char. */
3225 if (p >= p_end)
3226 break;
3227 p++;
3228
3229 if (p >= p_end)
3230 {
3231 /* Escape at very end of input. Treat same as unexpected char */
3233 break;
3234 }
3235
3236 if (*p >= '1' && *p <= '9')
3237 {
3238 /* Use the back reference of regexp. */
3239 int idx = *p - '0';
3240
3241 so = pmatch[idx].rm_so;
3242 eo = pmatch[idx].rm_eo;
3243 p++;
3244 }
3245 else if (*p == '&')
3246 {
3247 /* Use the entire matched string. */
3248 so = pmatch[0].rm_so;
3249 eo = pmatch[0].rm_eo;
3250 p++;
3251 }
3252 else if (*p == '\\')
3253 {
3254 /* \\ means transfer one \ to output. */
3256 p++;
3257 continue;
3258 }
3259 else
3260 {
3261 /*
3262 * If escape char is not followed by any expected char, just treat
3263 * it as ordinary data to copy. (XXX would it be better to throw
3264 * an error?)
3265 */
3267 continue;
3268 }
3269
3270 if (so >= 0 && eo >= 0)
3271 {
3272 /*
3273 * Copy the text that is back reference of regexp. Note so and eo
3274 * are counted in characters not bytes.
3275 */
3276 char *chunk_start;
3277 int chunk_len;
3278
3279 Assert(so >= data_pos);
3280 chunk_start = start_ptr;
3281 chunk_start += charlen_to_bytelen(chunk_start, so - data_pos);
3282 chunk_len = charlen_to_bytelen(chunk_start, eo - so);
3283 appendBinaryStringInfo(str, chunk_start, chunk_len);
3284 }
3285 }
3286}
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:262
Assert(PointerIsAligned(start, uint64))
const char * str
void appendBinaryStringInfo(StringInfo str, const void *data, int datalen)
Definition: stringinfo.c:281
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:242
static Size VARSIZE_ANY_EXHDR(const void *PTR)
Definition: varatt.h:472
static char * VARDATA_ANY(const void *PTR)
Definition: varatt.h:486
static int charlen_to_bytelen(const char *p, int n)
Definition: varlena.c:501
Datum replace_text(PG_FUNCTION_ARGS)
Definition: varlena.c:3092

References appendBinaryStringInfo(), appendStringInfoChar(), Assert(), charlen_to_bytelen(), idx(), replace_text(), str, VARDATA_ANY(), and VARSIZE_ANY_EXHDR().

Referenced by replace_text_regexp().

◆ appendStringInfoText()

static void appendStringInfoText ( StringInfo  str,
const text t 
)
static

◆ array_to_text()

Datum array_to_text ( PG_FUNCTION_ARGS  )

Definition at line 3862 of file varlena.c.

3863{
3865 char *fldsep = text_to_cstring(PG_GETARG_TEXT_PP(1));
3866
3867 PG_RETURN_TEXT_P(array_to_text_internal(fcinfo, v, fldsep, NULL));
3868}
#define PG_GETARG_ARRAYTYPE_P(n)
Definition: array.h:263
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:309
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:372
static text * array_to_text_internal(FunctionCallInfo fcinfo, ArrayType *v, const char *fldsep, const char *null_string)
Definition: varlena.c:3904
char * text_to_cstring(const text *t)
Definition: varlena.c:214

References array_to_text_internal(), PG_GETARG_ARRAYTYPE_P, PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, and text_to_cstring().

◆ array_to_text_internal()

static text * array_to_text_internal ( FunctionCallInfo  fcinfo,
ArrayType v,
const char *  fldsep,
const char *  null_string 
)
static

Definition at line 3904 of file varlena.c.

3906{
3907 text *result;
3908 int nitems,
3909 *dims,
3910 ndims;
3911 Oid element_type;
3912 int typlen;
3913 bool typbyval;
3914 char typalign;
3916 bool printed = false;
3917 char *p;
3918 bits8 *bitmap;
3919 int bitmask;
3920 int i;
3921 ArrayMetaState *my_extra;
3922
3923 ndims = ARR_NDIM(v);
3924 dims = ARR_DIMS(v);
3925 nitems = ArrayGetNItems(ndims, dims);
3926
3927 /* if there are no elements, return an empty string */
3928 if (nitems == 0)
3929 return cstring_to_text_with_len("", 0);
3930
3931 element_type = ARR_ELEMTYPE(v);
3933
3934 /*
3935 * We arrange to look up info about element type, including its output
3936 * conversion proc, only once per series of calls, assuming the element
3937 * type doesn't change underneath us.
3938 */
3939 my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
3940 if (my_extra == NULL)
3941 {
3942 fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
3943 sizeof(ArrayMetaState));
3944 my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
3945 my_extra->element_type = ~element_type;
3946 }
3947
3948 if (my_extra->element_type != element_type)
3949 {
3950 /*
3951 * Get info about element type, including its output conversion proc
3952 */
3953 get_type_io_data(element_type, IOFunc_output,
3954 &my_extra->typlen, &my_extra->typbyval,
3955 &my_extra->typalign, &my_extra->typdelim,
3956 &my_extra->typioparam, &my_extra->typiofunc);
3957 fmgr_info_cxt(my_extra->typiofunc, &my_extra->proc,
3958 fcinfo->flinfo->fn_mcxt);
3959 my_extra->element_type = element_type;
3960 }
3961 typlen = my_extra->typlen;
3962 typbyval = my_extra->typbyval;
3963 typalign = my_extra->typalign;
3964
3965 p = ARR_DATA_PTR(v);
3966 bitmap = ARR_NULLBITMAP(v);
3967 bitmask = 1;
3968
3969 for (i = 0; i < nitems; i++)
3970 {
3971 Datum itemvalue;
3972 char *value;
3973
3974 /* Get source element, checking for NULL */
3975 if (bitmap && (*bitmap & bitmask) == 0)
3976 {
3977 /* if null_string is NULL, we just ignore null elements */
3978 if (null_string != NULL)
3979 {
3980 if (printed)
3981 appendStringInfo(&buf, "%s%s", fldsep, null_string);
3982 else
3983 appendStringInfoString(&buf, null_string);
3984 printed = true;
3985 }
3986 }
3987 else
3988 {
3989 itemvalue = fetch_att(p, typbyval, typlen);
3990
3991 value = OutputFunctionCall(&my_extra->proc, itemvalue);
3992
3993 if (printed)
3994 appendStringInfo(&buf, "%s%s", fldsep, value);
3995 else
3997 printed = true;
3998
3999 p = att_addlength_pointer(p, typlen, p);
4000 p = (char *) att_align_nominal(p, typalign);
4001 }
4002
4003 /* advance bitmap pointer if any */
4004 if (bitmap)
4005 {
4006 bitmask <<= 1;
4007 if (bitmask == 0x100)
4008 {
4009 bitmap++;
4010 bitmask = 1;
4011 }
4012 }
4013 }
4014
4015 result = cstring_to_text_with_len(buf.data, buf.len);
4016 pfree(buf.data);
4017
4018 return result;
4019}
#define ARR_NDIM(a)
Definition: array.h:290
#define ARR_DATA_PTR(a)
Definition: array.h:322
#define ARR_NULLBITMAP(a)
Definition: array.h:300
#define ARR_ELEMTYPE(a)
Definition: array.h:292
#define ARR_DIMS(a)
Definition: array.h:294
int ArrayGetNItems(int ndim, const int *dims)
Definition: arrayutils.c:57
uint8 bits8
Definition: c.h:546
void fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
Definition: fmgr.c:137
char * OutputFunctionCall(FmgrInfo *flinfo, Datum val)
Definition: fmgr.c:1682
#define nitems(x)
Definition: indent.h:31
static struct @166 value
int i
Definition: isn.c:77
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:81
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:2492
@ IOFunc_output
Definition: lsyscache.h:37
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:1229
void pfree(void *pointer)
Definition: mcxt.c:1594
static char * buf
Definition: pg_test_fsync.c:72
char typalign
Definition: pg_type.h:176
uint64_t Datum
Definition: postgres.h:70
unsigned int Oid
Definition: postgres_ext.h:32
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:145
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:230
void initStringInfo(StringInfo str)
Definition: stringinfo.c:97
Oid typioparam
Definition: array.h:243
char typalign
Definition: array.h:241
Oid typiofunc
Definition: array.h:244
int16 typlen
Definition: array.h:239
Oid element_type
Definition: array.h:238
FmgrInfo proc
Definition: array.h:245
char typdelim
Definition: array.h:242
bool typbyval
Definition: array.h:240
void * fn_extra
Definition: fmgr.h:64
MemoryContext fn_mcxt
Definition: fmgr.h:65
FmgrInfo * flinfo
Definition: fmgr.h:87
Definition: c.h:693
#define att_align_nominal(cur_offset, attalign)
Definition: tupmacs.h:145
#define att_addlength_pointer(cur_offset, attlen, attptr)
Definition: tupmacs.h:180
static Datum fetch_att(const void *T, bool attbyval, int attlen)
Definition: tupmacs.h:50
text * cstring_to_text_with_len(const char *s, int len)
Definition: varlena.c:193

References appendStringInfo(), appendStringInfoString(), ARR_DATA_PTR, ARR_DIMS, ARR_ELEMTYPE, ARR_NDIM, ARR_NULLBITMAP, ArrayGetNItems(), att_addlength_pointer, att_align_nominal, buf, cstring_to_text_with_len(), ArrayMetaState::element_type, fetch_att(), FunctionCallInfoBaseData::flinfo, fmgr_info_cxt(), FmgrInfo::fn_extra, FmgrInfo::fn_mcxt, get_type_io_data(), i, if(), initStringInfo(), IOFunc_output, MemoryContextAlloc(), nitems, OutputFunctionCall(), pfree(), ArrayMetaState::proc, typalign, ArrayMetaState::typalign, ArrayMetaState::typbyval, ArrayMetaState::typdelim, ArrayMetaState::typiofunc, ArrayMetaState::typioparam, ArrayMetaState::typlen, and value.

Referenced by array_to_text(), array_to_text_null(), and concat_internal().

◆ array_to_text_null()

Datum array_to_text_null ( PG_FUNCTION_ARGS  )

Definition at line 3878 of file varlena.c.

3879{
3880 ArrayType *v;
3881 char *fldsep;
3882 char *null_string;
3883
3884 /* returns NULL when first or second parameter is NULL */
3885 if (PG_ARGISNULL(0) || PG_ARGISNULL(1))
3887
3888 v = PG_GETARG_ARRAYTYPE_P(0);
3890
3891 /* NULL null string is passed through as a null pointer */
3892 if (!PG_ARGISNULL(2))
3893 null_string = text_to_cstring(PG_GETARG_TEXT_PP(2));
3894 else
3895 null_string = NULL;
3896
3897 PG_RETURN_TEXT_P(array_to_text_internal(fcinfo, v, fldsep, null_string));
3898}
#define PG_ARGISNULL(n)
Definition: fmgr.h:209
#define PG_RETURN_NULL()
Definition: fmgr.h:345

References array_to_text_internal(), PG_ARGISNULL, PG_GETARG_ARRAYTYPE_P, PG_GETARG_TEXT_PP, PG_RETURN_NULL, PG_RETURN_TEXT_P, and text_to_cstring().

◆ bpcharfastcmp_c()

static int bpcharfastcmp_c ( Datum  x,
Datum  y,
SortSupport  ssup 
)
static

Definition at line 1788 of file varlena.c.

1789{
1790 BpChar *arg1 = DatumGetBpCharPP(x);
1791 BpChar *arg2 = DatumGetBpCharPP(y);
1792 char *a1p,
1793 *a2p;
1794 int len1,
1795 len2,
1796 result;
1797
1798 a1p = VARDATA_ANY(arg1);
1799 a2p = VARDATA_ANY(arg2);
1800
1801 len1 = bpchartruelen(a1p, VARSIZE_ANY_EXHDR(arg1));
1802 len2 = bpchartruelen(a2p, VARSIZE_ANY_EXHDR(arg2));
1803
1804 result = memcmp(a1p, a2p, Min(len1, len2));
1805 if ((result == 0) && (len1 != len2))
1806 result = (len1 < len2) ? -1 : 1;
1807
1808 /* We can't afford to leak memory here. */
1809 if (PointerGetDatum(arg1) != x)
1810 pfree(arg1);
1811 if (PointerGetDatum(arg2) != y)
1812 pfree(arg2);
1813
1814 return result;
1815}
#define Min(x, y)
Definition: c.h:1004
#define DatumGetBpCharPP(X)
Definition: fmgr.h:293
int y
Definition: isn.c:76
int x
Definition: isn.c:75
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:332
int bpchartruelen(char *s, int len)
Definition: varchar.c:676

References bpchartruelen(), DatumGetBpCharPP, Min, pfree(), PointerGetDatum(), VARDATA_ANY(), VARSIZE_ANY_EXHDR(), x, and y.

Referenced by varstr_sortsupport().

◆ btnametextcmp()

Datum btnametextcmp ( PG_FUNCTION_ARGS  )

Definition at line 2427 of file varlena.c.

2428{
2429 Name arg1 = PG_GETARG_NAME(0);
2430 text *arg2 = PG_GETARG_TEXT_PP(1);
2431 int32 result;
2432
2433 result = varstr_cmp(NameStr(*arg1), strlen(NameStr(*arg1)),
2434 VARDATA_ANY(arg2), VARSIZE_ANY_EXHDR(arg2),
2436
2437 PG_FREE_IF_COPY(arg2, 1);
2438
2439 PG_RETURN_INT32(result);
2440}
#define NameStr(name)
Definition: c.h:752
int32_t int32
Definition: c.h:535
#define PG_FREE_IF_COPY(ptr, n)
Definition: fmgr.h:260
#define PG_GETARG_NAME(n)
Definition: fmgr.h:278
#define PG_RETURN_INT32(x)
Definition: fmgr.h:354
Definition: c.h:747
int varstr_cmp(const char *arg1, int len1, const char *arg2, int len2, Oid collid)
Definition: varlena.c:1297

References NameStr, PG_FREE_IF_COPY, PG_GET_COLLATION, PG_GETARG_NAME, PG_GETARG_TEXT_PP, PG_RETURN_INT32, VARDATA_ANY(), VARSIZE_ANY_EXHDR(), and varstr_cmp().

Referenced by namegetext(), namegttext(), nameletext(), and namelttext().

◆ bttext_pattern_cmp()

Datum bttext_pattern_cmp ( PG_FUNCTION_ARGS  )

Definition at line 2610 of file varlena.c.

2611{
2612 text *arg1 = PG_GETARG_TEXT_PP(0);
2613 text *arg2 = PG_GETARG_TEXT_PP(1);
2614 int result;
2615
2616 result = internal_text_pattern_compare(arg1, arg2);
2617
2618 PG_FREE_IF_COPY(arg1, 0);
2619 PG_FREE_IF_COPY(arg2, 1);
2620
2621 PG_RETURN_INT32(result);
2622}
static int internal_text_pattern_compare(text *arg1, text *arg2)
Definition: varlena.c:2524

References internal_text_pattern_compare(), PG_FREE_IF_COPY, PG_GETARG_TEXT_PP, and PG_RETURN_INT32.

◆ bttext_pattern_sortsupport()

Datum bttext_pattern_sortsupport ( PG_FUNCTION_ARGS  )

Definition at line 2626 of file varlena.c.

2627{
2629 MemoryContext oldcontext;
2630
2631 oldcontext = MemoryContextSwitchTo(ssup->ssup_cxt);
2632
2633 /* Use generic string SortSupport, forcing "C" collation */
2634 varstr_sortsupport(ssup, TEXTOID, C_COLLATION_OID);
2635
2636 MemoryContextSwitchTo(oldcontext);
2637
2639}
#define PG_RETURN_VOID()
Definition: fmgr.h:349
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:276
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
struct SortSupportData * SortSupport
Definition: sortsupport.h:58
MemoryContext ssup_cxt
Definition: sortsupport.h:66
void varstr_sortsupport(SortSupport ssup, Oid typid, Oid collid)
Definition: varlena.c:1615

References MemoryContextSwitchTo(), PG_GETARG_POINTER, PG_RETURN_VOID, SortSupportData::ssup_cxt, and varstr_sortsupport().

◆ bttextcmp()

Datum bttextcmp ( PG_FUNCTION_ARGS  )

Definition at line 1573 of file varlena.c.

1574{
1575 text *arg1 = PG_GETARG_TEXT_PP(0);
1576 text *arg2 = PG_GETARG_TEXT_PP(1);
1577 int32 result;
1578
1579 result = text_cmp(arg1, arg2, PG_GET_COLLATION());
1580
1581 PG_FREE_IF_COPY(arg1, 0);
1582 PG_FREE_IF_COPY(arg2, 1);
1583
1584 PG_RETURN_INT32(result);
1585}
static int text_cmp(text *arg1, text *arg2, Oid collid)
Definition: varlena.c:1345

References PG_FREE_IF_COPY, PG_GET_COLLATION, PG_GETARG_TEXT_PP, PG_RETURN_INT32, and text_cmp().

Referenced by gbt_text_ssup_cmp(), and gbt_textcmp().

◆ bttextnamecmp()

Datum bttextnamecmp ( PG_FUNCTION_ARGS  )

Definition at line 2443 of file varlena.c.

2444{
2445 text *arg1 = PG_GETARG_TEXT_PP(0);
2446 Name arg2 = PG_GETARG_NAME(1);
2447 int32 result;
2448
2449 result = varstr_cmp(VARDATA_ANY(arg1), VARSIZE_ANY_EXHDR(arg1),
2450 NameStr(*arg2), strlen(NameStr(*arg2)),
2452
2453 PG_FREE_IF_COPY(arg1, 0);
2454
2455 PG_RETURN_INT32(result);
2456}

References NameStr, PG_FREE_IF_COPY, PG_GET_COLLATION, PG_GETARG_NAME, PG_GETARG_TEXT_PP, PG_RETURN_INT32, VARDATA_ANY(), VARSIZE_ANY_EXHDR(), and varstr_cmp().

Referenced by textgename(), textgtname(), textlename(), and textltname().

◆ bttextsortsupport()

Datum bttextsortsupport ( PG_FUNCTION_ARGS  )

Definition at line 1588 of file varlena.c.

1589{
1591 Oid collid = ssup->ssup_collation;
1592 MemoryContext oldcontext;
1593
1594 oldcontext = MemoryContextSwitchTo(ssup->ssup_cxt);
1595
1596 /* Use generic string SortSupport */
1597 varstr_sortsupport(ssup, TEXTOID, collid);
1598
1599 MemoryContextSwitchTo(oldcontext);
1600
1602}
Oid collid

References collid, MemoryContextSwitchTo(), PG_GETARG_POINTER, PG_RETURN_VOID, SortSupportData::ssup_collation, SortSupportData::ssup_cxt, and varstr_sortsupport().

◆ btvarstrequalimage()

Datum btvarstrequalimage ( PG_FUNCTION_ARGS  )

Definition at line 2284 of file varlena.c.

2285{
2286 /* Oid opcintype = PG_GETARG_OID(0); */
2289
2291
2293
2294 PG_RETURN_BOOL(locale->deterministic);
2295}
#define PG_RETURN_BOOL(x)
Definition: fmgr.h:359
static char * locale
Definition: initdb.c:140
pg_locale_t pg_newlocale_from_collation(Oid collid)
Definition: pg_locale.c:1166
static void check_collation_set(Oid collid)
Definition: varlena.c:1268

References check_collation_set(), collid, locale, PG_GET_COLLATION, pg_newlocale_from_collation(), and PG_RETURN_BOOL.

◆ build_concat_foutcache()

static FmgrInfo * build_concat_foutcache ( FunctionCallInfo  fcinfo,
int  argidx 
)
static

Definition at line 4480 of file varlena.c.

4481{
4482 FmgrInfo *foutcache;
4483 int i;
4484
4485 /* We keep the info in fn_mcxt so it survives across calls */
4486 foutcache = (FmgrInfo *) MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
4487 PG_NARGS() * sizeof(FmgrInfo));
4488
4489 for (i = argidx; i < PG_NARGS(); i++)
4490 {
4491 Oid valtype;
4492 Oid typOutput;
4493 bool typIsVarlena;
4494
4495 valtype = get_fn_expr_argtype(fcinfo->flinfo, i);
4496 if (!OidIsValid(valtype))
4497 elog(ERROR, "could not determine data type of concat() input");
4498
4499 getTypeOutputInfo(valtype, &typOutput, &typIsVarlena);
4500 fmgr_info_cxt(typOutput, &foutcache[i], fcinfo->flinfo->fn_mcxt);
4501 }
4502
4503 fcinfo->flinfo->fn_extra = foutcache;
4504
4505 return foutcache;
4506}
#define OidIsValid(objectId)
Definition: c.h:775
#define elog(elevel,...)
Definition: elog.h:226
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:1874
struct FmgrInfo FmgrInfo
#define PG_NARGS()
Definition: fmgr.h:203
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:3074
Definition: fmgr.h:57

References elog, ERROR, FunctionCallInfoBaseData::flinfo, fmgr_info_cxt(), FmgrInfo::fn_extra, FmgrInfo::fn_mcxt, get_fn_expr_argtype(), getTypeOutputInfo(), i, MemoryContextAlloc(), OidIsValid, and PG_NARGS.

Referenced by concat_internal().

◆ charlen_to_bytelen()

static int charlen_to_bytelen ( const char *  p,
int  n 
)
static

Definition at line 501 of file varlena.c.

502{
504 {
505 /* Optimization for single-byte encodings */
506 return n;
507 }
508 else
509 {
510 const char *s;
511
512 for (s = p; n > 0; n--)
513 s += pg_mblen(s);
514
515 return s - p;
516 }
517}
int pg_database_encoding_max_length(void)
Definition: mbutils.c:1547
int pg_mblen(const char *mbstr)
Definition: mbutils.c:1024

References pg_database_encoding_max_length(), and pg_mblen().

Referenced by appendStringInfoRegexpSubstr(), and replace_text_regexp().

◆ check_collation_set()

static void check_collation_set ( Oid  collid)
static

Definition at line 1268 of file varlena.c.

1269{
1270 if (!OidIsValid(collid))
1271 {
1272 /*
1273 * This typically means that the parser could not resolve a conflict
1274 * of implicit collations, so report it that way.
1275 */
1276 ereport(ERROR,
1277 (errcode(ERRCODE_INDETERMINATE_COLLATION),
1278 errmsg("could not determine which collation to use for string comparison"),
1279 errhint("Use the COLLATE clause to set the collation explicitly.")));
1280 }
1281}
#define ereport(elevel,...)
Definition: elog.h:150

References collid, ereport, errcode(), errhint(), errmsg(), ERROR, and OidIsValid.

Referenced by btvarstrequalimage(), nameeqtext(), namenetext(), text_position(), text_position_setup(), text_starts_with(), texteq(), texteqname(), textne(), textnename(), varstr_cmp(), and varstr_sortsupport().

◆ check_replace_text_has_escape()

static int check_replace_text_has_escape ( const text replace_text)
static

Definition at line 3169 of file varlena.c.

3170{
3171 int result = 0;
3172 const char *p = VARDATA_ANY(replace_text);
3173 const char *p_end = p + VARSIZE_ANY_EXHDR(replace_text);
3174
3175 while (p < p_end)
3176 {
3177 /* Find next escape char, if any. */
3178 p = memchr(p, '\\', p_end - p);
3179 if (p == NULL)
3180 break;
3181 p++;
3182 /* Note: a backslash at the end doesn't require extra processing. */
3183 if (p < p_end)
3184 {
3185 if (*p >= '1' && *p <= '9')
3186 return 2; /* Found a submatch specifier, so done */
3187 result = 1; /* Found some other sequence, keep looking */
3188 p++;
3189 }
3190 }
3191 return result;
3192}

References replace_text(), VARDATA_ANY(), and VARSIZE_ANY_EXHDR().

Referenced by replace_text_regexp().

◆ concat_internal()

static text * concat_internal ( const char *  sepstr,
int  argidx,
FunctionCallInfo  fcinfo 
)
static

Definition at line 4518 of file varlena.c.

4520{
4521 text *result;
4523 FmgrInfo *foutcache;
4524 bool first_arg = true;
4525 int i;
4526
4527 /*
4528 * concat(VARIADIC some-array) is essentially equivalent to
4529 * array_to_text(), ie concat the array elements with the given separator.
4530 * So we just pass the case off to that code.
4531 */
4532 if (get_fn_expr_variadic(fcinfo->flinfo))
4533 {
4534 ArrayType *arr;
4535
4536 /* Should have just the one argument */
4537 Assert(argidx == PG_NARGS() - 1);
4538
4539 /* concat(VARIADIC NULL) is defined as NULL */
4540 if (PG_ARGISNULL(argidx))
4541 return NULL;
4542
4543 /*
4544 * Non-null argument had better be an array. We assume that any call
4545 * context that could let get_fn_expr_variadic return true will have
4546 * checked that a VARIADIC-labeled parameter actually is an array. So
4547 * it should be okay to just Assert that it's an array rather than
4548 * doing a full-fledged error check.
4549 */
4551
4552 /* OK, safe to fetch the array value */
4553 arr = PG_GETARG_ARRAYTYPE_P(argidx);
4554
4555 /*
4556 * And serialize the array. We tell array_to_text to ignore null
4557 * elements, which matches the behavior of the loop below.
4558 */
4559 return array_to_text_internal(fcinfo, arr, sepstr, NULL);
4560 }
4561
4562 /* Normal case without explicit VARIADIC marker */
4564
4565 /* Get output function info, building it if first time through */
4566 foutcache = (FmgrInfo *) fcinfo->flinfo->fn_extra;
4567 if (foutcache == NULL)
4568 foutcache = build_concat_foutcache(fcinfo, argidx);
4569
4570 for (i = argidx; i < PG_NARGS(); i++)
4571 {
4572 if (!PG_ARGISNULL(i))
4573 {
4575
4576 /* add separator if appropriate */
4577 if (first_arg)
4578 first_arg = false;
4579 else
4580 appendStringInfoString(&str, sepstr);
4581
4582 /* call the appropriate type output function, append the result */
4584 OutputFunctionCall(&foutcache[i], value));
4585 }
4586 }
4587
4588 result = cstring_to_text_with_len(str.data, str.len);
4589 pfree(str.data);
4590
4591 return result;
4592}
bool get_fn_expr_variadic(FmgrInfo *flinfo)
Definition: fmgr.c:2008
Oid get_base_element_type(Oid typid)
Definition: lsyscache.c:2999
static FmgrInfo * build_concat_foutcache(FunctionCallInfo fcinfo, int argidx)
Definition: varlena.c:4480

References appendStringInfoString(), array_to_text_internal(), Assert(), build_concat_foutcache(), cstring_to_text_with_len(), FunctionCallInfoBaseData::flinfo, FmgrInfo::fn_extra, get_base_element_type(), get_fn_expr_argtype(), get_fn_expr_variadic(), i, if(), initStringInfo(), OidIsValid, OutputFunctionCall(), pfree(), PG_ARGISNULL, PG_GETARG_ARRAYTYPE_P, PG_GETARG_DATUM, PG_NARGS, str, and value.

Referenced by text_concat(), and text_concat_ws().

◆ convert_to_base()

static text * convert_to_base ( uint64  value,
int  base 
)
inlinestatic

Definition at line 4026 of file varlena.c.

4027{
4028 const char *digits = "0123456789abcdef";
4029
4030 /* We size the buffer for to_bin's longest possible return value. */
4031 char buf[sizeof(uint64) * BITS_PER_BYTE];
4032 char *const end = buf + sizeof(buf);
4033 char *ptr = end;
4034
4035 Assert(base > 1);
4036 Assert(base <= 16);
4037
4038 do
4039 {
4040 *--ptr = digits[value % base];
4041 value /= base;
4042 } while (ptr > buf && value);
4043
4044 return cstring_to_text_with_len(ptr, end - ptr);
4045}
uint64_t uint64
Definition: c.h:540
int digits
Definition: informix.c:691
#define BITS_PER_BYTE

References Assert(), BITS_PER_BYTE, buf, cstring_to_text_with_len(), digits, and value.

Referenced by to_bin32(), to_bin64(), to_hex32(), to_hex64(), to_oct32(), and to_oct64().

◆ cstring_to_text()

text * cstring_to_text ( const char *  s)

Definition at line 181 of file varlena.c.

182{
183 return cstring_to_text_with_len(s, strlen(s));
184}

References cstring_to_text_with_len().

Referenced by array_dims(), ASN1_STRING_to_text(), booltext(), brin_minmax_multi_summary_out(), brin_page_type(), build_test_info_result(), build_test_match_result(), casefold(), cidr_abbrev(), convert_charset(), cstring_to_xmltype(), current_query(), cvt_name_text(), datetime_to_char_body(), dblink_build_sql_delete(), dblink_build_sql_insert(), dblink_build_sql_update(), dblink_cancel_query(), dblink_close(), dblink_connect(), dblink_disconnect(), dblink_error_message(), dblink_exec(), dblink_open(), dmetaphone(), dmetaphone_alt(), exec_assign_c_string(), executeDateTimeMethod(), filter_list_to_array(), format_type(), get_command_tag(), get_command_type(), get_scalar(), get_val_in_hash(), hash_page_type(), icu_unicode_version(), inet_abbrev(), initcap(), injection_points_list(), json_in(), json_typeof(), jsonb_get_element(), jsonb_typeof(), JsonbValueAsText(), lower(), md5_bytea(), md5_text(), metaphone(), name_bpchar(), name_text(), network_host(), network_show(), oidvectortypes(), ParameterAclCreate(), ParameterAclLookup(), pg_collation_actual_version(), pg_collation_for(), pg_column_compression(), pg_crypt(), pg_current_logfile(), pg_database_collation_actual_version(), pg_describe_object(), pg_export_snapshot(), pg_get_statisticsobjdef_expressions(), pg_get_wal_replay_pause_state(), pg_parameter_aclmask(), pg_relation_filepath(), pg_size_pretty(), pg_size_pretty_numeric(), pg_stat_get_backend_activity(), pg_stat_get_backend_wait_event(), pg_stat_get_backend_wait_event_type(), pg_stat_get_slru(), pg_stats_ext_mcvlist_items(), pg_tablespace_location(), pg_walfile_name(), pg_xact_status(), pgsql_version(), pgxml_result_to_text(), quote_ident(), quote_ident_cstr(), quote_nullable(), sepgsql_getcon(), sepgsql_mcstrans_in(), sepgsql_mcstrans_out(), set_config_by_name(), show_all_file_settings(), show_config_by_name(), show_config_by_name_missing_ok(), ShowAllGUCConfig(), soundex(), split_part(), ssl_cipher(), ssl_client_dn(), ssl_issuer_dn(), ssl_version(), string_to_text(), test_canonicalize_path(), test_slru_page_read(), test_slru_page_readonly(), text_substring(), textin(), timeofday(), timetz_at_local(), tsquerytree(), unaccent_dict(), unicode_version(), upper(), xml_encode_special_chars(), xml_in(), and xml_recv().

◆ cstring_to_text_with_len()

text * cstring_to_text_with_len ( const char *  s,
int  len 
)

Definition at line 193 of file varlena.c.

194{
195 text *result = (text *) palloc(len + VARHDRSZ);
196
197 SET_VARSIZE(result, len + VARHDRSZ);
198 memcpy(VARDATA(result), s, len);
199
200 return result;
201}
#define VARHDRSZ
Definition: c.h:698
void * palloc(Size size)
Definition: mcxt.c:1365
const void size_t len
static char * VARDATA(const void *PTR)
Definition: varatt.h:305
static void SET_VARSIZE(void *PTR, Size len)
Definition: varatt.h:432

References len, palloc(), SET_VARSIZE(), VARDATA(), and VARHDRSZ.

Referenced by array_to_json(), array_to_json_pretty(), array_to_text_internal(), brin_minmax_multi_summary_out(), build_regexp_match_result(), build_regexp_split_result(), build_test_match_result(), cash_words(), compute_tsvector_stats(), concat_internal(), convert_to_base(), cstring_to_text(), daitch_mokotoff_coding(), datum_to_json(), do_text_output_multiline(), dotrim(), each_object_field_end(), each_worker_jsonb(), elements_array_element_end(), ExecEvalMergeSupportFunc(), ExecEvalXmlExpr(), executeDateTimeMethod(), executeLikeRegex(), find_or_create_child_node(), fsm_page_contents(), get_array_element_end(), get_array_end(), get_object_end(), get_object_field_end(), get_scalar(), gin_extract_tsquery(), gin_extract_tsvector(), hstore_akeys(), hstore_avals(), hstore_each(), hstore_fetchval(), hstore_skeys(), hstore_slice_to_array(), hstore_subscript_fetch(), hstore_svals(), hstore_to_array_internal(), hstore_to_json(), hstore_to_json_loose(), json_build_array_noargs(), json_build_array_worker(), json_build_object_noargs(), json_build_object_worker(), json_object(), json_object_two_arg(), json_recv(), json_strip_nulls(), jsonb_pretty(), JsonbValueAsText(), leftmostvalue_text(), LogicalOutputWrite(), parse_ident(), pg_gen_salt(), pg_gen_salt_rounds(), pg_get_function_sqlbody(), replace_text(), replace_text_regexp(), row_to_json(), row_to_json_pretty(), serialize_deflist(), split_part(), split_text(), ssl_extension_info(), string_agg_finalfn(), stringinfo_to_xmltype(), text_format(), text_left(), text_right(), textrecv(), transform_json_string_values(), tsquerytree(), tsvector_to_array(), tsvector_unnest(), unistr(), varchar(), varchar_input(), xmltext(), xmltotext_with_options(), and xslt_process().

◆ getClosestMatch()

const char * getClosestMatch ( ClosestMatchState state)

Definition at line 5339 of file varlena.c.

5340{
5341 Assert(state);
5342
5343 return state->match;
5344}
Definition: regguts.h:323

References Assert().

Referenced by dblink_fdw_validator(), file_fdw_validator(), postgres_fdw_validator(), and postgresql_fdw_validator().

◆ hexval()

static unsigned int hexval ( unsigned char  c)
static

Definition at line 5568 of file varlena.c.

5569{
5570 if (c >= '0' && c <= '9')
5571 return c - '0';
5572 if (c >= 'a' && c <= 'f')
5573 return c - 'a' + 0xA;
5574 if (c >= 'A' && c <= 'F')
5575 return c - 'A' + 0xA;
5576 elog(ERROR, "invalid hexadecimal digit");
5577 return 0; /* not reached */
5578}
char * c

References elog, and ERROR.

Referenced by hexval_n().

◆ hexval_n()

static unsigned int hexval_n ( const char *  instr,
size_t  n 
)
static

Definition at line 5584 of file varlena.c.

5585{
5586 unsigned int result = 0;
5587
5588 for (size_t i = 0; i < n; i++)
5589 result += hexval(instr[i]) << (4 * (n - i - 1));
5590
5591 return result;
5592}
static unsigned int hexval(unsigned char c)
Definition: varlena.c:5568

References hexval(), and i.

Referenced by unistr().

◆ icu_unicode_version()

Datum icu_unicode_version ( PG_FUNCTION_ARGS  )

Definition at line 5398 of file varlena.c.

5399{
5400#ifdef USE_ICU
5401 PG_RETURN_TEXT_P(cstring_to_text(U_UNICODE_VERSION));
5402#else
5404#endif
5405}
text * cstring_to_text(const char *s)
Definition: varlena.c:181

References cstring_to_text(), PG_RETURN_NULL, and PG_RETURN_TEXT_P.

Referenced by main().

◆ initClosestMatch()

void initClosestMatch ( ClosestMatchState state,
const char *  source,
int  max_d 
)

Definition at line 5284 of file varlena.c.

5285{
5286 Assert(state);
5287 Assert(max_d >= 0);
5288
5289 state->source = source;
5290 state->min_d = -1;
5291 state->max_d = max_d;
5292 state->match = NULL;
5293}
static rewind_source * source
Definition: pg_rewind.c:89

References Assert(), and source.

Referenced by dblink_fdw_validator(), file_fdw_validator(), postgres_fdw_validator(), and postgresql_fdw_validator().

◆ internal_text_pattern_compare()

static int internal_text_pattern_compare ( text arg1,
text arg2 
)
static

Definition at line 2524 of file varlena.c.

2525{
2526 int result;
2527 int len1,
2528 len2;
2529
2530 len1 = VARSIZE_ANY_EXHDR(arg1);
2531 len2 = VARSIZE_ANY_EXHDR(arg2);
2532
2533 result = memcmp(VARDATA_ANY(arg1), VARDATA_ANY(arg2), Min(len1, len2));
2534 if (result != 0)
2535 return result;
2536 else if (len1 < len2)
2537 return -1;
2538 else if (len1 > len2)
2539 return 1;
2540 else
2541 return 0;
2542}

References Min, VARDATA_ANY(), and VARSIZE_ANY_EXHDR().

Referenced by bttext_pattern_cmp(), text_pattern_ge(), text_pattern_gt(), text_pattern_le(), and text_pattern_lt().

◆ isxdigits_n()

static bool isxdigits_n ( const char *  instr,
size_t  n 
)
static

Definition at line 5558 of file varlena.c.

5559{
5560 for (size_t i = 0; i < n; i++)
5561 if (!isxdigit((unsigned char) instr[i]))
5562 return false;
5563
5564 return true;
5565}

References i.

Referenced by unistr().

◆ makeStringAggState()

static StringInfo makeStringAggState ( FunctionCallInfo  fcinfo)
static

Definition at line 4258 of file varlena.c.

4259{
4261 MemoryContext aggcontext;
4262 MemoryContext oldcontext;
4263
4264 if (!AggCheckCallContext(fcinfo, &aggcontext))
4265 {
4266 /* cannot be called directly because of internal-type argument */
4267 elog(ERROR, "string_agg_transfn called in non-aggregate context");
4268 }
4269
4270 /*
4271 * Create state in aggregate context. It'll stay there across subsequent
4272 * calls.
4273 */
4274 oldcontext = MemoryContextSwitchTo(aggcontext);
4276 MemoryContextSwitchTo(oldcontext);
4277
4278 return state;
4279}
int AggCheckCallContext(FunctionCallInfo fcinfo, MemoryContext *aggcontext)
Definition: nodeAgg.c:4613
StringInfo makeStringInfo(void)
Definition: stringinfo.c:72

References AggCheckCallContext(), elog, ERROR, makeStringInfo(), and MemoryContextSwitchTo().

Referenced by string_agg_combine(), string_agg_deserialize(), and string_agg_transfn().

◆ name_text()

Datum name_text ( PG_FUNCTION_ARGS  )

Definition at line 2669 of file varlena.c.

2670{
2671 Name s = PG_GETARG_NAME(0);
2672
2674}

References cstring_to_text(), NameStr, PG_GETARG_NAME, and PG_RETURN_TEXT_P.

Referenced by nameiclike(), and nameicnlike().

◆ nameeqtext()

Datum nameeqtext ( PG_FUNCTION_ARGS  )

Definition at line 2327 of file varlena.c.

2328{
2329 Name arg1 = PG_GETARG_NAME(0);
2330 text *arg2 = PG_GETARG_TEXT_PP(1);
2331 size_t len1 = strlen(NameStr(*arg1));
2332 size_t len2 = VARSIZE_ANY_EXHDR(arg2);
2334 bool result;
2335
2337
2338 if (collid == C_COLLATION_OID)
2339 result = (len1 == len2 &&
2340 memcmp(NameStr(*arg1), VARDATA_ANY(arg2), len1) == 0);
2341 else
2342 result = (varstr_cmp(NameStr(*arg1), len1,
2343 VARDATA_ANY(arg2), len2,
2344 collid) == 0);
2345
2346 PG_FREE_IF_COPY(arg2, 1);
2347
2348 PG_RETURN_BOOL(result);
2349}

References check_collation_set(), collid, NameStr, PG_FREE_IF_COPY, PG_GET_COLLATION, PG_GETARG_NAME, PG_GETARG_TEXT_PP, PG_RETURN_BOOL, VARDATA_ANY(), VARSIZE_ANY_EXHDR(), and varstr_cmp().

◆ namefastcmp_c()

static int namefastcmp_c ( Datum  x,
Datum  y,
SortSupport  ssup 
)
static

Definition at line 1821 of file varlena.c.

1822{
1823 Name arg1 = DatumGetName(x);
1824 Name arg2 = DatumGetName(y);
1825
1826 return strncmp(NameStr(*arg1), NameStr(*arg2), NAMEDATALEN);
1827}
#define NAMEDATALEN
static Name DatumGetName(Datum X)
Definition: postgres.h:370

References DatumGetName(), NAMEDATALEN, NameStr, x, and y.

Referenced by varstr_sortsupport().

◆ namefastcmp_locale()

static int namefastcmp_locale ( Datum  x,
Datum  y,
SortSupport  ssup 
)
static

Definition at line 1864 of file varlena.c.

1865{
1866 Name arg1 = DatumGetName(x);
1867 Name arg2 = DatumGetName(y);
1868
1869 return varstrfastcmp_locale(NameStr(*arg1), strlen(NameStr(*arg1)),
1870 NameStr(*arg2), strlen(NameStr(*arg2)),
1871 ssup);
1872}
static int varstrfastcmp_locale(char *a1p, int len1, char *a2p, int len2, SortSupport ssup)
Definition: varlena.c:1878

References DatumGetName(), NameStr, varstrfastcmp_locale(), x, and y.

Referenced by varstr_sortsupport().

◆ namegetext()

Datum namegetext ( PG_FUNCTION_ARGS  )

Definition at line 2483 of file varlena.c.

2484{
2486}
#define CmpCall(cmpfunc)
Definition: varlena.c:2458
Datum btnametextcmp(PG_FUNCTION_ARGS)
Definition: varlena.c:2427

References btnametextcmp(), CmpCall, and PG_RETURN_BOOL.

◆ namegttext()

Datum namegttext ( PG_FUNCTION_ARGS  )

Definition at line 2477 of file varlena.c.

2478{
2480}

References btnametextcmp(), CmpCall, and PG_RETURN_BOOL.

◆ nameletext()

Datum nameletext ( PG_FUNCTION_ARGS  )

Definition at line 2471 of file varlena.c.

2472{
2474}

References btnametextcmp(), CmpCall, and PG_RETURN_BOOL.

◆ namelttext()

Datum namelttext ( PG_FUNCTION_ARGS  )

Definition at line 2465 of file varlena.c.

2466{
2468}

References btnametextcmp(), CmpCall, and PG_RETURN_BOOL.

◆ namenetext()

Datum namenetext ( PG_FUNCTION_ARGS  )

Definition at line 2377 of file varlena.c.

2378{
2379 Name arg1 = PG_GETARG_NAME(0);
2380 text *arg2 = PG_GETARG_TEXT_PP(1);
2381 size_t len1 = strlen(NameStr(*arg1));
2382 size_t len2 = VARSIZE_ANY_EXHDR(arg2);
2384 bool result;
2385
2387
2388 if (collid == C_COLLATION_OID)
2389 result = !(len1 == len2 &&
2390 memcmp(NameStr(*arg1), VARDATA_ANY(arg2), len1) == 0);
2391 else
2392 result = !(varstr_cmp(NameStr(*arg1), len1,
2393 VARDATA_ANY(arg2), len2,
2394 collid) == 0);
2395
2396 PG_FREE_IF_COPY(arg2, 1);
2397
2398 PG_RETURN_BOOL(result);
2399}

References check_collation_set(), collid, NameStr, PG_FREE_IF_COPY, PG_GET_COLLATION, PG_GETARG_NAME, PG_GETARG_TEXT_PP, PG_RETURN_BOOL, VARDATA_ANY(), VARSIZE_ANY_EXHDR(), and varstr_cmp().

◆ pg_column_compression()

Datum pg_column_compression ( PG_FUNCTION_ARGS  )

Definition at line 4157 of file varlena.c.

4158{
4159 int typlen;
4160 char *result;
4161 ToastCompressionId cmid;
4162
4163 /* On first call, get the input type's typlen, and save at *fn_extra */
4164 if (fcinfo->flinfo->fn_extra == NULL)
4165 {
4166 /* Lookup the datatype of the supplied argument */
4167 Oid argtypeid = get_fn_expr_argtype(fcinfo->flinfo, 0);
4168
4169 typlen = get_typlen(argtypeid);
4170 if (typlen == 0) /* should not happen */
4171 elog(ERROR, "cache lookup failed for type %u", argtypeid);
4172
4173 fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
4174 sizeof(int));
4175 *((int *) fcinfo->flinfo->fn_extra) = typlen;
4176 }
4177 else
4178 typlen = *((int *) fcinfo->flinfo->fn_extra);
4179
4180 if (typlen != -1)
4182
4183 /* get the compression method id stored in the compressed varlena */
4184 cmid = toast_get_compression_id((struct varlena *)
4186 if (cmid == TOAST_INVALID_COMPRESSION_ID)
4188
4189 /* convert compression method id to compression method name */
4190 switch (cmid)
4191 {
4193 result = "pglz";
4194 break;
4196 result = "lz4";
4197 break;
4198 default:
4199 elog(ERROR, "invalid compression method id %d", cmid);
4200 }
4201
4203}
int16 get_typlen(Oid typid)
Definition: lsyscache.c:2364
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:322
ToastCompressionId toast_get_compression_id(struct varlena *attr)
ToastCompressionId
@ TOAST_INVALID_COMPRESSION_ID
@ TOAST_LZ4_COMPRESSION_ID
@ TOAST_PGLZ_COMPRESSION_ID

References cstring_to_text(), DatumGetPointer(), elog, ERROR, get_fn_expr_argtype(), get_typlen(), MemoryContextAlloc(), PG_GETARG_DATUM, PG_RETURN_NULL, PG_RETURN_TEXT_P, toast_get_compression_id(), TOAST_INVALID_COMPRESSION_ID, TOAST_LZ4_COMPRESSION_ID, and TOAST_PGLZ_COMPRESSION_ID.

◆ pg_column_size()

Datum pg_column_size ( PG_FUNCTION_ARGS  )

Definition at line 4110 of file varlena.c.

4111{
4113 int32 result;
4114 int typlen;
4115
4116 /* On first call, get the input type's typlen, and save at *fn_extra */
4117 if (fcinfo->flinfo->fn_extra == NULL)
4118 {
4119 /* Lookup the datatype of the supplied argument */
4120 Oid argtypeid = get_fn_expr_argtype(fcinfo->flinfo, 0);
4121
4122 typlen = get_typlen(argtypeid);
4123 if (typlen == 0) /* should not happen */
4124 elog(ERROR, "cache lookup failed for type %u", argtypeid);
4125
4126 fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
4127 sizeof(int));
4128 *((int *) fcinfo->flinfo->fn_extra) = typlen;
4129 }
4130 else
4131 typlen = *((int *) fcinfo->flinfo->fn_extra);
4132
4133 if (typlen == -1)
4134 {
4135 /* varlena type, possibly toasted */
4136 result = toast_datum_size(value);
4137 }
4138 else if (typlen == -2)
4139 {
4140 /* cstring */
4141 result = strlen(DatumGetCString(value)) + 1;
4142 }
4143 else
4144 {
4145 /* ordinary fixed-width type */
4146 result = typlen;
4147 }
4148
4149 PG_RETURN_INT32(result);
4150}
Size toast_datum_size(Datum value)
Definition: detoast.c:601
static char * DatumGetCString(Datum X)
Definition: postgres.h:345

References DatumGetCString(), elog, ERROR, get_fn_expr_argtype(), get_typlen(), MemoryContextAlloc(), PG_GETARG_DATUM, PG_RETURN_INT32, toast_datum_size(), and value.

◆ pg_column_toast_chunk_id()

Datum pg_column_toast_chunk_id ( PG_FUNCTION_ARGS  )

Definition at line 4210 of file varlena.c.

4211{
4212 int typlen;
4213 struct varlena *attr;
4214 struct varatt_external toast_pointer;
4215
4216 /* On first call, get the input type's typlen, and save at *fn_extra */
4217 if (fcinfo->flinfo->fn_extra == NULL)
4218 {
4219 /* Lookup the datatype of the supplied argument */
4220 Oid argtypeid = get_fn_expr_argtype(fcinfo->flinfo, 0);
4221
4222 typlen = get_typlen(argtypeid);
4223 if (typlen == 0) /* should not happen */
4224 elog(ERROR, "cache lookup failed for type %u", argtypeid);
4225
4226 fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
4227 sizeof(int));
4228 *((int *) fcinfo->flinfo->fn_extra) = typlen;
4229 }
4230 else
4231 typlen = *((int *) fcinfo->flinfo->fn_extra);
4232
4233 if (typlen != -1)
4235
4236 attr = (struct varlena *) DatumGetPointer(PG_GETARG_DATUM(0));
4237
4238 if (!VARATT_IS_EXTERNAL_ONDISK(attr))
4240
4241 VARATT_EXTERNAL_GET_POINTER(toast_pointer, attr);
4242
4243 PG_RETURN_OID(toast_pointer.va_valueid);
4244}
#define VARATT_EXTERNAL_GET_POINTER(toast_pointer, attr)
Definition: detoast.h:22
#define PG_RETURN_OID(x)
Definition: fmgr.h:360
static bool VARATT_IS_EXTERNAL_ONDISK(const void *PTR)
Definition: varatt.h:361

References DatumGetPointer(), elog, ERROR, get_fn_expr_argtype(), get_typlen(), MemoryContextAlloc(), PG_GETARG_DATUM, PG_RETURN_NULL, PG_RETURN_OID, varatt_external::va_valueid, VARATT_EXTERNAL_GET_POINTER, and VARATT_IS_EXTERNAL_ONDISK().

◆ replace_text()

Datum replace_text ( PG_FUNCTION_ARGS  )

Definition at line 3092 of file varlena.c.

3093{
3094 text *src_text = PG_GETARG_TEXT_PP(0);
3095 text *from_sub_text = PG_GETARG_TEXT_PP(1);
3096 text *to_sub_text = PG_GETARG_TEXT_PP(2);
3097 int src_text_len;
3098 int from_sub_text_len;
3100 text *ret_text;
3101 int chunk_len;
3102 char *curr_ptr;
3103 char *start_ptr;
3105 bool found;
3106
3107 src_text_len = VARSIZE_ANY_EXHDR(src_text);
3108 from_sub_text_len = VARSIZE_ANY_EXHDR(from_sub_text);
3109
3110 /* Return unmodified source string if empty source or pattern */
3111 if (src_text_len < 1 || from_sub_text_len < 1)
3112 {
3113 PG_RETURN_TEXT_P(src_text);
3114 }
3115
3116 text_position_setup(src_text, from_sub_text, PG_GET_COLLATION(), &state);
3117
3118 found = text_position_next(&state);
3119
3120 /* When the from_sub_text is not found, there is nothing to do. */
3121 if (!found)
3122 {
3124 PG_RETURN_TEXT_P(src_text);
3125 }
3127 start_ptr = VARDATA_ANY(src_text);
3128
3130
3131 do
3132 {
3134
3135 /* copy the data skipped over by last text_position_next() */
3136 chunk_len = curr_ptr - start_ptr;
3137 appendBinaryStringInfo(&str, start_ptr, chunk_len);
3138
3139 appendStringInfoText(&str, to_sub_text);
3140
3141 start_ptr = curr_ptr + state.last_match_len;
3142
3143 found = text_position_next(&state);
3144 if (found)
3146 }
3147 while (found);
3148
3149 /* copy trailing data */
3150 chunk_len = ((char *) src_text + VARSIZE_ANY(src_text)) - start_ptr;
3151 appendBinaryStringInfo(&str, start_ptr, chunk_len);
3152
3154
3155 ret_text = cstring_to_text_with_len(str.data, str.len);
3156 pfree(str.data);
3157
3158 PG_RETURN_TEXT_P(ret_text);
3159}
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
static Size VARSIZE_ANY(const void *PTR)
Definition: varatt.h:460
static void text_position_setup(text *t1, text *t2, Oid collid, TextPositionState *state)
Definition: varlena.c:917
static void text_position_cleanup(TextPositionState *state)
Definition: varlena.c:1261
static void appendStringInfoText(StringInfo str, const text *t)
Definition: varlena.c:3078
static char * text_position_get_match_ptr(TextPositionState *state)
Definition: varlena.c:1226
static bool text_position_next(TextPositionState *state)
Definition: varlena.c:1038

References appendBinaryStringInfo(), appendStringInfoText(), CHECK_FOR_INTERRUPTS, cstring_to_text_with_len(), initStringInfo(), pfree(), PG_GET_COLLATION, PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, str, text_position_cleanup(), text_position_get_match_ptr(), text_position_next(), text_position_setup(), VARDATA_ANY(), VARSIZE_ANY(), and VARSIZE_ANY_EXHDR().

Referenced by appendStringInfoRegexpSubstr(), check_replace_text_has_escape(), execute_extension_script(), and replace_text_regexp().

◆ replace_text_regexp()

text * replace_text_regexp ( text src_text,
text pattern_text,
text replace_text,
int  cflags,
Oid  collation,
int  search_start,
int  n 
)

Definition at line 3302 of file varlena.c.

3306{
3307 text *ret_text;
3308 regex_t *re;
3309 int src_text_len = VARSIZE_ANY_EXHDR(src_text);
3310 int nmatches = 0;
3312 regmatch_t pmatch[10]; /* main match, plus \1 to \9 */
3313 int nmatch = lengthof(pmatch);
3314 pg_wchar *data;
3315 size_t data_len;
3316 int data_pos;
3317 char *start_ptr;
3318 int escape_status;
3319
3321
3322 /* Convert data string to wide characters. */
3323 data = (pg_wchar *) palloc((src_text_len + 1) * sizeof(pg_wchar));
3324 data_len = pg_mb2wchar_with_len(VARDATA_ANY(src_text), data, src_text_len);
3325
3326 /* Check whether replace_text has escapes, especially regexp submatches. */
3328
3329 /* If no regexp submatches, we can use REG_NOSUB. */
3330 if (escape_status < 2)
3331 {
3332 cflags |= REG_NOSUB;
3333 /* Also tell pg_regexec we only want the whole-match location. */
3334 nmatch = 1;
3335 }
3336
3337 /* Prepare the regexp. */
3338 re = RE_compile_and_cache(pattern_text, cflags, collation);
3339
3340 /* start_ptr points to the data_pos'th character of src_text */
3341 start_ptr = (char *) VARDATA_ANY(src_text);
3342 data_pos = 0;
3343
3344 while (search_start <= data_len)
3345 {
3346 int regexec_result;
3347
3349
3350 regexec_result = pg_regexec(re,
3351 data,
3352 data_len,
3353 search_start,
3354 NULL, /* no details */
3355 nmatch,
3356 pmatch,
3357 0);
3358
3359 if (regexec_result == REG_NOMATCH)
3360 break;
3361
3362 if (regexec_result != REG_OKAY)
3363 {
3364 char errMsg[100];
3365
3366 pg_regerror(regexec_result, re, errMsg, sizeof(errMsg));
3367 ereport(ERROR,
3368 (errcode(ERRCODE_INVALID_REGULAR_EXPRESSION),
3369 errmsg("regular expression failed: %s", errMsg)));
3370 }
3371
3372 /*
3373 * Count matches, and decide whether to replace this match.
3374 */
3375 nmatches++;
3376 if (n > 0 && nmatches != n)
3377 {
3378 /*
3379 * No, so advance search_start, but not start_ptr/data_pos. (Thus,
3380 * we treat the matched text as if it weren't matched, and copy it
3381 * to the output later.)
3382 */
3383 search_start = pmatch[0].rm_eo;
3384 if (pmatch[0].rm_so == pmatch[0].rm_eo)
3385 search_start++;
3386 continue;
3387 }
3388
3389 /*
3390 * Copy the text to the left of the match position. Note we are given
3391 * character not byte indexes.
3392 */
3393 if (pmatch[0].rm_so - data_pos > 0)
3394 {
3395 int chunk_len;
3396
3397 chunk_len = charlen_to_bytelen(start_ptr,
3398 pmatch[0].rm_so - data_pos);
3399 appendBinaryStringInfo(&buf, start_ptr, chunk_len);
3400
3401 /*
3402 * Advance start_ptr over that text, to avoid multiple rescans of
3403 * it if the replace_text contains multiple back-references.
3404 */
3405 start_ptr += chunk_len;
3406 data_pos = pmatch[0].rm_so;
3407 }
3408
3409 /*
3410 * Copy the replace_text, processing escapes if any are present.
3411 */
3412 if (escape_status > 0)
3414 start_ptr, data_pos);
3415 else
3417
3418 /* Advance start_ptr and data_pos over the matched text. */
3419 start_ptr += charlen_to_bytelen(start_ptr,
3420 pmatch[0].rm_eo - data_pos);
3421 data_pos = pmatch[0].rm_eo;
3422
3423 /*
3424 * If we only want to replace one occurrence, we're done.
3425 */
3426 if (n > 0)
3427 break;
3428
3429 /*
3430 * Advance search position. Normally we start the next search at the
3431 * end of the previous match; but if the match was of zero length, we
3432 * have to advance by one character, or we'd just find the same match
3433 * again.
3434 */
3435 search_start = data_pos;
3436 if (pmatch[0].rm_so == pmatch[0].rm_eo)
3437 search_start++;
3438 }
3439
3440 /*
3441 * Copy the text to the right of the last match.
3442 */
3443 if (data_pos < data_len)
3444 {
3445 int chunk_len;
3446
3447 chunk_len = ((char *) src_text + VARSIZE_ANY(src_text)) - start_ptr;
3448 appendBinaryStringInfo(&buf, start_ptr, chunk_len);
3449 }
3450
3451 ret_text = cstring_to_text_with_len(buf.data, buf.len);
3452 pfree(buf.data);
3453 pfree(data);
3454
3455 return ret_text;
3456}
#define lengthof(array)
Definition: c.h:788
unsigned int pg_wchar
Definition: mbprint.c:31
int pg_mb2wchar_with_len(const char *from, pg_wchar *to, int len)
Definition: mbutils.c:987
const void * data
size_t pg_regerror(int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size)
Definition: regerror.c:60
#define REG_NOMATCH
Definition: regex.h:216
#define regmatch_t
Definition: regex.h:246
#define REG_OKAY
Definition: regex.h:215
#define REG_NOSUB
Definition: regex.h:185
#define regex_t
Definition: regex.h:245
int pg_regexec(regex_t *re, const chr *string, size_t len, size_t search_start, rm_detail_t *details, size_t nmatch, regmatch_t pmatch[], int flags)
Definition: regexec.c:185
regex_t * RE_compile_and_cache(text *text_re, int cflags, Oid collation)
Definition: regexp.c:141
static int check_replace_text_has_escape(const text *replace_text)
Definition: varlena.c:3169
static void appendStringInfoRegexpSubstr(StringInfo str, text *replace_text, regmatch_t *pmatch, char *start_ptr, int data_pos)
Definition: varlena.c:3202

References appendBinaryStringInfo(), appendStringInfoRegexpSubstr(), appendStringInfoText(), buf, charlen_to_bytelen(), CHECK_FOR_INTERRUPTS, check_replace_text_has_escape(), cstring_to_text_with_len(), data, ereport, errcode(), errmsg(), ERROR, initStringInfo(), lengthof, palloc(), pfree(), pg_mb2wchar_with_len(), pg_regerror(), pg_regexec(), RE_compile_and_cache(), REG_NOMATCH, REG_NOSUB, REG_OKAY, regex_t, regmatch_t, replace_text(), VARDATA_ANY(), VARSIZE_ANY(), and VARSIZE_ANY_EXHDR().

Referenced by textregexreplace(), textregexreplace_extended(), and textregexreplace_noopt().

◆ rest_of_char_same()

static bool rest_of_char_same ( const char *  s1,
const char *  s2,
int  len 
)
inlinestatic

Definition at line 5248 of file varlena.c.

5249{
5250 while (len > 0)
5251 {
5252 len--;
5253 if (s1[len] != s2[len])
5254 return false;
5255 }
5256 return true;
5257}
char * s1
char * s2

References len, s1, and s2.

Referenced by varstr_levenshtein().

◆ split_part()

Datum split_part ( PG_FUNCTION_ARGS  )

Definition at line 3464 of file varlena.c.

3465{
3466 text *inputstring = PG_GETARG_TEXT_PP(0);
3467 text *fldsep = PG_GETARG_TEXT_PP(1);
3468 int fldnum = PG_GETARG_INT32(2);
3469 int inputstring_len;
3470 int fldsep_len;
3472 char *start_ptr;
3473 char *end_ptr;
3474 text *result_text;
3475 bool found;
3476
3477 /* field number is 1 based */
3478 if (fldnum == 0)
3479 ereport(ERROR,
3480 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3481 errmsg("field position must not be zero")));
3482
3483 inputstring_len = VARSIZE_ANY_EXHDR(inputstring);
3484 fldsep_len = VARSIZE_ANY_EXHDR(fldsep);
3485
3486 /* return empty string for empty input string */
3487 if (inputstring_len < 1)
3489
3490 /* handle empty field separator */
3491 if (fldsep_len < 1)
3492 {
3493 /* if first or last field, return input string, else empty string */
3494 if (fldnum == 1 || fldnum == -1)
3495 PG_RETURN_TEXT_P(inputstring);
3496 else
3498 }
3499
3500 /* find the first field separator */
3501 text_position_setup(inputstring, fldsep, PG_GET_COLLATION(), &state);
3502
3503 found = text_position_next(&state);
3504
3505 /* special case if fldsep not found at all */
3506 if (!found)
3507 {
3509 /* if first or last field, return input string, else empty string */
3510 if (fldnum == 1 || fldnum == -1)
3511 PG_RETURN_TEXT_P(inputstring);
3512 else
3514 }
3515
3516 /*
3517 * take care of a negative field number (i.e. count from the right) by
3518 * converting to a positive field number; we need total number of fields
3519 */
3520 if (fldnum < 0)
3521 {
3522 /* we found a fldsep, so there are at least two fields */
3523 int numfields = 2;
3524
3525 while (text_position_next(&state))
3526 numfields++;
3527
3528 /* special case of last field does not require an extra pass */
3529 if (fldnum == -1)
3530 {
3531 start_ptr = text_position_get_match_ptr(&state) + state.last_match_len;
3532 end_ptr = VARDATA_ANY(inputstring) + inputstring_len;
3535 end_ptr - start_ptr));
3536 }
3537
3538 /* else, convert fldnum to positive notation */
3539 fldnum += numfields + 1;
3540
3541 /* if nonexistent field, return empty string */
3542 if (fldnum <= 0)
3543 {
3546 }
3547
3548 /* reset to pointing at first match, but now with positive fldnum */
3550 found = text_position_next(&state);
3551 Assert(found);
3552 }
3553
3554 /* identify bounds of first field */
3555 start_ptr = VARDATA_ANY(inputstring);
3557
3558 while (found && --fldnum > 0)
3559 {
3560 /* identify bounds of next field */
3561 start_ptr = end_ptr + state.last_match_len;
3562 found = text_position_next(&state);
3563 if (found)
3565 }
3566
3568
3569 if (fldnum > 0)
3570 {
3571 /* N'th field separator not found */
3572 /* if last field requested, return it, else empty string */
3573 if (fldnum == 1)
3574 {
3575 int last_len = start_ptr - VARDATA_ANY(inputstring);
3576
3577 result_text = cstring_to_text_with_len(start_ptr,
3578 inputstring_len - last_len);
3579 }
3580 else
3581 result_text = cstring_to_text("");
3582 }
3583 else
3584 {
3585 /* non-last field requested */
3586 result_text = cstring_to_text_with_len(start_ptr, end_ptr - start_ptr);
3587 }
3588
3589 PG_RETURN_TEXT_P(result_text);
3590}
#define PG_GETARG_INT32(n)
Definition: fmgr.h:269
static void text_position_reset(TextPositionState *state)
Definition: varlena.c:1253

References Assert(), cstring_to_text(), cstring_to_text_with_len(), ereport, errcode(), errmsg(), ERROR, PG_GET_COLLATION, PG_GETARG_INT32, PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, text_position_cleanup(), text_position_get_match_ptr(), text_position_next(), text_position_reset(), text_position_setup(), VARDATA_ANY(), and VARSIZE_ANY_EXHDR().

◆ split_text()

static bool split_text ( FunctionCallInfo  fcinfo,
SplitTextOutputData tstate 
)
static

Definition at line 3687 of file varlena.c.

3688{
3689 text *inputstring;
3690 text *fldsep;
3691 text *null_string;
3692 Oid collation = PG_GET_COLLATION();
3693 int inputstring_len;
3694 int fldsep_len;
3695 char *start_ptr;
3696 text *result_text;
3697
3698 /* when input string is NULL, then result is NULL too */
3699 if (PG_ARGISNULL(0))
3700 return false;
3701
3702 inputstring = PG_GETARG_TEXT_PP(0);
3703
3704 /* fldsep can be NULL */
3705 if (!PG_ARGISNULL(1))
3706 fldsep = PG_GETARG_TEXT_PP(1);
3707 else
3708 fldsep = NULL;
3709
3710 /* null_string can be NULL or omitted */
3711 if (PG_NARGS() > 2 && !PG_ARGISNULL(2))
3712 null_string = PG_GETARG_TEXT_PP(2);
3713 else
3714 null_string = NULL;
3715
3716 if (fldsep != NULL)
3717 {
3718 /*
3719 * Normal case with non-null fldsep. Use the text_position machinery
3720 * to search for occurrences of fldsep.
3721 */
3723
3724 inputstring_len = VARSIZE_ANY_EXHDR(inputstring);
3725 fldsep_len = VARSIZE_ANY_EXHDR(fldsep);
3726
3727 /* return empty set for empty input string */
3728 if (inputstring_len < 1)
3729 return true;
3730
3731 /* empty field separator: return input string as a one-element set */
3732 if (fldsep_len < 1)
3733 {
3734 split_text_accum_result(tstate, inputstring,
3735 null_string, collation);
3736 return true;
3737 }
3738
3739 text_position_setup(inputstring, fldsep, collation, &state);
3740
3741 start_ptr = VARDATA_ANY(inputstring);
3742
3743 for (;;)
3744 {
3745 bool found;
3746 char *end_ptr;
3747 int chunk_len;
3748
3750
3751 found = text_position_next(&state);
3752 if (!found)
3753 {
3754 /* fetch last field */
3755 chunk_len = ((char *) inputstring + VARSIZE_ANY(inputstring)) - start_ptr;
3756 end_ptr = NULL; /* not used, but some compilers complain */
3757 }
3758 else
3759 {
3760 /* fetch non-last field */
3762 chunk_len = end_ptr - start_ptr;
3763 }
3764
3765 /* build a temp text datum to pass to split_text_accum_result */
3766 result_text = cstring_to_text_with_len(start_ptr, chunk_len);
3767
3768 /* stash away this field */
3769 split_text_accum_result(tstate, result_text,
3770 null_string, collation);
3771
3772 pfree(result_text);
3773
3774 if (!found)
3775 break;
3776
3777 start_ptr = end_ptr + state.last_match_len;
3778 }
3779
3781 }
3782 else
3783 {
3784 /*
3785 * When fldsep is NULL, each character in the input string becomes a
3786 * separate element in the result set. The separator is effectively
3787 * the space between characters.
3788 */
3789 inputstring_len = VARSIZE_ANY_EXHDR(inputstring);
3790
3791 start_ptr = VARDATA_ANY(inputstring);
3792
3793 while (inputstring_len > 0)
3794 {
3795 int chunk_len = pg_mblen(start_ptr);
3796
3798
3799 /* build a temp text datum to pass to split_text_accum_result */
3800 result_text = cstring_to_text_with_len(start_ptr, chunk_len);
3801
3802 /* stash away this field */
3803 split_text_accum_result(tstate, result_text,
3804 null_string, collation);
3805
3806 pfree(result_text);
3807
3808 start_ptr += chunk_len;
3809 inputstring_len -= chunk_len;
3810 }
3811 }
3812
3813 return true;
3814}
static void split_text_accum_result(SplitTextOutputData *tstate, text *field_value, text *null_string, Oid collation)
Definition: varlena.c:3823

References CHECK_FOR_INTERRUPTS, cstring_to_text_with_len(), pfree(), PG_ARGISNULL, PG_GET_COLLATION, PG_GETARG_TEXT_PP, pg_mblen(), PG_NARGS, split_text_accum_result(), text_position_cleanup(), text_position_get_match_ptr(), text_position_next(), text_position_setup(), VARDATA_ANY(), VARSIZE_ANY(), and VARSIZE_ANY_EXHDR().

Referenced by text_to_array(), and text_to_table().

◆ split_text_accum_result()

static void split_text_accum_result ( SplitTextOutputData tstate,
text field_value,
text null_string,
Oid  collation 
)
static

Definition at line 3823 of file varlena.c.

3827{
3828 bool is_null = false;
3829
3830 if (null_string && text_isequal(field_value, null_string, collation))
3831 is_null = true;
3832
3833 if (tstate->tupstore)
3834 {
3835 Datum values[1];
3836 bool nulls[1];
3837
3838 values[0] = PointerGetDatum(field_value);
3839 nulls[0] = is_null;
3840
3842 tstate->tupdesc,
3843 values,
3844 nulls);
3845 }
3846 else
3847 {
3848 tstate->astate = accumArrayResult(tstate->astate,
3849 PointerGetDatum(field_value),
3850 is_null,
3851 TEXTOID,
3853 }
3854}
ArrayBuildState * accumArrayResult(ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
Definition: arrayfuncs.c:5350
static Datum values[MAXATTR]
Definition: bootstrap.c:153
MemoryContext CurrentMemoryContext
Definition: mcxt.c:160
TupleDesc tupdesc
Definition: varlena.c:110
ArrayBuildState * astate
Definition: varlena.c:108
Tuplestorestate * tupstore
Definition: varlena.c:109
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, const Datum *values, const bool *isnull)
Definition: tuplestore.c:784
static bool text_isequal(text *txt1, text *txt2, Oid collid)
Definition: varlena.c:3596

References accumArrayResult(), SplitTextOutputData::astate, CurrentMemoryContext, PointerGetDatum(), text_isequal(), SplitTextOutputData::tupdesc, tuplestore_putvalues(), SplitTextOutputData::tupstore, and values.

Referenced by split_text().

◆ SplitDirectoriesString()

bool SplitDirectoriesString ( char *  rawstring,
char  separator,
List **  namelist 
)

Definition at line 2871 of file varlena.c.

2873{
2874 char *nextp = rawstring;
2875 bool done = false;
2876
2877 *namelist = NIL;
2878
2879 while (scanner_isspace(*nextp))
2880 nextp++; /* skip leading whitespace */
2881
2882 if (*nextp == '\0')
2883 return true; /* allow empty string */
2884
2885 /* At the top of the loop, we are at start of a new directory. */
2886 do
2887 {
2888 char *curname;
2889 char *endp;
2890
2891 if (*nextp == '"')
2892 {
2893 /* Quoted name --- collapse quote-quote pairs */
2894 curname = nextp + 1;
2895 for (;;)
2896 {
2897 endp = strchr(nextp + 1, '"');
2898 if (endp == NULL)
2899 return false; /* mismatched quotes */
2900 if (endp[1] != '"')
2901 break; /* found end of quoted name */
2902 /* Collapse adjacent quotes into one quote, and look again */
2903 memmove(endp, endp + 1, strlen(endp));
2904 nextp = endp;
2905 }
2906 /* endp now points at the terminating quote */
2907 nextp = endp + 1;
2908 }
2909 else
2910 {
2911 /* Unquoted name --- extends to separator or end of string */
2912 curname = endp = nextp;
2913 while (*nextp && *nextp != separator)
2914 {
2915 /* trailing whitespace should not be included in name */
2916 if (!scanner_isspace(*nextp))
2917 endp = nextp + 1;
2918 nextp++;
2919 }
2920 if (curname == endp)
2921 return false; /* empty unquoted name not allowed */
2922 }
2923
2924 while (scanner_isspace(*nextp))
2925 nextp++; /* skip trailing whitespace */
2926
2927 if (*nextp == separator)
2928 {
2929 nextp++;
2930 while (scanner_isspace(*nextp))
2931 nextp++; /* skip leading whitespace for next */
2932 /* we expect another name, so done remains false */
2933 }
2934 else if (*nextp == '\0')
2935 done = true;
2936 else
2937 return false; /* invalid syntax */
2938
2939 /* Now safe to overwrite separator with a null */
2940 *endp = '\0';
2941
2942 /* Truncate path if it's overlength */
2943 if (strlen(curname) >= MAXPGPATH)
2944 curname[MAXPGPATH - 1] = '\0';
2945
2946 /*
2947 * Finished isolating current name --- add it to list
2948 */
2949 curname = pstrdup(curname);
2950 canonicalize_path(curname);
2951 *namelist = lappend(*namelist, curname);
2952
2953 /* Loop back if we didn't reach end of string */
2954 } while (!done);
2955
2956 return true;
2957}
List * lappend(List *list, void *datum)
Definition: list.c:339
char * pstrdup(const char *in)
Definition: mcxt.c:1759
#define MAXPGPATH
#define NIL
Definition: pg_list.h:68
void canonicalize_path(char *path)
Definition: path.c:337
bool scanner_isspace(char ch)
Definition: scansup.c:117

References canonicalize_path(), lappend(), MAXPGPATH, NIL, pstrdup(), and scanner_isspace().

Referenced by check_oauth_validator(), load_libraries(), and PostmasterMain().

◆ SplitGUCList()

bool SplitGUCList ( char *  rawstring,
char  separator,
List **  namelist 
)

Definition at line 2992 of file varlena.c.

2994{
2995 char *nextp = rawstring;
2996 bool done = false;
2997
2998 *namelist = NIL;
2999
3000 while (scanner_isspace(*nextp))
3001 nextp++; /* skip leading whitespace */
3002
3003 if (*nextp == '\0')
3004 return true; /* allow empty string */
3005
3006 /* At the top of the loop, we are at start of a new identifier. */
3007 do
3008 {
3009 char *curname;
3010 char *endp;
3011
3012 if (*nextp == '"')
3013 {
3014 /* Quoted name --- collapse quote-quote pairs */
3015 curname = nextp + 1;
3016 for (;;)
3017 {
3018 endp = strchr(nextp + 1, '"');
3019 if (endp == NULL)
3020 return false; /* mismatched quotes */
3021 if (endp[1] != '"')
3022 break; /* found end of quoted name */
3023 /* Collapse adjacent quotes into one quote, and look again */
3024 memmove(endp, endp + 1, strlen(endp));
3025 nextp = endp;
3026 }
3027 /* endp now points at the terminating quote */
3028 nextp = endp + 1;
3029 }
3030 else
3031 {
3032 /* Unquoted name --- extends to separator or whitespace */
3033 curname = nextp;
3034 while (*nextp && *nextp != separator &&
3035 !scanner_isspace(*nextp))
3036 nextp++;
3037 endp = nextp;
3038 if (curname == nextp)
3039 return false; /* empty unquoted name not allowed */
3040 }
3041
3042 while (scanner_isspace(*nextp))
3043 nextp++; /* skip trailing whitespace */
3044
3045 if (*nextp == separator)
3046 {
3047 nextp++;
3048 while (scanner_isspace(*nextp))
3049 nextp++; /* skip leading whitespace for next */
3050 /* we expect another name, so done remains false */
3051 }
3052 else if (*nextp == '\0')
3053 done = true;
3054 else
3055 return false; /* invalid syntax */
3056
3057 /* Now safe to overwrite separator with a null */
3058 *endp = '\0';
3059
3060 /*
3061 * Finished isolating current name --- add it to list
3062 */
3063 *namelist = lappend(*namelist, curname);
3064
3065 /* Loop back if we didn't reach end of string */
3066 } while (!done);
3067
3068 return true;
3069}

References lappend(), NIL, and scanner_isspace().

Referenced by check_debug_io_direct(), dumpFunc(), parse_hba_auth_opt(), pg_get_functiondef(), and PostmasterMain().

◆ SplitIdentifierString()

bool SplitIdentifierString ( char *  rawstring,
char  separator,
List **  namelist 
)

Definition at line 2744 of file varlena.c.

2746{
2747 char *nextp = rawstring;
2748 bool done = false;
2749
2750 *namelist = NIL;
2751
2752 while (scanner_isspace(*nextp))
2753 nextp++; /* skip leading whitespace */
2754
2755 if (*nextp == '\0')
2756 return true; /* allow empty string */
2757
2758 /* At the top of the loop, we are at start of a new identifier. */
2759 do
2760 {
2761 char *curname;
2762 char *endp;
2763
2764 if (*nextp == '"')
2765 {
2766 /* Quoted name --- collapse quote-quote pairs, no downcasing */
2767 curname = nextp + 1;
2768 for (;;)
2769 {
2770 endp = strchr(nextp + 1, '"');
2771 if (endp == NULL)
2772 return false; /* mismatched quotes */
2773 if (endp[1] != '"')
2774 break; /* found end of quoted name */
2775 /* Collapse adjacent quotes into one quote, and look again */
2776 memmove(endp, endp + 1, strlen(endp));
2777 nextp = endp;
2778 }
2779 /* endp now points at the terminating quote */
2780 nextp = endp + 1;
2781 }
2782 else
2783 {
2784 /* Unquoted name --- extends to separator or whitespace */
2785 char *downname;
2786 int len;
2787
2788 curname = nextp;
2789 while (*nextp && *nextp != separator &&
2790 !scanner_isspace(*nextp))
2791 nextp++;
2792 endp = nextp;
2793 if (curname == nextp)
2794 return false; /* empty unquoted name not allowed */
2795
2796 /*
2797 * Downcase the identifier, using same code as main lexer does.
2798 *
2799 * XXX because we want to overwrite the input in-place, we cannot
2800 * support a downcasing transformation that increases the string
2801 * length. This is not a problem given the current implementation
2802 * of downcase_truncate_identifier, but we'll probably have to do
2803 * something about this someday.
2804 */
2805 len = endp - curname;
2806 downname = downcase_truncate_identifier(curname, len, false);
2807 Assert(strlen(downname) <= len);
2808 strncpy(curname, downname, len); /* strncpy is required here */
2809 pfree(downname);
2810 }
2811
2812 while (scanner_isspace(*nextp))
2813 nextp++; /* skip trailing whitespace */
2814
2815 if (*nextp == separator)
2816 {
2817 nextp++;
2818 while (scanner_isspace(*nextp))
2819 nextp++; /* skip leading whitespace for next */
2820 /* we expect another name, so done remains false */
2821 }
2822 else if (*nextp == '\0')
2823 done = true;
2824 else
2825 return false; /* invalid syntax */
2826
2827 /* Now safe to overwrite separator with a null */
2828 *endp = '\0';
2829
2830 /* Truncate name if it's overlength */
2831 truncate_identifier(curname, strlen(curname), false);
2832
2833 /*
2834 * Finished isolating current name --- add it to list
2835 */
2836 *namelist = lappend(*namelist, curname);
2837
2838 /* Loop back if we didn't reach end of string */
2839 } while (!done);
2840
2841 return true;
2842}
void truncate_identifier(char *ident, int len, bool warn)
Definition: scansup.c:93
char * downcase_truncate_identifier(const char *ident, int len, bool warn)
Definition: scansup.c:37

References Assert(), downcase_truncate_identifier(), lappend(), len, NIL, pfree(), scanner_isspace(), and truncate_identifier().

Referenced by check_createrole_self_grant(), check_datestyle(), check_log_connections(), check_log_destination(), check_restrict_nonsystem_relation_kind(), check_search_path(), check_temp_tablespaces(), check_wal_consistency_checking(), ExtractExtensionList(), parse_extension_control_file(), parse_output_parameters(), parse_publication_options(), plpgsql_extra_checks_check_hook(), PrepareTempTablespaces(), preprocessNamespacePath(), stringToQualifiedNameList(), textToQualifiedNameList(), and validate_sync_standby_slots().

◆ string_agg_combine()

Datum string_agg_combine ( PG_FUNCTION_ARGS  )

Definition at line 4337 of file varlena.c.

4338{
4339 StringInfo state1;
4340 StringInfo state2;
4341 MemoryContext agg_context;
4342
4343 if (!AggCheckCallContext(fcinfo, &agg_context))
4344 elog(ERROR, "aggregate function called in non-aggregate context");
4345
4346 state1 = PG_ARGISNULL(0) ? NULL : (StringInfo) PG_GETARG_POINTER(0);
4347 state2 = PG_ARGISNULL(1) ? NULL : (StringInfo) PG_GETARG_POINTER(1);
4348
4349 if (state2 == NULL)
4350 {
4351 /*
4352 * NULL state2 is easy, just return state1, which we know is already
4353 * in the agg_context
4354 */
4355 if (state1 == NULL)
4357 PG_RETURN_POINTER(state1);
4358 }
4359
4360 if (state1 == NULL)
4361 {
4362 /* We must copy state2's data into the agg_context */
4363 MemoryContext old_context;
4364
4365 old_context = MemoryContextSwitchTo(agg_context);
4366 state1 = makeStringAggState(fcinfo);
4367 appendBinaryStringInfo(state1, state2->data, state2->len);
4368 state1->cursor = state2->cursor;
4369 MemoryContextSwitchTo(old_context);
4370 }
4371 else if (state2->len > 0)
4372 {
4373 /* Combine ... state1->cursor does not change in this case */
4374 appendBinaryStringInfo(state1, state2->data, state2->len);
4375 }
4376
4377 PG_RETURN_POINTER(state1);
4378}
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:361
struct StringInfoData * StringInfo
Definition: string.h:15
static StringInfo makeStringAggState(FunctionCallInfo fcinfo)
Definition: varlena.c:4258

References AggCheckCallContext(), appendBinaryStringInfo(), StringInfoData::cursor, StringInfoData::data, elog, ERROR, StringInfoData::len, makeStringAggState(), MemoryContextSwitchTo(), PG_ARGISNULL, PG_GETARG_POINTER, PG_RETURN_NULL, and PG_RETURN_POINTER.

◆ string_agg_deserialize()

Datum string_agg_deserialize ( PG_FUNCTION_ARGS  )

Definition at line 4418 of file varlena.c.

4419{
4420 bytea *sstate;
4421 StringInfo result;
4423 char *data;
4424 int datalen;
4425
4426 /* cannot be called directly because of internal-type argument */
4427 Assert(AggCheckCallContext(fcinfo, NULL));
4428
4429 sstate = PG_GETARG_BYTEA_PP(0);
4430
4431 /*
4432 * Initialize a StringInfo so that we can "receive" it using the standard
4433 * recv-function infrastructure.
4434 */
4436 VARSIZE_ANY_EXHDR(sstate));
4437
4438 result = makeStringAggState(fcinfo);
4439
4440 /* cursor */
4441 result->cursor = pq_getmsgint(&buf, 4);
4442
4443 /* data */
4444 datalen = VARSIZE_ANY_EXHDR(sstate) - 4;
4445 data = (char *) pq_getmsgbytes(&buf, datalen);
4446 appendBinaryStringInfo(result, data, datalen);
4447
4448 pq_getmsgend(&buf);
4449
4450 PG_RETURN_POINTER(result);
4451}
#define PG_GETARG_BYTEA_PP(n)
Definition: fmgr.h:308
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:415
void pq_getmsgend(StringInfo msg)
Definition: pqformat.c:635
const char * pq_getmsgbytes(StringInfo msg, int datalen)
Definition: pqformat.c:508
static void initReadOnlyStringInfo(StringInfo str, char *data, int len)
Definition: stringinfo.h:157

References AggCheckCallContext(), appendBinaryStringInfo(), Assert(), buf, StringInfoData::cursor, data, initReadOnlyStringInfo(), makeStringAggState(), PG_GETARG_BYTEA_PP, PG_RETURN_POINTER, pq_getmsgbytes(), pq_getmsgend(), pq_getmsgint(), VARDATA_ANY(), and VARSIZE_ANY_EXHDR().

◆ string_agg_finalfn()

Datum string_agg_finalfn ( PG_FUNCTION_ARGS  )

Definition at line 4454 of file varlena.c.

4455{
4457
4458 /* cannot be called directly because of internal-type argument */
4459 Assert(AggCheckCallContext(fcinfo, NULL));
4460
4462
4463 if (state != NULL)
4464 {
4465 /* As per comment in transfn, strip data before the cursor position */
4467 state->len - state->cursor));
4468 }
4469 else
4471}

References AggCheckCallContext(), Assert(), cstring_to_text_with_len(), PG_ARGISNULL, PG_GETARG_POINTER, PG_RETURN_NULL, and PG_RETURN_TEXT_P.

◆ string_agg_serialize()

Datum string_agg_serialize ( PG_FUNCTION_ARGS  )

Definition at line 4387 of file varlena.c.

4388{
4391 bytea *result;
4392
4393 /* cannot be called directly because of internal-type argument */
4394 Assert(AggCheckCallContext(fcinfo, NULL));
4395
4397
4399
4400 /* cursor */
4401 pq_sendint(&buf, state->cursor, 4);
4402
4403 /* data */
4404 pq_sendbytes(&buf, state->data, state->len);
4405
4406 result = pq_endtypsend(&buf);
4407
4408 PG_RETURN_BYTEA_P(result);
4409}
#define PG_RETURN_BYTEA_P(x)
Definition: fmgr.h:371
void pq_sendbytes(StringInfo buf, const void *data, int datalen)
Definition: pqformat.c:126
void pq_begintypsend(StringInfo buf)
Definition: pqformat.c:326
bytea * pq_endtypsend(StringInfo buf)
Definition: pqformat.c:346
static void pq_sendint(StringInfo buf, uint32 i, int b)
Definition: pqformat.h:171

References AggCheckCallContext(), Assert(), buf, PG_GETARG_POINTER, PG_RETURN_BYTEA_P, pq_begintypsend(), pq_endtypsend(), pq_sendbytes(), and pq_sendint().

◆ string_agg_transfn()

Datum string_agg_transfn ( PG_FUNCTION_ARGS  )

Definition at line 4282 of file varlena.c.

4283{
4285
4287
4288 /* Append the value unless null, preceding it with the delimiter. */
4289 if (!PG_ARGISNULL(1))
4290 {
4292 bool isfirst = false;
4293
4294 /*
4295 * You might think we can just throw away the first delimiter, however
4296 * we must keep it as we may be a parallel worker doing partial
4297 * aggregation building a state to send to the main process. We need
4298 * to keep the delimiter of every aggregation so that the combine
4299 * function can properly join up the strings of two separately
4300 * partially aggregated results. The first delimiter is only stripped
4301 * off in the final function. To know how much to strip off the front
4302 * of the string, we store the length of the first delimiter in the
4303 * StringInfo's cursor field, which we don't otherwise need here.
4304 */
4305 if (state == NULL)
4306 {
4307 state = makeStringAggState(fcinfo);
4308 isfirst = true;
4309 }
4310
4311 if (!PG_ARGISNULL(2))
4312 {
4313 text *delim = PG_GETARG_TEXT_PP(2);
4314
4316 if (isfirst)
4317 state->cursor = VARSIZE_ANY_EXHDR(delim);
4318 }
4319
4321 }
4322
4323 /*
4324 * The transition type for string_agg() is declared to be "internal",
4325 * which is a pass-by-value type the same size as a pointer.
4326 */
4327 if (state)
4330}

References appendStringInfoText(), makeStringAggState(), PG_ARGISNULL, PG_GETARG_POINTER, PG_GETARG_TEXT_PP, PG_RETURN_NULL, PG_RETURN_POINTER, value, and VARSIZE_ANY_EXHDR().

◆ text_catenate()

static text * text_catenate ( text t1,
text t2 
)
static

Definition at line 460 of file varlena.c.

461{
462 text *result;
463 int len1,
464 len2,
465 len;
466 char *ptr;
467
468 len1 = VARSIZE_ANY_EXHDR(t1);
469 len2 = VARSIZE_ANY_EXHDR(t2);
470
471 /* paranoia ... probably should throw error instead? */
472 if (len1 < 0)
473 len1 = 0;
474 if (len2 < 0)
475 len2 = 0;
476
477 len = len1 + len2 + VARHDRSZ;
478 result = (text *) palloc(len);
479
480 /* Set size of result string... */
481 SET_VARSIZE(result, len);
482
483 /* Fill data field of result string... */
484 ptr = VARDATA(result);
485 if (len1 > 0)
486 memcpy(ptr, VARDATA_ANY(t1), len1);
487 if (len2 > 0)
488 memcpy(ptr + len1, VARDATA_ANY(t2), len2);
489
490 return result;
491}

References len, palloc(), SET_VARSIZE(), VARDATA(), VARDATA_ANY(), VARHDRSZ, and VARSIZE_ANY_EXHDR().

Referenced by text_overlay(), and textcat().

◆ text_cmp()

static int text_cmp ( text arg1,
text arg2,
Oid  collid 
)
static

Definition at line 1345 of file varlena.c.

1346{
1347 char *a1p,
1348 *a2p;
1349 int len1,
1350 len2;
1351
1352 a1p = VARDATA_ANY(arg1);
1353 a2p = VARDATA_ANY(arg2);
1354
1355 len1 = VARSIZE_ANY_EXHDR(arg1);
1356 len2 = VARSIZE_ANY_EXHDR(arg2);
1357
1358 return varstr_cmp(a1p, len1, a2p, len2, collid);
1359}

References collid, VARDATA_ANY(), VARSIZE_ANY_EXHDR(), and varstr_cmp().

Referenced by bttextcmp(), text_ge(), text_gt(), text_larger(), text_le(), text_lt(), text_smaller(), texteq(), and textne().

◆ text_concat()

Datum text_concat ( PG_FUNCTION_ARGS  )

Definition at line 4598 of file varlena.c.

4599{
4600 text *result;
4601
4602 result = concat_internal("", 0, fcinfo);
4603 if (result == NULL)
4605 PG_RETURN_TEXT_P(result);
4606}
static text * concat_internal(const char *sepstr, int argidx, FunctionCallInfo fcinfo)
Definition: varlena.c:4518

References concat_internal(), PG_RETURN_NULL, and PG_RETURN_TEXT_P.

◆ text_concat_ws()

Datum text_concat_ws ( PG_FUNCTION_ARGS  )

Definition at line 4613 of file varlena.c.

4614{
4615 char *sep;
4616 text *result;
4617
4618 /* return NULL when separator is NULL */
4619 if (PG_ARGISNULL(0))
4622
4623 result = concat_internal(sep, 1, fcinfo);
4624 if (result == NULL)
4626 PG_RETURN_TEXT_P(result);
4627}

References concat_internal(), PG_ARGISNULL, PG_GETARG_TEXT_PP, PG_RETURN_NULL, PG_RETURN_TEXT_P, and text_to_cstring().

◆ text_format()

Datum text_format ( PG_FUNCTION_ARGS  )

Definition at line 4734 of file varlena.c.

4735{
4736 text *fmt;
4738 const char *cp;
4739 const char *start_ptr;
4740 const char *end_ptr;
4741 text *result;
4742 int arg;
4743 bool funcvariadic;
4744 int nargs;
4745 Datum *elements = NULL;
4746 bool *nulls = NULL;
4747 Oid element_type = InvalidOid;
4748 Oid prev_type = InvalidOid;
4749 Oid prev_width_type = InvalidOid;
4750 FmgrInfo typoutputfinfo;
4751 FmgrInfo typoutputinfo_width;
4752
4753 /* When format string is null, immediately return null */
4754 if (PG_ARGISNULL(0))
4756
4757 /* If argument is marked VARIADIC, expand array into elements */
4758 if (get_fn_expr_variadic(fcinfo->flinfo))
4759 {
4760 ArrayType *arr;
4761 int16 elmlen;
4762 bool elmbyval;
4763 char elmalign;
4764 int nitems;
4765
4766 /* Should have just the one argument */
4767 Assert(PG_NARGS() == 2);
4768
4769 /* If argument is NULL, we treat it as zero-length array */
4770 if (PG_ARGISNULL(1))
4771 nitems = 0;
4772 else
4773 {
4774 /*
4775 * Non-null argument had better be an array. We assume that any
4776 * call context that could let get_fn_expr_variadic return true
4777 * will have checked that a VARIADIC-labeled parameter actually is
4778 * an array. So it should be okay to just Assert that it's an
4779 * array rather than doing a full-fledged error check.
4780 */
4782
4783 /* OK, safe to fetch the array value */
4784 arr = PG_GETARG_ARRAYTYPE_P(1);
4785
4786 /* Get info about array element type */
4787 element_type = ARR_ELEMTYPE(arr);
4788 get_typlenbyvalalign(element_type,
4789 &elmlen, &elmbyval, &elmalign);
4790
4791 /* Extract all array elements */
4792 deconstruct_array(arr, element_type, elmlen, elmbyval, elmalign,
4793 &elements, &nulls, &nitems);
4794 }
4795
4796 nargs = nitems + 1;
4797 funcvariadic = true;
4798 }
4799 else
4800 {
4801 /* Non-variadic case, we'll process the arguments individually */
4802 nargs = PG_NARGS();
4803 funcvariadic = false;
4804 }
4805
4806 /* Setup for main loop. */
4807 fmt = PG_GETARG_TEXT_PP(0);
4808 start_ptr = VARDATA_ANY(fmt);
4809 end_ptr = start_ptr + VARSIZE_ANY_EXHDR(fmt);
4811 arg = 1; /* next argument position to print */
4812
4813 /* Scan format string, looking for conversion specifiers. */
4814 for (cp = start_ptr; cp < end_ptr; cp++)
4815 {
4816 int argpos;
4817 int widthpos;
4818 int flags;
4819 int width;
4820 Datum value;
4821 bool isNull;
4822 Oid typid;
4823
4824 /*
4825 * If it's not the start of a conversion specifier, just copy it to
4826 * the output buffer.
4827 */
4828 if (*cp != '%')
4829 {
4831 continue;
4832 }
4833
4834 ADVANCE_PARSE_POINTER(cp, end_ptr);
4835
4836 /* Easy case: %% outputs a single % */
4837 if (*cp == '%')
4838 {
4840 continue;
4841 }
4842
4843 /* Parse the optional portions of the format specifier */
4844 cp = text_format_parse_format(cp, end_ptr,
4845 &argpos, &widthpos,
4846 &flags, &width);
4847
4848 /*
4849 * Next we should see the main conversion specifier. Whether or not
4850 * an argument position was present, it's known that at least one
4851 * character remains in the string at this point. Experience suggests
4852 * that it's worth checking that that character is one of the expected
4853 * ones before we try to fetch arguments, so as to produce the least
4854 * confusing response to a mis-formatted specifier.
4855 */
4856 if (strchr("sIL", *cp) == NULL)
4857 ereport(ERROR,
4858 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4859 errmsg("unrecognized format() type specifier \"%.*s\"",
4860 pg_mblen(cp), cp),
4861 errhint("For a single \"%%\" use \"%%%%\".")));
4862
4863 /* If indirect width was specified, get its value */
4864 if (widthpos >= 0)
4865 {
4866 /* Collect the specified or next argument position */
4867 if (widthpos > 0)
4868 arg = widthpos;
4869 if (arg >= nargs)
4870 ereport(ERROR,
4871 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4872 errmsg("too few arguments for format()")));
4873
4874 /* Get the value and type of the selected argument */
4875 if (!funcvariadic)
4876 {
4878 isNull = PG_ARGISNULL(arg);
4879 typid = get_fn_expr_argtype(fcinfo->flinfo, arg);
4880 }
4881 else
4882 {
4883 value = elements[arg - 1];
4884 isNull = nulls[arg - 1];
4885 typid = element_type;
4886 }
4887 if (!OidIsValid(typid))
4888 elog(ERROR, "could not determine data type of format() input");
4889
4890 arg++;
4891
4892 /* We can treat NULL width the same as zero */
4893 if (isNull)
4894 width = 0;
4895 else if (typid == INT4OID)
4896 width = DatumGetInt32(value);
4897 else if (typid == INT2OID)
4898 width = DatumGetInt16(value);
4899 else
4900 {
4901 /* For less-usual datatypes, convert to text then to int */
4902 char *str;
4903
4904 if (typid != prev_width_type)
4905 {
4906 Oid typoutputfunc;
4907 bool typIsVarlena;
4908
4909 getTypeOutputInfo(typid, &typoutputfunc, &typIsVarlena);
4910 fmgr_info(typoutputfunc, &typoutputinfo_width);
4911 prev_width_type = typid;
4912 }
4913
4914 str = OutputFunctionCall(&typoutputinfo_width, value);
4915
4916 /* pg_strtoint32 will complain about bad data or overflow */
4917 width = pg_strtoint32(str);
4918
4919 pfree(str);
4920 }
4921 }
4922
4923 /* Collect the specified or next argument position */
4924 if (argpos > 0)
4925 arg = argpos;
4926 if (arg >= nargs)
4927 ereport(ERROR,
4928 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4929 errmsg("too few arguments for format()")));
4930
4931 /* Get the value and type of the selected argument */
4932 if (!funcvariadic)
4933 {
4935 isNull = PG_ARGISNULL(arg);
4936 typid = get_fn_expr_argtype(fcinfo->flinfo, arg);
4937 }
4938 else
4939 {
4940 value = elements[arg - 1];
4941 isNull = nulls[arg - 1];
4942 typid = element_type;
4943 }
4944 if (!OidIsValid(typid))
4945 elog(ERROR, "could not determine data type of format() input");
4946
4947 arg++;
4948
4949 /*
4950 * Get the appropriate typOutput function, reusing previous one if
4951 * same type as previous argument. That's particularly useful in the
4952 * variadic-array case, but often saves work even for ordinary calls.
4953 */
4954 if (typid != prev_type)
4955 {
4956 Oid typoutputfunc;
4957 bool typIsVarlena;
4958
4959 getTypeOutputInfo(typid, &typoutputfunc, &typIsVarlena);
4960 fmgr_info(typoutputfunc, &typoutputfinfo);
4961 prev_type = typid;
4962 }
4963
4964 /*
4965 * And now we can format the value.
4966 */
4967 switch (*cp)
4968 {
4969 case 's':
4970 case 'I':
4971 case 'L':
4972 text_format_string_conversion(&str, *cp, &typoutputfinfo,
4973 value, isNull,
4974 flags, width);
4975 break;
4976 default:
4977 /* should not get here, because of previous check */
4978 ereport(ERROR,
4979 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4980 errmsg("unrecognized format() type specifier \"%.*s\"",
4981 pg_mblen(cp), cp),
4982 errhint("For a single \"%%\" use \"%%%%\".")));
4983 break;
4984 }
4985 }
4986
4987 /* Don't need deconstruct_array results anymore. */
4988 if (elements != NULL)
4989 pfree(elements);
4990 if (nulls != NULL)
4991 pfree(nulls);
4992
4993 /* Generate results. */
4994 result = cstring_to_text_with_len(str.data, str.len);
4995 pfree(str.data);
4996
4997 PG_RETURN_TEXT_P(result);
4998}
void deconstruct_array(ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3631
int16_t int16
Definition: c.h:534
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:127
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition: lsyscache.c:2438
int32 pg_strtoint32(const char *s)
Definition: numutils.c:383
void * arg
static int16 DatumGetInt16(Datum X)
Definition: postgres.h:172
#define InvalidOid
Definition: postgres_ext.h:37
#define appendStringInfoCharMacro(str, ch)
Definition: stringinfo.h:231
static void text_format_string_conversion(StringInfo buf, char conversion, FmgrInfo *typOutputInfo, Datum value, bool isNull, int flags, int width)
Definition: varlena.c:5137
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:5060
#define ADVANCE_PARSE_POINTER(ptr, end_ptr)
Definition: varlena.c:4721

References ADVANCE_PARSE_POINTER, appendStringInfoCharMacro, arg, ARR_ELEMTYPE, Assert(), cstring_to_text_with_len(), DatumGetInt16(), DatumGetInt32(), deconstruct_array(), elog, ereport, errcode(), errhint(), errmsg(), ERROR, fmgr_info(), get_base_element_type(), get_fn_expr_argtype(), get_fn_expr_variadic(), get_typlenbyvalalign(), getTypeOutputInfo(), initStringInfo(), InvalidOid, nitems, OidIsValid, OutputFunctionCall(), pfree(), PG_ARGISNULL, PG_GETARG_ARRAYTYPE_P, PG_GETARG_DATUM, PG_GETARG_TEXT_PP, pg_mblen(), PG_NARGS, PG_RETURN_NULL, PG_RETURN_TEXT_P, pg_strtoint32(), str, text_format_parse_format(), text_format_string_conversion(), value, VARDATA_ANY(), and VARSIZE_ANY_EXHDR().

Referenced by text_format_nv().

◆ text_format_append_string()

static void text_format_append_string ( StringInfo  buf,
const char *  str,
int  flags,
int  width 
)
static

Definition at line 5186 of file varlena.c.

5188{
5189 bool align_to_left = false;
5190 int len;
5191
5192 /* fast path for typical easy case */
5193 if (width == 0)
5194 {
5196 return;
5197 }
5198
5199 if (width < 0)
5200 {
5201 /* Negative width: implicit '-' flag, then take absolute value */
5202 align_to_left = true;
5203 /* -INT_MIN is undefined */
5204 if (width <= INT_MIN)
5205 ereport(ERROR,
5206 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
5207 errmsg("number is out of range")));
5208 width = -width;
5209 }
5210 else if (flags & TEXT_FORMAT_FLAG_MINUS)
5211 align_to_left = true;
5212
5213 len = pg_mbstrlen(str);
5214 if (align_to_left)
5215 {
5216 /* left justify */
5218 if (len < width)
5219 appendStringInfoSpaces(buf, width - len);
5220 }
5221 else
5222 {
5223 /* right justify */
5224 if (len < width)
5225 appendStringInfoSpaces(buf, width - len);
5227 }
5228}
int pg_mbstrlen(const char *mbstr)
Definition: mbutils.c:1038
void appendStringInfoSpaces(StringInfo str, int count)
Definition: stringinfo.c:260
#define TEXT_FORMAT_FLAG_MINUS
Definition: varlena.c:4719

References appendStringInfoSpaces(), appendStringInfoString(), buf, ereport, errcode(), errmsg(), ERROR, len, pg_mbstrlen(), str, and TEXT_FORMAT_FLAG_MINUS.

Referenced by text_format_string_conversion().

◆ text_format_nv()

Datum text_format_nv ( PG_FUNCTION_ARGS  )

Definition at line 5238 of file varlena.c.

5239{
5240 return text_format(fcinfo);
5241}
Datum text_format(PG_FUNCTION_ARGS)
Definition: varlena.c:4734

References text_format().

◆ text_format_parse_digits()

static bool text_format_parse_digits ( const char **  ptr,
const char *  end_ptr,
int *  value 
)
static

Definition at line 5011 of file varlena.c.

5012{
5013 bool found = false;
5014 const char *cp = *ptr;
5015 int val = 0;
5016
5017 while (*cp >= '0' && *cp <= '9')
5018 {
5019 int8 digit = (*cp - '0');
5020
5021 if (unlikely(pg_mul_s32_overflow(val, 10, &val)) ||
5023 ereport(ERROR,
5024 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
5025 errmsg("number is out of range")));
5026 ADVANCE_PARSE_POINTER(cp, end_ptr);
5027 found = true;
5028 }
5029
5030 *ptr = cp;
5031 *value = val;
5032
5033 return found;
5034}
int8_t int8
Definition: c.h:533
#define unlikely(x)
Definition: c.h:403
long val
Definition: informix.c:689
static bool pg_mul_s32_overflow(int32 a, int32 b, int32 *result)
Definition: int.h:187
static bool pg_add_s32_overflow(int32 a, int32 b, int32 *result)
Definition: int.h:151

References ADVANCE_PARSE_POINTER, ereport, errcode(), errmsg(), ERROR, pg_add_s32_overflow(), pg_mul_s32_overflow(), unlikely, val, and value.

Referenced by text_format_parse_format().

◆ text_format_parse_format()

static const char * text_format_parse_format ( const char *  start_ptr,
const char *  end_ptr,
int *  argpos,
int *  widthpos,
int *  flags,
int *  width 
)
static

Definition at line 5060 of file varlena.c.

5063{
5064 const char *cp = start_ptr;
5065 int n;
5066
5067 /* set defaults for output parameters */
5068 *argpos = -1;
5069 *widthpos = -1;
5070 *flags = 0;
5071 *width = 0;
5072
5073 /* try to identify first number */
5074 if (text_format_parse_digits(&cp, end_ptr, &n))
5075 {
5076 if (*cp != '$')
5077 {
5078 /* Must be just a width and a type, so we're done */
5079 *width = n;
5080 return cp;
5081 }
5082 /* The number was argument position */
5083 *argpos = n;
5084 /* Explicit 0 for argument index is immediately refused */
5085 if (n == 0)
5086 ereport(ERROR,
5087 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5088 errmsg("format specifies argument 0, but arguments are numbered from 1")));
5089 ADVANCE_PARSE_POINTER(cp, end_ptr);
5090 }
5091
5092 /* Handle flags (only minus is supported now) */
5093 while (*cp == '-')
5094 {
5095 *flags |= TEXT_FORMAT_FLAG_MINUS;
5096 ADVANCE_PARSE_POINTER(cp, end_ptr);
5097 }
5098
5099 if (*cp == '*')
5100 {
5101 /* Handle indirect width */
5102 ADVANCE_PARSE_POINTER(cp, end_ptr);
5103 if (text_format_parse_digits(&cp, end_ptr, &n))
5104 {
5105 /* number in this position must be closed by $ */
5106 if (*cp != '$')
5107 ereport(ERROR,
5108 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5109 errmsg("width argument position must be ended by \"$\"")));
5110 /* The number was width argument position */
5111 *widthpos = n;
5112 /* Explicit 0 for argument index is immediately refused */
5113 if (n == 0)
5114 ereport(ERROR,
5115 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5116 errmsg("format specifies argument 0, but arguments are numbered from 1")));
5117 ADVANCE_PARSE_POINTER(cp, end_ptr);
5118 }
5119 else
5120 *widthpos = 0; /* width's argument position is unspecified */
5121 }
5122 else
5123 {
5124 /* Check for direct width specification */
5125 if (text_format_parse_digits(&cp, end_ptr, &n))
5126 *width = n;
5127 }
5128
5129 /* cp should now be pointing at type character */
5130 return cp;
5131}
static bool text_format_parse_digits(const char **ptr, const char *end_ptr, int *value)
Definition: varlena.c:5011

References ADVANCE_PARSE_POINTER, ereport, errcode(), errmsg(), ERROR, TEXT_FORMAT_FLAG_MINUS, and text_format_parse_digits().

Referenced by text_format().

◆ text_format_string_conversion()

static void text_format_string_conversion ( StringInfo  buf,
char  conversion,
FmgrInfo typOutputInfo,
Datum  value,
bool  isNull,
int  flags,
int  width 
)
static

Definition at line 5137 of file varlena.c.

5141{
5142 char *str;
5143
5144 /* Handle NULL arguments before trying to stringify the value. */
5145 if (isNull)
5146 {
5147 if (conversion == 's')
5148 text_format_append_string(buf, "", flags, width);
5149 else if (conversion == 'L')
5150 text_format_append_string(buf, "NULL", flags, width);
5151 else if (conversion == 'I')
5152 ereport(ERROR,
5153 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5154 errmsg("null values cannot be formatted as an SQL identifier")));
5155 return;
5156 }
5157
5158 /* Stringify. */
5159 str = OutputFunctionCall(typOutputInfo, value);
5160
5161 /* Escape. */
5162 if (conversion == 'I')
5163 {
5164 /* quote_identifier may or may not allocate a new string. */
5166 }
5167 else if (conversion == 'L')
5168 {
5169 char *qstr = quote_literal_cstr(str);
5170
5171 text_format_append_string(buf, qstr, flags, width);
5172 /* quote_literal_cstr() always allocates a new string */
5173 pfree(qstr);
5174 }
5175 else
5176 text_format_append_string(buf, str, flags, width);
5177
5178 /* Cleanup. */
5179 pfree(str);
5180}
char * quote_literal_cstr(const char *rawstr)
Definition: quote.c:103
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:13030
static void text_format_append_string(StringInfo buf, const char *str, int flags, int width)
Definition: varlena.c:5186

References buf, ereport, errcode(), errmsg(), ERROR, OutputFunctionCall(), pfree(), quote_identifier(), quote_literal_cstr(), str, text_format_append_string(), and value.

Referenced by text_format().

◆ text_ge()

Datum text_ge ( PG_FUNCTION_ARGS  )

Definition at line 1519 of file varlena.c.

1520{
1521 text *arg1 = PG_GETARG_TEXT_PP(0);
1522 text *arg2 = PG_GETARG_TEXT_PP(1);
1523 bool result;
1524
1525 result = (text_cmp(arg1, arg2, PG_GET_COLLATION()) >= 0);
1526
1527 PG_FREE_IF_COPY(arg1, 0);
1528 PG_FREE_IF_COPY(arg2, 1);
1529
1530 PG_RETURN_BOOL(result);
1531}

References PG_FREE_IF_COPY, PG_GET_COLLATION, PG_GETARG_TEXT_PP, PG_RETURN_BOOL, and text_cmp().

Referenced by gbt_textge().

◆ text_gt()

Datum text_gt ( PG_FUNCTION_ARGS  )

Definition at line 1504 of file varlena.c.

1505{
1506 text *arg1 = PG_GETARG_TEXT_PP(0);
1507 text *arg2 = PG_GETARG_TEXT_PP(1);
1508 bool result;
1509
1510 result = (text_cmp(arg1, arg2, PG_GET_COLLATION()) > 0);
1511
1512 PG_FREE_IF_COPY(arg1, 0);
1513 PG_FREE_IF_COPY(arg2, 1);
1514
1515 PG_RETURN_BOOL(result);
1516}

References PG_FREE_IF_COPY, PG_GET_COLLATION, PG_GETARG_TEXT_PP, PG_RETURN_BOOL, and text_cmp().

Referenced by gbt_textgt().

◆ text_isequal()

static bool text_isequal ( text txt1,
text txt2,
Oid  collid 
)
static

Definition at line 3596 of file varlena.c.

3597{
3599 collid,
3600 PointerGetDatum(txt1),
3601 PointerGetDatum(txt2)));
3602}
static bool DatumGetBool(Datum X)
Definition: postgres.h:100
Datum texteq(PG_FUNCTION_ARGS)
Definition: varlena.c:1370

References collid, DatumGetBool(), DirectFunctionCall2Coll(), PointerGetDatum(), and texteq().

Referenced by split_text_accum_result().

◆ text_larger()

Datum text_larger ( PG_FUNCTION_ARGS  )

Definition at line 2298 of file varlena.c.

2299{
2300 text *arg1 = PG_GETARG_TEXT_PP(0);
2301 text *arg2 = PG_GETARG_TEXT_PP(1);
2302 text *result;
2303
2304 result = ((text_cmp(arg1, arg2, PG_GET_COLLATION()) > 0) ? arg1 : arg2);
2305
2306 PG_RETURN_TEXT_P(result);
2307}

References PG_GET_COLLATION, PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, and text_cmp().

◆ text_le()

Datum text_le ( PG_FUNCTION_ARGS  )

Definition at line 1489 of file varlena.c.

1490{
1491 text *arg1 = PG_GETARG_TEXT_PP(0);
1492 text *arg2 = PG_GETARG_TEXT_PP(1);
1493 bool result;
1494
1495 result = (text_cmp(arg1, arg2, PG_GET_COLLATION()) <= 0);
1496
1497 PG_FREE_IF_COPY(arg1, 0);
1498 PG_FREE_IF_COPY(arg2, 1);
1499
1500 PG_RETURN_BOOL(result);
1501}

References PG_FREE_IF_COPY, PG_GET_COLLATION, PG_GETARG_TEXT_PP, PG_RETURN_BOOL, and text_cmp().

Referenced by gbt_textle().

◆ text_left()

Datum text_left ( PG_FUNCTION_ARGS  )

Definition at line 4634 of file varlena.c.

4635{
4636 int n = PG_GETARG_INT32(1);
4637
4638 if (n < 0)
4639 {
4641 const char *p = VARDATA_ANY(str);
4642 int len = VARSIZE_ANY_EXHDR(str);
4643 int rlen;
4644
4645 n = pg_mbstrlen_with_len(p, len) + n;
4646 rlen = pg_mbcharcliplen(p, len, n);
4648 }
4649 else
4651}
int pg_mbstrlen_with_len(const char *mbstr, int limit)
Definition: mbutils.c:1058
int pg_mbcharcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:1126
static text * text_substring(Datum str, int32 start, int32 length, bool length_not_specified)
Definition: varlena.c:580

References cstring_to_text_with_len(), len, PG_GETARG_DATUM, PG_GETARG_INT32, PG_GETARG_TEXT_PP, pg_mbcharcliplen(), pg_mbstrlen_with_len(), PG_RETURN_TEXT_P, str, text_substring(), VARDATA_ANY(), and VARSIZE_ANY_EXHDR().

◆ text_length()

static int32 text_length ( Datum  str)
static

Definition at line 407 of file varlena.c.

408{
409 /* fastpath when max encoding length is one */
412 else
413 {
414 text *t = DatumGetTextPP(str);
415
417 }
418}
Size toast_raw_datum_size(Datum value)
Definition: detoast.c:545
#define DatumGetTextPP(X)
Definition: fmgr.h:292

References DatumGetTextPP, pg_database_encoding_max_length(), pg_mbstrlen_with_len(), str, toast_raw_datum_size(), VARDATA_ANY(), VARHDRSZ, and VARSIZE_ANY_EXHDR().

Referenced by textlen(), and textoverlay_no_len().

◆ text_lt()

Datum text_lt ( PG_FUNCTION_ARGS  )

Definition at line 1474 of file varlena.c.

1475{
1476 text *arg1 = PG_GETARG_TEXT_PP(0);
1477 text *arg2 = PG_GETARG_TEXT_PP(1);
1478 bool result;
1479
1480 result = (text_cmp(arg1, arg2, PG_GET_COLLATION()) < 0);
1481
1482 PG_FREE_IF_COPY(arg1, 0);
1483 PG_FREE_IF_COPY(arg2, 1);
1484
1485 PG_RETURN_BOOL(result);
1486}

References PG_FREE_IF_COPY, PG_GET_COLLATION, PG_GETARG_TEXT_PP, PG_RETURN_BOOL, and text_cmp().

Referenced by gbt_textlt().

◆ text_name()

Datum text_name ( PG_FUNCTION_ARGS  )

Definition at line 2646 of file varlena.c.

2647{
2648 text *s = PG_GETARG_TEXT_PP(0);
2649 Name result;
2650 int len;
2651
2653
2654 /* Truncate oversize input */
2655 if (len >= NAMEDATALEN)
2657
2658 /* We use palloc0 here to ensure result is zero-padded */
2659 result = (Name) palloc0(NAMEDATALEN);
2660 memcpy(NameStr(*result), VARDATA_ANY(s), len);
2661
2662 PG_RETURN_NAME(result);
2663}
NameData * Name
Definition: c.h:750
#define PG_RETURN_NAME(x)
Definition: fmgr.h:363
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:1084
void * palloc0(Size size)
Definition: mcxt.c:1395

References len, NAMEDATALEN, NameStr, palloc0(), PG_GETARG_TEXT_PP, pg_mbcliplen(), PG_RETURN_NAME, VARDATA_ANY(), and VARSIZE_ANY_EXHDR().

◆ text_overlay()

static text * text_overlay ( text t1,
text t2,
int  sp,
int  sl 
)
static

Definition at line 811 of file varlena.c.

812{
813 text *result;
814 text *s1;
815 text *s2;
816 int sp_pl_sl;
817
818 /*
819 * Check for possible integer-overflow cases. For negative sp, throw a
820 * "substring length" error because that's what should be expected
821 * according to the spec's definition of OVERLAY().
822 */
823 if (sp <= 0)
825 (errcode(ERRCODE_SUBSTRING_ERROR),
826 errmsg("negative substring length not allowed")));
827 if (pg_add_s32_overflow(sp, sl, &sp_pl_sl))
829 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
830 errmsg("integer out of range")));
831
832 s1 = text_substring(PointerGetDatum(t1), 1, sp - 1, false);
833 s2 = text_substring(PointerGetDatum(t1), sp_pl_sl, -1, true);
834 result = text_catenate(s1, t2);
835 result = text_catenate(result, s2);
836
837 return result;
838}
static text * text_catenate(text *t1, text *t2)
Definition: varlena.c:460

References ereport, errcode(), errmsg(), ERROR, pg_add_s32_overflow(), PointerGetDatum(), s1, s2, text_catenate(), and text_substring().

Referenced by textoverlay(), and textoverlay_no_len().

◆ text_pattern_ge()

Datum text_pattern_ge ( PG_FUNCTION_ARGS  )

Definition at line 2578 of file varlena.c.

2579{
2580 text *arg1 = PG_GETARG_TEXT_PP(0);
2581 text *arg2 = PG_GETARG_TEXT_PP(1);
2582 int result;
2583
2584 result = internal_text_pattern_compare(arg1, arg2);
2585
2586 PG_FREE_IF_COPY(arg1, 0);
2587 PG_FREE_IF_COPY(arg2, 1);
2588
2589 PG_RETURN_BOOL(result >= 0);
2590}

References internal_text_pattern_compare(), PG_FREE_IF_COPY, PG_GETARG_TEXT_PP, and PG_RETURN_BOOL.

◆ text_pattern_gt()

Datum text_pattern_gt ( PG_FUNCTION_ARGS  )

Definition at line 2594 of file varlena.c.

2595{
2596 text *arg1 = PG_GETARG_TEXT_PP(0);
2597 text *arg2 = PG_GETARG_TEXT_PP(1);
2598 int result;
2599
2600 result = internal_text_pattern_compare(arg1, arg2);
2601
2602 PG_FREE_IF_COPY(arg1, 0);
2603 PG_FREE_IF_COPY(arg2, 1);
2604
2605 PG_RETURN_BOOL(result > 0);
2606}

References internal_text_pattern_compare(), PG_FREE_IF_COPY, PG_GETARG_TEXT_PP, and PG_RETURN_BOOL.

◆ text_pattern_le()

Datum text_pattern_le ( PG_FUNCTION_ARGS  )

Definition at line 2562 of file varlena.c.

2563{
2564 text *arg1 = PG_GETARG_TEXT_PP(0);
2565 text *arg2 = PG_GETARG_TEXT_PP(1);
2566 int result;
2567
2568 result = internal_text_pattern_compare(arg1, arg2);
2569
2570 PG_FREE_IF_COPY(arg1, 0);
2571 PG_FREE_IF_COPY(arg2, 1);
2572
2573 PG_RETURN_BOOL(result <= 0);
2574}

References internal_text_pattern_compare(), PG_FREE_IF_COPY, PG_GETARG_TEXT_PP, and PG_RETURN_BOOL.

◆ text_pattern_lt()

Datum text_pattern_lt ( PG_FUNCTION_ARGS  )

Definition at line 2546 of file varlena.c.

2547{
2548 text *arg1 = PG_GETARG_TEXT_PP(0);
2549 text *arg2 = PG_GETARG_TEXT_PP(1);
2550 int result;
2551
2552 result = internal_text_pattern_compare(arg1, arg2);
2553
2554 PG_FREE_IF_COPY(arg1, 0);
2555 PG_FREE_IF_COPY(arg2, 1);
2556
2557 PG_RETURN_BOOL(result < 0);
2558}

References internal_text_pattern_compare(), PG_FREE_IF_COPY, PG_GETARG_TEXT_PP, and PG_RETURN_BOOL.

◆ text_position()

static int text_position ( text t1,
text t2,
Oid  collid 
)
static

Definition at line 871 of file varlena.c.

872{
874 int result;
875
877
878 /* Empty needle always matches at position 1 */
879 if (VARSIZE_ANY_EXHDR(t2) < 1)
880 return 1;
881
882 /* Otherwise, can't match if haystack is shorter than needle */
883 if (VARSIZE_ANY_EXHDR(t1) < VARSIZE_ANY_EXHDR(t2) &&
884 pg_newlocale_from_collation(collid)->deterministic)
885 return 0;
886
888 /* don't need greedy mode here */
889 state.greedy = false;
890
892 result = 0;
893 else
896 return result;
897}
static int text_position_get_match_pos(TextPositionState *state)
Definition: varlena.c:1237

References check_collation_set(), collid, pg_newlocale_from_collation(), text_position_cleanup(), text_position_get_match_pos(), text_position_next(), text_position_setup(), and VARSIZE_ANY_EXHDR().

Referenced by textpos().

◆ text_position_cleanup()

static void text_position_cleanup ( TextPositionState state)
static

Definition at line 1261 of file varlena.c.

1262{
1263 /* no cleanup needed */
1264}

Referenced by replace_text(), split_part(), split_text(), and text_position().

◆ text_position_get_match_pos()

static int text_position_get_match_pos ( TextPositionState state)
static

Definition at line 1237 of file varlena.c.

1238{
1239 /* Convert the byte position to char position. */
1240 state->refpos += pg_mbstrlen_with_len(state->refpoint,
1241 state->last_match - state->refpoint);
1242 state->refpoint = state->last_match;
1243 return state->refpos + 1;
1244}

References pg_mbstrlen_with_len().

Referenced by text_position().

◆ text_position_get_match_ptr()

static char * text_position_get_match_ptr ( TextPositionState state)
static

Definition at line 1226 of file varlena.c.

1227{
1228 return state->last_match;
1229}

Referenced by replace_text(), split_part(), and split_text().

◆ text_position_next()

static bool text_position_next ( TextPositionState state)
static

Definition at line 1038 of file varlena.c.

1039{
1040 int needle_len = state->len2;
1041 char *start_ptr;
1042 char *matchptr;
1043
1044 if (needle_len <= 0)
1045 return false; /* result for empty pattern */
1046
1047 /* Start from the point right after the previous match. */
1048 if (state->last_match)
1049 start_ptr = state->last_match + state->last_match_len;
1050 else
1051 start_ptr = state->str1;
1052
1053retry:
1054 matchptr = text_position_next_internal(start_ptr, state);
1055
1056 if (!matchptr)
1057 return false;
1058
1059 /*
1060 * Found a match for the byte sequence. If this is a multibyte encoding,
1061 * where one character's byte sequence can appear inside a longer
1062 * multi-byte character, we need to verify that the match was at a
1063 * character boundary, not in the middle of a multi-byte character.
1064 */
1065 if (state->is_multibyte_char_in_char && state->locale->deterministic)
1066 {
1067 /* Walk one character at a time, until we reach the match. */
1068
1069 /* the search should never move backwards. */
1070 Assert(state->refpoint <= matchptr);
1071
1072 while (state->refpoint < matchptr)
1073 {
1074 /* step to next character. */
1075 state->refpoint += pg_mblen(state->refpoint);
1076 state->refpos++;
1077
1078 /*
1079 * If we stepped over the match's start position, then it was a
1080 * false positive, where the byte sequence appeared in the middle
1081 * of a multi-byte character. Skip it, and continue the search at
1082 * the next character boundary.
1083 */
1084 if (state->refpoint > matchptr)
1085 {
1086 start_ptr = state->refpoint;
1087 goto retry;
1088 }
1089 }
1090 }
1091
1092 state->last_match = matchptr;
1093 state->last_match_len = state->last_match_len_tmp;
1094 return true;
1095}
static char * text_position_next_internal(char *start_ptr, TextPositionState *state)
Definition: varlena.c:1103

References Assert(), pg_mblen(), and text_position_next_internal().

Referenced by replace_text(), split_part(), split_text(), and text_position().

◆ text_position_next_internal()

static char * text_position_next_internal ( char *  start_ptr,
TextPositionState state 
)
static

Definition at line 1103 of file varlena.c.

1104{
1105 int haystack_len = state->len1;
1106 int needle_len = state->len2;
1107 int skiptablemask = state->skiptablemask;
1108 const char *haystack = state->str1;
1109 const char *needle = state->str2;
1110 const char *haystack_end = &haystack[haystack_len];
1111 const char *hptr;
1112
1113 Assert(start_ptr >= haystack && start_ptr <= haystack_end);
1114
1115 state->last_match_len_tmp = needle_len;
1116
1117 if (!state->locale->deterministic)
1118 {
1119 /*
1120 * With a nondeterministic collation, we have to use an unoptimized
1121 * route. We walk through the haystack and see if at each position
1122 * there is a substring of the remaining string that is equal to the
1123 * needle under the given collation.
1124 *
1125 * Note, the found substring could have a different length than the
1126 * needle, including being empty. Callers that want to skip over the
1127 * found string need to read the length of the found substring from
1128 * last_match_len rather than just using the length of their needle.
1129 *
1130 * Most callers will require "greedy" semantics, meaning that we need
1131 * to find the longest such substring, not the shortest. For callers
1132 * that don't need greedy semantics, we can finish on the first match.
1133 */
1134 const char *result_hptr = NULL;
1135
1136 hptr = start_ptr;
1137 while (hptr < haystack_end)
1138 {
1139 /*
1140 * First check the common case that there is a match in the
1141 * haystack of exactly the length of the needle.
1142 */
1143 if (!state->greedy &&
1144 haystack_end - hptr >= needle_len &&
1145 pg_strncoll(hptr, needle_len, needle, needle_len, state->locale) == 0)
1146 return (char *) hptr;
1147
1148 /*
1149 * Else check if any of the possible substrings starting at hptr
1150 * are equal to the needle.
1151 */
1152 for (const char *test_end = hptr; test_end < haystack_end; test_end += pg_mblen(test_end))
1153 {
1154 if (pg_strncoll(hptr, (test_end - hptr), needle, needle_len, state->locale) == 0)
1155 {
1156 state->last_match_len_tmp = (test_end - hptr);
1157 result_hptr = hptr;
1158 if (!state->greedy)
1159 break;
1160 }
1161 }
1162 if (result_hptr)
1163 break;
1164
1165 hptr += pg_mblen(hptr);
1166 }
1167
1168 return (char *) result_hptr;
1169 }
1170 else if (needle_len == 1)
1171 {
1172 /* No point in using B-M-H for a one-character needle */
1173 char nchar = *needle;
1174
1175 hptr = start_ptr;
1176 while (hptr < haystack_end)
1177 {
1178 if (*hptr == nchar)
1179 return (char *) hptr;
1180 hptr++;
1181 }
1182 }
1183 else
1184 {
1185 const char *needle_last = &needle[needle_len - 1];
1186
1187 /* Start at startpos plus the length of the needle */
1188 hptr = start_ptr + needle_len - 1;
1189 while (hptr < haystack_end)
1190 {
1191 /* Match the needle scanning *backward* */
1192 const char *nptr;
1193 const char *p;
1194
1195 nptr = needle_last;
1196 p = hptr;
1197 while (*nptr == *p)
1198 {
1199 /* Matched it all? If so, return 1-based position */
1200 if (nptr == needle)
1201 return (char *) p;
1202 nptr--, p--;
1203 }
1204
1205 /*
1206 * No match, so use the haystack char at hptr to decide how far to
1207 * advance. If the needle had any occurrence of that character
1208 * (or more precisely, one sharing the same skiptable entry)
1209 * before its last character, then we advance far enough to align
1210 * the last such needle character with that haystack position.
1211 * Otherwise we can advance by the whole needle length.
1212 */
1213 hptr += state->skiptable[(unsigned char) *hptr & skiptablemask];
1214 }
1215 }
1216
1217 return 0; /* not found */
1218}
int pg_strncoll(const char *arg1, ssize_t len1, const char *arg2, ssize_t len2, pg_locale_t locale)
Definition: pg_locale.c:1290

References Assert(), pg_mblen(), and pg_strncoll().

Referenced by text_position_next().

◆ text_position_reset()

static void text_position_reset ( TextPositionState state)
static

Definition at line 1253 of file varlena.c.

1254{
1255 state->last_match = NULL;
1256 state->refpoint = state->str1;
1257 state->refpos = 0;
1258}

Referenced by split_part().

◆ text_position_setup()

static void text_position_setup ( text t1,
text t2,
Oid  collid,
TextPositionState state 
)
static

Definition at line 917 of file varlena.c.

918{
919 int len1 = VARSIZE_ANY_EXHDR(t1);
920 int len2 = VARSIZE_ANY_EXHDR(t2);
921
923
925
926 /*
927 * Most callers need greedy mode, but some might want to unset this to
928 * optimize.
929 */
930 state->greedy = true;
931
932 Assert(len2 > 0);
933
934 /*
935 * Even with a multi-byte encoding, we perform the search using the raw
936 * byte sequence, ignoring multibyte issues. For UTF-8, that works fine,
937 * because in UTF-8 the byte sequence of one character cannot contain
938 * another character. For other multi-byte encodings, we do the search
939 * initially as a simple byte search, ignoring multibyte issues, but
940 * verify afterwards that the match we found is at a character boundary,
941 * and continue the search if it was a false match.
942 */
944 state->is_multibyte_char_in_char = false;
945 else if (GetDatabaseEncoding() == PG_UTF8)
946 state->is_multibyte_char_in_char = false;
947 else
948 state->is_multibyte_char_in_char = true;
949
950 state->str1 = VARDATA_ANY(t1);
951 state->str2 = VARDATA_ANY(t2);
952 state->len1 = len1;
953 state->len2 = len2;
954 state->last_match = NULL;
955 state->refpoint = state->str1;
956 state->refpos = 0;
957
958 /*
959 * Prepare the skip table for Boyer-Moore-Horspool searching. In these
960 * notes we use the terminology that the "haystack" is the string to be
961 * searched (t1) and the "needle" is the pattern being sought (t2).
962 *
963 * If the needle is empty or bigger than the haystack then there is no
964 * point in wasting cycles initializing the table. We also choose not to
965 * use B-M-H for needles of length 1, since the skip table can't possibly
966 * save anything in that case.
967 *
968 * (With nondeterministic collations, the search is already
969 * multibyte-aware, so we don't need this.)
970 */
971 if (len1 >= len2 && len2 > 1 && state->locale->deterministic)
972 {
973 int searchlength = len1 - len2;
974 int skiptablemask;
975 int last;
976 int i;
977 const char *str2 = state->str2;
978
979 /*
980 * First we must determine how much of the skip table to use. The
981 * declaration of TextPositionState allows up to 256 elements, but for
982 * short search problems we don't really want to have to initialize so
983 * many elements --- it would take too long in comparison to the
984 * actual search time. So we choose a useful skip table size based on
985 * the haystack length minus the needle length. The closer the needle
986 * length is to the haystack length the less useful skipping becomes.
987 *
988 * Note: since we use bit-masking to select table elements, the skip
989 * table size MUST be a power of 2, and so the mask must be 2^N-1.
990 */
991 if (searchlength < 16)
992 skiptablemask = 3;
993 else if (searchlength < 64)
994 skiptablemask = 7;
995 else if (searchlength < 128)
996 skiptablemask = 15;
997 else if (searchlength < 512)
998 skiptablemask = 31;
999 else if (searchlength < 2048)
1000 skiptablemask = 63;
1001 else if (searchlength < 4096)
1002 skiptablemask = 127;
1003 else
1004 skiptablemask = 255;
1005 state->skiptablemask = skiptablemask;
1006
1007 /*
1008 * Initialize the skip table. We set all elements to the needle
1009 * length, since this is the correct skip distance for any character
1010 * not found in the needle.
1011 */
1012 for (i = 0; i <= skiptablemask; i++)
1013 state->skiptable[i] = len2;
1014
1015 /*
1016 * Now examine the needle. For each character except the last one,
1017 * set the corresponding table element to the appropriate skip
1018 * distance. Note that when two characters share the same skip table
1019 * entry, the one later in the needle must determine the skip
1020 * distance.
1021 */
1022 last = len2 - 1;
1023
1024 for (i = 0; i < last; i++)
1025 state->skiptable[(unsigned char) str2[i] & skiptablemask] = last - i;
1026 }
1027}
for(;;)
int GetDatabaseEncoding(void)
Definition: mbutils.c:1262
@ PG_UTF8
Definition: pg_wchar.h:232

References Assert(), check_collation_set(), collid, for(), GetDatabaseEncoding(), i, pg_database_encoding_max_length(), pg_newlocale_from_collation(), PG_UTF8, VARDATA_ANY(), and VARSIZE_ANY_EXHDR().

Referenced by replace_text(), split_part(), split_text(), and text_position().

◆ text_reverse()

Datum text_reverse ( PG_FUNCTION_ARGS  )

Definition at line 4679 of file varlena.c.

4680{
4682 const char *p = VARDATA_ANY(str);
4683 int len = VARSIZE_ANY_EXHDR(str);
4684 const char *endp = p + len;
4685 text *result;
4686 char *dst;
4687
4688 result = palloc(len + VARHDRSZ);
4689 dst = (char *) VARDATA(result) + len;
4690 SET_VARSIZE(result, len + VARHDRSZ);
4691
4693 {
4694 /* multibyte version */
4695 while (p < endp)
4696 {
4697 int sz;
4698
4699 sz = pg_mblen(p);
4700 dst -= sz;
4701 memcpy(dst, p, sz);
4702 p += sz;
4703 }
4704 }
4705 else
4706 {
4707 /* single byte version */
4708 while (p < endp)
4709 *(--dst) = *p++;
4710 }
4711
4712 PG_RETURN_TEXT_P(result);
4713}

References len, palloc(), pg_database_encoding_max_length(), PG_GETARG_TEXT_PP, pg_mblen(), PG_RETURN_TEXT_P, SET_VARSIZE(), str, VARDATA(), VARDATA_ANY(), VARHDRSZ, and VARSIZE_ANY_EXHDR().

◆ text_right()

Datum text_right ( PG_FUNCTION_ARGS  )

Definition at line 4658 of file varlena.c.

4659{
4661 const char *p = VARDATA_ANY(str);
4662 int len = VARSIZE_ANY_EXHDR(str);
4663 int n = PG_GETARG_INT32(1);
4664 int off;
4665
4666 if (n < 0)
4667 n = -n;
4668 else
4669 n = pg_mbstrlen_with_len(p, len) - n;
4670 off = pg_mbcharcliplen(p, len, n);
4671
4673}

References cstring_to_text_with_len(), len, PG_GETARG_INT32, PG_GETARG_TEXT_PP, pg_mbcharcliplen(), pg_mbstrlen_with_len(), PG_RETURN_TEXT_P, str, VARDATA_ANY(), and VARSIZE_ANY_EXHDR().

◆ text_smaller()

Datum text_smaller ( PG_FUNCTION_ARGS  )

Definition at line 2310 of file varlena.c.

2311{
2312 text *arg1 = PG_GETARG_TEXT_PP(0);
2313 text *arg2 = PG_GETARG_TEXT_PP(1);
2314 text *result;
2315
2316 result = ((text_cmp(arg1, arg2, PG_GET_COLLATION()) < 0) ? arg1 : arg2);
2317
2318 PG_RETURN_TEXT_P(result);
2319}

References PG_GET_COLLATION, PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, and text_cmp().

◆ text_starts_with()

Datum text_starts_with ( PG_FUNCTION_ARGS  )

Definition at line 1534 of file varlena.c.

1535{
1536 Datum arg1 = PG_GETARG_DATUM(0);
1537 Datum arg2 = PG_GETARG_DATUM(1);
1539 pg_locale_t mylocale;
1540 bool result;
1541 Size len1,
1542 len2;
1543
1545
1547
1548 if (!mylocale->deterministic)
1549 ereport(ERROR,
1550 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1551 errmsg("nondeterministic collations are not supported for substring searches")));
1552
1553 len1 = toast_raw_datum_size(arg1);
1554 len2 = toast_raw_datum_size(arg2);
1555 if (len2 > len1)
1556 result = false;
1557 else
1558 {
1559 text *targ1 = text_substring(arg1, 1, len2, false);
1560 text *targ2 = DatumGetTextPP(arg2);
1561
1562 result = (memcmp(VARDATA_ANY(targ1), VARDATA_ANY(targ2),
1563 VARSIZE_ANY_EXHDR(targ2)) == 0);
1564
1565 PG_FREE_IF_COPY(targ1, 0);
1566 PG_FREE_IF_COPY(targ2, 1);
1567 }
1568
1569 PG_RETURN_BOOL(result);
1570}
size_t Size
Definition: c.h:611

References check_collation_set(), collid, DatumGetTextPP, pg_locale_struct::deterministic, ereport, errcode(), errmsg(), ERROR, PG_FREE_IF_COPY, PG_GET_COLLATION, PG_GETARG_DATUM, pg_newlocale_from_collation(), PG_RETURN_BOOL, text_substring(), toast_raw_datum_size(), VARDATA_ANY(), and VARSIZE_ANY_EXHDR().

Referenced by spg_text_leaf_consistent(), and t_starts_with().

◆ text_substr()

◆ text_substr_no_len()

Datum text_substr_no_len ( PG_FUNCTION_ARGS  )

Definition at line 561 of file varlena.c.

562{
565 -1, true));
566}

References PG_GETARG_DATUM, PG_GETARG_INT32, PG_RETURN_TEXT_P, and text_substring().

◆ text_substring()

static text * text_substring ( Datum  str,
int32  start,
int32  length,
bool  length_not_specified 
)
static

Definition at line 580 of file varlena.c.

581{
583 int32 S = start; /* start position */
584 int32 S1; /* adjusted start position */
585 int32 L1; /* adjusted substring length */
586 int32 E; /* end position */
587
588 /*
589 * SQL99 says S can be zero or negative (which we don't document), but we
590 * still must fetch from the start of the string.
591 * https://www.postgresql.org/message-id/170905442373.643.11536838320909376197%40wrigleys.postgresql.org
592 */
593 S1 = Max(S, 1);
594
595 /* life is easy if the encoding max length is 1 */
596 if (eml == 1)
597 {
598 if (length_not_specified) /* special case - get length to end of
599 * string */
600 L1 = -1;
601 else if (length < 0)
602 {
603 /* SQL99 says to throw an error for E < S, i.e., negative length */
605 (errcode(ERRCODE_SUBSTRING_ERROR),
606 errmsg("negative substring length not allowed")));
607 L1 = -1; /* silence stupider compilers */
608 }
609 else if (pg_add_s32_overflow(S, length, &E))
610 {
611 /*
612 * L could be large enough for S + L to overflow, in which case
613 * the substring must run to end of string.
614 */
615 L1 = -1;
616 }
617 else
618 {
619 /*
620 * A zero or negative value for the end position can happen if the
621 * start was negative or one. SQL99 says to return a zero-length
622 * string.
623 */
624 if (E < 1)
625 return cstring_to_text("");
626
627 L1 = E - S1;
628 }
629
630 /*
631 * If the start position is past the end of the string, SQL99 says to
632 * return a zero-length string -- DatumGetTextPSlice() will do that
633 * for us. We need only convert S1 to zero-based starting position.
634 */
635 return DatumGetTextPSlice(str, S1 - 1, L1);
636 }
637 else if (eml > 1)
638 {
639 /*
640 * When encoding max length is > 1, we can't get LC without
641 * detoasting, so we'll grab a conservatively large slice now and go
642 * back later to do the right thing
643 */
644 int32 slice_start;
645 int32 slice_size;
646 int32 slice_strlen;
647 text *slice;
648 int32 E1;
649 int32 i;
650 char *p;
651 char *s;
652 text *ret;
653
654 /*
655 * We need to start at position zero because there is no way to know
656 * in advance which byte offset corresponds to the supplied start
657 * position.
658 */
659 slice_start = 0;
660
661 if (length_not_specified) /* special case - get length to end of
662 * string */
663 slice_size = L1 = -1;
664 else if (length < 0)
665 {
666 /* SQL99 says to throw an error for E < S, i.e., negative length */
668 (errcode(ERRCODE_SUBSTRING_ERROR),
669 errmsg("negative substring length not allowed")));
670 slice_size = L1 = -1; /* silence stupider compilers */
671 }
672 else if (pg_add_s32_overflow(S, length, &E))
673 {
674 /*
675 * L could be large enough for S + L to overflow, in which case
676 * the substring must run to end of string.
677 */
678 slice_size = L1 = -1;
679 }
680 else
681 {
682 /*
683 * A zero or negative value for the end position can happen if the
684 * start was negative or one. SQL99 says to return a zero-length
685 * string.
686 */
687 if (E < 1)
688 return cstring_to_text("");
689
690 /*
691 * if E is past the end of the string, the tuple toaster will
692 * truncate the length for us
693 */
694 L1 = E - S1;
695
696 /*
697 * Total slice size in bytes can't be any longer than the start
698 * position plus substring length times the encoding max length.
699 * If that overflows, we can just use -1.
700 */
701 if (pg_mul_s32_overflow(E, eml, &slice_size))
702 slice_size = -1;
703 }
704
705 /*
706 * If we're working with an untoasted source, no need to do an extra
707 * copying step.
708 */
711 slice = DatumGetTextPSlice(str, slice_start, slice_size);
712 else
713 slice = (text *) DatumGetPointer(str);
714
715 /* see if we got back an empty string */
716 if (VARSIZE_ANY_EXHDR(slice) == 0)
717 {
718 if (slice != (text *) DatumGetPointer(str))
719 pfree(slice);
720 return cstring_to_text("");
721 }
722
723 /* Now we can get the actual length of the slice in MB characters */
724 slice_strlen = pg_mbstrlen_with_len(VARDATA_ANY(slice),
725 VARSIZE_ANY_EXHDR(slice));
726
727 /*
728 * Check that the start position wasn't > slice_strlen. If so, SQL99
729 * says to return a zero-length string.
730 */
731 if (S1 > slice_strlen)
732 {
733 if (slice != (text *) DatumGetPointer(str))
734 pfree(slice);
735 return cstring_to_text("");
736 }
737
738 /*
739 * Adjust L1 and E1 now that we know the slice string length. Again
740 * remember that S1 is one based, and slice_start is zero based.
741 */
742 if (L1 > -1)
743 E1 = Min(S1 + L1, slice_start + 1 + slice_strlen);
744 else
745 E1 = slice_start + 1 + slice_strlen;
746
747 /*
748 * Find the start position in the slice; remember S1 is not zero based
749 */
750 p = VARDATA_ANY(slice);
751 for (i = 0; i < S1 - 1; i++)
752 p += pg_mblen(p);
753
754 /* hang onto a pointer to our start position */
755 s = p;
756
757 /*
758 * Count the actual bytes used by the substring of the requested
759 * length.
760 */
761 for (i = S1; i < E1; i++)
762 p += pg_mblen(p);
763
764 ret = (text *) palloc(VARHDRSZ + (p - s));
765 SET_VARSIZE(ret, VARHDRSZ + (p - s));
766 memcpy(VARDATA(ret), s, (p - s));
767
768 if (slice != (text *) DatumGetPointer(str))
769 pfree(slice);
770
771 return ret;
772 }
773 else
774 elog(ERROR, "invalid backend encoding: encoding max length < 1");
775
776 /* not reached: suppress compiler warning */
777 return NULL;
778}
#define Max(x, y)
Definition: c.h:998
#define DatumGetTextPSlice(X, m, n)
Definition: fmgr.h:304
return str start
#define S(n, x)
Definition: sha1.c:73
static bool VARATT_IS_EXTERNAL(const void *PTR)
Definition: varatt.h:354
static bool VARATT_IS_COMPRESSED(const void *PTR)
Definition: varatt.h:347

References cstring_to_text(), DatumGetPointer(), DatumGetTextPSlice, elog, ereport, errcode(), errmsg(), ERROR, i, Max, Min, palloc(), pfree(), pg_add_s32_overflow(), pg_database_encoding_max_length(), pg_mblen(), pg_mbstrlen_with_len(), pg_mul_s32_overflow(), S, SET_VARSIZE(), start, str, VARATT_IS_COMPRESSED(), VARATT_IS_EXTERNAL(), VARDATA(), VARDATA_ANY(), VARHDRSZ, and VARSIZE_ANY_EXHDR().

Referenced by text_left(), text_overlay(), text_starts_with(), text_substr(), and text_substr_no_len().

◆ text_to_array()

Datum text_to_array ( PG_FUNCTION_ARGS  )

Definition at line 3610 of file varlena.c.

3611{
3612 SplitTextOutputData tstate;
3613
3614 /* For array output, tstate should start as all zeroes */
3615 memset(&tstate, 0, sizeof(tstate));
3616
3617 if (!split_text(fcinfo, &tstate))
3619
3620 if (tstate.astate == NULL)
3622
3625}
#define PG_RETURN_ARRAYTYPE_P(x)
Definition: array.h:265
ArrayType * construct_empty_array(Oid elmtype)
Definition: arrayfuncs.c:3580
Datum makeArrayResult(ArrayBuildState *astate, MemoryContext rcontext)
Definition: arrayfuncs.c:5420
#define PG_RETURN_DATUM(x)
Definition: fmgr.h:353
static bool split_text(FunctionCallInfo fcinfo, SplitTextOutputData *tstate)
Definition: varlena.c:3687

References SplitTextOutputData::astate, construct_empty_array(), CurrentMemoryContext, makeArrayResult(), PG_RETURN_ARRAYTYPE_P, PG_RETURN_DATUM, PG_RETURN_NULL, and split_text().

Referenced by text_to_array_null().

◆ text_to_array_null()

Datum text_to_array_null ( PG_FUNCTION_ARGS  )

Definition at line 3636 of file varlena.c.

3637{
3638 return text_to_array(fcinfo);
3639}
Datum text_to_array(PG_FUNCTION_ARGS)
Definition: varlena.c:3610

References text_to_array().

◆ text_to_cstring()

char * text_to_cstring ( const text t)

Definition at line 214 of file varlena.c.

215{
216 /* must cast away the const, unfortunately */
217 text *tunpacked = pg_detoast_datum_packed(unconstify(text *, t));
218 int len = VARSIZE_ANY_EXHDR(tunpacked);
219 char *result;
220
221 result = (char *) palloc(len + 1);
222 memcpy(result, VARDATA_ANY(tunpacked), len);
223 result[len] = '\0';
224
225 if (tunpacked != t)
226 pfree(tunpacked);
227
228 return result;
229}
#define unconstify(underlying_type, expr)
Definition: c.h:1245
struct varlena * pg_detoast_datum_packed(struct varlena *datum)
Definition: fmgr.c:1828

References len, palloc(), pfree(), pg_detoast_datum_packed(), unconstify, VARDATA_ANY(), and VARSIZE_ANY_EXHDR().

Referenced by array_to_text(), array_to_text_null(), binary_upgrade_add_sub_rel_state(), binary_upgrade_create_empty_extension(), binary_upgrade_replorigin_advance(), binary_upgrade_set_missing_value(), connectby_text(), connectby_text_serial(), convert_and_check_filename(), convert_any_priv_string(), convert_column_name(), convert_database_name(), convert_foreign_data_wrapper_name(), convert_function_name(), convert_language_name(), convert_schema_name(), convert_server_name(), convert_tablespace_name(), convert_type_name(), crosstab(), crosstab_hash(), cursor_to_xml(), cursor_to_xmlschema(), daitch_mokotoff(), database_to_xml(), database_to_xml_and_xmlschema(), database_to_xmlschema(), datetime_to_char_body(), dblink_cancel_query(), dblink_close(), dblink_connect(), dblink_disconnect(), dblink_error_message(), dblink_exec(), dblink_fetch(), dblink_get_notify(), dblink_is_busy(), dblink_open(), dblink_record_internal(), dblink_send_query(), deserialize_deflist(), difference(), dmetaphone(), dmetaphone_alt(), do_to_timestamp(), errno_from_string(), ExecAlterExtensionStmt(), execute_extension_script(), executeDateTimeMethod(), get_raw_page_fork(), get_raw_page_fork_1_9(), has_param_priv_byname(), has_sequence_privilege_id_name(), has_sequence_privilege_name(), has_sequence_privilege_name_name(), injection_points_attach(), injection_points_cached(), injection_points_detach(), injection_points_load(), injection_points_run(), injection_points_stats_numcalls(), injection_points_wakeup(), json_object_field(), json_object_field_text(), jsonb_set_lax(), JsonItemFromDatum(), ltree_addtext(), ltree_textadd(), NUM_cache(), parse_datetime(), parse_ident(), pg_backup_start(), pg_create_restore_point(), pg_crypt(), pg_current_logfile(), pg_get_expr_worker(), pg_get_logical_snapshot_info(), pg_get_logical_snapshot_meta(), pg_get_serial_sequence(), pg_index_column_has_property(), pg_index_has_property(), pg_indexam_has_property(), pg_input_is_valid_common(), pg_logical_emit_message_bytea(), pg_ls_replslotdir(), pg_notify(), pg_prewarm(), pg_relation_size(), pg_replication_origin_advance(), pg_replication_origin_create(), pg_replication_origin_drop(), pg_replication_origin_oid(), pg_replication_origin_progress(), pg_replication_origin_session_setup(), pg_size_bytes(), pg_split_walfile_name(), pg_stat_get_progress_info(), pg_stat_get_replication_slot(), pg_stat_have_stats(), pg_stat_reset_replication_slot(), pg_stat_reset_shared(), pg_stat_reset_slru(), pgxml_texttoxmlchar(), phraseto_tsquery_byid(), plainto_tsquery_byid(), postgres_fdw_disconnect(), query_to_xml(), query_to_xml_and_xmlschema(), query_to_xmlschema(), quote_ident(), quote_ident_cstr(), range_constructor3(), regress_setenv(), replorigin_by_oid(), schema_to_xml(), schema_to_xml_and_xmlschema(), schema_to_xmlschema(), sepgsql_mcstrans_in(), sepgsql_mcstrans_out(), soundex(), table_to_xml(), table_to_xml_and_xmlschema(), table_to_xmlschema(), test_canonicalize_path(), test_predtest(), test_slru_page_write(), text2ltree(), text_concat_ws(), textToQualifiedNameList(), to_date(), to_regclass(), to_regcollation(), to_regdatabase(), to_regnamespace(), to_regoper(), to_regoperator(), to_regproc(), to_regprocedure(), to_regrole(), to_regtype(), to_regtypemod(), to_tsquery_byid(), ts_stat_sql(), tsquery_rewrite_query(), tuple_data_split(), unicode_is_normalized(), unicode_normalize_func(), verify_heapam(), websearch_to_tsquery_byid(), X509_NAME_field_to_text(), xml_out_internal(), xmlconcat(), xmlpi(), xmlroot(), and xpath_table().

◆ text_to_cstring_buffer()

void text_to_cstring_buffer ( const text src,
char *  dst,
size_t  dst_len 
)

Definition at line 245 of file varlena.c.

246{
247 /* must cast away the const, unfortunately */
248 text *srcunpacked = pg_detoast_datum_packed(unconstify(text *, src));
249 size_t src_len = VARSIZE_ANY_EXHDR(srcunpacked);
250
251 if (dst_len > 0)
252 {
253 dst_len--;
254 if (dst_len >= src_len)
255 dst_len = src_len;
256 else /* ensure truncation is encoding-safe */
257 dst_len = pg_mbcliplen(VARDATA_ANY(srcunpacked), src_len, dst_len);
258 memcpy(dst, VARDATA_ANY(srcunpacked), dst_len);
259 dst[dst_len] = '\0';
260 }
261
262 if (srcunpacked != src)
263 pfree(srcunpacked);
264}

References pfree(), pg_detoast_datum_packed(), pg_mbcliplen(), unconstify, VARDATA_ANY(), and VARSIZE_ANY_EXHDR().

Referenced by be_lo_export(), lo_import_internal(), lookup_timezone(), parse_sane_timezone(), pg_gen_salt(), pg_gen_salt_rounds(), timestamp_zone(), timestamptz_zone(), and timetz_zone().

◆ text_to_table()

Datum text_to_table ( PG_FUNCTION_ARGS  )

Definition at line 3647 of file varlena.c.

3648{
3649 ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
3650 SplitTextOutputData tstate;
3651
3652 tstate.astate = NULL;
3654 tstate.tupstore = rsi->setResult;
3655 tstate.tupdesc = rsi->setDesc;
3656
3657 (void) split_text(fcinfo, &tstate);
3658
3659 return (Datum) 0;
3660}
void InitMaterializedSRF(FunctionCallInfo fcinfo, bits32 flags)
Definition: funcapi.c:76
#define MAT_SRF_USE_EXPECTED_DESC
Definition: funcapi.h:296
TupleDesc setDesc
Definition: execnodes.h:364
Tuplestorestate * setResult
Definition: execnodes.h:363

References SplitTextOutputData::astate, InitMaterializedSRF(), MAT_SRF_USE_EXPECTED_DESC, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, and split_text().

Referenced by text_to_table_null().

◆ text_to_table_null()

Datum text_to_table_null ( PG_FUNCTION_ARGS  )

Definition at line 3671 of file varlena.c.

3672{
3673 return text_to_table(fcinfo);
3674}
Datum text_to_table(PG_FUNCTION_ARGS)
Definition: varlena.c:3647

References text_to_table().

◆ textcat()

Datum textcat ( PG_FUNCTION_ARGS  )

Definition at line 445 of file varlena.c.

446{
447 text *t1 = PG_GETARG_TEXT_PP(0);
448 text *t2 = PG_GETARG_TEXT_PP(1);
449
451}

References PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, and text_catenate().

◆ texteq()

Datum texteq ( PG_FUNCTION_ARGS  )

Definition at line 1370 of file varlena.c.

1371{
1373 pg_locale_t mylocale = 0;
1374 bool result;
1375
1377
1379
1380 if (mylocale->deterministic)
1381 {
1382 Datum arg1 = PG_GETARG_DATUM(0);
1383 Datum arg2 = PG_GETARG_DATUM(1);
1384 Size len1,
1385 len2;
1386
1387 /*
1388 * Since we only care about equality or not-equality, we can avoid all
1389 * the expense of strcoll() here, and just do bitwise comparison. In
1390 * fact, we don't even have to do a bitwise comparison if we can show
1391 * the lengths of the strings are unequal; which might save us from
1392 * having to detoast one or both values.
1393 */
1394 len1 = toast_raw_datum_size(arg1);
1395 len2 = toast_raw_datum_size(arg2);
1396 if (len1 != len2)
1397 result = false;
1398 else
1399 {
1400 text *targ1 = DatumGetTextPP(arg1);
1401 text *targ2 = DatumGetTextPP(arg2);
1402
1403 result = (memcmp(VARDATA_ANY(targ1), VARDATA_ANY(targ2),
1404 len1 - VARHDRSZ) == 0);
1405
1406 PG_FREE_IF_COPY(targ1, 0);
1407 PG_FREE_IF_COPY(targ2, 1);
1408 }
1409 }
1410 else
1411 {
1412 text *arg1 = PG_GETARG_TEXT_PP(0);
1413 text *arg2 = PG_GETARG_TEXT_PP(1);
1414
1415 result = (text_cmp(arg1, arg2, collid) == 0);
1416
1417 PG_FREE_IF_COPY(arg1, 0);
1418 PG_FREE_IF_COPY(arg2, 1);
1419 }
1420
1421 PG_RETURN_BOOL(result);
1422}

References check_collation_set(), collid, DatumGetTextPP, pg_locale_struct::deterministic, PG_FREE_IF_COPY, PG_GET_COLLATION, PG_GETARG_DATUM, PG_GETARG_TEXT_PP, pg_newlocale_from_collation(), PG_RETURN_BOOL, text_cmp(), toast_raw_datum_size(), VARDATA_ANY(), and VARHDRSZ.

Referenced by gbt_texteq(), text_isequal(), and texteqfast().

◆ texteqname()

Datum texteqname ( PG_FUNCTION_ARGS  )

Definition at line 2352 of file varlena.c.

2353{
2354 text *arg1 = PG_GETARG_TEXT_PP(0);
2355 Name arg2 = PG_GETARG_NAME(1);
2356 size_t len1 = VARSIZE_ANY_EXHDR(arg1);
2357 size_t len2 = strlen(NameStr(*arg2));
2359 bool result;
2360
2362
2363 if (collid == C_COLLATION_OID)
2364 result = (len1 == len2 &&
2365 memcmp(VARDATA_ANY(arg1), NameStr(*arg2), len1) == 0);
2366 else
2367 result = (varstr_cmp(VARDATA_ANY(arg1), len1,
2368 NameStr(*arg2), len2,
2369 collid) == 0);
2370
2371 PG_FREE_IF_COPY(arg1, 0);
2372
2373 PG_RETURN_BOOL(result);
2374}

References check_collation_set(), collid, NameStr, PG_FREE_IF_COPY, PG_GET_COLLATION, PG_GETARG_NAME, PG_GETARG_TEXT_PP, PG_RETURN_BOOL, VARDATA_ANY(), VARSIZE_ANY_EXHDR(), and varstr_cmp().

◆ textgename()

Datum textgename ( PG_FUNCTION_ARGS  )

Definition at line 2507 of file varlena.c.

2508{
2510}
Datum bttextnamecmp(PG_FUNCTION_ARGS)
Definition: varlena.c:2443

References bttextnamecmp(), CmpCall, and PG_RETURN_BOOL.

◆ textgtname()

Datum textgtname ( PG_FUNCTION_ARGS  )

Definition at line 2501 of file varlena.c.

2502{
2504}

References bttextnamecmp(), CmpCall, and PG_RETURN_BOOL.

◆ textin()

Datum textin ( PG_FUNCTION_ARGS  )

Definition at line 275 of file varlena.c.

276{
277 char *inputText = PG_GETARG_CSTRING(0);
278
280}
#define PG_GETARG_CSTRING(n)
Definition: fmgr.h:277

References cstring_to_text(), PG_GETARG_CSTRING, and PG_RETURN_TEXT_P.

Referenced by ExecEvalJsonExprPath().

◆ textlen()

Datum textlen ( PG_FUNCTION_ARGS  )

Definition at line 389 of file varlena.c.

390{
392
393 /* try to avoid decompressing argument */
395}
static int32 text_length(Datum str)
Definition: varlena.c:407

References PG_GETARG_DATUM, PG_RETURN_INT32, str, and text_length().

◆ textlename()

Datum textlename ( PG_FUNCTION_ARGS  )

Definition at line 2495 of file varlena.c.

2496{
2498}

References bttextnamecmp(), CmpCall, and PG_RETURN_BOOL.

◆ textltname()

Datum textltname ( PG_FUNCTION_ARGS  )

Definition at line 2489 of file varlena.c.

2490{
2492}

References bttextnamecmp(), CmpCall, and PG_RETURN_BOOL.

◆ textne()

Datum textne ( PG_FUNCTION_ARGS  )

Definition at line 1425 of file varlena.c.

1426{
1428 pg_locale_t mylocale;
1429 bool result;
1430
1432
1434
1435 if (mylocale->deterministic)
1436 {
1437 Datum arg1 = PG_GETARG_DATUM(0);
1438 Datum arg2 = PG_GETARG_DATUM(1);
1439 Size len1,
1440 len2;
1441
1442 /* See comment in texteq() */
1443 len1 = toast_raw_datum_size(arg1);
1444 len2 = toast_raw_datum_size(arg2);
1445 if (len1 != len2)
1446 result = true;
1447 else
1448 {
1449 text *targ1 = DatumGetTextPP(arg1);
1450 text *targ2 = DatumGetTextPP(arg2);
1451
1452 result = (memcmp(VARDATA_ANY(targ1), VARDATA_ANY(targ2),
1453 len1 - VARHDRSZ) != 0);
1454
1455 PG_FREE_IF_COPY(targ1, 0);
1456 PG_FREE_IF_COPY(targ2, 1);
1457 }
1458 }
1459 else
1460 {
1461 text *arg1 = PG_GETARG_TEXT_PP(0);
1462 text *arg2 = PG_GETARG_TEXT_PP(1);
1463
1464 result = (text_cmp(arg1, arg2, collid) != 0);
1465
1466 PG_FREE_IF_COPY(arg1, 0);
1467 PG_FREE_IF_COPY(arg2, 1);
1468 }
1469
1470 PG_RETURN_BOOL(result);
1471}

References check_collation_set(), collid, DatumGetTextPP, pg_locale_struct::deterministic, PG_FREE_IF_COPY, PG_GET_COLLATION, PG_GETARG_DATUM, PG_GETARG_TEXT_PP, pg_newlocale_from_collation(), PG_RETURN_BOOL, text_cmp(), toast_raw_datum_size(), VARDATA_ANY(), and VARHDRSZ.

◆ textnename()

Datum textnename ( PG_FUNCTION_ARGS  )

Definition at line 2402 of file varlena.c.

2403{
2404 text *arg1 = PG_GETARG_TEXT_PP(0);
2405 Name arg2 = PG_GETARG_NAME(1);
2406 size_t len1 = VARSIZE_ANY_EXHDR(arg1);
2407 size_t len2 = strlen(NameStr(*arg2));
2409 bool result;
2410
2412
2413 if (collid == C_COLLATION_OID)
2414 result = !(len1 == len2 &&
2415 memcmp(VARDATA_ANY(arg1), NameStr(*arg2), len1) == 0);
2416 else
2417 result = !(varstr_cmp(VARDATA_ANY(arg1), len1,
2418 NameStr(*arg2), len2,
2419 collid) == 0);
2420
2421 PG_FREE_IF_COPY(arg1, 0);
2422
2423 PG_RETURN_BOOL(result);
2424}

References check_collation_set(), collid, NameStr, PG_FREE_IF_COPY, PG_GET_COLLATION, PG_GETARG_NAME, PG_GETARG_TEXT_PP, PG_RETURN_BOOL, VARDATA_ANY(), VARSIZE_ANY_EXHDR(), and varstr_cmp().

◆ textoctetlen()

Datum textoctetlen ( PG_FUNCTION_ARGS  )

Definition at line 426 of file varlena.c.

427{
429
430 /* We need not detoast the input at all */
432}

References PG_GETARG_DATUM, PG_RETURN_INT32, str, toast_raw_datum_size(), and VARHDRSZ.

◆ textout()

Datum textout ( PG_FUNCTION_ARGS  )

Definition at line 286 of file varlena.c.

287{
288 Datum txt = PG_GETARG_DATUM(0);
289
291}
#define TextDatumGetCString(d)
Definition: builtins.h:98
#define PG_RETURN_CSTRING(x)
Definition: fmgr.h:362

References PG_GETARG_DATUM, PG_RETURN_CSTRING, and TextDatumGetCString.

Referenced by pg_node_tree_out(), plsample_func_handler(), and plsample_trigger_handler().

◆ textoverlay()

Datum textoverlay ( PG_FUNCTION_ARGS  )

Definition at line 788 of file varlena.c.

789{
790 text *t1 = PG_GETARG_TEXT_PP(0);
791 text *t2 = PG_GETARG_TEXT_PP(1);
792 int sp = PG_GETARG_INT32(2); /* substring start position */
793 int sl = PG_GETARG_INT32(3); /* substring length */
794
795 PG_RETURN_TEXT_P(text_overlay(t1, t2, sp, sl));
796}
static text * text_overlay(text *t1, text *t2, int sp, int sl)
Definition: varlena.c:811

References PG_GETARG_INT32, PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, and text_overlay().

◆ textoverlay_no_len()

Datum textoverlay_no_len ( PG_FUNCTION_ARGS  )

Definition at line 799 of file varlena.c.

800{
801 text *t1 = PG_GETARG_TEXT_PP(0);
802 text *t2 = PG_GETARG_TEXT_PP(1);
803 int sp = PG_GETARG_INT32(2); /* substring start position */
804 int sl;
805
806 sl = text_length(PointerGetDatum(t2)); /* defaults to length(t2) */
807 PG_RETURN_TEXT_P(text_overlay(t1, t2, sp, sl));
808}

References PG_GETARG_INT32, PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, PointerGetDatum(), text_length(), and text_overlay().

◆ textpos()

Datum textpos ( PG_FUNCTION_ARGS  )

Definition at line 848 of file varlena.c.

849{
851 text *search_str = PG_GETARG_TEXT_PP(1);
852
854}
static int text_position(text *t1, text *t2, Oid collid)
Definition: varlena.c:871

References PG_GET_COLLATION, PG_GETARG_TEXT_PP, PG_RETURN_INT32, str, and text_position().

◆ textrecv()

Datum textrecv ( PG_FUNCTION_ARGS  )

Definition at line 297 of file varlena.c.

298{
300 text *result;
301 char *str;
302 int nbytes;
303
304 str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
305
306 result = cstring_to_text_with_len(str, nbytes);
307 pfree(str);
308 PG_RETURN_TEXT_P(result);
309}
char * pq_getmsgtext(StringInfo msg, int rawbytes, int *nbytes)
Definition: pqformat.c:546

References buf, cstring_to_text_with_len(), pfree(), PG_GETARG_POINTER, PG_RETURN_TEXT_P, pq_getmsgtext(), and str.

◆ textsend()

Datum textsend ( PG_FUNCTION_ARGS  )

Definition at line 315 of file varlena.c.

316{
317 text *t = PG_GETARG_TEXT_PP(0);
319
323}
void pq_sendtext(StringInfo buf, const char *str, int slen)
Definition: pqformat.c:172

References buf, PG_GETARG_TEXT_PP, PG_RETURN_BYTEA_P, pq_begintypsend(), pq_endtypsend(), pq_sendtext(), VARDATA_ANY(), and VARSIZE_ANY_EXHDR().

Referenced by bpcharsend(), pg_node_tree_send(), and varcharsend().

◆ textToQualifiedNameList()

List * textToQualifiedNameList ( text textval)

Definition at line 2686 of file varlena.c.

2687{
2688 char *rawname;
2689 List *result = NIL;
2690 List *namelist;
2691 ListCell *l;
2692
2693 /* Convert to C string (handles possible detoasting). */
2694 /* Note we rely on being able to modify rawname below. */
2695 rawname = text_to_cstring(textval);
2696
2697 if (!SplitIdentifierString(rawname, '.', &namelist))
2698 ereport(ERROR,
2699 (errcode(ERRCODE_INVALID_NAME),
2700 errmsg("invalid name syntax")));
2701
2702 if (namelist == NIL)
2703 ereport(ERROR,
2704 (errcode(ERRCODE_INVALID_NAME),
2705 errmsg("invalid name syntax")));
2706
2707 foreach(l, namelist)
2708 {
2709 char *curname = (char *) lfirst(l);
2710
2711 result = lappend(result, makeString(pstrdup(curname)));
2712 }
2713
2714 pfree(rawname);
2715 list_free(namelist);
2716
2717 return result;
2718}
void list_free(List *list)
Definition: list.c:1546
#define lfirst(lc)
Definition: pg_list.h:172
Definition: pg_list.h:54
String * makeString(char *str)
Definition: value.c:63
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:2744

References ereport, errcode(), errmsg(), ERROR, lappend(), lfirst, list_free(), makeString(), NIL, pfree(), pstrdup(), SplitIdentifierString(), and text_to_cstring().

Referenced by bt_metap(), bt_multi_page_stats(), bt_page_items_internal(), bt_page_stats_internal(), convert_table_name(), currtid_byrelname(), get_raw_page_internal(), get_rel_from_relname(), nextval(), pg_get_serial_sequence(), pg_get_viewdef_name(), pg_get_viewdef_name_ext(), pg_relpages(), pg_relpages_v1_5(), pgrowlocks(), pgstatindex(), pgstatindex_v1_5(), pgstattuple(), pgstattuple_v1_5(), row_security_active_name(), text_regclass(), ts_parse_byname(), and ts_token_type_byname().

◆ to_bin32()

Datum to_bin32 ( PG_FUNCTION_ARGS  )

Definition at line 4052 of file varlena.c.

4053{
4055
4057}
uint32_t uint32
Definition: c.h:539
static text * convert_to_base(uint64 value, int base)
Definition: varlena.c:4026

References convert_to_base(), PG_GETARG_INT32, PG_RETURN_TEXT_P, and value.

◆ to_bin64()

Datum to_bin64 ( PG_FUNCTION_ARGS  )

Definition at line 4059 of file varlena.c.

4060{
4062
4064}
#define PG_GETARG_INT64(n)
Definition: fmgr.h:283

References convert_to_base(), PG_GETARG_INT64, PG_RETURN_TEXT_P, and value.

◆ to_hex32()

Datum to_hex32 ( PG_FUNCTION_ARGS  )

Definition at line 4090 of file varlena.c.

4091{
4093
4095}

References convert_to_base(), PG_GETARG_INT32, PG_RETURN_TEXT_P, and value.

Referenced by gin_page_opaque_info(), and gist_page_opaque_info().

◆ to_hex64()

Datum to_hex64 ( PG_FUNCTION_ARGS  )

Definition at line 4097 of file varlena.c.

4098{
4100
4102}

References convert_to_base(), PG_GETARG_INT64, PG_RETURN_TEXT_P, and value.

◆ to_oct32()

Datum to_oct32 ( PG_FUNCTION_ARGS  )

Definition at line 4071 of file varlena.c.

4072{
4074
4076}

References convert_to_base(), PG_GETARG_INT32, PG_RETURN_TEXT_P, and value.

◆ to_oct64()

Datum to_oct64 ( PG_FUNCTION_ARGS  )

Definition at line 4078 of file varlena.c.

4079{
4081
4083}

References convert_to_base(), PG_GETARG_INT64, PG_RETURN_TEXT_P, and value.

◆ unicode_assigned()

Datum unicode_assigned ( PG_FUNCTION_ARGS  )

Definition at line 5412 of file varlena.c.

5413{
5415 unsigned char *p;
5416 int size;
5417
5419 ereport(ERROR,
5420 (errmsg("Unicode categorization can only be performed if server encoding is UTF8")));
5421
5422 /* convert to pg_wchar */
5424 p = (unsigned char *) VARDATA_ANY(input);
5425 for (int i = 0; i < size; i++)
5426 {
5427 pg_wchar uchar = utf8_to_unicode(p);
5428 int category = unicode_category(uchar);
5429
5430 if (category == PG_U_UNASSIGNED)
5431 PG_RETURN_BOOL(false);
5432
5433 p += pg_utf_mblen(p);
5434 }
5435
5436 PG_RETURN_BOOL(true);
5437}
FILE * input
static pg_wchar utf8_to_unicode(const unsigned char *c)
Definition: mbprint.c:53
#define pg_utf_mblen
Definition: pg_wchar.h:633
pg_unicode_category unicode_category(pg_wchar code)
@ PG_U_UNASSIGNED

References ereport, errmsg(), ERROR, GetDatabaseEncoding(), i, input, PG_GETARG_TEXT_PP, pg_mbstrlen_with_len(), PG_RETURN_BOOL, PG_U_UNASSIGNED, PG_UTF8, pg_utf_mblen, unicode_category(), utf8_to_unicode(), VARDATA_ANY(), and VARSIZE_ANY_EXHDR().

◆ unicode_is_normalized()

Datum unicode_is_normalized ( PG_FUNCTION_ARGS  )

Definition at line 5506 of file varlena.c.

5507{
5509 char *formstr = text_to_cstring(PG_GETARG_TEXT_PP(1));
5511 int size;
5512 pg_wchar *input_chars;
5513 pg_wchar *output_chars;
5514 unsigned char *p;
5515 int i;
5516 UnicodeNormalizationQC quickcheck;
5517 int output_size;
5518 bool result;
5519
5520 form = unicode_norm_form_from_string(formstr);
5521
5522 /* convert to pg_wchar */
5524 input_chars = palloc((size + 1) * sizeof(pg_wchar));
5525 p = (unsigned char *) VARDATA_ANY(input);
5526 for (i = 0; i < size; i++)
5527 {
5528 input_chars[i] = utf8_to_unicode(p);
5529 p += pg_utf_mblen(p);
5530 }
5531 input_chars[i] = (pg_wchar) '\0';
5532 Assert((char *) p == VARDATA_ANY(input) + VARSIZE_ANY_EXHDR(input));
5533
5534 /* quick check (see UAX #15) */
5535 quickcheck = unicode_is_normalized_quickcheck(form, input_chars);
5536 if (quickcheck == UNICODE_NORM_QC_YES)
5537 PG_RETURN_BOOL(true);
5538 else if (quickcheck == UNICODE_NORM_QC_NO)
5539 PG_RETURN_BOOL(false);
5540
5541 /* normalize and compare with original */
5542 output_chars = unicode_normalize(form, input_chars);
5543
5544 output_size = 0;
5545 for (pg_wchar *wp = output_chars; *wp; wp++)
5546 output_size++;
5547
5548 result = (size == output_size) &&
5549 (memcmp(input_chars, output_chars, size * sizeof(pg_wchar)) == 0);
5550
5551 PG_RETURN_BOOL(result);
5552}
UnicodeNormalizationQC unicode_is_normalized_quickcheck(UnicodeNormalizationForm form, const pg_wchar *input)
Definition: unicode_norm.c:598
pg_wchar * unicode_normalize(UnicodeNormalizationForm form, const pg_wchar *input)
Definition: unicode_norm.c:402
UnicodeNormalizationForm
Definition: unicode_norm.h:20
UnicodeNormalizationQC
Definition: unicode_norm.h:29
@ UNICODE_NORM_QC_YES
Definition: unicode_norm.h:31
@ UNICODE_NORM_QC_NO
Definition: unicode_norm.h:30
static UnicodeNormalizationForm unicode_norm_form_from_string(const char *formstr)
Definition: varlena.c:5352

References Assert(), i, input, palloc(), PG_GETARG_TEXT_PP, pg_mbstrlen_with_len(), PG_RETURN_BOOL, pg_utf_mblen, text_to_cstring(), unicode_is_normalized_quickcheck(), unicode_norm_form_from_string(), UNICODE_NORM_QC_NO, UNICODE_NORM_QC_YES, unicode_normalize(), utf8_to_unicode(), VARDATA_ANY(), and VARSIZE_ANY_EXHDR().

◆ unicode_norm_form_from_string()

static UnicodeNormalizationForm unicode_norm_form_from_string ( const char *  formstr)
static

Definition at line 5352 of file varlena.c.

5353{
5354 UnicodeNormalizationForm form = -1;
5355
5356 /*
5357 * Might as well check this while we're here.
5358 */
5360 ereport(ERROR,
5361 (errcode(ERRCODE_SYNTAX_ERROR),
5362 errmsg("Unicode normalization can only be performed if server encoding is UTF8")));
5363
5364 if (pg_strcasecmp(formstr, "NFC") == 0)
5365 form = UNICODE_NFC;
5366 else if (pg_strcasecmp(formstr, "NFD") == 0)
5367 form = UNICODE_NFD;
5368 else if (pg_strcasecmp(formstr, "NFKC") == 0)
5369 form = UNICODE_NFKC;
5370 else if (pg_strcasecmp(formstr, "NFKD") == 0)
5371 form = UNICODE_NFKD;
5372 else
5373 ereport(ERROR,
5374 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5375 errmsg("invalid normalization form: %s", formstr)));
5376
5377 return form;
5378}
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
@ UNICODE_NFKD
Definition: unicode_norm.h:24
@ UNICODE_NFD
Definition: unicode_norm.h:22
@ UNICODE_NFC
Definition: unicode_norm.h:21
@ UNICODE_NFKC
Definition: unicode_norm.h:23

References ereport, errcode(), errmsg(), ERROR, GetDatabaseEncoding(), pg_strcasecmp(), PG_UTF8, UNICODE_NFC, UNICODE_NFD, UNICODE_NFKC, and UNICODE_NFKD.

Referenced by unicode_is_normalized(), and unicode_normalize_func().

◆ unicode_normalize_func()

Datum unicode_normalize_func ( PG_FUNCTION_ARGS  )

Definition at line 5440 of file varlena.c.

5441{
5443 char *formstr = text_to_cstring(PG_GETARG_TEXT_PP(1));
5445 int size;
5446 pg_wchar *input_chars;
5447 pg_wchar *output_chars;
5448 unsigned char *p;
5449 text *result;
5450 int i;
5451
5452 form = unicode_norm_form_from_string(formstr);
5453
5454 /* convert to pg_wchar */
5456 input_chars = palloc((size + 1) * sizeof(pg_wchar));
5457 p = (unsigned char *) VARDATA_ANY(input);
5458 for (i = 0; i < size; i++)
5459 {
5460 input_chars[i] = utf8_to_unicode(p);
5461 p += pg_utf_mblen(p);
5462 }
5463 input_chars[i] = (pg_wchar) '\0';
5464 Assert((char *) p == VARDATA_ANY(input) + VARSIZE_ANY_EXHDR(input));
5465
5466 /* action */
5467 output_chars = unicode_normalize(form, input_chars);
5468
5469 /* convert back to UTF-8 string */
5470 size = 0;
5471 for (pg_wchar *wp = output_chars; *wp; wp++)
5472 {
5473 unsigned char buf[4];
5474
5475 unicode_to_utf8(*wp, buf);
5476 size += pg_utf_mblen(buf);
5477 }
5478
5479 result = palloc(size + VARHDRSZ);
5480 SET_VARSIZE(result, size + VARHDRSZ);
5481
5482 p = (unsigned char *) VARDATA_ANY(result);
5483 for (pg_wchar *wp = output_chars; *wp; wp++)
5484 {
5485 unicode_to_utf8(*wp, p);
5486 p += pg_utf_mblen(p);
5487 }
5488 Assert((char *) p == (char *) result + size + VARHDRSZ);
5489
5490 PG_RETURN_TEXT_P(result);
5491}
static unsigned char * unicode_to_utf8(pg_wchar c, unsigned char *utf8string)
Definition: pg_wchar.h:575

References Assert(), buf, i, input, palloc(), PG_GETARG_TEXT_PP, pg_mbstrlen_with_len(), PG_RETURN_TEXT_P, pg_utf_mblen, SET_VARSIZE(), text_to_cstring(), unicode_norm_form_from_string(), unicode_normalize(), unicode_to_utf8(), utf8_to_unicode(), VARDATA_ANY(), VARHDRSZ, and VARSIZE_ANY_EXHDR().

◆ unicode_version()

Datum unicode_version ( PG_FUNCTION_ARGS  )

Definition at line 5389 of file varlena.c.

5390{
5392}
#define PG_UNICODE_VERSION

References cstring_to_text(), PG_RETURN_TEXT_P, and PG_UNICODE_VERSION.

◆ unistr()

Datum unistr ( PG_FUNCTION_ARGS  )

Definition at line 5598 of file varlena.c.

5599{
5600 text *input_text = PG_GETARG_TEXT_PP(0);
5601 char *instr;
5602 int len;
5604 text *result;
5605 pg_wchar pair_first = 0;
5606 char cbuf[MAX_UNICODE_EQUIVALENT_STRING + 1];
5607
5608 instr = VARDATA_ANY(input_text);
5609 len = VARSIZE_ANY_EXHDR(input_text);
5610
5612
5613 while (len > 0)
5614 {
5615 if (instr[0] == '\\')
5616 {
5617 if (len >= 2 &&
5618 instr[1] == '\\')
5619 {
5620 if (pair_first)
5621 goto invalid_pair;
5622 appendStringInfoChar(&str, '\\');
5623 instr += 2;
5624 len -= 2;
5625 }
5626 else if ((len >= 5 && isxdigits_n(instr + 1, 4)) ||
5627 (len >= 6 && instr[1] == 'u' && isxdigits_n(instr + 2, 4)))
5628 {
5629 pg_wchar unicode;
5630 int offset = instr[1] == 'u' ? 2 : 1;
5631
5632 unicode = hexval_n(instr + offset, 4);
5633
5634 if (!is_valid_unicode_codepoint(unicode))
5635 ereport(ERROR,
5636 errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5637 errmsg("invalid Unicode code point: %04X", unicode));
5638
5639 if (pair_first)
5640 {
5641 if (is_utf16_surrogate_second(unicode))
5642 {
5643 unicode = surrogate_pair_to_codepoint(pair_first, unicode);
5644 pair_first = 0;
5645 }
5646 else
5647 goto invalid_pair;
5648 }
5649 else if (is_utf16_surrogate_second(unicode))
5650 goto invalid_pair;
5651
5652 if (is_utf16_surrogate_first(unicode))
5653 pair_first = unicode;
5654 else
5655 {
5656 pg_unicode_to_server(unicode, (unsigned char *) cbuf);
5658 }
5659
5660 instr += 4 + offset;
5661 len -= 4 + offset;
5662 }
5663 else if (len >= 8 && instr[1] == '+' && isxdigits_n(instr + 2, 6))
5664 {
5665 pg_wchar unicode;
5666
5667 unicode = hexval_n(instr + 2, 6);
5668
5669 if (!is_valid_unicode_codepoint(unicode))
5670 ereport(ERROR,
5671 errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5672 errmsg("invalid Unicode code point: %04X", unicode));
5673
5674 if (pair_first)
5675 {
5676 if (is_utf16_surrogate_second(unicode))
5677 {
5678 unicode = surrogate_pair_to_codepoint(pair_first, unicode);
5679 pair_first = 0;
5680 }
5681 else
5682 goto invalid_pair;
5683 }
5684 else if (is_utf16_surrogate_second(unicode))
5685 goto invalid_pair;
5686
5687 if (is_utf16_surrogate_first(unicode))
5688 pair_first = unicode;
5689 else
5690 {
5691 pg_unicode_to_server(unicode, (unsigned char *) cbuf);
5693 }
5694
5695 instr += 8;
5696 len -= 8;
5697 }
5698 else if (len >= 10 && instr[1] == 'U' && isxdigits_n(instr + 2, 8))
5699 {
5700 pg_wchar unicode;
5701
5702 unicode = hexval_n(instr + 2, 8);
5703
5704 if (!is_valid_unicode_codepoint(unicode))
5705 ereport(ERROR,
5706 errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5707 errmsg("invalid Unicode code point: %04X", unicode));
5708
5709 if (pair_first)
5710 {
5711 if (is_utf16_surrogate_second(unicode))
5712 {
5713 unicode = surrogate_pair_to_codepoint(pair_first, unicode);
5714 pair_first = 0;
5715 }
5716 else
5717 goto invalid_pair;
5718 }
5719 else if (is_utf16_surrogate_second(unicode))
5720 goto invalid_pair;
5721
5722 if (is_utf16_surrogate_first(unicode))
5723 pair_first = unicode;
5724 else
5725 {
5726 pg_unicode_to_server(unicode, (unsigned char *) cbuf);
5728 }
5729
5730 instr += 10;
5731 len -= 10;
5732 }
5733 else
5734 ereport(ERROR,
5735 (errcode(ERRCODE_SYNTAX_ERROR),
5736 errmsg("invalid Unicode escape"),
5737 errhint("Unicode escapes must be \\XXXX, \\+XXXXXX, \\uXXXX, or \\UXXXXXXXX.")));
5738 }
5739 else
5740 {
5741 if (pair_first)
5742 goto invalid_pair;
5743
5744 appendStringInfoChar(&str, *instr++);
5745 len--;
5746 }
5747 }
5748
5749 /* unfinished surrogate pair? */
5750 if (pair_first)
5751 goto invalid_pair;
5752
5753 result = cstring_to_text_with_len(str.data, str.len);
5754 pfree(str.data);
5755
5756 PG_RETURN_TEXT_P(result);
5757
5758invalid_pair:
5759 ereport(ERROR,
5760 (errcode(ERRCODE_SYNTAX_ERROR),
5761 errmsg("invalid Unicode surrogate pair")));
5762 PG_RETURN_NULL(); /* keep compiler quiet */
5763}
void pg_unicode_to_server(pg_wchar c, unsigned char *s)
Definition: mbutils.c:865
#define MAX_UNICODE_EQUIVALENT_STRING
Definition: pg_wchar.h:329
static bool is_valid_unicode_codepoint(pg_wchar c)
Definition: pg_wchar.h:519
static pg_wchar surrogate_pair_to_codepoint(pg_wchar first, pg_wchar second)
Definition: pg_wchar.h:537
static bool is_utf16_surrogate_first(pg_wchar c)
Definition: pg_wchar.h:525
static bool is_utf16_surrogate_second(pg_wchar c)
Definition: pg_wchar.h:531
static unsigned int hexval_n(const char *instr, size_t n)
Definition: varlena.c:5584
static bool isxdigits_n(const char *instr, size_t n)
Definition: varlena.c:5558

References appendStringInfoChar(), appendStringInfoString(), cstring_to_text_with_len(), ereport, errcode(), errhint(), errmsg(), ERROR, hexval_n(), initStringInfo(), is_utf16_surrogate_first(), is_utf16_surrogate_second(), is_valid_unicode_codepoint(), isxdigits_n(), len, MAX_UNICODE_EQUIVALENT_STRING, pfree(), PG_GETARG_TEXT_PP, PG_RETURN_NULL, PG_RETURN_TEXT_P, pg_unicode_to_server(), str, surrogate_pair_to_codepoint(), VARDATA_ANY(), and VARSIZE_ANY_EXHDR().

◆ unknownin()

Datum unknownin ( PG_FUNCTION_ARGS  )

Definition at line 330 of file varlena.c.

331{
332 char *str = PG_GETARG_CSTRING(0);
333
334 /* representation is same as cstring */
336}

References PG_GETARG_CSTRING, PG_RETURN_CSTRING, pstrdup(), and str.

◆ unknownout()

Datum unknownout ( PG_FUNCTION_ARGS  )

Definition at line 342 of file varlena.c.

343{
344 /* representation is same as cstring */
345 char *str = PG_GETARG_CSTRING(0);
346
348}

References PG_GETARG_CSTRING, PG_RETURN_CSTRING, pstrdup(), and str.

◆ unknownrecv()

Datum unknownrecv ( PG_FUNCTION_ARGS  )

Definition at line 354 of file varlena.c.

355{
357 char *str;
358 int nbytes;
359
360 str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
361 /* representation is same as cstring */
363}

References buf, PG_GETARG_POINTER, PG_RETURN_CSTRING, pq_getmsgtext(), and str.

◆ unknownsend()

Datum unknownsend ( PG_FUNCTION_ARGS  )

Definition at line 369 of file varlena.c.

370{
371 /* representation is same as cstring */
372 char *str = PG_GETARG_CSTRING(0);
374
376 pq_sendtext(&buf, str, strlen(str));
378}

References buf, PG_GETARG_CSTRING, PG_RETURN_BYTEA_P, pq_begintypsend(), pq_endtypsend(), pq_sendtext(), and str.

◆ updateClosestMatch()

void updateClosestMatch ( ClosestMatchState state,
const char *  candidate 
)

Definition at line 5304 of file varlena.c.

5305{
5306 int dist;
5307
5308 Assert(state);
5309
5310 if (state->source == NULL || state->source[0] == '\0' ||
5311 candidate == NULL || candidate[0] == '\0')
5312 return;
5313
5314 /*
5315 * To avoid ERROR-ing, we check the lengths here instead of setting
5316 * 'trusted' to false in the call to varstr_levenshtein_less_equal().
5317 */
5318 if (strlen(state->source) > MAX_LEVENSHTEIN_STRLEN ||
5319 strlen(candidate) > MAX_LEVENSHTEIN_STRLEN)
5320 return;
5321
5322 dist = varstr_levenshtein_less_equal(state->source, strlen(state->source),
5323 candidate, strlen(candidate), 1, 1, 1,
5324 state->max_d, true);
5325 if (dist <= state->max_d &&
5326 dist <= strlen(state->source) / 2 &&
5327 (state->min_d == -1 || dist < state->min_d))
5328 {
5329 state->min_d = dist;
5330 state->match = candidate;
5331 }
5332}
#define MAX_LEVENSHTEIN_STRLEN
Definition: levenshtein.c:26
int varstr_levenshtein_less_equal(const char *source, int slen, const char *target, int tlen, int ins_c, int del_c, int sub_c, int max_d, bool trusted)

References Assert(), MAX_LEVENSHTEIN_STRLEN, and varstr_levenshtein_less_equal().

Referenced by dblink_fdw_validator(), file_fdw_validator(), postgres_fdw_validator(), and postgresql_fdw_validator().

◆ varlenafastcmp_locale()

static int varlenafastcmp_locale ( Datum  x,
Datum  y,
SortSupport  ssup 
)
static

Definition at line 1833 of file varlena.c.

1834{
1837 char *a1p,
1838 *a2p;
1839 int len1,
1840 len2,
1841 result;
1842
1843 a1p = VARDATA_ANY(arg1);
1844 a2p = VARDATA_ANY(arg2);
1845
1846 len1 = VARSIZE_ANY_EXHDR(arg1);
1847 len2 = VARSIZE_ANY_EXHDR(arg2);
1848
1849 result = varstrfastcmp_locale(a1p, len1, a2p, len2, ssup);
1850
1851 /* We can't afford to leak memory here. */
1852 if (PointerGetDatum(arg1) != x)
1853 pfree(arg1);
1854 if (PointerGetDatum(arg2) != y)
1855 pfree(arg2);
1856
1857 return result;
1858}
#define DatumGetVarStringPP(X)
Definition: varlena.c:120

References DatumGetVarStringPP, pfree(), PointerGetDatum(), VARDATA_ANY(), VARSIZE_ANY_EXHDR(), varstrfastcmp_locale(), x, and y.

Referenced by varstr_sortsupport().

◆ varstr_abbrev_abort()

static bool varstr_abbrev_abort ( int  memtupcount,
SortSupport  ssup 
)
static

Definition at line 2170 of file varlena.c.

2171{
2173 double abbrev_distinct,
2174 key_distinct;
2175
2176 Assert(ssup->abbreviate);
2177
2178 /* Have a little patience */
2179 if (memtupcount < 100)
2180 return false;
2181
2182 abbrev_distinct = estimateHyperLogLog(&sss->abbr_card);
2183 key_distinct = estimateHyperLogLog(&sss->full_card);
2184
2185 /*
2186 * Clamp cardinality estimates to at least one distinct value. While
2187 * NULLs are generally disregarded, if only NULL values were seen so far,
2188 * that might misrepresent costs if we failed to clamp.
2189 */
2190 if (abbrev_distinct <= 1.0)
2191 abbrev_distinct = 1.0;
2192
2193 if (key_distinct <= 1.0)
2194 key_distinct = 1.0;
2195
2196 /*
2197 * In the worst case all abbreviated keys are identical, while at the same
2198 * time there are differences within full key strings not captured in
2199 * abbreviations.
2200 */
2201 if (trace_sort)
2202 {
2203 double norm_abbrev_card = abbrev_distinct / (double) memtupcount;
2204
2205 elog(LOG, "varstr_abbrev: abbrev_distinct after %d: %f "
2206 "(key_distinct: %f, norm_abbrev_card: %f, prop_card: %f)",
2207 memtupcount, abbrev_distinct, key_distinct, norm_abbrev_card,
2208 sss->prop_card);
2209 }
2210
2211 /*
2212 * If the number of distinct abbreviated keys approximately matches the
2213 * number of distinct authoritative original keys, that's reason enough to
2214 * proceed. We can win even with a very low cardinality set if most
2215 * tie-breakers only memcmp(). This is by far the most important
2216 * consideration.
2217 *
2218 * While comparisons that are resolved at the abbreviated key level are
2219 * considerably cheaper than tie-breakers resolved with memcmp(), both of
2220 * those two outcomes are so much cheaper than a full strcoll() once
2221 * sorting is underway that it doesn't seem worth it to weigh abbreviated
2222 * cardinality against the overall size of the set in order to more
2223 * accurately model costs. Assume that an abbreviated comparison, and an
2224 * abbreviated comparison with a cheap memcmp()-based authoritative
2225 * resolution are equivalent.
2226 */
2227 if (abbrev_distinct > key_distinct * sss->prop_card)
2228 {
2229 /*
2230 * When we have exceeded 10,000 tuples, decay required cardinality
2231 * aggressively for next call.
2232 *
2233 * This is useful because the number of comparisons required on
2234 * average increases at a linearithmic rate, and at roughly 10,000
2235 * tuples that factor will start to dominate over the linear costs of
2236 * string transformation (this is a conservative estimate). The decay
2237 * rate is chosen to be a little less aggressive than halving -- which
2238 * (since we're called at points at which memtupcount has doubled)
2239 * would never see the cost model actually abort past the first call
2240 * following a decay. This decay rate is mostly a precaution against
2241 * a sudden, violent swing in how well abbreviated cardinality tracks
2242 * full key cardinality. The decay also serves to prevent a marginal
2243 * case from being aborted too late, when too much has already been
2244 * invested in string transformation.
2245 *
2246 * It's possible for sets of several million distinct strings with
2247 * mere tens of thousands of distinct abbreviated keys to still
2248 * benefit very significantly. This will generally occur provided
2249 * each abbreviated key is a proxy for a roughly uniform number of the
2250 * set's full keys. If it isn't so, we hope to catch that early and
2251 * abort. If it isn't caught early, by the time the problem is
2252 * apparent it's probably not worth aborting.
2253 */
2254 if (memtupcount > 10000)
2255 sss->prop_card *= 0.65;
2256
2257 return false;
2258 }
2259
2260 /*
2261 * Abort abbreviation strategy.
2262 *
2263 * The worst case, where all abbreviated keys are identical while all
2264 * original strings differ will typically only see a regression of about
2265 * 10% in execution time for small to medium sized lists of strings.
2266 * Whereas on modern CPUs where cache stalls are the dominant cost, we can
2267 * often expect very large improvements, particularly with sets of strings
2268 * of moderately high to high abbreviated cardinality. There is little to
2269 * lose but much to gain, which our strategy reflects.
2270 */
2271 if (trace_sort)
2272 elog(LOG, "varstr_abbrev: aborted abbreviation at %d "
2273 "(abbrev_distinct: %f, key_distinct: %f, prop_card: %f)",
2274 memtupcount, abbrev_distinct, key_distinct, sss->prop_card);
2275
2276 return true;
2277}
#define LOG
Definition: elog.h:31
double estimateHyperLogLog(hyperLogLogState *cState)
Definition: hyperloglog.c:186
void * ssup_extra
Definition: sortsupport.h:87
hyperLogLogState full_card
Definition: varlena.c:97
hyperLogLogState abbr_card
Definition: varlena.c:96
bool trace_sort
Definition: tuplesort.c:124

References VarStringSortSupport::abbr_card, SortSupportData::abbreviate, Assert(), elog, estimateHyperLogLog(), VarStringSortSupport::full_card, LOG, VarStringSortSupport::prop_card, SortSupportData::ssup_extra, and trace_sort.

Referenced by varstr_sortsupport().

◆ varstr_abbrev_convert()

static Datum varstr_abbrev_convert ( Datum  original,
SortSupport  ssup 
)
static

Definition at line 1978 of file varlena.c.

1979{
1980 const size_t max_prefix_bytes = sizeof(Datum);
1982 VarString *authoritative = DatumGetVarStringPP(original);
1983 char *authoritative_data = VARDATA_ANY(authoritative);
1984
1985 /* working state */
1986 Datum res;
1987 char *pres;
1988 int len;
1989 uint32 hash;
1990
1991 pres = (char *) &res;
1992 /* memset(), so any non-overwritten bytes are NUL */
1993 memset(pres, 0, max_prefix_bytes);
1994 len = VARSIZE_ANY_EXHDR(authoritative);
1995
1996 /* Get number of bytes, ignoring trailing spaces */
1997 if (sss->typid == BPCHAROID)
1998 len = bpchartruelen(authoritative_data, len);
1999
2000 /*
2001 * If we're using the C collation, use memcpy(), rather than strxfrm(), to
2002 * abbreviate keys. The full comparator for the C locale is always
2003 * memcmp(). It would be incorrect to allow bytea callers (callers that
2004 * always force the C collation -- bytea isn't a collatable type, but this
2005 * approach is convenient) to use strxfrm(). This is because bytea
2006 * strings may contain NUL bytes. Besides, this should be faster, too.
2007 *
2008 * More generally, it's okay that bytea callers can have NUL bytes in
2009 * strings because abbreviated cmp need not make a distinction between
2010 * terminating NUL bytes, and NUL bytes representing actual NULs in the
2011 * authoritative representation. Hopefully a comparison at or past one
2012 * abbreviated key's terminating NUL byte will resolve the comparison
2013 * without consulting the authoritative representation; specifically, some
2014 * later non-NUL byte in the longer string can resolve the comparison
2015 * against a subsequent terminating NUL in the shorter string. There will
2016 * usually be what is effectively a "length-wise" resolution there and
2017 * then.
2018 *
2019 * If that doesn't work out -- if all bytes in the longer string
2020 * positioned at or past the offset of the smaller string's (first)
2021 * terminating NUL are actually representative of NUL bytes in the
2022 * authoritative binary string (perhaps with some *terminating* NUL bytes
2023 * towards the end of the longer string iff it happens to still be small)
2024 * -- then an authoritative tie-breaker will happen, and do the right
2025 * thing: explicitly consider string length.
2026 */
2027 if (sss->collate_c)
2028 memcpy(pres, authoritative_data, Min(len, max_prefix_bytes));
2029 else
2030 {
2031 Size bsize;
2032
2033 /*
2034 * We're not using the C collation, so fall back on strxfrm or ICU
2035 * analogs.
2036 */
2037
2038 /* By convention, we use buffer 1 to store and NUL-terminate */
2039 if (len >= sss->buflen1)
2040 {
2041 sss->buflen1 = Max(len + 1, Min(sss->buflen1 * 2, MaxAllocSize));
2042 sss->buf1 = repalloc(sss->buf1, sss->buflen1);
2043 }
2044
2045 /* Might be able to reuse strxfrm() blob from last call */
2046 if (sss->last_len1 == len && sss->cache_blob &&
2047 memcmp(sss->buf1, authoritative_data, len) == 0)
2048 {
2049 memcpy(pres, sss->buf2, Min(max_prefix_bytes, sss->last_len2));
2050 /* No change affecting cardinality, so no hashing required */
2051 goto done;
2052 }
2053
2054 memcpy(sss->buf1, authoritative_data, len);
2055
2056 /*
2057 * pg_strxfrm() and pg_strxfrm_prefix expect NUL-terminated strings.
2058 */
2059 sss->buf1[len] = '\0';
2060 sss->last_len1 = len;
2061
2063 {
2064 if (sss->buflen2 < max_prefix_bytes)
2065 {
2066 sss->buflen2 = Max(max_prefix_bytes,
2067 Min(sss->buflen2 * 2, MaxAllocSize));
2068 sss->buf2 = repalloc(sss->buf2, sss->buflen2);
2069 }
2070
2071 bsize = pg_strxfrm_prefix(sss->buf2, sss->buf1,
2072 max_prefix_bytes, sss->locale);
2073 sss->last_len2 = bsize;
2074 }
2075 else
2076 {
2077 /*
2078 * Loop: Call pg_strxfrm(), possibly enlarge buffer, and try
2079 * again. The pg_strxfrm() function leaves the result buffer
2080 * content undefined if the result did not fit, so we need to
2081 * retry until everything fits, even though we only need the first
2082 * few bytes in the end.
2083 */
2084 for (;;)
2085 {
2086 bsize = pg_strxfrm(sss->buf2, sss->buf1, sss->buflen2,
2087 sss->locale);
2088
2089 sss->last_len2 = bsize;
2090 if (bsize < sss->buflen2)
2091 break;
2092
2093 /*
2094 * Grow buffer and retry.
2095 */
2096 sss->buflen2 = Max(bsize + 1,
2097 Min(sss->buflen2 * 2, MaxAllocSize));
2098 sss->buf2 = repalloc(sss->buf2, sss->buflen2);
2099 }
2100 }
2101
2102 /*
2103 * Every Datum byte is always compared. This is safe because the
2104 * strxfrm() blob is itself NUL terminated, leaving no danger of
2105 * misinterpreting any NUL bytes not intended to be interpreted as
2106 * logically representing termination.
2107 *
2108 * (Actually, even if there were NUL bytes in the blob it would be
2109 * okay. See remarks on bytea case above.)
2110 */
2111 memcpy(pres, sss->buf2, Min(max_prefix_bytes, bsize));
2112 }
2113
2114 /*
2115 * Maintain approximate cardinality of both abbreviated keys and original,
2116 * authoritative keys using HyperLogLog. Used as cheap insurance against
2117 * the worst case, where we do many string transformations for no saving
2118 * in full strcoll()-based comparisons. These statistics are used by
2119 * varstr_abbrev_abort().
2120 *
2121 * First, Hash key proper, or a significant fraction of it. Mix in length
2122 * in order to compensate for cases where differences are past
2123 * PG_CACHE_LINE_SIZE bytes, so as to limit the overhead of hashing.
2124 */
2125 hash = DatumGetUInt32(hash_any((unsigned char *) authoritative_data,
2127
2128 if (len > PG_CACHE_LINE_SIZE)
2130
2132
2133 /* Hash abbreviated key */
2134 {
2135 uint32 tmp;
2136
2137 tmp = DatumGetUInt32(res) ^ (uint32) (DatumGetUInt64(res) >> 32);
2139 }
2140
2142
2143 /* Cache result, perhaps saving an expensive strxfrm() call next time */
2144 sss->cache_blob = true;
2145done:
2146
2147 /*
2148 * Byteswap on little-endian machines.
2149 *
2150 * This is needed so that ssup_datum_unsigned_cmp() (an unsigned integer
2151 * 3-way comparator) works correctly on all platforms. If we didn't do
2152 * this, the comparator would have to call memcmp() with a pair of
2153 * pointers to the first byte of each abbreviated key, which is slower.
2154 */
2155 res = DatumBigEndianToNative(res);
2156
2157 /* Don't leak memory here */
2158 if (PointerGetDatum(authoritative) != original)
2159 pfree(authoritative);
2160
2161 return res;
2162}
#define MaxAllocSize
Definition: fe_memutils.h:22
static Datum hash_uint32(uint32 k)
Definition: hashfn.h:43
static Datum hash_any(const unsigned char *k, int keylen)
Definition: hashfn.h:31
void addHyperLogLog(hyperLogLogState *cState, uint32 hash)
Definition: hyperloglog.c:167
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1610
#define DatumBigEndianToNative(x)
Definition: pg_bswap.h:145
#define PG_CACHE_LINE_SIZE
bool pg_strxfrm_prefix_enabled(pg_locale_t locale)
Definition: pg_locale.c:1356
size_t pg_strxfrm(char *dest, const char *src, size_t destsize, pg_locale_t locale)
Definition: pg_locale.c:1320
size_t pg_strxfrm_prefix(char *dest, const char *src, size_t destsize, pg_locale_t locale)
Definition: pg_locale.c:1367
static uint32 DatumGetUInt32(Datum X)
Definition: postgres.h:232
static uint64 DatumGetUInt64(Datum X)
Definition: postgres.h:413
static unsigned hash(unsigned *uv, int n)
Definition: rege_dfa.c:715
pg_locale_t locale
Definition: varlena.c:99

References VarStringSortSupport::abbr_card, addHyperLogLog(), bpchartruelen(), VarStringSortSupport::buf1, VarStringSortSupport::buf2, VarStringSortSupport::buflen1, VarStringSortSupport::buflen2, VarStringSortSupport::cache_blob, VarStringSortSupport::collate_c, DatumBigEndianToNative, DatumGetUInt32(), DatumGetUInt64(), DatumGetVarStringPP, VarStringSortSupport::full_card, hash(), hash_any(), hash_uint32(), VarStringSortSupport::last_len1, VarStringSortSupport::last_len2, len, VarStringSortSupport::locale, Max, MaxAllocSize, Min, pfree(), PG_CACHE_LINE_SIZE, pg_strxfrm(), pg_strxfrm_prefix(), pg_strxfrm_prefix_enabled(), PointerGetDatum(), repalloc(), SortSupportData::ssup_extra, VarStringSortSupport::typid, VARDATA_ANY(), and VARSIZE_ANY_EXHDR().

Referenced by varstr_sortsupport().

◆ varstr_cmp()

int varstr_cmp ( const char *  arg1,
int  len1,
const char *  arg2,
int  len2,
Oid  collid 
)

Definition at line 1297 of file varlena.c.

1298{
1299 int result;
1300 pg_locale_t mylocale;
1301
1303
1305
1306 if (mylocale->collate_is_c)
1307 {
1308 result = memcmp(arg1, arg2, Min(len1, len2));
1309 if ((result == 0) && (len1 != len2))
1310 result = (len1 < len2) ? -1 : 1;
1311 }
1312 else
1313 {
1314 /*
1315 * memcmp() can't tell us which of two unequal strings sorts first,
1316 * but it's a cheap way to tell if they're equal. Testing shows that
1317 * memcmp() followed by strcoll() is only trivially slower than
1318 * strcoll() by itself, so we don't lose much if this doesn't work out
1319 * very often, and if it does - for example, because there are many
1320 * equal strings in the input - then we win big by avoiding expensive
1321 * collation-aware comparisons.
1322 */
1323 if (len1 == len2 && memcmp(arg1, arg2, len1) == 0)
1324 return 0;
1325
1326 result = pg_strncoll(arg1, len1, arg2, len2, mylocale);
1327
1328 /* Break tie if necessary. */
1329 if (result == 0 && mylocale->deterministic)
1330 {
1331 result = memcmp(arg1, arg2, Min(len1, len2));
1332 if ((result == 0) && (len1 != len2))
1333 result = (len1 < len2) ? -1 : 1;
1334 }
1335 }
1336
1337 return result;
1338}

References check_collation_set(), pg_locale_struct::collate_is_c, collid, pg_locale_struct::deterministic, Min, pg_newlocale_from_collation(), and pg_strncoll().

Referenced by bpchar_larger(), bpchar_smaller(), bpcharcmp(), bpchareq(), bpcharge(), bpchargt(), bpcharle(), bpcharlt(), bpcharne(), btnametextcmp(), bttextnamecmp(), citextcmp(), compareJsonbScalarValue(), gin_compare_jsonb(), make_greater_string(), namecmp(), nameeqtext(), namenetext(), spg_text_leaf_consistent(), text_cmp(), texteqname(), and textnename().

◆ varstr_sortsupport()

void varstr_sortsupport ( SortSupport  ssup,
Oid  typid,
Oid  collid 
)

Definition at line 1615 of file varlena.c.

1616{
1617 bool abbreviate = ssup->abbreviate;
1618 bool collate_c = false;
1621
1623
1625
1626 /*
1627 * If possible, set ssup->comparator to a function which can be used to
1628 * directly compare two datums. If we can do this, we'll avoid the
1629 * overhead of a trip through the fmgr layer for every comparison, which
1630 * can be substantial.
1631 *
1632 * Most typically, we'll set the comparator to varlenafastcmp_locale,
1633 * which uses strcoll() to perform comparisons. We use that for the
1634 * BpChar case too, but type NAME uses namefastcmp_locale. However, if
1635 * LC_COLLATE = C, we can make things quite a bit faster with
1636 * varstrfastcmp_c, bpcharfastcmp_c, or namefastcmp_c, all of which use
1637 * memcmp() rather than strcoll().
1638 */
1639 if (locale->collate_is_c)
1640 {
1641 if (typid == BPCHAROID)
1643 else if (typid == NAMEOID)
1644 {
1645 ssup->comparator = namefastcmp_c;
1646 /* Not supporting abbreviation with type NAME, for now */
1647 abbreviate = false;
1648 }
1649 else
1651
1652 collate_c = true;
1653 }
1654 else
1655 {
1656 /*
1657 * We use varlenafastcmp_locale except for type NAME.
1658 */
1659 if (typid == NAMEOID)
1660 {
1662 /* Not supporting abbreviation with type NAME, for now */
1663 abbreviate = false;
1664 }
1665 else
1667
1668 /*
1669 * Unfortunately, it seems that abbreviation for non-C collations is
1670 * broken on many common platforms; see pg_strxfrm_enabled().
1671 *
1672 * Even apart from the risk of broken locales, it's possible that
1673 * there are platforms where the use of abbreviated keys should be
1674 * disabled at compile time. For example, macOS's strxfrm()
1675 * implementation is known to not effectively concentrate a
1676 * significant amount of entropy from the original string in earlier
1677 * transformed blobs. It's possible that other supported platforms
1678 * are similarly encumbered. So, if we ever get past disabling this
1679 * categorically, we may still want or need to disable it for
1680 * particular platforms.
1681 */
1683 abbreviate = false;
1684 }
1685
1686 /*
1687 * If we're using abbreviated keys, or if we're using a locale-aware
1688 * comparison, we need to initialize a VarStringSortSupport object. Both
1689 * cases will make use of the temporary buffers we initialize here for
1690 * scratch space (and to detect requirement for BpChar semantics from
1691 * caller), and the abbreviation case requires additional state.
1692 */
1693 if (abbreviate || !collate_c)
1694 {
1695 sss = palloc(sizeof(VarStringSortSupport));
1696 sss->buf1 = palloc(TEXTBUFLEN);
1697 sss->buflen1 = TEXTBUFLEN;
1698 sss->buf2 = palloc(TEXTBUFLEN);
1699 sss->buflen2 = TEXTBUFLEN;
1700 /* Start with invalid values */
1701 sss->last_len1 = -1;
1702 sss->last_len2 = -1;
1703 /* Initialize */
1704 sss->last_returned = 0;
1705 if (collate_c)
1706 sss->locale = NULL;
1707 else
1708 sss->locale = locale;
1709
1710 /*
1711 * To avoid somehow confusing a strxfrm() blob and an original string,
1712 * constantly keep track of the variety of data that buf1 and buf2
1713 * currently contain.
1714 *
1715 * Comparisons may be interleaved with conversion calls. Frequently,
1716 * conversions and comparisons are batched into two distinct phases,
1717 * but the correctness of caching cannot hinge upon this. For
1718 * comparison caching, buffer state is only trusted if cache_blob is
1719 * found set to false, whereas strxfrm() caching only trusts the state
1720 * when cache_blob is found set to true.
1721 *
1722 * Arbitrarily initialize cache_blob to true.
1723 */
1724 sss->cache_blob = true;
1725 sss->collate_c = collate_c;
1726 sss->typid = typid;
1727 ssup->ssup_extra = sss;
1728
1729 /*
1730 * If possible, plan to use the abbreviated keys optimization. The
1731 * core code may switch back to authoritative comparator should
1732 * abbreviation be aborted.
1733 */
1734 if (abbreviate)
1735 {
1736 sss->prop_card = 0.20;
1737 initHyperLogLog(&sss->abbr_card, 10);
1738 initHyperLogLog(&sss->full_card, 10);
1739 ssup->abbrev_full_comparator = ssup->comparator;
1743 }
1744 }
1745}
void initHyperLogLog(hyperLogLogState *cState, uint8 bwidth)
Definition: hyperloglog.c:66
bool pg_strxfrm_enabled(pg_locale_t locale)
Definition: pg_locale.c:1304
int(* comparator)(Datum x, Datum y, SortSupport ssup)
Definition: sortsupport.h:106
Datum(* abbrev_converter)(Datum original, SortSupport ssup)
Definition: sortsupport.h:172
int(* abbrev_full_comparator)(Datum x, Datum y, SortSupport ssup)
Definition: sortsupport.h:191
bool(* abbrev_abort)(int memtupcount, SortSupport ssup)
Definition: sortsupport.h:182
int ssup_datum_unsigned_cmp(Datum x, Datum y, SortSupport ssup)
Definition: tuplesort.c:3133
static bool varstr_abbrev_abort(int memtupcount, SortSupport ssup)
Definition: varlena.c:2170
static int varlenafastcmp_locale(Datum x, Datum y, SortSupport ssup)
Definition: varlena.c:1833
static int bpcharfastcmp_c(Datum x, Datum y, SortSupport ssup)
Definition: varlena.c:1788
static int namefastcmp_c(Datum x, Datum y, SortSupport ssup)
Definition: varlena.c:1821
static int namefastcmp_locale(Datum x, Datum y, SortSupport ssup)
Definition: varlena.c:1864
static Datum varstr_abbrev_convert(Datum original, SortSupport ssup)
Definition: varlena.c:1978
static int varstrfastcmp_c(Datum x, Datum y, SortSupport ssup)
Definition: varlena.c:1751
#define TEXTBUFLEN
Definition: varlena.c:117

References VarStringSortSupport::abbr_card, SortSupportData::abbrev_abort, SortSupportData::abbrev_converter, SortSupportData::abbrev_full_comparator, SortSupportData::abbreviate, bpcharfastcmp_c(), VarStringSortSupport::buf1, VarStringSortSupport::buf2, VarStringSortSupport::buflen1, VarStringSortSupport::buflen2, VarStringSortSupport::cache_blob, check_collation_set(), VarStringSortSupport::collate_c, collid, SortSupportData::comparator, VarStringSortSupport::full_card, initHyperLogLog(), VarStringSortSupport::last_len1, VarStringSortSupport::last_len2, VarStringSortSupport::last_returned, VarStringSortSupport::locale, locale, namefastcmp_c(), namefastcmp_locale(), palloc(), pg_newlocale_from_collation(), pg_strxfrm_enabled(), VarStringSortSupport::prop_card, ssup_datum_unsigned_cmp(), SortSupportData::ssup_extra, TEXTBUFLEN, VarStringSortSupport::typid, varlenafastcmp_locale(), varstr_abbrev_abort(), varstr_abbrev_convert(), and varstrfastcmp_c().

Referenced by bpchar_sortsupport(), btbpchar_pattern_sortsupport(), btnamesortsupport(), bttext_pattern_sortsupport(), bttextsortsupport(), and bytea_sortsupport().

◆ varstrfastcmp_c()

static int varstrfastcmp_c ( Datum  x,
Datum  y,
SortSupport  ssup 
)
static

Definition at line 1751 of file varlena.c.

1752{
1755 char *a1p,
1756 *a2p;
1757 int len1,
1758 len2,
1759 result;
1760
1761 a1p = VARDATA_ANY(arg1);
1762 a2p = VARDATA_ANY(arg2);
1763
1764 len1 = VARSIZE_ANY_EXHDR(arg1);
1765 len2 = VARSIZE_ANY_EXHDR(arg2);
1766
1767 result = memcmp(a1p, a2p, Min(len1, len2));
1768 if ((result == 0) && (len1 != len2))
1769 result = (len1 < len2) ? -1 : 1;
1770
1771 /* We can't afford to leak memory here. */
1772 if (PointerGetDatum(arg1) != x)
1773 pfree(arg1);
1774 if (PointerGetDatum(arg2) != y)
1775 pfree(arg2);
1776
1777 return result;
1778}

References DatumGetVarStringPP, Min, pfree(), PointerGetDatum(), VARDATA_ANY(), VARSIZE_ANY_EXHDR(), x, and y.

Referenced by varstr_sortsupport().

◆ varstrfastcmp_locale()

static int varstrfastcmp_locale ( char *  a1p,
int  len1,
char *  a2p,
int  len2,
SortSupport  ssup 
)
static

Definition at line 1878 of file varlena.c.

1879{
1881 int result;
1882 bool arg1_match;
1883
1884 /* Fast pre-check for equality, as discussed in varstr_cmp() */
1885 if (len1 == len2 && memcmp(a1p, a2p, len1) == 0)
1886 {
1887 /*
1888 * No change in buf1 or buf2 contents, so avoid changing last_len1 or
1889 * last_len2. Existing contents of buffers might still be used by
1890 * next call.
1891 *
1892 * It's fine to allow the comparison of BpChar padding bytes here,
1893 * even though that implies that the memcmp() will usually be
1894 * performed for BpChar callers (though multibyte characters could
1895 * still prevent that from occurring). The memcmp() is still very
1896 * cheap, and BpChar's funny semantics have us remove trailing spaces
1897 * (not limited to padding), so we need make no distinction between
1898 * padding space characters and "real" space characters.
1899 */
1900 return 0;
1901 }
1902
1903 if (sss->typid == BPCHAROID)
1904 {
1905 /* Get true number of bytes, ignoring trailing spaces */
1906 len1 = bpchartruelen(a1p, len1);
1907 len2 = bpchartruelen(a2p, len2);
1908 }
1909
1910 if (len1 >= sss->buflen1)
1911 {
1912 sss->buflen1 = Max(len1 + 1, Min(sss->buflen1 * 2, MaxAllocSize));
1913 sss->buf1 = repalloc(sss->buf1, sss->buflen1);
1914 }
1915 if (len2 >= sss->buflen2)
1916 {
1917 sss->buflen2 = Max(len2 + 1, Min(sss->buflen2 * 2, MaxAllocSize));
1918 sss->buf2 = repalloc(sss->buf2, sss->buflen2);
1919 }
1920
1921 /*
1922 * We're likely to be asked to compare the same strings repeatedly, and
1923 * memcmp() is so much cheaper than strcoll() that it pays to try to cache
1924 * comparisons, even though in general there is no reason to think that
1925 * that will work out (every string datum may be unique). Caching does
1926 * not slow things down measurably when it doesn't work out, and can speed
1927 * things up by rather a lot when it does. In part, this is because the
1928 * memcmp() compares data from cachelines that are needed in L1 cache even
1929 * when the last comparison's result cannot be reused.
1930 */
1931 arg1_match = true;
1932 if (len1 != sss->last_len1 || memcmp(sss->buf1, a1p, len1) != 0)
1933 {
1934 arg1_match = false;
1935 memcpy(sss->buf1, a1p, len1);
1936 sss->buf1[len1] = '\0';
1937 sss->last_len1 = len1;
1938 }
1939
1940 /*
1941 * If we're comparing the same two strings as last time, we can return the
1942 * same answer without calling strcoll() again. This is more likely than
1943 * it seems (at least with moderate to low cardinality sets), because
1944 * quicksort compares the same pivot against many values.
1945 */
1946 if (len2 != sss->last_len2 || memcmp(sss->buf2, a2p, len2) != 0)
1947 {
1948 memcpy(sss->buf2, a2p, len2);
1949 sss->buf2[len2] = '\0';
1950 sss->last_len2 = len2;
1951 }
1952 else if (arg1_match && !sss->cache_blob)
1953 {
1954 /* Use result cached following last actual strcoll() call */
1955 return sss->last_returned;
1956 }
1957
1958 result = pg_strcoll(sss->buf1, sss->buf2, sss->locale);
1959
1960 /* Break tie if necessary. */
1961 if (result == 0 && sss->locale->deterministic)
1962 result = strcmp(sss->buf1, sss->buf2);
1963
1964 /* Cache result, perhaps saving an expensive strcoll() call next time */
1965 sss->cache_blob = false;
1966 sss->last_returned = result;
1967 return result;
1968}
int pg_strcoll(const char *arg1, const char *arg2, pg_locale_t locale)
Definition: pg_locale.c:1270

References bpchartruelen(), VarStringSortSupport::buf1, VarStringSortSupport::buf2, VarStringSortSupport::buflen1, VarStringSortSupport::buflen2, VarStringSortSupport::cache_blob, pg_locale_struct::deterministic, if(), VarStringSortSupport::last_len1, VarStringSortSupport::last_len2, VarStringSortSupport::last_returned, VarStringSortSupport::locale, Max, MaxAllocSize, Min, pg_strcoll(), repalloc(), SortSupportData::ssup_extra, and VarStringSortSupport::typid.

Referenced by namefastcmp_locale(), and varlenafastcmp_locale().