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:1330
int errcode(int sqlerrcode)
Definition: elog.c:863
int errmsg(const char *fmt,...)
Definition: elog.c:1080
#define ERROR
Definition: elog.h:39

Definition at line 4732 of file varlena.c.

◆ CmpCall

#define CmpCall (   cmpfunc)
Value:
Datum DirectFunctionCall2Coll(PGFunction func, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:813
#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 2469 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 5272 of file varlena.c.

◆ TEXT_FORMAT_FLAG_MINUS

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

Definition at line 4730 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 3213 of file varlena.c.

3216{
3217 const char *p = VARDATA_ANY(replace_text);
3218 const char *p_end = p + VARSIZE_ANY_EXHDR(replace_text);
3219
3220 while (p < p_end)
3221 {
3222 const char *chunk_start = p;
3223 int so;
3224 int eo;
3225
3226 /* Find next escape char, if any. */
3227 p = memchr(p, '\\', p_end - p);
3228 if (p == NULL)
3229 p = p_end;
3230
3231 /* Copy the text we just scanned over, if any. */
3232 if (p > chunk_start)
3233 appendBinaryStringInfo(str, chunk_start, p - chunk_start);
3234
3235 /* Done if at end of string, else advance over escape char. */
3236 if (p >= p_end)
3237 break;
3238 p++;
3239
3240 if (p >= p_end)
3241 {
3242 /* Escape at very end of input. Treat same as unexpected char */
3244 break;
3245 }
3246
3247 if (*p >= '1' && *p <= '9')
3248 {
3249 /* Use the back reference of regexp. */
3250 int idx = *p - '0';
3251
3252 so = pmatch[idx].rm_so;
3253 eo = pmatch[idx].rm_eo;
3254 p++;
3255 }
3256 else if (*p == '&')
3257 {
3258 /* Use the entire matched string. */
3259 so = pmatch[0].rm_so;
3260 eo = pmatch[0].rm_eo;
3261 p++;
3262 }
3263 else if (*p == '\\')
3264 {
3265 /* \\ means transfer one \ to output. */
3267 p++;
3268 continue;
3269 }
3270 else
3271 {
3272 /*
3273 * If escape char is not followed by any expected char, just treat
3274 * it as ordinary data to copy. (XXX would it be better to throw
3275 * an error?)
3276 */
3278 continue;
3279 }
3280
3281 if (so >= 0 && eo >= 0)
3282 {
3283 /*
3284 * Copy the text that is back reference of regexp. Note so and eo
3285 * are counted in characters not bytes.
3286 */
3287 char *chunk_start;
3288 int chunk_len;
3289
3290 Assert(so >= data_pos);
3291 chunk_start = start_ptr;
3292 chunk_start += charlen_to_bytelen(chunk_start, so - data_pos);
3293 chunk_len = charlen_to_bytelen(chunk_start, eo - so);
3294 appendBinaryStringInfo(str, chunk_start, chunk_len);
3295 }
3296 }
3297}
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:3103

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 3873 of file varlena.c.

3874{
3876 char *fldsep = text_to_cstring(PG_GETARG_TEXT_PP(1));
3877
3878 PG_RETURN_TEXT_P(array_to_text_internal(fcinfo, v, fldsep, NULL));
3879}
#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:3915
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 3915 of file varlena.c.

3917{
3918 text *result;
3919 int nitems,
3920 *dims,
3921 ndims;
3922 Oid element_type;
3923 int typlen;
3924 bool typbyval;
3925 char typalign;
3927 bool printed = false;
3928 char *p;
3929 bits8 *bitmap;
3930 int bitmask;
3931 int i;
3932 ArrayMetaState *my_extra;
3933
3934 ndims = ARR_NDIM(v);
3935 dims = ARR_DIMS(v);
3936 nitems = ArrayGetNItems(ndims, dims);
3937
3938 /* if there are no elements, return an empty string */
3939 if (nitems == 0)
3940 return cstring_to_text_with_len("", 0);
3941
3942 element_type = ARR_ELEMTYPE(v);
3944
3945 /*
3946 * We arrange to look up info about element type, including its output
3947 * conversion proc, only once per series of calls, assuming the element
3948 * type doesn't change underneath us.
3949 */
3950 my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
3951 if (my_extra == NULL)
3952 {
3953 fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
3954 sizeof(ArrayMetaState));
3955 my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
3956 my_extra->element_type = ~element_type;
3957 }
3958
3959 if (my_extra->element_type != element_type)
3960 {
3961 /*
3962 * Get info about element type, including its output conversion proc
3963 */
3964 get_type_io_data(element_type, IOFunc_output,
3965 &my_extra->typlen, &my_extra->typbyval,
3966 &my_extra->typalign, &my_extra->typdelim,
3967 &my_extra->typioparam, &my_extra->typiofunc);
3968 fmgr_info_cxt(my_extra->typiofunc, &my_extra->proc,
3969 fcinfo->flinfo->fn_mcxt);
3970 my_extra->element_type = element_type;
3971 }
3972 typlen = my_extra->typlen;
3973 typbyval = my_extra->typbyval;
3974 typalign = my_extra->typalign;
3975
3976 p = ARR_DATA_PTR(v);
3977 bitmap = ARR_NULLBITMAP(v);
3978 bitmask = 1;
3979
3980 for (i = 0; i < nitems; i++)
3981 {
3982 Datum itemvalue;
3983 char *value;
3984
3985 /* Get source element, checking for NULL */
3986 if (bitmap && (*bitmap & bitmask) == 0)
3987 {
3988 /* if null_string is NULL, we just ignore null elements */
3989 if (null_string != NULL)
3990 {
3991 if (printed)
3992 appendStringInfo(&buf, "%s%s", fldsep, null_string);
3993 else
3994 appendStringInfoString(&buf, null_string);
3995 printed = true;
3996 }
3997 }
3998 else
3999 {
4000 itemvalue = fetch_att(p, typbyval, typlen);
4001
4002 value = OutputFunctionCall(&my_extra->proc, itemvalue);
4003
4004 if (printed)
4005 appendStringInfo(&buf, "%s%s", fldsep, value);
4006 else
4008 printed = true;
4009
4010 p = att_addlength_pointer(p, typlen, p);
4011 p = (char *) att_align_nominal(p, typalign);
4012 }
4013
4014 /* advance bitmap pointer if any */
4015 if (bitmap)
4016 {
4017 bitmask <<= 1;
4018 if (bitmask == 0x100)
4019 {
4020 bitmap++;
4021 bitmask = 1;
4022 }
4023 }
4024 }
4025
4026 result = cstring_to_text_with_len(buf.data, buf.len);
4027 pfree(buf.data);
4028
4029 return result;
4030}
#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:559
void fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
Definition: fmgr.c:138
char * OutputFunctionCall(FmgrInfo *flinfo, Datum val)
Definition: fmgr.c:1683
#define nitems(x)
Definition: indent.h:31
static struct @171 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:2490
@ 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[DEFAULT_XLOG_SEG_SIZE]
Definition: pg_test_fsync.c:71
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:706
#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 3889 of file varlena.c.

3890{
3891 ArrayType *v;
3892 char *fldsep;
3893 char *null_string;
3894
3895 /* returns NULL when first or second parameter is NULL */
3896 if (PG_ARGISNULL(0) || PG_ARGISNULL(1))
3898
3899 v = PG_GETARG_ARRAYTYPE_P(0);
3901
3902 /* NULL null string is passed through as a null pointer */
3903 if (!PG_ARGISNULL(2))
3904 null_string = text_to_cstring(PG_GETARG_TEXT_PP(2));
3905 else
3906 null_string = NULL;
3907
3908 PG_RETURN_TEXT_P(array_to_text_internal(fcinfo, v, fldsep, null_string));
3909}
#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 1799 of file varlena.c.

1800{
1801 BpChar *arg1 = DatumGetBpCharPP(x);
1802 BpChar *arg2 = DatumGetBpCharPP(y);
1803 char *a1p,
1804 *a2p;
1805 int len1,
1806 len2,
1807 result;
1808
1809 a1p = VARDATA_ANY(arg1);
1810 a2p = VARDATA_ANY(arg2);
1811
1812 len1 = bpchartruelen(a1p, VARSIZE_ANY_EXHDR(arg1));
1813 len2 = bpchartruelen(a2p, VARSIZE_ANY_EXHDR(arg2));
1814
1815 result = memcmp(a1p, a2p, Min(len1, len2));
1816 if ((result == 0) && (len1 != len2))
1817 result = (len1 < len2) ? -1 : 1;
1818
1819 /* We can't afford to leak memory here. */
1820 if (PointerGetDatum(arg1) != x)
1821 pfree(arg1);
1822 if (PointerGetDatum(arg2) != y)
1823 pfree(arg2);
1824
1825 return result;
1826}
#define Min(x, y)
Definition: c.h:1016
#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 2438 of file varlena.c.

2439{
2440 Name arg1 = PG_GETARG_NAME(0);
2441 text *arg2 = PG_GETARG_TEXT_PP(1);
2442 int32 result;
2443
2444 result = varstr_cmp(NameStr(*arg1), strlen(NameStr(*arg1)),
2445 VARDATA_ANY(arg2), VARSIZE_ANY_EXHDR(arg2),
2447
2448 PG_FREE_IF_COPY(arg2, 1);
2449
2450 PG_RETURN_INT32(result);
2451}
#define NameStr(name)
Definition: c.h:765
int32_t int32
Definition: c.h:548
#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:760
int varstr_cmp(const char *arg1, int len1, const char *arg2, int len2, Oid collid)
Definition: varlena.c:1308

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 2621 of file varlena.c.

2622{
2623 text *arg1 = PG_GETARG_TEXT_PP(0);
2624 text *arg2 = PG_GETARG_TEXT_PP(1);
2625 int result;
2626
2627 result = internal_text_pattern_compare(arg1, arg2);
2628
2629 PG_FREE_IF_COPY(arg1, 0);
2630 PG_FREE_IF_COPY(arg2, 1);
2631
2632 PG_RETURN_INT32(result);
2633}
static int internal_text_pattern_compare(text *arg1, text *arg2)
Definition: varlena.c:2535

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 2637 of file varlena.c.

2638{
2640 MemoryContext oldcontext;
2641
2642 oldcontext = MemoryContextSwitchTo(ssup->ssup_cxt);
2643
2644 /* Use generic string SortSupport, forcing "C" collation */
2645 varstr_sortsupport(ssup, TEXTOID, C_COLLATION_OID);
2646
2647 MemoryContextSwitchTo(oldcontext);
2648
2650}
#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:1626

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

◆ bttextcmp()

Datum bttextcmp ( PG_FUNCTION_ARGS  )

Definition at line 1584 of file varlena.c.

1585{
1586 text *arg1 = PG_GETARG_TEXT_PP(0);
1587 text *arg2 = PG_GETARG_TEXT_PP(1);
1588 int32 result;
1589
1590 result = text_cmp(arg1, arg2, PG_GET_COLLATION());
1591
1592 PG_FREE_IF_COPY(arg1, 0);
1593 PG_FREE_IF_COPY(arg2, 1);
1594
1595 PG_RETURN_INT32(result);
1596}
static int text_cmp(text *arg1, text *arg2, Oid collid)
Definition: varlena.c:1356

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 2454 of file varlena.c.

2455{
2456 text *arg1 = PG_GETARG_TEXT_PP(0);
2457 Name arg2 = PG_GETARG_NAME(1);
2458 int32 result;
2459
2460 result = varstr_cmp(VARDATA_ANY(arg1), VARSIZE_ANY_EXHDR(arg1),
2461 NameStr(*arg2), strlen(NameStr(*arg2)),
2463
2464 PG_FREE_IF_COPY(arg1, 0);
2465
2466 PG_RETURN_INT32(result);
2467}

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 1599 of file varlena.c.

1600{
1602 Oid collid = ssup->ssup_collation;
1603 MemoryContext oldcontext;
1604
1605 oldcontext = MemoryContextSwitchTo(ssup->ssup_cxt);
1606
1607 /* Use generic string SortSupport */
1608 varstr_sortsupport(ssup, TEXTOID, collid);
1609
1610 MemoryContextSwitchTo(oldcontext);
1611
1613}
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 2295 of file varlena.c.

2296{
2297 /* Oid opcintype = PG_GETARG_OID(0); */
2300
2302
2304
2305 PG_RETURN_BOOL(locale->deterministic);
2306}
#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:1186
static void check_collation_set(Oid collid)
Definition: varlena.c:1279

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 4491 of file varlena.c.

4492{
4493 FmgrInfo *foutcache;
4494 int i;
4495
4496 /* We keep the info in fn_mcxt so it survives across calls */
4497 foutcache = (FmgrInfo *) MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
4498 PG_NARGS() * sizeof(FmgrInfo));
4499
4500 for (i = argidx; i < PG_NARGS(); i++)
4501 {
4502 Oid valtype;
4503 Oid typOutput;
4504 bool typIsVarlena;
4505
4506 valtype = get_fn_expr_argtype(fcinfo->flinfo, i);
4507 if (!OidIsValid(valtype))
4508 elog(ERROR, "could not determine data type of concat() input");
4509
4510 getTypeOutputInfo(valtype, &typOutput, &typIsVarlena);
4511 fmgr_info_cxt(typOutput, &foutcache[i], fcinfo->flinfo->fn_mcxt);
4512 }
4513
4514 fcinfo->flinfo->fn_extra = foutcache;
4515
4516 return foutcache;
4517}
#define OidIsValid(objectId)
Definition: c.h:788
#define elog(elevel,...)
Definition: elog.h:226
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition: fmgr.c:1875
struct FmgrInfo FmgrInfo
#define PG_NARGS()
Definition: fmgr.h:203
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:3072
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:1549
int pg_mblen(const char *mbstr)
Definition: mbutils.c:1026

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 1279 of file varlena.c.

1280{
1281 if (!OidIsValid(collid))
1282 {
1283 /*
1284 * This typically means that the parser could not resolve a conflict
1285 * of implicit collations, so report it that way.
1286 */
1287 ereport(ERROR,
1288 (errcode(ERRCODE_INDETERMINATE_COLLATION),
1289 errmsg("could not determine which collation to use for string comparison"),
1290 errhint("Use the COLLATE clause to set the collation explicitly.")));
1291 }
1292}
#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 3180 of file varlena.c.

3181{
3182 int result = 0;
3183 const char *p = VARDATA_ANY(replace_text);
3184 const char *p_end = p + VARSIZE_ANY_EXHDR(replace_text);
3185
3186 while (p < p_end)
3187 {
3188 /* Find next escape char, if any. */
3189 p = memchr(p, '\\', p_end - p);
3190 if (p == NULL)
3191 break;
3192 p++;
3193 /* Note: a backslash at the end doesn't require extra processing. */
3194 if (p < p_end)
3195 {
3196 if (*p >= '1' && *p <= '9')
3197 return 2; /* Found a submatch specifier, so done */
3198 result = 1; /* Found some other sequence, keep looking */
3199 p++;
3200 }
3201 }
3202 return result;
3203}

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 4529 of file varlena.c.

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

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 4037 of file varlena.c.

4038{
4039 const char *digits = "0123456789abcdef";
4040
4041 /* We size the buffer for to_bin's longest possible return value. */
4042 char buf[sizeof(uint64) * BITS_PER_BYTE];
4043 char *const end = buf + sizeof(buf);
4044 char *ptr = end;
4045
4046 Assert(base > 1);
4047 Assert(base <= 16);
4048
4049 do
4050 {
4051 *--ptr = digits[value % base];
4052 value /= base;
4053 } while (ptr > buf && value);
4054
4055 return cstring_to_text_with_len(ptr, end - ptr);
4056}
uint64_t uint64
Definition: c.h:553
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_custom_stats_var_report(), 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:711
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 5350 of file varlena.c.

5351{
5352 Assert(state);
5353
5354 return state->match;
5355}
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 5579 of file varlena.c.

5580{
5581 if (c >= '0' && c <= '9')
5582 return c - '0';
5583 if (c >= 'a' && c <= 'f')
5584 return c - 'a' + 0xA;
5585 if (c >= 'A' && c <= 'F')
5586 return c - 'A' + 0xA;
5587 elog(ERROR, "invalid hexadecimal digit");
5588 return 0; /* not reached */
5589}
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 5595 of file varlena.c.

5596{
5597 unsigned int result = 0;
5598
5599 for (size_t i = 0; i < n; i++)
5600 result += hexval(instr[i]) << (4 * (n - i - 1));
5601
5602 return result;
5603}
static unsigned int hexval(unsigned char c)
Definition: varlena.c:5579

References hexval(), and i.

Referenced by unistr().

◆ icu_unicode_version()

Datum icu_unicode_version ( PG_FUNCTION_ARGS  )

Definition at line 5409 of file varlena.c.

5410{
5411#ifdef USE_ICU
5412 PG_RETURN_TEXT_P(cstring_to_text(U_UNICODE_VERSION));
5413#else
5415#endif
5416}
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 5295 of file varlena.c.

5296{
5297 Assert(state);
5298 Assert(max_d >= 0);
5299
5300 state->source = source;
5301 state->min_d = -1;
5302 state->max_d = max_d;
5303 state->match = NULL;
5304}
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 2535 of file varlena.c.

2536{
2537 int result;
2538 int len1,
2539 len2;
2540
2541 len1 = VARSIZE_ANY_EXHDR(arg1);
2542 len2 = VARSIZE_ANY_EXHDR(arg2);
2543
2544 result = memcmp(VARDATA_ANY(arg1), VARDATA_ANY(arg2), Min(len1, len2));
2545 if (result != 0)
2546 return result;
2547 else if (len1 < len2)
2548 return -1;
2549 else if (len1 > len2)
2550 return 1;
2551 else
2552 return 0;
2553}

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 5569 of file varlena.c.

5570{
5571 for (size_t i = 0; i < n; i++)
5572 if (!isxdigit((unsigned char) instr[i]))
5573 return false;
5574
5575 return true;
5576}

References i.

Referenced by unistr().

◆ makeStringAggState()

static StringInfo makeStringAggState ( FunctionCallInfo  fcinfo)
static

Definition at line 4269 of file varlena.c.

4270{
4272 MemoryContext aggcontext;
4273 MemoryContext oldcontext;
4274
4275 if (!AggCheckCallContext(fcinfo, &aggcontext))
4276 {
4277 /* cannot be called directly because of internal-type argument */
4278 elog(ERROR, "string_agg_transfn called in non-aggregate context");
4279 }
4280
4281 /*
4282 * Create state in aggregate context. It'll stay there across subsequent
4283 * calls.
4284 */
4285 oldcontext = MemoryContextSwitchTo(aggcontext);
4287 MemoryContextSwitchTo(oldcontext);
4288
4289 return state;
4290}
int AggCheckCallContext(FunctionCallInfo fcinfo, MemoryContext *aggcontext)
Definition: nodeAgg.c:4607
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 2680 of file varlena.c.

2681{
2682 Name s = PG_GETARG_NAME(0);
2683
2685}

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 2338 of file varlena.c.

2339{
2340 Name arg1 = PG_GETARG_NAME(0);
2341 text *arg2 = PG_GETARG_TEXT_PP(1);
2342 size_t len1 = strlen(NameStr(*arg1));
2343 size_t len2 = VARSIZE_ANY_EXHDR(arg2);
2345 bool result;
2346
2348
2349 if (collid == C_COLLATION_OID)
2350 result = (len1 == len2 &&
2351 memcmp(NameStr(*arg1), VARDATA_ANY(arg2), len1) == 0);
2352 else
2353 result = (varstr_cmp(NameStr(*arg1), len1,
2354 VARDATA_ANY(arg2), len2,
2355 collid) == 0);
2356
2357 PG_FREE_IF_COPY(arg2, 1);
2358
2359 PG_RETURN_BOOL(result);
2360}

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 1832 of file varlena.c.

1833{
1834 Name arg1 = DatumGetName(x);
1835 Name arg2 = DatumGetName(y);
1836
1837 return strncmp(NameStr(*arg1), NameStr(*arg2), NAMEDATALEN);
1838}
#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 1875 of file varlena.c.

1876{
1877 Name arg1 = DatumGetName(x);
1878 Name arg2 = DatumGetName(y);
1879
1880 return varstrfastcmp_locale(NameStr(*arg1), strlen(NameStr(*arg1)),
1881 NameStr(*arg2), strlen(NameStr(*arg2)),
1882 ssup);
1883}
static int varstrfastcmp_locale(char *a1p, int len1, char *a2p, int len2, SortSupport ssup)
Definition: varlena.c:1889

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

Referenced by varstr_sortsupport().

◆ namegetext()

Datum namegetext ( PG_FUNCTION_ARGS  )

Definition at line 2494 of file varlena.c.

2495{
2497}
#define CmpCall(cmpfunc)
Definition: varlena.c:2469
Datum btnametextcmp(PG_FUNCTION_ARGS)
Definition: varlena.c:2438

References btnametextcmp(), CmpCall, and PG_RETURN_BOOL.

◆ namegttext()

Datum namegttext ( PG_FUNCTION_ARGS  )

Definition at line 2488 of file varlena.c.

2489{
2491}

References btnametextcmp(), CmpCall, and PG_RETURN_BOOL.

◆ nameletext()

Datum nameletext ( PG_FUNCTION_ARGS  )

Definition at line 2482 of file varlena.c.

2483{
2485}

References btnametextcmp(), CmpCall, and PG_RETURN_BOOL.

◆ namelttext()

Datum namelttext ( PG_FUNCTION_ARGS  )

Definition at line 2476 of file varlena.c.

2477{
2479}

References btnametextcmp(), CmpCall, and PG_RETURN_BOOL.

◆ namenetext()

Datum namenetext ( PG_FUNCTION_ARGS  )

Definition at line 2388 of file varlena.c.

2389{
2390 Name arg1 = PG_GETARG_NAME(0);
2391 text *arg2 = PG_GETARG_TEXT_PP(1);
2392 size_t len1 = strlen(NameStr(*arg1));
2393 size_t len2 = VARSIZE_ANY_EXHDR(arg2);
2395 bool result;
2396
2398
2399 if (collid == C_COLLATION_OID)
2400 result = !(len1 == len2 &&
2401 memcmp(NameStr(*arg1), VARDATA_ANY(arg2), len1) == 0);
2402 else
2403 result = !(varstr_cmp(NameStr(*arg1), len1,
2404 VARDATA_ANY(arg2), len2,
2405 collid) == 0);
2406
2407 PG_FREE_IF_COPY(arg2, 1);
2408
2409 PG_RETURN_BOOL(result);
2410}

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 4168 of file varlena.c.

4169{
4170 int typlen;
4171 char *result;
4172 ToastCompressionId cmid;
4173
4174 /* On first call, get the input type's typlen, and save at *fn_extra */
4175 if (fcinfo->flinfo->fn_extra == NULL)
4176 {
4177 /* Lookup the datatype of the supplied argument */
4178 Oid argtypeid = get_fn_expr_argtype(fcinfo->flinfo, 0);
4179
4180 typlen = get_typlen(argtypeid);
4181 if (typlen == 0) /* should not happen */
4182 elog(ERROR, "cache lookup failed for type %u", argtypeid);
4183
4184 fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
4185 sizeof(int));
4186 *((int *) fcinfo->flinfo->fn_extra) = typlen;
4187 }
4188 else
4189 typlen = *((int *) fcinfo->flinfo->fn_extra);
4190
4191 if (typlen != -1)
4193
4194 /* get the compression method id stored in the compressed varlena */
4195 cmid = toast_get_compression_id((struct varlena *)
4197 if (cmid == TOAST_INVALID_COMPRESSION_ID)
4199
4200 /* convert compression method id to compression method name */
4201 switch (cmid)
4202 {
4204 result = "pglz";
4205 break;
4207 result = "lz4";
4208 break;
4209 default:
4210 elog(ERROR, "invalid compression method id %d", cmid);
4211 }
4212
4214}
int16 get_typlen(Oid typid)
Definition: lsyscache.c:2362
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 4121 of file varlena.c.

4122{
4124 int32 result;
4125 int typlen;
4126
4127 /* On first call, get the input type's typlen, and save at *fn_extra */
4128 if (fcinfo->flinfo->fn_extra == NULL)
4129 {
4130 /* Lookup the datatype of the supplied argument */
4131 Oid argtypeid = get_fn_expr_argtype(fcinfo->flinfo, 0);
4132
4133 typlen = get_typlen(argtypeid);
4134 if (typlen == 0) /* should not happen */
4135 elog(ERROR, "cache lookup failed for type %u", argtypeid);
4136
4137 fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
4138 sizeof(int));
4139 *((int *) fcinfo->flinfo->fn_extra) = typlen;
4140 }
4141 else
4142 typlen = *((int *) fcinfo->flinfo->fn_extra);
4143
4144 if (typlen == -1)
4145 {
4146 /* varlena type, possibly toasted */
4147 result = toast_datum_size(value);
4148 }
4149 else if (typlen == -2)
4150 {
4151 /* cstring */
4152 result = strlen(DatumGetCString(value)) + 1;
4153 }
4154 else
4155 {
4156 /* ordinary fixed-width type */
4157 result = typlen;
4158 }
4159
4160 PG_RETURN_INT32(result);
4161}
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 4221 of file varlena.c.

4222{
4223 int typlen;
4224 struct varlena *attr;
4225 struct varatt_external toast_pointer;
4226
4227 /* On first call, get the input type's typlen, and save at *fn_extra */
4228 if (fcinfo->flinfo->fn_extra == NULL)
4229 {
4230 /* Lookup the datatype of the supplied argument */
4231 Oid argtypeid = get_fn_expr_argtype(fcinfo->flinfo, 0);
4232
4233 typlen = get_typlen(argtypeid);
4234 if (typlen == 0) /* should not happen */
4235 elog(ERROR, "cache lookup failed for type %u", argtypeid);
4236
4237 fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
4238 sizeof(int));
4239 *((int *) fcinfo->flinfo->fn_extra) = typlen;
4240 }
4241 else
4242 typlen = *((int *) fcinfo->flinfo->fn_extra);
4243
4244 if (typlen != -1)
4246
4247 attr = (struct varlena *) DatumGetPointer(PG_GETARG_DATUM(0));
4248
4249 if (!VARATT_IS_EXTERNAL_ONDISK(attr))
4251
4252 VARATT_EXTERNAL_GET_POINTER(toast_pointer, attr);
4253
4254 PG_RETURN_OID(toast_pointer.va_valueid);
4255}
#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 3103 of file varlena.c.

3104{
3105 text *src_text = PG_GETARG_TEXT_PP(0);
3106 text *from_sub_text = PG_GETARG_TEXT_PP(1);
3107 text *to_sub_text = PG_GETARG_TEXT_PP(2);
3108 int src_text_len;
3109 int from_sub_text_len;
3111 text *ret_text;
3112 int chunk_len;
3113 char *curr_ptr;
3114 char *start_ptr;
3116 bool found;
3117
3118 src_text_len = VARSIZE_ANY_EXHDR(src_text);
3119 from_sub_text_len = VARSIZE_ANY_EXHDR(from_sub_text);
3120
3121 /* Return unmodified source string if empty source or pattern */
3122 if (src_text_len < 1 || from_sub_text_len < 1)
3123 {
3124 PG_RETURN_TEXT_P(src_text);
3125 }
3126
3127 text_position_setup(src_text, from_sub_text, PG_GET_COLLATION(), &state);
3128
3129 found = text_position_next(&state);
3130
3131 /* When the from_sub_text is not found, there is nothing to do. */
3132 if (!found)
3133 {
3135 PG_RETURN_TEXT_P(src_text);
3136 }
3138 start_ptr = VARDATA_ANY(src_text);
3139
3141
3142 do
3143 {
3145
3146 /* copy the data skipped over by last text_position_next() */
3147 chunk_len = curr_ptr - start_ptr;
3148 appendBinaryStringInfo(&str, start_ptr, chunk_len);
3149
3150 appendStringInfoText(&str, to_sub_text);
3151
3152 start_ptr = curr_ptr + state.last_match_len;
3153
3154 found = text_position_next(&state);
3155 if (found)
3157 }
3158 while (found);
3159
3160 /* copy trailing data */
3161 chunk_len = ((char *) src_text + VARSIZE_ANY(src_text)) - start_ptr;
3162 appendBinaryStringInfo(&str, start_ptr, chunk_len);
3163
3165
3166 ret_text = cstring_to_text_with_len(str.data, str.len);
3167 pfree(str.data);
3168
3169 PG_RETURN_TEXT_P(ret_text);
3170}
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:123
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:1272
static void appendStringInfoText(StringInfo str, const text *t)
Definition: varlena.c:3089
static char * text_position_get_match_ptr(TextPositionState *state)
Definition: varlena.c:1237
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 3313 of file varlena.c.

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

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 5259 of file varlena.c.

5260{
5261 while (len > 0)
5262 {
5263 len--;
5264 if (s1[len] != s2[len])
5265 return false;
5266 }
5267 return true;
5268}
char * s1
char * s2

References len, s1, and s2.

Referenced by varstr_levenshtein().

◆ split_part()

Datum split_part ( PG_FUNCTION_ARGS  )

Definition at line 3475 of file varlena.c.

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

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 3698 of file varlena.c.

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

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 3834 of file varlena.c.

3838{
3839 bool is_null = false;
3840
3841 if (null_string && text_isequal(field_value, null_string, collation))
3842 is_null = true;
3843
3844 if (tstate->tupstore)
3845 {
3846 Datum values[1];
3847 bool nulls[1];
3848
3849 values[0] = PointerGetDatum(field_value);
3850 nulls[0] = is_null;
3851
3853 tstate->tupdesc,
3854 values,
3855 nulls);
3856 }
3857 else
3858 {
3859 tstate->astate = accumArrayResult(tstate->astate,
3860 PointerGetDatum(field_value),
3861 is_null,
3862 TEXTOID,
3864 }
3865}
ArrayBuildState * accumArrayResult(ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
Definition: arrayfuncs.c:5351
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:3607

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 2882 of file varlena.c.

2884{
2885 char *nextp = rawstring;
2886 bool done = false;
2887
2888 *namelist = NIL;
2889
2890 while (scanner_isspace(*nextp))
2891 nextp++; /* skip leading whitespace */
2892
2893 if (*nextp == '\0')
2894 return true; /* empty string represents empty list */
2895
2896 /* At the top of the loop, we are at start of a new directory. */
2897 do
2898 {
2899 char *curname;
2900 char *endp;
2901
2902 if (*nextp == '"')
2903 {
2904 /* Quoted name --- collapse quote-quote pairs */
2905 curname = nextp + 1;
2906 for (;;)
2907 {
2908 endp = strchr(nextp + 1, '"');
2909 if (endp == NULL)
2910 return false; /* mismatched quotes */
2911 if (endp[1] != '"')
2912 break; /* found end of quoted name */
2913 /* Collapse adjacent quotes into one quote, and look again */
2914 memmove(endp, endp + 1, strlen(endp));
2915 nextp = endp;
2916 }
2917 /* endp now points at the terminating quote */
2918 nextp = endp + 1;
2919 }
2920 else
2921 {
2922 /* Unquoted name --- extends to separator or end of string */
2923 curname = endp = nextp;
2924 while (*nextp && *nextp != separator)
2925 {
2926 /* trailing whitespace should not be included in name */
2927 if (!scanner_isspace(*nextp))
2928 endp = nextp + 1;
2929 nextp++;
2930 }
2931 if (curname == endp)
2932 return false; /* empty unquoted name not allowed */
2933 }
2934
2935 while (scanner_isspace(*nextp))
2936 nextp++; /* skip trailing whitespace */
2937
2938 if (*nextp == separator)
2939 {
2940 nextp++;
2941 while (scanner_isspace(*nextp))
2942 nextp++; /* skip leading whitespace for next */
2943 /* we expect another name, so done remains false */
2944 }
2945 else if (*nextp == '\0')
2946 done = true;
2947 else
2948 return false; /* invalid syntax */
2949
2950 /* Now safe to overwrite separator with a null */
2951 *endp = '\0';
2952
2953 /* Truncate path if it's overlength */
2954 if (strlen(curname) >= MAXPGPATH)
2955 curname[MAXPGPATH - 1] = '\0';
2956
2957 /*
2958 * Finished isolating current name --- add it to list
2959 */
2960 curname = pstrdup(curname);
2961 canonicalize_path(curname);
2962 *namelist = lappend(*namelist, curname);
2963
2964 /* Loop back if we didn't reach end of string */
2965 } while (!done);
2966
2967 return true;
2968}
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 3003 of file varlena.c.

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

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 2755 of file varlena.c.

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

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

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 4429 of file varlena.c.

4430{
4431 bytea *sstate;
4432 StringInfo result;
4434 char *data;
4435 int datalen;
4436
4437 /* cannot be called directly because of internal-type argument */
4438 Assert(AggCheckCallContext(fcinfo, NULL));
4439
4440 sstate = PG_GETARG_BYTEA_PP(0);
4441
4442 /*
4443 * Initialize a StringInfo so that we can "receive" it using the standard
4444 * recv-function infrastructure.
4445 */
4447 VARSIZE_ANY_EXHDR(sstate));
4448
4449 result = makeStringAggState(fcinfo);
4450
4451 /* cursor */
4452 result->cursor = pq_getmsgint(&buf, 4);
4453
4454 /* data */
4455 datalen = VARSIZE_ANY_EXHDR(sstate) - 4;
4456 data = (char *) pq_getmsgbytes(&buf, datalen);
4457 appendBinaryStringInfo(result, data, datalen);
4458
4459 pq_getmsgend(&buf);
4460
4461 PG_RETURN_POINTER(result);
4462}
#define PG_GETARG_BYTEA_PP(n)
Definition: fmgr.h:308
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:414
void pq_getmsgend(StringInfo msg)
Definition: pqformat.c:634
const char * pq_getmsgbytes(StringInfo msg, int datalen)
Definition: pqformat.c:507
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 4465 of file varlena.c.

4466{
4468
4469 /* cannot be called directly because of internal-type argument */
4470 Assert(AggCheckCallContext(fcinfo, NULL));
4471
4473
4474 if (state != NULL)
4475 {
4476 /* As per comment in transfn, strip data before the cursor position */
4478 state->len - state->cursor));
4479 }
4480 else
4482}

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 4398 of file varlena.c.

4399{
4402 bytea *result;
4403
4404 /* cannot be called directly because of internal-type argument */
4405 Assert(AggCheckCallContext(fcinfo, NULL));
4406
4408
4410
4411 /* cursor */
4412 pq_sendint(&buf, state->cursor, 4);
4413
4414 /* data */
4415 pq_sendbytes(&buf, state->data, state->len);
4416
4417 result = pq_endtypsend(&buf);
4418
4419 PG_RETURN_BYTEA_P(result);
4420}
#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:325
bytea * pq_endtypsend(StringInfo buf)
Definition: pqformat.c:345
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 4293 of file varlena.c.

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

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 1356 of file varlena.c.

1357{
1358 char *a1p,
1359 *a2p;
1360 int len1,
1361 len2;
1362
1363 a1p = VARDATA_ANY(arg1);
1364 a2p = VARDATA_ANY(arg2);
1365
1366 len1 = VARSIZE_ANY_EXHDR(arg1);
1367 len2 = VARSIZE_ANY_EXHDR(arg2);
1368
1369 return varstr_cmp(a1p, len1, a2p, len2, collid);
1370}

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 4609 of file varlena.c.

4610{
4611 text *result;
4612
4613 result = concat_internal("", 0, fcinfo);
4614 if (result == NULL)
4616 PG_RETURN_TEXT_P(result);
4617}
static text * concat_internal(const char *sepstr, int argidx, FunctionCallInfo fcinfo)
Definition: varlena.c:4529

References concat_internal(), PG_RETURN_NULL, and PG_RETURN_TEXT_P.

◆ text_concat_ws()

Datum text_concat_ws ( PG_FUNCTION_ARGS  )

Definition at line 4624 of file varlena.c.

4625{
4626 char *sep;
4627 text *result;
4628
4629 /* return NULL when separator is NULL */
4630 if (PG_ARGISNULL(0))
4633
4634 result = concat_internal(sep, 1, fcinfo);
4635 if (result == NULL)
4637 PG_RETURN_TEXT_P(result);
4638}

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 4745 of file varlena.c.

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

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 5197 of file varlena.c.

5199{
5200 bool align_to_left = false;
5201 int len;
5202
5203 /* fast path for typical easy case */
5204 if (width == 0)
5205 {
5207 return;
5208 }
5209
5210 if (width < 0)
5211 {
5212 /* Negative width: implicit '-' flag, then take absolute value */
5213 align_to_left = true;
5214 /* -INT_MIN is undefined */
5215 if (width <= INT_MIN)
5216 ereport(ERROR,
5217 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
5218 errmsg("number is out of range")));
5219 width = -width;
5220 }
5221 else if (flags & TEXT_FORMAT_FLAG_MINUS)
5222 align_to_left = true;
5223
5224 len = pg_mbstrlen(str);
5225 if (align_to_left)
5226 {
5227 /* left justify */
5229 if (len < width)
5230 appendStringInfoSpaces(buf, width - len);
5231 }
5232 else
5233 {
5234 /* right justify */
5235 if (len < width)
5236 appendStringInfoSpaces(buf, width - len);
5238 }
5239}
int pg_mbstrlen(const char *mbstr)
Definition: mbutils.c:1040
void appendStringInfoSpaces(StringInfo str, int count)
Definition: stringinfo.c:260
#define TEXT_FORMAT_FLAG_MINUS
Definition: varlena.c:4730

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 5249 of file varlena.c.

5250{
5251 return text_format(fcinfo);
5252}
Datum text_format(PG_FUNCTION_ARGS)
Definition: varlena.c:4745

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 5022 of file varlena.c.

5023{
5024 bool found = false;
5025 const char *cp = *ptr;
5026 int val = 0;
5027
5028 while (*cp >= '0' && *cp <= '9')
5029 {
5030 int8 digit = (*cp - '0');
5031
5032 if (unlikely(pg_mul_s32_overflow(val, 10, &val)) ||
5034 ereport(ERROR,
5035 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
5036 errmsg("number is out of range")));
5037 ADVANCE_PARSE_POINTER(cp, end_ptr);
5038 found = true;
5039 }
5040
5041 *ptr = cp;
5042 *value = val;
5043
5044 return found;
5045}
int8_t int8
Definition: c.h:546
#define unlikely(x)
Definition: c.h:418
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 5071 of file varlena.c.

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

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 5148 of file varlena.c.

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

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 1530 of file varlena.c.

1531{
1532 text *arg1 = PG_GETARG_TEXT_PP(0);
1533 text *arg2 = PG_GETARG_TEXT_PP(1);
1534 bool result;
1535
1536 result = (text_cmp(arg1, arg2, PG_GET_COLLATION()) >= 0);
1537
1538 PG_FREE_IF_COPY(arg1, 0);
1539 PG_FREE_IF_COPY(arg2, 1);
1540
1541 PG_RETURN_BOOL(result);
1542}

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 1515 of file varlena.c.

1516{
1517 text *arg1 = PG_GETARG_TEXT_PP(0);
1518 text *arg2 = PG_GETARG_TEXT_PP(1);
1519 bool result;
1520
1521 result = (text_cmp(arg1, arg2, PG_GET_COLLATION()) > 0);
1522
1523 PG_FREE_IF_COPY(arg1, 0);
1524 PG_FREE_IF_COPY(arg2, 1);
1525
1526 PG_RETURN_BOOL(result);
1527}

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 3607 of file varlena.c.

3608{
3610 collid,
3611 PointerGetDatum(txt1),
3612 PointerGetDatum(txt2)));
3613}
static bool DatumGetBool(Datum X)
Definition: postgres.h:100
Datum texteq(PG_FUNCTION_ARGS)
Definition: varlena.c:1381

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

Referenced by split_text_accum_result().

◆ text_larger()

Datum text_larger ( PG_FUNCTION_ARGS  )

Definition at line 2309 of file varlena.c.

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

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 1500 of file varlena.c.

1501{
1502 text *arg1 = PG_GETARG_TEXT_PP(0);
1503 text *arg2 = PG_GETARG_TEXT_PP(1);
1504 bool result;
1505
1506 result = (text_cmp(arg1, arg2, PG_GET_COLLATION()) <= 0);
1507
1508 PG_FREE_IF_COPY(arg1, 0);
1509 PG_FREE_IF_COPY(arg2, 1);
1510
1511 PG_RETURN_BOOL(result);
1512}

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 4645 of file varlena.c.

4646{
4647 int n = PG_GETARG_INT32(1);
4648
4649 if (n < 0)
4650 {
4652 const char *p = VARDATA_ANY(str);
4653 int len = VARSIZE_ANY_EXHDR(str);
4654 int rlen;
4655
4656 n = pg_mbstrlen_with_len(p, len) + n;
4657 rlen = pg_mbcharcliplen(p, len, n);
4659 }
4660 else
4662}
int pg_mbstrlen_with_len(const char *mbstr, int limit)
Definition: mbutils.c:1060
int pg_mbcharcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:1128
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 1485 of file varlena.c.

1486{
1487 text *arg1 = PG_GETARG_TEXT_PP(0);
1488 text *arg2 = PG_GETARG_TEXT_PP(1);
1489 bool result;
1490
1491 result = (text_cmp(arg1, arg2, PG_GET_COLLATION()) < 0);
1492
1493 PG_FREE_IF_COPY(arg1, 0);
1494 PG_FREE_IF_COPY(arg2, 1);
1495
1496 PG_RETURN_BOOL(result);
1497}

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 2657 of file varlena.c.

2658{
2659 text *s = PG_GETARG_TEXT_PP(0);
2660 Name result;
2661 int len;
2662
2664
2665 /* Truncate oversize input */
2666 if (len >= NAMEDATALEN)
2668
2669 /* We use palloc0 here to ensure result is zero-padded */
2670 result = (Name) palloc0(NAMEDATALEN);
2671 memcpy(NameStr(*result), VARDATA_ANY(s), len);
2672
2673 PG_RETURN_NAME(result);
2674}
NameData * Name
Definition: c.h:763
#define PG_RETURN_NAME(x)
Definition: fmgr.h:363
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:1086
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 2589 of file varlena.c.

2590{
2591 text *arg1 = PG_GETARG_TEXT_PP(0);
2592 text *arg2 = PG_GETARG_TEXT_PP(1);
2593 int result;
2594
2595 result = internal_text_pattern_compare(arg1, arg2);
2596
2597 PG_FREE_IF_COPY(arg1, 0);
2598 PG_FREE_IF_COPY(arg2, 1);
2599
2600 PG_RETURN_BOOL(result >= 0);
2601}

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 2605 of file varlena.c.

2606{
2607 text *arg1 = PG_GETARG_TEXT_PP(0);
2608 text *arg2 = PG_GETARG_TEXT_PP(1);
2609 int result;
2610
2611 result = internal_text_pattern_compare(arg1, arg2);
2612
2613 PG_FREE_IF_COPY(arg1, 0);
2614 PG_FREE_IF_COPY(arg2, 1);
2615
2616 PG_RETURN_BOOL(result > 0);
2617}

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 2573 of file varlena.c.

2574{
2575 text *arg1 = PG_GETARG_TEXT_PP(0);
2576 text *arg2 = PG_GETARG_TEXT_PP(1);
2577 int result;
2578
2579 result = internal_text_pattern_compare(arg1, arg2);
2580
2581 PG_FREE_IF_COPY(arg1, 0);
2582 PG_FREE_IF_COPY(arg2, 1);
2583
2584 PG_RETURN_BOOL(result <= 0);
2585}

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 2557 of file varlena.c.

2558{
2559 text *arg1 = PG_GETARG_TEXT_PP(0);
2560 text *arg2 = PG_GETARG_TEXT_PP(1);
2561 int result;
2562
2563 result = internal_text_pattern_compare(arg1, arg2);
2564
2565 PG_FREE_IF_COPY(arg1, 0);
2566 PG_FREE_IF_COPY(arg2, 1);
2567
2568 PG_RETURN_BOOL(result < 0);
2569}

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:1248

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 1272 of file varlena.c.

1273{
1274 /* no cleanup needed */
1275}

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 1248 of file varlena.c.

1249{
1250 /* Convert the byte position to char position. */
1251 state->refpos += pg_mbstrlen_with_len(state->refpoint,
1252 state->last_match - state->refpoint);
1253 state->refpoint = state->last_match;
1254 return state->refpos + 1;
1255}

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 1237 of file varlena.c.

1238{
1239 return state->last_match;
1240}

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

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 1264 of file varlena.c.

1265{
1266 state->last_match = NULL;
1267 state->refpoint = state->str1;
1268 state->refpos = 0;
1269}

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:1264
@ 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 4690 of file varlena.c.

4691{
4693 const char *p = VARDATA_ANY(str);
4694 int len = VARSIZE_ANY_EXHDR(str);
4695 const char *endp = p + len;
4696 text *result;
4697 char *dst;
4698
4699 result = palloc(len + VARHDRSZ);
4700 dst = (char *) VARDATA(result) + len;
4701 SET_VARSIZE(result, len + VARHDRSZ);
4702
4704 {
4705 /* multibyte version */
4706 while (p < endp)
4707 {
4708 int sz;
4709
4710 sz = pg_mblen(p);
4711 dst -= sz;
4712 memcpy(dst, p, sz);
4713 p += sz;
4714 }
4715 }
4716 else
4717 {
4718 /* single byte version */
4719 while (p < endp)
4720 *(--dst) = *p++;
4721 }
4722
4723 PG_RETURN_TEXT_P(result);
4724}

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 4669 of file varlena.c.

4670{
4672 const char *p = VARDATA_ANY(str);
4673 int len = VARSIZE_ANY_EXHDR(str);
4674 int n = PG_GETARG_INT32(1);
4675 int off;
4676
4677 if (n < 0)
4678 n = -n;
4679 else
4680 n = pg_mbstrlen_with_len(p, len) - n;
4681 off = pg_mbcharcliplen(p, len, n);
4682
4684}

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 2321 of file varlena.c.

2322{
2323 text *arg1 = PG_GETARG_TEXT_PP(0);
2324 text *arg2 = PG_GETARG_TEXT_PP(1);
2325 text *result;
2326
2327 result = ((text_cmp(arg1, arg2, PG_GET_COLLATION()) < 0) ? arg1 : arg2);
2328
2329 PG_RETURN_TEXT_P(result);
2330}

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 1545 of file varlena.c.

1546{
1547 Datum arg1 = PG_GETARG_DATUM(0);
1548 Datum arg2 = PG_GETARG_DATUM(1);
1550 pg_locale_t mylocale;
1551 bool result;
1552 Size len1,
1553 len2;
1554
1556
1558
1559 if (!mylocale->deterministic)
1560 ereport(ERROR,
1561 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1562 errmsg("nondeterministic collations are not supported for substring searches")));
1563
1564 len1 = toast_raw_datum_size(arg1);
1565 len2 = toast_raw_datum_size(arg2);
1566 if (len2 > len1)
1567 result = false;
1568 else
1569 {
1570 text *targ1 = text_substring(arg1, 1, len2, false);
1571 text *targ2 = DatumGetTextPP(arg2);
1572
1573 result = (memcmp(VARDATA_ANY(targ1), VARDATA_ANY(targ2),
1574 VARSIZE_ANY_EXHDR(targ2)) == 0);
1575
1576 PG_FREE_IF_COPY(targ1, 0);
1577 PG_FREE_IF_COPY(targ2, 1);
1578 }
1579
1580 PG_RETURN_BOOL(result);
1581}
size_t Size
Definition: c.h:624

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:1010
#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 3621 of file varlena.c.

3622{
3623 SplitTextOutputData tstate;
3624
3625 /* For array output, tstate should start as all zeroes */
3626 memset(&tstate, 0, sizeof(tstate));
3627
3628 if (!split_text(fcinfo, &tstate))
3630
3631 if (tstate.astate == NULL)
3633
3636}
#define PG_RETURN_ARRAYTYPE_P(x)
Definition: array.h:265
ArrayType * construct_empty_array(Oid elmtype)
Definition: arrayfuncs.c:3581
Datum makeArrayResult(ArrayBuildState *astate, MemoryContext rcontext)
Definition: arrayfuncs.c:5421
#define PG_RETURN_DATUM(x)
Definition: fmgr.h:353
static bool split_text(FunctionCallInfo fcinfo, SplitTextOutputData *tstate)
Definition: varlena.c:3698

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 3647 of file varlena.c.

3648{
3649 return text_to_array(fcinfo);
3650}
Datum text_to_array(PG_FUNCTION_ARGS)
Definition: varlena.c:3621

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:1243
struct varlena * pg_detoast_datum_packed(struct varlena *datum)
Definition: fmgr.c:1829

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_attach_func(), injection_points_cached(), injection_points_detach(), injection_points_load(), injection_points_run(), 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_publication_sequences(), 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_custom_stats_var_create(), test_custom_stats_var_drop(), test_custom_stats_var_report(), test_custom_stats_var_update(), 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 3658 of file varlena.c.

3659{
3660 ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
3661 SplitTextOutputData tstate;
3662
3663 tstate.astate = NULL;
3665 tstate.tupstore = rsi->setResult;
3666 tstate.tupdesc = rsi->setDesc;
3667
3668 (void) split_text(fcinfo, &tstate);
3669
3670 return (Datum) 0;
3671}
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 3682 of file varlena.c.

3683{
3684 return text_to_table(fcinfo);
3685}
Datum text_to_table(PG_FUNCTION_ARGS)
Definition: varlena.c:3658

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 1381 of file varlena.c.

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

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 2363 of file varlena.c.

2364{
2365 text *arg1 = PG_GETARG_TEXT_PP(0);
2366 Name arg2 = PG_GETARG_NAME(1);
2367 size_t len1 = VARSIZE_ANY_EXHDR(arg1);
2368 size_t len2 = strlen(NameStr(*arg2));
2370 bool result;
2371
2373
2374 if (collid == C_COLLATION_OID)
2375 result = (len1 == len2 &&
2376 memcmp(VARDATA_ANY(arg1), NameStr(*arg2), len1) == 0);
2377 else
2378 result = (varstr_cmp(VARDATA_ANY(arg1), len1,
2379 NameStr(*arg2), len2,
2380 collid) == 0);
2381
2382 PG_FREE_IF_COPY(arg1, 0);
2383
2384 PG_RETURN_BOOL(result);
2385}

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 2518 of file varlena.c.

2519{
2521}
Datum bttextnamecmp(PG_FUNCTION_ARGS)
Definition: varlena.c:2454

References bttextnamecmp(), CmpCall, and PG_RETURN_BOOL.

◆ textgtname()

Datum textgtname ( PG_FUNCTION_ARGS  )

Definition at line 2512 of file varlena.c.

2513{
2515}

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 2506 of file varlena.c.

2507{
2509}

References bttextnamecmp(), CmpCall, and PG_RETURN_BOOL.

◆ textltname()

Datum textltname ( PG_FUNCTION_ARGS  )

Definition at line 2500 of file varlena.c.

2501{
2503}

References bttextnamecmp(), CmpCall, and PG_RETURN_BOOL.

◆ textne()

Datum textne ( PG_FUNCTION_ARGS  )

Definition at line 1436 of file varlena.c.

1437{
1439 pg_locale_t mylocale;
1440 bool result;
1441
1443
1445
1446 if (mylocale->deterministic)
1447 {
1448 Datum arg1 = PG_GETARG_DATUM(0);
1449 Datum arg2 = PG_GETARG_DATUM(1);
1450 Size len1,
1451 len2;
1452
1453 /* See comment in texteq() */
1454 len1 = toast_raw_datum_size(arg1);
1455 len2 = toast_raw_datum_size(arg2);
1456 if (len1 != len2)
1457 result = true;
1458 else
1459 {
1460 text *targ1 = DatumGetTextPP(arg1);
1461 text *targ2 = DatumGetTextPP(arg2);
1462
1463 result = (memcmp(VARDATA_ANY(targ1), VARDATA_ANY(targ2),
1464 len1 - VARHDRSZ) != 0);
1465
1466 PG_FREE_IF_COPY(targ1, 0);
1467 PG_FREE_IF_COPY(targ2, 1);
1468 }
1469 }
1470 else
1471 {
1472 text *arg1 = PG_GETARG_TEXT_PP(0);
1473 text *arg2 = PG_GETARG_TEXT_PP(1);
1474
1475 result = (text_cmp(arg1, arg2, collid) != 0);
1476
1477 PG_FREE_IF_COPY(arg1, 0);
1478 PG_FREE_IF_COPY(arg2, 1);
1479 }
1480
1481 PG_RETURN_BOOL(result);
1482}

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 2413 of file varlena.c.

2414{
2415 text *arg1 = PG_GETARG_TEXT_PP(0);
2416 Name arg2 = PG_GETARG_NAME(1);
2417 size_t len1 = VARSIZE_ANY_EXHDR(arg1);
2418 size_t len2 = strlen(NameStr(*arg2));
2420 bool result;
2421
2423
2424 if (collid == C_COLLATION_OID)
2425 result = !(len1 == len2 &&
2426 memcmp(VARDATA_ANY(arg1), NameStr(*arg2), len1) == 0);
2427 else
2428 result = !(varstr_cmp(VARDATA_ANY(arg1), len1,
2429 NameStr(*arg2), len2,
2430 collid) == 0);
2431
2432 PG_FREE_IF_COPY(arg1, 0);
2433
2434 PG_RETURN_BOOL(result);
2435}

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:545

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 2697 of file varlena.c.

2698{
2699 char *rawname;
2700 List *result = NIL;
2701 List *namelist;
2702 ListCell *l;
2703
2704 /* Convert to C string (handles possible detoasting). */
2705 /* Note we rely on being able to modify rawname below. */
2706 rawname = text_to_cstring(textval);
2707
2708 if (!SplitIdentifierString(rawname, '.', &namelist))
2709 ereport(ERROR,
2710 (errcode(ERRCODE_INVALID_NAME),
2711 errmsg("invalid name syntax")));
2712
2713 if (namelist == NIL)
2714 ereport(ERROR,
2715 (errcode(ERRCODE_INVALID_NAME),
2716 errmsg("invalid name syntax")));
2717
2718 foreach(l, namelist)
2719 {
2720 char *curname = (char *) lfirst(l);
2721
2722 result = lappend(result, makeString(pstrdup(curname)));
2723 }
2724
2725 pfree(rawname);
2726 list_free(namelist);
2727
2728 return result;
2729}
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:2755

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 4063 of file varlena.c.

4064{
4066
4068}
uint32_t uint32
Definition: c.h:552
static text * convert_to_base(uint64 value, int base)
Definition: varlena.c:4037

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

◆ to_bin64()

Datum to_bin64 ( PG_FUNCTION_ARGS  )

Definition at line 4070 of file varlena.c.

4071{
4073
4075}
#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 4101 of file varlena.c.

4102{
4104
4106}

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 4108 of file varlena.c.

4109{
4111
4113}

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

◆ to_oct32()

Datum to_oct32 ( PG_FUNCTION_ARGS  )

Definition at line 4082 of file varlena.c.

4083{
4085
4087}

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

◆ to_oct64()

Datum to_oct64 ( PG_FUNCTION_ARGS  )

Definition at line 4089 of file varlena.c.

4090{
4092
4094}

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

◆ unicode_assigned()

Datum unicode_assigned ( PG_FUNCTION_ARGS  )

Definition at line 5423 of file varlena.c.

5424{
5426 unsigned char *p;
5427 int size;
5428
5430 ereport(ERROR,
5431 (errmsg("Unicode categorization can only be performed if server encoding is UTF8")));
5432
5433 /* convert to char32_t */
5435 p = (unsigned char *) VARDATA_ANY(input);
5436 for (int i = 0; i < size; i++)
5437 {
5438 char32_t uchar = utf8_to_unicode(p);
5439 int category = unicode_category(uchar);
5440
5441 if (category == PG_U_UNASSIGNED)
5442 PG_RETURN_BOOL(false);
5443
5444 p += pg_utf_mblen(p);
5445 }
5446
5447 PG_RETURN_BOOL(true);
5448}
FILE * input
static char32_t 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(char32_t 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 5517 of file varlena.c.

5518{
5520 char *formstr = text_to_cstring(PG_GETARG_TEXT_PP(1));
5522 int size;
5523 char32_t *input_chars;
5524 char32_t *output_chars;
5525 unsigned char *p;
5526 int i;
5527 UnicodeNormalizationQC quickcheck;
5528 int output_size;
5529 bool result;
5530
5531 form = unicode_norm_form_from_string(formstr);
5532
5533 /* convert to char32_t */
5535 input_chars = palloc((size + 1) * sizeof(char32_t));
5536 p = (unsigned char *) VARDATA_ANY(input);
5537 for (i = 0; i < size; i++)
5538 {
5539 input_chars[i] = utf8_to_unicode(p);
5540 p += pg_utf_mblen(p);
5541 }
5542 input_chars[i] = (char32_t) '\0';
5543 Assert((char *) p == VARDATA_ANY(input) + VARSIZE_ANY_EXHDR(input));
5544
5545 /* quick check (see UAX #15) */
5546 quickcheck = unicode_is_normalized_quickcheck(form, input_chars);
5547 if (quickcheck == UNICODE_NORM_QC_YES)
5548 PG_RETURN_BOOL(true);
5549 else if (quickcheck == UNICODE_NORM_QC_NO)
5550 PG_RETURN_BOOL(false);
5551
5552 /* normalize and compare with original */
5553 output_chars = unicode_normalize(form, input_chars);
5554
5555 output_size = 0;
5556 for (char32_t *wp = output_chars; *wp; wp++)
5557 output_size++;
5558
5559 result = (size == output_size) &&
5560 (memcmp(input_chars, output_chars, size * sizeof(char32_t)) == 0);
5561
5562 PG_RETURN_BOOL(result);
5563}
uint32_t char32_t
Definition: c.h:1390
UnicodeNormalizationQC unicode_is_normalized_quickcheck(UnicodeNormalizationForm form, const char32_t *input)
Definition: unicode_norm.c:598
char32_t * unicode_normalize(UnicodeNormalizationForm form, const char32_t *input)
Definition: unicode_norm.c:402
UnicodeNormalizationForm
Definition: unicode_norm.h:18
UnicodeNormalizationQC
Definition: unicode_norm.h:27
@ UNICODE_NORM_QC_YES
Definition: unicode_norm.h:29
@ UNICODE_NORM_QC_NO
Definition: unicode_norm.h:28
static UnicodeNormalizationForm unicode_norm_form_from_string(const char *formstr)
Definition: varlena.c:5363

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 5363 of file varlena.c.

5364{
5365 UnicodeNormalizationForm form = -1;
5366
5367 /*
5368 * Might as well check this while we're here.
5369 */
5371 ereport(ERROR,
5372 (errcode(ERRCODE_SYNTAX_ERROR),
5373 errmsg("Unicode normalization can only be performed if server encoding is UTF8")));
5374
5375 if (pg_strcasecmp(formstr, "NFC") == 0)
5376 form = UNICODE_NFC;
5377 else if (pg_strcasecmp(formstr, "NFD") == 0)
5378 form = UNICODE_NFD;
5379 else if (pg_strcasecmp(formstr, "NFKC") == 0)
5380 form = UNICODE_NFKC;
5381 else if (pg_strcasecmp(formstr, "NFKD") == 0)
5382 form = UNICODE_NFKD;
5383 else
5384 ereport(ERROR,
5385 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
5386 errmsg("invalid normalization form: %s", formstr)));
5387
5388 return form;
5389}
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:32
@ UNICODE_NFKD
Definition: unicode_norm.h:22
@ UNICODE_NFD
Definition: unicode_norm.h:20
@ UNICODE_NFC
Definition: unicode_norm.h:19
@ UNICODE_NFKC
Definition: unicode_norm.h:21

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 5451 of file varlena.c.

5452{
5454 char *formstr = text_to_cstring(PG_GETARG_TEXT_PP(1));
5456 int size;
5457 char32_t *input_chars;
5458 char32_t *output_chars;
5459 unsigned char *p;
5460 text *result;
5461 int i;
5462
5463 form = unicode_norm_form_from_string(formstr);
5464
5465 /* convert to char32_t */
5467 input_chars = palloc((size + 1) * sizeof(char32_t));
5468 p = (unsigned char *) VARDATA_ANY(input);
5469 for (i = 0; i < size; i++)
5470 {
5471 input_chars[i] = utf8_to_unicode(p);
5472 p += pg_utf_mblen(p);
5473 }
5474 input_chars[i] = (char32_t) '\0';
5475 Assert((char *) p == VARDATA_ANY(input) + VARSIZE_ANY_EXHDR(input));
5476
5477 /* action */
5478 output_chars = unicode_normalize(form, input_chars);
5479
5480 /* convert back to UTF-8 string */
5481 size = 0;
5482 for (char32_t *wp = output_chars; *wp; wp++)
5483 {
5484 unsigned char buf[4];
5485
5486 unicode_to_utf8(*wp, buf);
5487 size += pg_utf_mblen(buf);
5488 }
5489
5490 result = palloc(size + VARHDRSZ);
5491 SET_VARSIZE(result, size + VARHDRSZ);
5492
5493 p = (unsigned char *) VARDATA_ANY(result);
5494 for (char32_t *wp = output_chars; *wp; wp++)
5495 {
5496 unicode_to_utf8(*wp, p);
5497 p += pg_utf_mblen(p);
5498 }
5499 Assert((char *) p == (char *) result + size + VARHDRSZ);
5500
5501 PG_RETURN_TEXT_P(result);
5502}
static unsigned char * unicode_to_utf8(char32_t 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 5400 of file varlena.c.

5401{
5403}
#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 5609 of file varlena.c.

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

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 5315 of file varlena.c.

5316{
5317 int dist;
5318
5319 Assert(state);
5320
5321 if (state->source == NULL || state->source[0] == '\0' ||
5322 candidate == NULL || candidate[0] == '\0')
5323 return;
5324
5325 /*
5326 * To avoid ERROR-ing, we check the lengths here instead of setting
5327 * 'trusted' to false in the call to varstr_levenshtein_less_equal().
5328 */
5329 if (strlen(state->source) > MAX_LEVENSHTEIN_STRLEN ||
5330 strlen(candidate) > MAX_LEVENSHTEIN_STRLEN)
5331 return;
5332
5333 dist = varstr_levenshtein_less_equal(state->source, strlen(state->source),
5334 candidate, strlen(candidate), 1, 1, 1,
5335 state->max_d, true);
5336 if (dist <= state->max_d &&
5337 dist <= strlen(state->source) / 2 &&
5338 (state->min_d == -1 || dist < state->min_d))
5339 {
5340 state->min_d = dist;
5341 state->match = candidate;
5342 }
5343}
#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 1844 of file varlena.c.

1845{
1848 char *a1p,
1849 *a2p;
1850 int len1,
1851 len2,
1852 result;
1853
1854 a1p = VARDATA_ANY(arg1);
1855 a2p = VARDATA_ANY(arg2);
1856
1857 len1 = VARSIZE_ANY_EXHDR(arg1);
1858 len2 = VARSIZE_ANY_EXHDR(arg2);
1859
1860 result = varstrfastcmp_locale(a1p, len1, a2p, len2, ssup);
1861
1862 /* We can't afford to leak memory here. */
1863 if (PointerGetDatum(arg1) != x)
1864 pfree(arg1);
1865 if (PointerGetDatum(arg2) != y)
1866 pfree(arg2);
1867
1868 return result;
1869}
#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 2181 of file varlena.c.

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

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 1989 of file varlena.c.

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

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

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 1626 of file varlena.c.

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

1763{
1766 char *a1p,
1767 *a2p;
1768 int len1,
1769 len2,
1770 result;
1771
1772 a1p = VARDATA_ANY(arg1);
1773 a2p = VARDATA_ANY(arg2);
1774
1775 len1 = VARSIZE_ANY_EXHDR(arg1);
1776 len2 = VARSIZE_ANY_EXHDR(arg2);
1777
1778 result = memcmp(a1p, a2p, Min(len1, len2));
1779 if ((result == 0) && (len1 != len2))
1780 result = (len1 < len2) ? -1 : 1;
1781
1782 /* We can't afford to leak memory here. */
1783 if (PointerGetDatum(arg1) != x)
1784 pfree(arg1);
1785 if (PointerGetDatum(arg2) != y)
1786 pfree(arg2);
1787
1788 return result;
1789}

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 1889 of file varlena.c.

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

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().