PostgreSQL Source Code git master
Loading...
Searching...
No Matches
varlena.c File Reference
#include "postgres.h"
#include <ctype.h>
#include <limits.h>
#include "access/detoast.h"
#include "access/toast_compression.h"
#include "access/tupmacs.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/tuplestore.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 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 int pg_mbcharcliplen_chars (const char *mbstr, int len, int limit)
 
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 chartext_position_next_internal (char *start_ptr, TextPositionState *state)
 
static chartext_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 chartext_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)
 
chartext_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)
 
charscan_quoted_identifier (char **endp, char **nextp)
 
charscan_identifier (char **endp, char **nextp, char separator, bool downcase_unquoted)
 
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 chargetClosestMatch (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)) \
errmsg("unterminated format() type specifier"), \
errhint("For a single \"%%\" use \"%%%%\"."))); \
} while (0)
int errcode(int sqlerrcode)
Definition elog.c:875
int errhint(const char *fmt,...) pg_attribute_printf(1
#define ERROR
Definition elog.h:40
static char * errmsg
static int fb(int x)

Definition at line 4771 of file varlena.c.

4772 { \
4773 if (++(ptr) >= (end_ptr)) \
4774 ereport(ERROR, \
4776 errmsg("unterminated format() type specifier"), \
4777 errhint("For a single \"%%\" use \"%%%%\"."))); \
4778 } while (0)

◆ CmpCall

#define CmpCall (   cmpfunc)
Value:
Datum DirectFunctionCall2Coll(PGFunction func, Oid collation, Datum arg1, Datum arg2)
Definition fmgr.c:814
#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:202

Definition at line 2492 of file varlena.c.

◆ DatumGetVarStringP

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

Definition at line 121 of file varlena.c.

◆ DatumGetVarStringPP

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

Definition at line 122 of file varlena.c.

◆ LEVENSHTEIN_LESS_EQUAL

#define LEVENSHTEIN_LESS_EQUAL

Definition at line 5311 of file varlena.c.

◆ TEXT_FORMAT_FLAG_MINUS

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

Definition at line 4769 of file varlena.c.

◆ TEXTBUFLEN

#define TEXTBUFLEN   1024

Definition at line 119 of file varlena.c.

Typedef Documentation

◆ VarString

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

3250{
3251 const char *p = VARDATA_ANY(replace_text);
3252 const char *p_end = p + VARSIZE_ANY_EXHDR(replace_text);
3253
3254 while (p < p_end)
3255 {
3256 const char *chunk_start = p;
3257 int so;
3258 int eo;
3259
3260 /* Find next escape char, if any. */
3261 p = memchr(p, '\\', p_end - p);
3262 if (p == NULL)
3263 p = p_end;
3264
3265 /* Copy the text we just scanned over, if any. */
3266 if (p > chunk_start)
3268
3269 /* Done if at end of string, else advance over escape char. */
3270 if (p >= p_end)
3271 break;
3272 p++;
3273
3274 if (p >= p_end)
3275 {
3276 /* Escape at very end of input. Treat same as unexpected char */
3278 break;
3279 }
3280
3281 if (*p >= '1' && *p <= '9')
3282 {
3283 /* Use the back reference of regexp. */
3284 int idx = *p - '0';
3285
3286 so = pmatch[idx].rm_so;
3287 eo = pmatch[idx].rm_eo;
3288 p++;
3289 }
3290 else if (*p == '&')
3291 {
3292 /* Use the entire matched string. */
3293 so = pmatch[0].rm_so;
3294 eo = pmatch[0].rm_eo;
3295 p++;
3296 }
3297 else if (*p == '\\')
3298 {
3299 /* \\ means transfer one \ to output. */
3301 p++;
3302 continue;
3303 }
3304 else
3305 {
3306 /*
3307 * If escape char is not followed by any expected char, just treat
3308 * it as ordinary data to copy. (XXX would it be better to throw
3309 * an error?)
3310 */
3312 continue;
3313 }
3314
3315 if (so >= 0 && eo >= 0)
3316 {
3317 /*
3318 * Copy the text that is back reference of regexp. Note so and eo
3319 * are counted in characters not bytes.
3320 */
3321 char *chunk_start;
3322 int chunk_len;
3323
3324 Assert(so >= data_pos);
3329 }
3330 }
3331}
Datum idx(PG_FUNCTION_ARGS)
Definition _int_op.c:263
#define Assert(condition)
Definition c.h:943
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:507
Datum replace_text(PG_FUNCTION_ARGS)
Definition varlena.c:3137

References appendBinaryStringInfo(), appendStringInfoChar(), Assert, charlen_to_bytelen(), fb(), 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 3910 of file varlena.c.

3911{
3914
3916}
#define PG_GETARG_ARRAYTYPE_P(n)
Definition array.h:263
#define PG_GETARG_TEXT_PP(n)
Definition fmgr.h:310
#define PG_RETURN_TEXT_P(x)
Definition fmgr.h:374
static text * array_to_text_internal(FunctionCallInfo fcinfo, ArrayType *v, const char *fldsep, const char *null_string)
Definition varlena.c:3952
char * text_to_cstring(const text *t)
Definition varlena.c:217

References array_to_text_internal(), fb(), 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 3952 of file varlena.c.

3954{
3955 text *result;
3956 int nitems,
3957 *dims,
3958 ndims;
3959 Oid element_type;
3960 int typlen;
3961 bool typbyval;
3962 char typalign;
3963 uint8 typalignby;
3965 bool printed = false;
3966 char *p;
3967 uint8 *bitmap;
3968 int bitmask;
3969 int i;
3971
3972 ndims = ARR_NDIM(v);
3973 dims = ARR_DIMS(v);
3974 nitems = ArrayGetNItems(ndims, dims);
3975
3976 /* if there are no elements, return an empty string */
3977 if (nitems == 0)
3978 return cstring_to_text_with_len("", 0);
3979
3980 element_type = ARR_ELEMTYPE(v);
3982
3983 /*
3984 * We arrange to look up info about element type, including its output
3985 * conversion proc, only once per series of calls, assuming the element
3986 * type doesn't change underneath us.
3987 */
3988 my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
3989 if (my_extra == NULL)
3990 {
3991 fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
3992 sizeof(ArrayMetaState));
3993 my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
3994 my_extra->element_type = ~element_type;
3995 }
3996
3997 if (my_extra->element_type != element_type)
3998 {
3999 /*
4000 * Get info about element type, including its output conversion proc
4001 */
4002 get_type_io_data(element_type, IOFunc_output,
4003 &my_extra->typlen, &my_extra->typbyval,
4004 &my_extra->typalign, &my_extra->typdelim,
4005 &my_extra->typioparam, &my_extra->typiofunc);
4006 fmgr_info_cxt(my_extra->typiofunc, &my_extra->proc,
4007 fcinfo->flinfo->fn_mcxt);
4008 my_extra->element_type = element_type;
4009 }
4010 typlen = my_extra->typlen;
4011 typbyval = my_extra->typbyval;
4012 typalign = my_extra->typalign;
4013 typalignby = typalign_to_alignby(typalign);
4014
4015 p = ARR_DATA_PTR(v);
4016 bitmap = ARR_NULLBITMAP(v);
4017 bitmask = 1;
4018
4019 for (i = 0; i < nitems; i++)
4020 {
4022 char *value;
4023
4024 /* Get source element, checking for NULL */
4025 if (bitmap && (*bitmap & bitmask) == 0)
4026 {
4027 /* if null_string is NULL, we just ignore null elements */
4028 if (null_string != NULL)
4029 {
4030 if (printed)
4032 else
4034 printed = true;
4035 }
4036 }
4037 else
4038 {
4039 itemvalue = fetch_att(p, typbyval, typlen);
4040
4042
4043 if (printed)
4044 appendStringInfo(&buf, "%s%s", fldsep, value);
4045 else
4047 printed = true;
4048
4049 p = att_addlength_pointer(p, typlen, p);
4050 p = (char *) att_nominal_alignby(p, typalignby);
4051 }
4052
4053 /* advance bitmap pointer if any */
4054 if (bitmap)
4055 {
4056 bitmask <<= 1;
4057 if (bitmask == 0x100)
4058 {
4059 bitmap++;
4060 bitmask = 1;
4061 }
4062 }
4063 }
4064
4066 pfree(buf.data);
4067
4068 return result;
4069}
#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_t uint8
Definition c.h:622
uint32 result
void fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
Definition fmgr.c:139
char * OutputFunctionCall(FmgrInfo *flinfo, Datum val)
Definition fmgr.c:1684
#define nitems(x)
Definition indent.h:31
static struct @177 value
int i
Definition isn.c:77
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:2556
@ IOFunc_output
Definition lsyscache.h:37
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition mcxt.c:1235
void pfree(void *pointer)
Definition mcxt.c:1619
static char buf[DEFAULT_XLOG_SEG_SIZE]
char typalign
Definition pg_type.h:178
uint64_t Datum
Definition postgres.h:70
unsigned int Oid
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
void * fn_extra
Definition fmgr.h:64
MemoryContext fn_mcxt
Definition fmgr.h:65
FmgrInfo * flinfo
Definition fmgr.h:87
Definition c.h:776
#define att_nominal_alignby(cur_offset, attalignby)
Definition tupmacs.h:411
#define att_addlength_pointer(cur_offset, attlen, attptr)
Definition tupmacs.h:431
static uint8 typalign_to_alignby(char typalign)
Definition tupmacs.h:302
static Datum fetch_att(const void *T, bool attbyval, int attlen)
Definition tupmacs.h:108
text * cstring_to_text_with_len(const char *s, int len)
Definition varlena.c:196

References appendStringInfo(), appendStringInfoString(), ARR_DATA_PTR, ARR_DIMS, ARR_ELEMTYPE, ARR_NDIM, ARR_NULLBITMAP, ArrayGetNItems(), att_addlength_pointer, att_nominal_alignby, buf, cstring_to_text_with_len(), fb(), fetch_att(), FunctionCallInfoBaseData::flinfo, fmgr_info_cxt(), FmgrInfo::fn_extra, FmgrInfo::fn_mcxt, get_type_io_data(), i, initStringInfo(), IOFunc_output, MemoryContextAlloc(), nitems, OutputFunctionCall(), pfree(), result, typalign, typalign_to_alignby(), 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 3926 of file varlena.c.

3927{
3928 ArrayType *v;
3929 char *fldsep;
3930 char *null_string;
3931
3932 /* returns NULL when first or second parameter is NULL */
3933 if (PG_ARGISNULL(0) || PG_ARGISNULL(1))
3935
3936 v = PG_GETARG_ARRAYTYPE_P(0);
3938
3939 /* NULL null string is passed through as a null pointer */
3940 if (!PG_ARGISNULL(2))
3942 else
3943 null_string = NULL;
3944
3946}
#define PG_ARGISNULL(n)
Definition fmgr.h:209
#define PG_RETURN_NULL()
Definition fmgr.h:346

References array_to_text_internal(), fb(), 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 1845 of file varlena.c.

1846{
1849 char *a1p,
1850 *a2p;
1851 int len1,
1852 len2,
1853 result;
1854
1855 a1p = VARDATA_ANY(arg1);
1856 a2p = VARDATA_ANY(arg2);
1857
1860
1861 result = memcmp(a1p, a2p, Min(len1, len2));
1862 if ((result == 0) && (len1 != len2))
1863 result = (len1 < len2) ? -1 : 1;
1864
1865 /* We can't afford to leak memory here. */
1866 if (PointerGetDatum(arg1) != x)
1867 pfree(arg1);
1868 if (PointerGetDatum(arg2) != y)
1869 pfree(arg2);
1870
1871 return result;
1872}
#define Min(x, y)
Definition c.h:1091
#define DatumGetBpCharPP(X)
Definition fmgr.h:294
int y
Definition isn.c:76
int x
Definition isn.c:75
#define PointerGetDatum(X)
Definition postgres.h:354
int bpchartruelen(char *s, int len)
Definition varchar.c:679

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

Referenced by varstr_sortsupport().

◆ btnametextcmp()

Datum btnametextcmp ( PG_FUNCTION_ARGS  )

Definition at line 2461 of file varlena.c.

2462{
2465 int32 result;
2466
2470
2472
2474}
#define NameStr(name)
Definition c.h:835
int32_t int32
Definition c.h:620
#define PG_FREE_IF_COPY(ptr, n)
Definition fmgr.h:260
#define PG_GETARG_NAME(n)
Definition fmgr.h:279
#define PG_RETURN_INT32(x)
Definition fmgr.h:355
Definition c.h:830
int varstr_cmp(const char *arg1, int len1, const char *arg2, int len2, Oid collid)
Definition varlena.c:1355

References fb(), NameStr, PG_FREE_IF_COPY, PG_GET_COLLATION, PG_GETARG_NAME, PG_GETARG_TEXT_PP, PG_RETURN_INT32, result, 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 2644 of file varlena.c.

2645{
2648 int result;
2649
2651
2654
2656}
static int internal_text_pattern_compare(text *arg1, text *arg2)
Definition varlena.c:2558

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

◆ bttext_pattern_sortsupport()

Datum bttext_pattern_sortsupport ( PG_FUNCTION_ARGS  )

Definition at line 2660 of file varlena.c.

2661{
2663 MemoryContext oldcontext;
2664
2665 oldcontext = MemoryContextSwitchTo(ssup->ssup_cxt);
2666
2667 /* Use generic string SortSupport, forcing "C" collation */
2669
2670 MemoryContextSwitchTo(oldcontext);
2671
2673}
struct SortSupportData * SortSupport
Definition execnodes.h:61
#define PG_RETURN_VOID()
Definition fmgr.h:350
#define PG_GETARG_POINTER(n)
Definition fmgr.h:277
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:138
MemoryContext ssup_cxt
Definition sortsupport.h:66
void varstr_sortsupport(SortSupport ssup, Oid typid, Oid collid)
Definition varlena.c:1672

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

◆ bttextcmp()

Datum bttextcmp ( PG_FUNCTION_ARGS  )

Definition at line 1632 of file varlena.c.

1633{
1636 int32 result;
1637
1639
1642
1644}
static int text_cmp(text *arg1, text *arg2, Oid collid)
Definition varlena.c:1404

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

Referenced by gbt_text_ssup_cmp(), and gbt_textcmp().

◆ bttextnamecmp()

◆ bttextsortsupport()

Datum bttextsortsupport ( PG_FUNCTION_ARGS  )

Definition at line 1647 of file varlena.c.

1648{
1650 Oid collid = ssup->ssup_collation;
1651 MemoryContext oldcontext;
1652
1653 oldcontext = MemoryContextSwitchTo(ssup->ssup_cxt);
1654
1655 /* Use generic string SortSupport */
1657
1658 MemoryContextSwitchTo(oldcontext);
1659
1661}
Oid collid

References collid, fb(), 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 2316 of file varlena.c.

2317{
2318#ifdef NOT_USED
2319 Oid opcintype = PG_GETARG_OID(0);
2320#endif
2322 pg_locale_t locale;
2323
2325
2327
2329}
#define PG_GETARG_OID(n)
Definition fmgr.h:275
#define PG_RETURN_BOOL(x)
Definition fmgr.h:360
pg_locale_t pg_newlocale_from_collation(Oid collid)
Definition pg_locale.c:1189
static void check_collation_set(Oid collid)
Definition varlena.c:1326

References check_collation_set(), collid, pg_locale_struct::deterministic, PG_GET_COLLATION, PG_GETARG_OID, pg_newlocale_from_collation(), and PG_RETURN_BOOL.

◆ build_concat_foutcache()

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

Definition at line 4530 of file varlena.c.

4531{
4533 int i;
4534
4535 /* We keep the info in fn_mcxt so it survives across calls */
4537 PG_NARGS() * sizeof(FmgrInfo));
4538
4539 for (i = argidx; i < PG_NARGS(); i++)
4540 {
4541 Oid valtype;
4542 Oid typOutput;
4543 bool typIsVarlena;
4544
4545 valtype = get_fn_expr_argtype(fcinfo->flinfo, i);
4546 if (!OidIsValid(valtype))
4547 elog(ERROR, "could not determine data type of concat() input");
4548
4551 }
4552
4553 fcinfo->flinfo->fn_extra = foutcache;
4554
4555 return foutcache;
4556}
#define OidIsValid(objectId)
Definition c.h:858
#define elog(elevel,...)
Definition elog.h:228
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition fmgr.c:1876
#define PG_NARGS()
Definition fmgr.h:203
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition lsyscache.c:3140

References elog, ERROR, fb(), 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 507 of file varlena.c.

508{
510 {
511 /* Optimization for single-byte encodings */
512 return n;
513 }
514 else
515 {
516 const char *s;
517
518 for (s = p; n > 0; n--)
519 s += pg_mblen_unbounded(s); /* caller verified encoding */
520
521 return s - p;
522 }
523}
int pg_mblen_unbounded(const char *mbstr)
Definition mbutils.c:1137
int pg_database_encoding_max_length(void)
Definition mbutils.c:1673

References pg_database_encoding_max_length(), and pg_mblen_unbounded().

Referenced by appendStringInfoRegexpSubstr(), and replace_text_regexp().

◆ check_collation_set()

static void check_collation_set ( Oid  collid)
static

Definition at line 1326 of file varlena.c.

1327{
1328 if (!OidIsValid(collid))
1329 {
1330 /*
1331 * This typically means that the parser could not resolve a conflict
1332 * of implicit collations, so report it that way.
1333 */
1334 ereport(ERROR,
1336 errmsg("could not determine which collation to use for string comparison"),
1337 errhint("Use the COLLATE clause to set the collation explicitly.")));
1338 }
1339}
#define ereport(elevel,...)
Definition elog.h:152

References collid, ereport, errcode(), errhint(), errmsg, ERROR, fb(), 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 3214 of file varlena.c.

3215{
3216 int result = 0;
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 /* Find next escape char, if any. */
3223 p = memchr(p, '\\', p_end - p);
3224 if (p == NULL)
3225 break;
3226 p++;
3227 /* Note: a backslash at the end doesn't require extra processing. */
3228 if (p < p_end)
3229 {
3230 if (*p >= '1' && *p <= '9')
3231 return 2; /* Found a submatch specifier, so done */
3232 result = 1; /* Found some other sequence, keep looking */
3233 p++;
3234 }
3235 }
3236 return result;
3237}

References fb(), replace_text(), result, 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 4568 of file varlena.c.

4570{
4571 text *result;
4574 bool first_arg = true;
4575 int i;
4576
4577 /*
4578 * concat(VARIADIC some-array) is essentially equivalent to
4579 * array_to_text(), ie concat the array elements with the given separator.
4580 * So we just pass the case off to that code.
4581 */
4582 if (get_fn_expr_variadic(fcinfo->flinfo))
4583 {
4584 ArrayType *arr;
4585
4586 /* Should have just the one argument */
4587 Assert(argidx == PG_NARGS() - 1);
4588
4589 /* concat(VARIADIC NULL) is defined as NULL */
4590 if (PG_ARGISNULL(argidx))
4591 return NULL;
4592
4593 /*
4594 * Non-null argument had better be an array. We assume that any call
4595 * context that could let get_fn_expr_variadic return true will have
4596 * checked that a VARIADIC-labeled parameter actually is an array. So
4597 * it should be okay to just Assert that it's an array rather than
4598 * doing a full-fledged error check.
4599 */
4601
4602 /* OK, safe to fetch the array value */
4604
4605 /*
4606 * And serialize the array. We tell array_to_text to ignore null
4607 * elements, which matches the behavior of the loop below.
4608 */
4609 return array_to_text_internal(fcinfo, arr, sepstr, NULL);
4610 }
4611
4612 /* Normal case without explicit VARIADIC marker */
4614
4615 /* Get output function info, building it if first time through */
4616 foutcache = (FmgrInfo *) fcinfo->flinfo->fn_extra;
4617 if (foutcache == NULL)
4619
4620 for (i = argidx; i < PG_NARGS(); i++)
4621 {
4622 if (!PG_ARGISNULL(i))
4623 {
4625
4626 /* add separator if appropriate */
4627 if (first_arg)
4628 first_arg = false;
4629 else
4631
4632 /* call the appropriate type output function, append the result */
4635 }
4636 }
4637
4639 pfree(str.data);
4640
4641 return result;
4642}
bool get_fn_expr_variadic(FmgrInfo *flinfo)
Definition fmgr.c:2010
Oid get_base_element_type(Oid typid)
Definition lsyscache.c:3065
static FmgrInfo * build_concat_foutcache(FunctionCallInfo fcinfo, int argidx)
Definition varlena.c:4530

References appendStringInfoString(), array_to_text_internal(), Assert, build_concat_foutcache(), cstring_to_text_with_len(), fb(), FunctionCallInfoBaseData::flinfo, FmgrInfo::fn_extra, get_base_element_type(), get_fn_expr_argtype(), get_fn_expr_variadic(), i, initStringInfo(), OidIsValid, OutputFunctionCall(), pfree(), PG_ARGISNULL, PG_GETARG_ARRAYTYPE_P, PG_GETARG_DATUM, PG_NARGS, result, 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 4076 of file varlena.c.

4077{
4078 const char *digits = "0123456789abcdef";
4079
4080 /* We size the buffer for to_bin's longest possible return value. */
4081 char buf[sizeof(uint64) * BITS_PER_BYTE];
4082 char *const end = buf + sizeof(buf);
4083 char *ptr = end;
4084
4085 Assert(base > 1);
4086 Assert(base <= 16);
4087
4088 do
4089 {
4090 *--ptr = digits[value % base];
4091 value /= base;
4092 } while (ptr > buf && value);
4093
4094 return cstring_to_text_with_len(ptr, end - ptr);
4095}
uint64_t uint64
Definition c.h:625
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 184 of file varlena.c.

185{
186 return cstring_to_text_with_len(s, strlen(s));
187}

References cstring_to_text_with_len(), and fb().

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(), postgres_fdw_connection(), 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_fdw_connection(), test_lwlock_get_lwlock_identifier(), 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(), xml_recv(), and xslt_process().

◆ cstring_to_text_with_len()

text * cstring_to_text_with_len ( const char s,
int  len 
)

Definition at line 196 of file varlena.c.

197{
198 text *result = (text *) palloc(len + VARHDRSZ);
199
201 memcpy(VARDATA(result), s, len);
202
203 return result;
204}
#define VARHDRSZ
Definition c.h:781
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))
void * palloc(Size size)
Definition mcxt.c:1390
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, memcpy(), palloc(), result, 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(), executeStringInternalMethod(), 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 5389 of file varlena.c.

5390{
5391 Assert(state);
5392
5393 return state->match;
5394}

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

5620{
5621 if (c >= '0' && c <= '9')
5622 return c - '0';
5623 if (c >= 'a' && c <= 'f')
5624 return c - 'a' + 0xA;
5625 if (c >= 'A' && c <= 'F')
5626 return c - 'A' + 0xA;
5627 elog(ERROR, "invalid hexadecimal digit");
5628 return 0; /* not reached */
5629}
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 5635 of file varlena.c.

5636{
5637 unsigned int result = 0;
5638
5639 for (size_t i = 0; i < n; i++)
5640 result += hexval(instr[i]) << (4 * (n - i - 1));
5641
5642 return result;
5643}
static unsigned int hexval(unsigned char c)
Definition varlena.c:5619

References hexval(), i, and result.

Referenced by unistr().

◆ icu_unicode_version()

Datum icu_unicode_version ( PG_FUNCTION_ARGS  )

Definition at line 5448 of file varlena.c.

5449{
5450 const char *version = pg_icu_unicode_version();
5451
5452 if (version)
5454 else
5456}
const char * pg_icu_unicode_version(void)
Definition pg_locale.c:1647
text * cstring_to_text(const char *s)
Definition varlena.c:184

References cstring_to_text(), pg_icu_unicode_version(), 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 5334 of file varlena.c.

5335{
5336 Assert(state);
5337 Assert(max_d >= 0);
5338
5339 state->source = source;
5340 state->min_d = -1;
5341 state->max_d = max_d;
5342 state->match = NULL;
5343}
static rewind_source * source
Definition pg_rewind.c:89

References Assert, fb(), 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 2558 of file varlena.c.

2559{
2560 int result;
2561 int len1,
2562 len2;
2563
2564 len1 = VARSIZE_ANY_EXHDR(arg1);
2565 len2 = VARSIZE_ANY_EXHDR(arg2);
2566
2567 result = memcmp(VARDATA_ANY(arg1), VARDATA_ANY(arg2), Min(len1, len2));
2568 if (result != 0)
2569 return result;
2570 else if (len1 < len2)
2571 return -1;
2572 else if (len1 > len2)
2573 return 1;
2574 else
2575 return 0;
2576}

References fb(), Min, result, 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 5609 of file varlena.c.

5610{
5611 for (size_t i = 0; i < n; i++)
5612 if (!isxdigit((unsigned char) instr[i]))
5613 return false;
5614
5615 return true;
5616}

References fb(), and i.

Referenced by unistr().

◆ makeStringAggState()

static StringInfo makeStringAggState ( FunctionCallInfo  fcinfo)
static

Definition at line 4308 of file varlena.c.

4309{
4311 MemoryContext aggcontext;
4312 MemoryContext oldcontext;
4313
4314 if (!AggCheckCallContext(fcinfo, &aggcontext))
4315 {
4316 /* cannot be called directly because of internal-type argument */
4317 elog(ERROR, "string_agg_transfn called in non-aggregate context");
4318 }
4319
4320 /*
4321 * Create state in aggregate context. It'll stay there across subsequent
4322 * calls.
4323 */
4324 oldcontext = MemoryContextSwitchTo(aggcontext);
4326 MemoryContextSwitchTo(oldcontext);
4327
4328 return state;
4329}
int AggCheckCallContext(FunctionCallInfo fcinfo, MemoryContext *aggcontext)
Definition nodeAgg.c:4609
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 2705 of file varlena.c.

2706{
2707 Name s = PG_GETARG_NAME(0);
2708
2710}

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

2362{
2365 size_t len1 = strlen(NameStr(*arg1));
2366 size_t len2 = VARSIZE_ANY_EXHDR(arg2);
2368 bool result;
2369
2371
2372 if (collid == C_COLLATION_OID)
2373 result = (len1 == len2 &&
2374 memcmp(NameStr(*arg1), VARDATA_ANY(arg2), len1) == 0);
2375 else
2376 result = (varstr_cmp(NameStr(*arg1), len1,
2377 VARDATA_ANY(arg2), len2,
2378 collid) == 0);
2379
2381
2383}

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

◆ namefastcmp_c()

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

Definition at line 1878 of file varlena.c.

1879{
1882
1884}
#define NAMEDATALEN
static Name DatumGetName(Datum X)
Definition postgres.h:393

References DatumGetName(), fb(), 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 1921 of file varlena.c.

1922{
1925
1928 ssup);
1929}
static int varstrfastcmp_locale(char *a1p, int len1, char *a2p, int len2, SortSupport ssup)
Definition varlena.c:1935

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

Referenced by varstr_sortsupport().

◆ namegetext()

Datum namegetext ( PG_FUNCTION_ARGS  )

Definition at line 2517 of file varlena.c.

2518{
2520}
#define CmpCall(cmpfunc)
Definition varlena.c:2492
Datum btnametextcmp(PG_FUNCTION_ARGS)
Definition varlena.c:2461

References btnametextcmp(), CmpCall, and PG_RETURN_BOOL.

◆ namegttext()

Datum namegttext ( PG_FUNCTION_ARGS  )

Definition at line 2511 of file varlena.c.

2512{
2514}

References btnametextcmp(), CmpCall, and PG_RETURN_BOOL.

◆ nameletext()

Datum nameletext ( PG_FUNCTION_ARGS  )

Definition at line 2505 of file varlena.c.

2506{
2508}

References btnametextcmp(), CmpCall, and PG_RETURN_BOOL.

◆ namelttext()

Datum namelttext ( PG_FUNCTION_ARGS  )

Definition at line 2499 of file varlena.c.

2500{
2502}

References btnametextcmp(), CmpCall, and PG_RETURN_BOOL.

◆ namenetext()

Datum namenetext ( PG_FUNCTION_ARGS  )

Definition at line 2411 of file varlena.c.

2412{
2415 size_t len1 = strlen(NameStr(*arg1));
2416 size_t len2 = VARSIZE_ANY_EXHDR(arg2);
2418 bool result;
2419
2421
2422 if (collid == C_COLLATION_OID)
2423 result = !(len1 == len2 &&
2424 memcmp(NameStr(*arg1), VARDATA_ANY(arg2), len1) == 0);
2425 else
2426 result = !(varstr_cmp(NameStr(*arg1), len1,
2427 VARDATA_ANY(arg2), len2,
2428 collid) == 0);
2429
2431
2433}

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

◆ pg_column_compression()

Datum pg_column_compression ( PG_FUNCTION_ARGS  )

Definition at line 4207 of file varlena.c.

4208{
4209 int typlen;
4210 char *result;
4212
4213 /* On first call, get the input type's typlen, and save at *fn_extra */
4214 if (fcinfo->flinfo->fn_extra == NULL)
4215 {
4216 /* Lookup the datatype of the supplied argument */
4217 Oid argtypeid = get_fn_expr_argtype(fcinfo->flinfo, 0);
4218
4219 typlen = get_typlen(argtypeid);
4220 if (typlen == 0) /* should not happen */
4221 elog(ERROR, "cache lookup failed for type %u", argtypeid);
4222
4223 fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
4224 sizeof(int));
4225 *((int *) fcinfo->flinfo->fn_extra) = typlen;
4226 }
4227 else
4228 typlen = *((int *) fcinfo->flinfo->fn_extra);
4229
4230 if (typlen != -1)
4232
4233 /* get the compression method id stored in the compressed varlena */
4238
4239 /* convert compression method id to compression method name */
4240 switch (cmid)
4241 {
4243 result = "pglz";
4244 break;
4246 result = "lz4";
4247 break;
4248 default:
4249 elog(ERROR, "invalid compression method id %d", cmid);
4250 }
4251
4253}
int16 get_typlen(Oid typid)
Definition lsyscache.c:2428
static Pointer DatumGetPointer(Datum X)
Definition postgres.h:332
ToastCompressionId toast_get_compression_id(varlena *attr)
ToastCompressionId
@ TOAST_INVALID_COMPRESSION_ID
@ TOAST_LZ4_COMPRESSION_ID
@ TOAST_PGLZ_COMPRESSION_ID

References cstring_to_text(), DatumGetPointer(), elog, ERROR, fb(), get_fn_expr_argtype(), get_typlen(), MemoryContextAlloc(), PG_GETARG_DATUM, PG_RETURN_NULL, PG_RETURN_TEXT_P, result, 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 4160 of file varlena.c.

4161{
4163 int32 result;
4164 int typlen;
4165
4166 /* On first call, get the input type's typlen, and save at *fn_extra */
4167 if (fcinfo->flinfo->fn_extra == NULL)
4168 {
4169 /* Lookup the datatype of the supplied argument */
4170 Oid argtypeid = get_fn_expr_argtype(fcinfo->flinfo, 0);
4171
4172 typlen = get_typlen(argtypeid);
4173 if (typlen == 0) /* should not happen */
4174 elog(ERROR, "cache lookup failed for type %u", argtypeid);
4175
4176 fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
4177 sizeof(int));
4178 *((int *) fcinfo->flinfo->fn_extra) = typlen;
4179 }
4180 else
4181 typlen = *((int *) fcinfo->flinfo->fn_extra);
4182
4183 if (typlen == -1)
4184 {
4185 /* varlena type, possibly toasted */
4187 }
4188 else if (typlen == -2)
4189 {
4190 /* cstring */
4192 }
4193 else
4194 {
4195 /* ordinary fixed-width type */
4196 result = typlen;
4197 }
4198
4200}
Size toast_datum_size(Datum value)
Definition detoast.c:601
static char * DatumGetCString(Datum X)
Definition postgres.h:365

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

◆ pg_column_toast_chunk_id()

Datum pg_column_toast_chunk_id ( PG_FUNCTION_ARGS  )

Definition at line 4260 of file varlena.c.

4261{
4262 int typlen;
4263 varlena *attr;
4264 varatt_external toast_pointer;
4265
4266 /* On first call, get the input type's typlen, and save at *fn_extra */
4267 if (fcinfo->flinfo->fn_extra == NULL)
4268 {
4269 /* Lookup the datatype of the supplied argument */
4270 Oid argtypeid = get_fn_expr_argtype(fcinfo->flinfo, 0);
4271
4272 typlen = get_typlen(argtypeid);
4273 if (typlen == 0) /* should not happen */
4274 elog(ERROR, "cache lookup failed for type %u", argtypeid);
4275
4276 fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
4277 sizeof(int));
4278 *((int *) fcinfo->flinfo->fn_extra) = typlen;
4279 }
4280 else
4281 typlen = *((int *) fcinfo->flinfo->fn_extra);
4282
4283 if (typlen != -1)
4285
4287
4288 if (!VARATT_IS_EXTERNAL_ONDISK(attr))
4290
4291 VARATT_EXTERNAL_GET_POINTER(toast_pointer, attr);
4292
4293 PG_RETURN_OID(toast_pointer.va_valueid);
4294}
#define VARATT_EXTERNAL_GET_POINTER(toast_pointer, attr)
Definition detoast.h:22
#define PG_RETURN_OID(x)
Definition fmgr.h:361
static bool VARATT_IS_EXTERNAL_ONDISK(const void *PTR)
Definition varatt.h:361

References DatumGetPointer(), elog, ERROR, fb(), 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().

◆ pg_mbcharcliplen_chars()

static int pg_mbcharcliplen_chars ( const char mbstr,
int  len,
int  limit 
)
static

Definition at line 804 of file varlena.c.

805{
806 int nch = 0;
807 int l;
808
809 Assert(len > 0);
810 Assert(limit > 0);
812
813 while (len > 0 && *mbstr)
814 {
816 nch++;
817 if (nch == limit)
818 break;
819 len -= l;
820 mbstr += l;
821 }
822 return nch;
823}
int pg_mblen_with_len(const char *mbstr, int limit)
Definition mbutils.c:1108

References Assert, fb(), len, pg_database_encoding_max_length(), and pg_mblen_with_len().

Referenced by text_substring().

◆ replace_text()

Datum replace_text ( PG_FUNCTION_ARGS  )

Definition at line 3137 of file varlena.c.

3138{
3142 int src_text_len;
3145 text *ret_text;
3146 int chunk_len;
3147 char *curr_ptr;
3148 char *start_ptr;
3150 bool found;
3151
3154
3155 /* Return unmodified source string if empty source or pattern */
3156 if (src_text_len < 1 || from_sub_text_len < 1)
3157 {
3159 }
3160
3162
3163 found = text_position_next(&state);
3164
3165 /* When the from_sub_text is not found, there is nothing to do. */
3166 if (!found)
3167 {
3170 }
3173
3175
3176 do
3177 {
3179
3180 /* copy the data skipped over by last text_position_next() */
3183
3185
3186 start_ptr = curr_ptr + state.last_match_len;
3187
3188 found = text_position_next(&state);
3189 if (found)
3191 }
3192 while (found);
3193
3194 /* copy trailing data */
3197
3199
3201 pfree(str.data);
3202
3204}
#define CHECK_FOR_INTERRUPTS()
Definition miscadmin.h:125
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:962
static void text_position_cleanup(TextPositionState *state)
Definition varlena.c:1319
static void appendStringInfoText(StringInfo str, const text *t)
Definition varlena.c:3123
static char * text_position_get_match_ptr(TextPositionState *state)
Definition varlena.c:1284
static bool text_position_next(TextPositionState *state)
Definition varlena.c:1083

References appendBinaryStringInfo(), appendStringInfoText(), CHECK_FOR_INTERRUPTS, cstring_to_text_with_len(), fb(), 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(), executeStringInternalMethod(), 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 3347 of file varlena.c.

3351{
3352 text *ret_text;
3353 regex_t *re;
3355 int nmatches = 0;
3357 regmatch_t pmatch[10]; /* main match, plus \1 to \9 */
3358 int nmatch = lengthof(pmatch);
3359 pg_wchar *data;
3360 size_t data_len;
3361 int data_pos;
3362 char *start_ptr;
3363 int escape_status;
3364
3366
3367 /* Convert data string to wide characters. */
3368 data = (pg_wchar *) palloc((src_text_len + 1) * sizeof(pg_wchar));
3370
3371 /* Check whether replace_text has escapes, especially regexp submatches. */
3373
3374 /* If no regexp submatches, we can use REG_NOSUB. */
3375 if (escape_status < 2)
3376 {
3377 cflags |= REG_NOSUB;
3378 /* Also tell pg_regexec we only want the whole-match location. */
3379 nmatch = 1;
3380 }
3381
3382 /* Prepare the regexp. */
3383 re = RE_compile_and_cache(pattern_text, cflags, collation);
3384
3385 /* start_ptr points to the data_pos'th character of src_text */
3386 start_ptr = (char *) VARDATA_ANY(src_text);
3387 data_pos = 0;
3388
3389 while (search_start <= data_len)
3390 {
3391 int regexec_result;
3392
3394
3396 data,
3397 data_len,
3398 search_start,
3399 NULL, /* no details */
3400 nmatch,
3401 pmatch,
3402 0);
3403
3405 break;
3406
3407 if (regexec_result != REG_OKAY)
3408 {
3409 char errMsg[100];
3410
3411 pg_regerror(regexec_result, re, errMsg, sizeof(errMsg));
3412 ereport(ERROR,
3414 errmsg("regular expression failed: %s", errMsg)));
3415 }
3416
3417 /*
3418 * Count matches, and decide whether to replace this match.
3419 */
3420 nmatches++;
3421 if (n > 0 && nmatches != n)
3422 {
3423 /*
3424 * No, so advance search_start, but not start_ptr/data_pos. (Thus,
3425 * we treat the matched text as if it weren't matched, and copy it
3426 * to the output later.)
3427 */
3428 search_start = pmatch[0].rm_eo;
3429 if (pmatch[0].rm_so == pmatch[0].rm_eo)
3430 search_start++;
3431 continue;
3432 }
3433
3434 /*
3435 * Copy the text to the left of the match position. Note we are given
3436 * character not byte indexes.
3437 */
3438 if (pmatch[0].rm_so - data_pos > 0)
3439 {
3440 int chunk_len;
3441
3443 pmatch[0].rm_so - data_pos);
3445
3446 /*
3447 * Advance start_ptr over that text, to avoid multiple rescans of
3448 * it if the replace_text contains multiple back-references.
3449 */
3451 data_pos = pmatch[0].rm_so;
3452 }
3453
3454 /*
3455 * Copy the replace_text, processing escapes if any are present.
3456 */
3457 if (escape_status > 0)
3460 else
3462
3463 /* Advance start_ptr and data_pos over the matched text. */
3465 pmatch[0].rm_eo - data_pos);
3466 data_pos = pmatch[0].rm_eo;
3467
3468 /*
3469 * If we only want to replace one occurrence, we're done.
3470 */
3471 if (n > 0)
3472 break;
3473
3474 /*
3475 * Advance search position. Normally we start the next search at the
3476 * end of the previous match; but if the match was of zero length, we
3477 * have to advance by one character, or we'd just find the same match
3478 * again.
3479 */
3480 search_start = data_pos;
3481 if (pmatch[0].rm_so == pmatch[0].rm_eo)
3482 search_start++;
3483 }
3484
3485 /*
3486 * Copy the text to the right of the last match.
3487 */
3488 if (data_pos < data_len)
3489 {
3490 int chunk_len;
3491
3494 }
3495
3497 pfree(buf.data);
3498 pfree(data);
3499
3500 return ret_text;
3501}
#define lengthof(array)
Definition c.h:873
unsigned int pg_wchar
Definition mbprint.c:31
int pg_mb2wchar_with_len(const char *from, pg_wchar *to, int len)
Definition mbutils.c:997
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:3214
static void appendStringInfoRegexpSubstr(StringInfo str, text *replace_text, regmatch_t *pmatch, char *start_ptr, int data_pos)
Definition varlena.c:3247

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, fb(), 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 5298 of file varlena.c.

5299{
5300 while (len > 0)
5301 {
5302 len--;
5303 if (s1[len] != s2[len])
5304 return false;
5305 }
5306 return true;
5307}
char * s1
char * s2

References len, s1, and s2.

Referenced by varstr_levenshtein().

◆ scan_identifier()

char * scan_identifier ( char **  endp,
char **  nextp,
char  separator,
bool  downcase_unquoted 
)

Definition at line 2805 of file varlena.c.

2806{
2807 char *token;
2808
2809 if (**nextp == '"')
2811
2812 /* Unquoted identifier --- extends to separator or whitespace */
2813 token = *nextp;
2814
2815 while (**nextp && **nextp != separator && !scanner_isspace(**nextp))
2816 (*nextp)++;
2817
2818 if (*nextp == token)
2819 return NULL; /* empty token */
2820
2821 *endp = *nextp;
2822
2824 {
2825 /*
2826 * Downcase the identifier, using same code as main lexer does.
2827 *
2828 * XXX because we want to overwrite the input in-place, we cannot
2829 * support a downcasing transformation that increases the string
2830 * length. This is not a problem given the current implementation of
2831 * downcase_truncate_identifier, but we'll probably have to do
2832 * something about this someday.
2833 */
2834 int len = *endp - token;
2836
2838 strncpy(token, downname, len); /* strncpy is required here */
2839 pfree(downname);
2840 }
2841
2842 return token;
2843}
#define token
char * downcase_truncate_identifier(const char *ident, int len, bool warn)
Definition scansup.c:38
bool scanner_isspace(char ch)
Definition scansup.c:105
char * scan_quoted_identifier(char **endp, char **nextp)
Definition varlena.c:2770

References Assert, downcase_truncate_identifier(), fb(), len, pfree(), scan_quoted_identifier(), scanner_isspace(), and token.

Referenced by auto_explain_split_options(), SplitGUCList(), and SplitIdentifierString().

◆ scan_quoted_identifier()

char * scan_quoted_identifier ( char **  endp,
char **  nextp 
)

Definition at line 2770 of file varlena.c.

2771{
2772 char *token = *nextp + 1;
2773
2774 for (;;)
2775 {
2776 *endp = strchr(*nextp + 1, '"');
2777 if (*endp == NULL)
2778 return NULL; /* mismatched quotes */
2779 if ((*endp)[1] != '"')
2780 break; /* found end of quoted identifier */
2781 /* Collapse adjacent quotes into one quote, and look again */
2782 memmove(*endp, *endp + 1, strlen(*endp));
2783 *nextp = *endp;
2784 }
2785 /* *endp now points at the terminating quote */
2786 *nextp = *endp + 1;
2787
2788 return token;
2789}

References fb(), and token.

Referenced by scan_identifier(), and SplitDirectoriesString().

◆ split_part()

Datum split_part ( PG_FUNCTION_ARGS  )

Definition at line 3509 of file varlena.c.

3510{
3513 int fldnum = PG_GETARG_INT32(2);
3514 int inputstring_len;
3515 int fldsep_len;
3517 char *start_ptr;
3518 char *end_ptr;
3520 bool found;
3521
3522 /* field number is 1 based */
3523 if (fldnum == 0)
3524 ereport(ERROR,
3526 errmsg("field position must not be zero")));
3527
3530
3531 /* return empty string for empty input string */
3532 if (inputstring_len < 1)
3534
3535 /* handle empty field separator */
3536 if (fldsep_len < 1)
3537 {
3538 /* if first or last field, return input string, else empty string */
3539 if (fldnum == 1 || fldnum == -1)
3541 else
3543 }
3544
3545 /* find the first field separator */
3547
3548 found = text_position_next(&state);
3549
3550 /* special case if fldsep not found at all */
3551 if (!found)
3552 {
3554 /* if first or last field, return input string, else empty string */
3555 if (fldnum == 1 || fldnum == -1)
3557 else
3559 }
3560
3561 /*
3562 * take care of a negative field number (i.e. count from the right) by
3563 * converting to a positive field number; we need total number of fields
3564 */
3565 if (fldnum < 0)
3566 {
3567 /* we found a fldsep, so there are at least two fields */
3568 int numfields = 2;
3569
3570 while (text_position_next(&state))
3571 numfields++;
3572
3573 /* special case of last field does not require an extra pass */
3574 if (fldnum == -1)
3575 {
3576 start_ptr = text_position_get_match_ptr(&state) + state.last_match_len;
3580 end_ptr - start_ptr));
3581 }
3582
3583 /* else, convert fldnum to positive notation */
3584 fldnum += numfields + 1;
3585
3586 /* if nonexistent field, return empty string */
3587 if (fldnum <= 0)
3588 {
3591 }
3592
3593 /* reset to pointing at first match, but now with positive fldnum */
3595 found = text_position_next(&state);
3596 Assert(found);
3597 }
3598
3599 /* identify bounds of first field */
3602
3603 while (found && --fldnum > 0)
3604 {
3605 /* identify bounds of next field */
3606 start_ptr = end_ptr + state.last_match_len;
3607 found = text_position_next(&state);
3608 if (found)
3610 }
3611
3613
3614 if (fldnum > 0)
3615 {
3616 /* N'th field separator not found */
3617 /* if last field requested, return it, else empty string */
3618 if (fldnum == 1)
3619 {
3621
3624 }
3625 else
3627 }
3628 else
3629 {
3630 /* non-last field requested */
3632 }
3633
3635}
#define PG_GETARG_INT32(n)
Definition fmgr.h:269
static void text_position_reset(TextPositionState *state)
Definition varlena.c:1311

References Assert, cstring_to_text(), cstring_to_text_with_len(), ereport, errcode(), errmsg, ERROR, fb(), 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().

Referenced by executeStringInternalMethod().

◆ split_text()

static bool split_text ( FunctionCallInfo  fcinfo,
SplitTextOutputData tstate 
)
static

Definition at line 3732 of file varlena.c.

3733{
3735 text *fldsep;
3737 Oid collation = PG_GET_COLLATION();
3738 int inputstring_len;
3739 int fldsep_len;
3740 char *start_ptr;
3742
3743 /* when input string is NULL, then result is NULL too */
3744 if (PG_ARGISNULL(0))
3745 return false;
3746
3748
3749 /* fldsep can be NULL */
3750 if (!PG_ARGISNULL(1))
3752 else
3753 fldsep = NULL;
3754
3755 /* null_string can be NULL or omitted */
3756 if (PG_NARGS() > 2 && !PG_ARGISNULL(2))
3758 else
3759 null_string = NULL;
3760
3761 if (fldsep != NULL)
3762 {
3763 /*
3764 * Normal case with non-null fldsep. Use the text_position machinery
3765 * to search for occurrences of fldsep.
3766 */
3768
3771
3772 /* return empty set for empty input string */
3773 if (inputstring_len < 1)
3774 return true;
3775
3776 /* empty field separator: return input string as a one-element set */
3777 if (fldsep_len < 1)
3778 {
3780 null_string, collation);
3781 return true;
3782 }
3783
3785
3787
3788 for (;;)
3789 {
3790 bool found;
3791 char *end_ptr;
3792 int chunk_len;
3793
3795
3796 found = text_position_next(&state);
3797 if (!found)
3798 {
3799 /* fetch last field */
3801 end_ptr = NULL; /* not used, but some compilers complain */
3802 }
3803 else
3804 {
3805 /* fetch non-last field */
3808 }
3809
3810 /* build a temp text datum to pass to split_text_accum_result */
3812
3813 /* stash away this field */
3815 null_string, collation);
3816
3818
3819 if (!found)
3820 break;
3821
3822 start_ptr = end_ptr + state.last_match_len;
3823 }
3824
3826 }
3827 else
3828 {
3829 const char *end_ptr;
3830
3831 /*
3832 * When fldsep is NULL, each character in the input string becomes a
3833 * separate element in the result set. The separator is effectively
3834 * the space between characters.
3835 */
3837
3840
3841 while (inputstring_len > 0)
3842 {
3844
3846
3847 /* build a temp text datum to pass to split_text_accum_result */
3849
3850 /* stash away this field */
3852 null_string, collation);
3853
3855
3858 }
3859 }
3860
3861 return true;
3862}
int pg_mblen_range(const char *mbstr, const char *end)
Definition mbutils.c:1084
static void split_text_accum_result(SplitTextOutputData *tstate, text *field_value, text *null_string, Oid collation)
Definition varlena.c:3871

References CHECK_FOR_INTERRUPTS, cstring_to_text_with_len(), fb(), pfree(), PG_ARGISNULL, PG_GET_COLLATION, PG_GETARG_TEXT_PP, pg_mblen_range(), 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 3871 of file varlena.c.

3875{
3876 bool is_null = false;
3877
3878 if (null_string && text_isequal(field_value, null_string, collation))
3879 is_null = true;
3880
3881 if (tstate->tupstore)
3882 {
3883 Datum values[1];
3884 bool nulls[1];
3885
3887 nulls[0] = is_null;
3888
3889 tuplestore_putvalues(tstate->tupstore,
3890 tstate->tupdesc,
3891 values,
3892 nulls);
3893 }
3894 else
3895 {
3896 tstate->astate = accumArrayResult(tstate->astate,
3898 is_null,
3899 TEXTOID,
3901 }
3902}
ArrayBuildState * accumArrayResult(ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
static Datum values[MAXATTR]
Definition bootstrap.c:190
MemoryContext CurrentMemoryContext
Definition mcxt.c:161
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, const Datum *values, const bool *isnull)
Definition tuplestore.c:785
static bool text_isequal(text *txt1, text *txt2, Oid collid)
Definition varlena.c:3641

References accumArrayResult(), CurrentMemoryContext, fb(), PointerGetDatum, text_isequal(), tuplestore_putvalues(), and values.

Referenced by split_text().

◆ SplitDirectoriesString()

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

Definition at line 2953 of file varlena.c.

2955{
2956 char *nextp = rawstring;
2957 bool done = false;
2958
2959 *namelist = NIL;
2960
2961 while (scanner_isspace(*nextp))
2962 nextp++; /* skip leading whitespace */
2963
2964 if (*nextp == '\0')
2965 return true; /* empty string represents empty list */
2966
2967 /* At the top of the loop, we are at start of a new directory. */
2968 do
2969 {
2970 char *curname;
2971 char *endp;
2972
2973 if (*nextp == '"')
2974 {
2975 /* Quoted name --- collapse quote-quote pairs */
2977 if (curname == NULL)
2978 return false; /* mismatched quotes */
2979 }
2980 else
2981 {
2982 /* Unquoted name --- extends to separator or end of string */
2983 curname = endp = nextp;
2984 while (*nextp && *nextp != separator)
2985 {
2986 /* trailing whitespace should not be included in name */
2987 if (!scanner_isspace(*nextp))
2988 endp = nextp + 1;
2989 nextp++;
2990 }
2991 if (curname == endp)
2992 return false; /* empty unquoted name not allowed */
2993 }
2994
2995 while (scanner_isspace(*nextp))
2996 nextp++; /* skip trailing whitespace */
2997
2998 if (*nextp == separator)
2999 {
3000 nextp++;
3001 while (scanner_isspace(*nextp))
3002 nextp++; /* skip leading whitespace for next */
3003 /* we expect another name, so done remains false */
3004 }
3005 else if (*nextp == '\0')
3006 done = true;
3007 else
3008 return false; /* invalid syntax */
3009
3010 /* Now safe to overwrite separator with a null */
3011 *endp = '\0';
3012
3013 /* Truncate path if it's overlength */
3014 if (strlen(curname) >= MAXPGPATH)
3015 curname[MAXPGPATH - 1] = '\0';
3016
3017 /*
3018 * Finished isolating current name --- add it to list
3019 */
3023
3024 /* Loop back if we didn't reach end of string */
3025 } while (!done);
3026
3027 return true;
3028}
List * lappend(List *list, void *datum)
Definition list.c:339
char * pstrdup(const char *in)
Definition mcxt.c:1910
#define MAXPGPATH
#define NIL
Definition pg_list.h:68
void canonicalize_path(char *path)
Definition path.c:337

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

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

◆ SplitGUCList()

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

Definition at line 3063 of file varlena.c.

3065{
3066 char *nextp = rawstring;
3067 bool done = false;
3068
3069 *namelist = NIL;
3070
3071 while (scanner_isspace(*nextp))
3072 nextp++; /* skip leading whitespace */
3073
3074 if (*nextp == '\0')
3075 return true; /* empty string represents empty list */
3076
3077 /* At the top of the loop, we are at start of a new identifier. */
3078 do
3079 {
3080 char *curname;
3081 char *endp;
3082
3084 if (curname == NULL)
3085 return false; /* mismatched quotes or empty name */
3086
3087 while (scanner_isspace(*nextp))
3088 nextp++; /* skip trailing whitespace */
3089
3090 if (*nextp == separator)
3091 {
3092 nextp++;
3093 while (scanner_isspace(*nextp))
3094 nextp++; /* skip leading whitespace for next */
3095 /* we expect another name, so done remains false */
3096 }
3097 else if (*nextp == '\0')
3098 done = true;
3099 else
3100 return false; /* invalid syntax */
3101
3102 /* Now safe to overwrite separator with a null */
3103 *endp = '\0';
3104
3105 /*
3106 * Finished isolating current name --- add it to list
3107 */
3109
3110 /* Loop back if we didn't reach end of string */
3111 } while (!done);
3112
3113 return true;
3114}
char * scan_identifier(char **endp, char **nextp, char separator, bool downcase_unquoted)
Definition varlena.c:2805

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

Referenced by append_guc_value(), check_debug_io_direct(), check_log_min_messages(), dumpFunc(), pg_get_functiondef(), and PostmasterMain().

◆ SplitIdentifierString()

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

Definition at line 2870 of file varlena.c.

2872{
2873 char *nextp = rawstring;
2874 bool done = false;
2875
2876 *namelist = NIL;
2877
2878 while (scanner_isspace(*nextp))
2879 nextp++; /* skip leading whitespace */
2880
2881 if (*nextp == '\0')
2882 return true; /* empty string represents empty list */
2883
2884 /* At the top of the loop, we are at start of a new identifier. */
2885 do
2886 {
2887 char *curname;
2888 char *endp;
2889
2891 if (curname == NULL)
2892 return false; /* mismatched quotes or empty name */
2893
2894 while (scanner_isspace(*nextp))
2895 nextp++; /* skip trailing whitespace */
2896
2897 if (*nextp == separator)
2898 {
2899 nextp++;
2900 while (scanner_isspace(*nextp))
2901 nextp++; /* skip leading whitespace for next */
2902 /* we expect another name, so done remains false */
2903 }
2904 else if (*nextp == '\0')
2905 done = true;
2906 else
2907 return false; /* invalid syntax */
2908
2909 /* Now safe to overwrite separator with a null */
2910 *endp = '\0';
2911
2912 /* Truncate name if it's overlength */
2914
2915 /*
2916 * Finished isolating current name --- add it to list
2917 */
2919
2920 /* Loop back if we didn't reach end of string */
2921 } while (!done);
2922
2923 return true;
2924}
void truncate_identifier(char *ident, int len, bool warn)
Definition scansup.c:81

References fb(), lappend(), NIL, scan_identifier(), 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 4387 of file varlena.c.

4388{
4391 MemoryContext agg_context;
4392
4393 if (!AggCheckCallContext(fcinfo, &agg_context))
4394 elog(ERROR, "aggregate function called in non-aggregate context");
4395
4398
4399 if (state2 == NULL)
4400 {
4401 /*
4402 * NULL state2 is easy, just return state1, which we know is already
4403 * in the agg_context
4404 */
4405 if (state1 == NULL)
4408 }
4409
4410 if (state1 == NULL)
4411 {
4412 /* We must copy state2's data into the agg_context */
4414
4415 old_context = MemoryContextSwitchTo(agg_context);
4416 state1 = makeStringAggState(fcinfo);
4418 state1->cursor = state2->cursor;
4420 }
4421 else if (state2->len > 0)
4422 {
4423 /* Combine ... state1->cursor does not change in this case */
4425 }
4426
4428}
#define PG_RETURN_POINTER(x)
Definition fmgr.h:363
struct StringInfoData * StringInfo
Definition string.h:15
static StringInfo makeStringAggState(FunctionCallInfo fcinfo)
Definition varlena.c:4308

References AggCheckCallContext(), appendBinaryStringInfo(), elog, ERROR, fb(), 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 4468 of file varlena.c.

4469{
4470 bytea *sstate;
4473 char *data;
4474 int datalen;
4475
4476 /* cannot be called directly because of internal-type argument */
4478
4479 sstate = PG_GETARG_BYTEA_PP(0);
4480
4481 /*
4482 * Initialize a StringInfo so that we can "receive" it using the standard
4483 * recv-function infrastructure.
4484 */
4486 VARSIZE_ANY_EXHDR(sstate));
4487
4488 result = makeStringAggState(fcinfo);
4489
4490 /* cursor */
4491 result->cursor = pq_getmsgint(&buf, 4);
4492
4493 /* data */
4494 datalen = VARSIZE_ANY_EXHDR(sstate) - 4;
4495 data = (char *) pq_getmsgbytes(&buf, datalen);
4497
4498 pq_getmsgend(&buf);
4499
4501}
#define PG_GETARG_BYTEA_PP(n)
Definition fmgr.h:309
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, data, fb(), initReadOnlyStringInfo(), makeStringAggState(), PG_GETARG_BYTEA_PP, PG_RETURN_POINTER, pq_getmsgbytes(), pq_getmsgend(), pq_getmsgint(), result, VARDATA_ANY(), and VARSIZE_ANY_EXHDR().

◆ string_agg_finalfn()

Datum string_agg_finalfn ( PG_FUNCTION_ARGS  )

Definition at line 4504 of file varlena.c.

4505{
4507
4508 /* cannot be called directly because of internal-type argument */
4510
4512
4513 if (state != NULL)
4514 {
4515 /* As per comment in transfn, strip data before the cursor position */
4517 state->len - state->cursor));
4518 }
4519 else
4521}

References AggCheckCallContext(), Assert, cstring_to_text_with_len(), fb(), 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 4437 of file varlena.c.

4438{
4441 bytea *result;
4442
4443 /* cannot be called directly because of internal-type argument */
4445
4447
4449
4450 /* cursor */
4451 pq_sendint(&buf, state->cursor, 4);
4452
4453 /* data */
4454 pq_sendbytes(&buf, state->data, state->len);
4455
4457
4459}
#define PG_RETURN_BYTEA_P(x)
Definition fmgr.h:373
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, fb(), PG_GETARG_POINTER, PG_RETURN_BYTEA_P, pq_begintypsend(), pq_endtypsend(), pq_sendbytes(), pq_sendint(), and result.

◆ string_agg_transfn()

Datum string_agg_transfn ( PG_FUNCTION_ARGS  )

Definition at line 4332 of file varlena.c.

4333{
4335
4337
4338 /* Append the value unless null, preceding it with the delimiter. */
4339 if (!PG_ARGISNULL(1))
4340 {
4342 bool isfirst = false;
4343
4344 /*
4345 * You might think we can just throw away the first delimiter, however
4346 * we must keep it as we may be a parallel worker doing partial
4347 * aggregation building a state to send to the main process. We need
4348 * to keep the delimiter of every aggregation so that the combine
4349 * function can properly join up the strings of two separately
4350 * partially aggregated results. The first delimiter is only stripped
4351 * off in the final function. To know how much to strip off the front
4352 * of the string, we store the length of the first delimiter in the
4353 * StringInfo's cursor field, which we don't otherwise need here.
4354 */
4355 if (state == NULL)
4356 {
4357 state = makeStringAggState(fcinfo);
4358 isfirst = true;
4359 }
4360
4361 if (!PG_ARGISNULL(2))
4362 {
4363 text *delim = PG_GETARG_TEXT_PP(2);
4364
4366 if (isfirst)
4367 state->cursor = VARSIZE_ANY_EXHDR(delim);
4368 }
4369
4371 }
4372
4373 /*
4374 * The transition type for string_agg() is declared to be "internal",
4375 * which is a pass-by-value type the same size as a pointer.
4376 */
4377 if (state)
4380}

References appendStringInfoText(), fb(), 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 463 of file varlena.c.

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

References fb(), len, memcpy(), palloc(), result, 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 1404 of file varlena.c.

1405{
1406 char *a1p,
1407 *a2p;
1408 int len1,
1409 len2;
1410
1411 a1p = VARDATA_ANY(arg1);
1412 a2p = VARDATA_ANY(arg2);
1413
1414 len1 = VARSIZE_ANY_EXHDR(arg1);
1415 len2 = VARSIZE_ANY_EXHDR(arg2);
1416
1417 return varstr_cmp(a1p, len1, a2p, len2, collid);
1418}

References collid, fb(), 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 4648 of file varlena.c.

4649{
4650 text *result;
4651
4652 result = concat_internal("", 0, fcinfo);
4653 if (result == NULL)
4656}
static text * concat_internal(const char *sepstr, int argidx, FunctionCallInfo fcinfo)
Definition varlena.c:4568

References concat_internal(), fb(), PG_RETURN_NULL, PG_RETURN_TEXT_P, and result.

◆ text_concat_ws()

Datum text_concat_ws ( PG_FUNCTION_ARGS  )

Definition at line 4663 of file varlena.c.

4664{
4665 char *sep;
4666 text *result;
4667
4668 /* return NULL when separator is NULL */
4669 if (PG_ARGISNULL(0))
4672
4673 result = concat_internal(sep, 1, fcinfo);
4674 if (result == NULL)
4677}

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

◆ text_format()

Datum text_format ( PG_FUNCTION_ARGS  )

Definition at line 4784 of file varlena.c.

4785{
4786 text *fmt;
4788 const char *cp;
4789 const char *start_ptr;
4790 const char *end_ptr;
4791 text *result;
4792 int arg;
4793 bool funcvariadic;
4794 int nargs;
4795 Datum *elements = NULL;
4796 bool *nulls = NULL;
4797 Oid element_type = InvalidOid;
4802
4803 /* When format string is null, immediately return null */
4804 if (PG_ARGISNULL(0))
4806
4807 /* If argument is marked VARIADIC, expand array into elements */
4808 if (get_fn_expr_variadic(fcinfo->flinfo))
4809 {
4810 ArrayType *arr;
4811 int16 elmlen;
4812 bool elmbyval;
4813 char elmalign;
4814 int nitems;
4815
4816 /* Should have just the one argument */
4817 Assert(PG_NARGS() == 2);
4818
4819 /* If argument is NULL, we treat it as zero-length array */
4820 if (PG_ARGISNULL(1))
4821 nitems = 0;
4822 else
4823 {
4824 /*
4825 * Non-null argument had better be an array. We assume that any
4826 * call context that could let get_fn_expr_variadic return true
4827 * will have checked that a VARIADIC-labeled parameter actually is
4828 * an array. So it should be okay to just Assert that it's an
4829 * array rather than doing a full-fledged error check.
4830 */
4832
4833 /* OK, safe to fetch the array value */
4834 arr = PG_GETARG_ARRAYTYPE_P(1);
4835
4836 /* Get info about array element type */
4837 element_type = ARR_ELEMTYPE(arr);
4838 get_typlenbyvalalign(element_type,
4839 &elmlen, &elmbyval, &elmalign);
4840
4841 /* Extract all array elements */
4842 deconstruct_array(arr, element_type, elmlen, elmbyval, elmalign,
4843 &elements, &nulls, &nitems);
4844 }
4845
4846 nargs = nitems + 1;
4847 funcvariadic = true;
4848 }
4849 else
4850 {
4851 /* Non-variadic case, we'll process the arguments individually */
4852 nargs = PG_NARGS();
4853 funcvariadic = false;
4854 }
4855
4856 /* Setup for main loop. */
4861 arg = 1; /* next argument position to print */
4862
4863 /* Scan format string, looking for conversion specifiers. */
4864 for (cp = start_ptr; cp < end_ptr; cp++)
4865 {
4866 int argpos;
4867 int widthpos;
4868 int flags;
4869 int width;
4870 Datum value;
4871 bool isNull;
4872 Oid typid;
4873
4874 /*
4875 * If it's not the start of a conversion specifier, just copy it to
4876 * the output buffer.
4877 */
4878 if (*cp != '%')
4879 {
4881 continue;
4882 }
4883
4885
4886 /* Easy case: %% outputs a single % */
4887 if (*cp == '%')
4888 {
4890 continue;
4891 }
4892
4893 /* Parse the optional portions of the format specifier */
4895 &argpos, &widthpos,
4896 &flags, &width);
4897
4898 /*
4899 * Next we should see the main conversion specifier. Whether or not
4900 * an argument position was present, it's known that at least one
4901 * character remains in the string at this point. Experience suggests
4902 * that it's worth checking that that character is one of the expected
4903 * ones before we try to fetch arguments, so as to produce the least
4904 * confusing response to a mis-formatted specifier.
4905 */
4906 if (strchr("sIL", *cp) == NULL)
4907 ereport(ERROR,
4909 errmsg("unrecognized format() type specifier \"%.*s\"",
4911 errhint("For a single \"%%\" use \"%%%%\".")));
4912
4913 /* If indirect width was specified, get its value */
4914 if (widthpos >= 0)
4915 {
4916 /* Collect the specified or next argument position */
4917 if (widthpos > 0)
4918 arg = widthpos;
4919 if (arg >= nargs)
4920 ereport(ERROR,
4922 errmsg("too few arguments for format()")));
4923
4924 /* Get the value and type of the selected argument */
4925 if (!funcvariadic)
4926 {
4928 isNull = PG_ARGISNULL(arg);
4929 typid = get_fn_expr_argtype(fcinfo->flinfo, arg);
4930 }
4931 else
4932 {
4933 value = elements[arg - 1];
4934 isNull = nulls[arg - 1];
4935 typid = element_type;
4936 }
4937 if (!OidIsValid(typid))
4938 elog(ERROR, "could not determine data type of format() input");
4939
4940 arg++;
4941
4942 /* We can treat NULL width the same as zero */
4943 if (isNull)
4944 width = 0;
4945 else if (typid == INT4OID)
4946 width = DatumGetInt32(value);
4947 else if (typid == INT2OID)
4948 width = DatumGetInt16(value);
4949 else
4950 {
4951 /* For less-usual datatypes, convert to text then to int */
4952 char *str;
4953
4954 if (typid != prev_width_type)
4955 {
4957 bool typIsVarlena;
4958
4961 prev_width_type = typid;
4962 }
4963
4965
4966 /* pg_strtoint32 will complain about bad data or overflow */
4967 width = pg_strtoint32(str);
4968
4969 pfree(str);
4970 }
4971 }
4972
4973 /* Collect the specified or next argument position */
4974 if (argpos > 0)
4975 arg = argpos;
4976 if (arg >= nargs)
4977 ereport(ERROR,
4979 errmsg("too few arguments for format()")));
4980
4981 /* Get the value and type of the selected argument */
4982 if (!funcvariadic)
4983 {
4985 isNull = PG_ARGISNULL(arg);
4986 typid = get_fn_expr_argtype(fcinfo->flinfo, arg);
4987 }
4988 else
4989 {
4990 value = elements[arg - 1];
4991 isNull = nulls[arg - 1];
4992 typid = element_type;
4993 }
4994 if (!OidIsValid(typid))
4995 elog(ERROR, "could not determine data type of format() input");
4996
4997 arg++;
4998
4999 /*
5000 * Get the appropriate typOutput function, reusing previous one if
5001 * same type as previous argument. That's particularly useful in the
5002 * variadic-array case, but often saves work even for ordinary calls.
5003 */
5004 if (typid != prev_type)
5005 {
5007 bool typIsVarlena;
5008
5011 prev_type = typid;
5012 }
5013
5014 /*
5015 * And now we can format the value.
5016 */
5017 switch (*cp)
5018 {
5019 case 's':
5020 case 'I':
5021 case 'L':
5023 value, isNull,
5024 flags, width);
5025 break;
5026 default:
5027 /* should not get here, because of previous check */
5028 ereport(ERROR,
5030 errmsg("unrecognized format() type specifier \"%.*s\"",
5032 errhint("For a single \"%%\" use \"%%%%\".")));
5033 break;
5034 }
5035 }
5036
5037 /* Don't need deconstruct_array results anymore. */
5038 if (elements != NULL)
5039 pfree(elements);
5040 if (nulls != NULL)
5041 pfree(nulls);
5042
5043 /* Generate results. */
5045 pfree(str.data);
5046
5048}
void deconstruct_array(const ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
int16_t int16
Definition c.h:619
Datum arg
Definition elog.c:1323
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition fmgr.c:129
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition lsyscache.c:2502
int32 pg_strtoint32(const char *s)
Definition numutils.c:382
static int16 DatumGetInt16(Datum X)
Definition postgres.h:162
#define InvalidOid
#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:5187
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:5110
#define ADVANCE_PARSE_POINTER(ptr, end_ptr)
Definition varlena.c:4771

References ADVANCE_PARSE_POINTER, appendStringInfoCharMacro, arg, ARR_ELEMTYPE, Assert, cstring_to_text_with_len(), DatumGetInt16(), DatumGetInt32(), deconstruct_array(), elog, ereport, errcode(), errhint(), errmsg, ERROR, fb(), 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_range(), PG_NARGS, PG_RETURN_NULL, PG_RETURN_TEXT_P, pg_strtoint32(), result, 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 5236 of file varlena.c.

5238{
5239 bool align_to_left = false;
5240 int len;
5241
5242 /* fast path for typical easy case */
5243 if (width == 0)
5244 {
5246 return;
5247 }
5248
5249 if (width < 0)
5250 {
5251 /* Negative width: implicit '-' flag, then take absolute value */
5252 align_to_left = true;
5253 /* -INT_MIN is undefined */
5254 if (width <= INT_MIN)
5255 ereport(ERROR,
5257 errmsg("number is out of range")));
5258 width = -width;
5259 }
5260 else if (flags & TEXT_FORMAT_FLAG_MINUS)
5261 align_to_left = true;
5262
5263 len = pg_mbstrlen(str);
5264 if (align_to_left)
5265 {
5266 /* left justify */
5268 if (len < width)
5269 appendStringInfoSpaces(buf, width - len);
5270 }
5271 else
5272 {
5273 /* right justify */
5274 if (len < width)
5275 appendStringInfoSpaces(buf, width - len);
5277 }
5278}
int pg_mbstrlen(const char *mbstr)
Definition mbutils.c:1165
void appendStringInfoSpaces(StringInfo str, int count)
Definition stringinfo.c:260
#define TEXT_FORMAT_FLAG_MINUS
Definition varlena.c:4769

References appendStringInfoSpaces(), appendStringInfoString(), buf, ereport, errcode(), errmsg, ERROR, fb(), 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 5288 of file varlena.c.

5289{
5290 return text_format(fcinfo);
5291}
Datum text_format(PG_FUNCTION_ARGS)
Definition varlena.c:4784

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

5062{
5063 bool found = false;
5064 const char *cp = *ptr;
5065 int val = 0;
5066
5067 while (*cp >= '0' && *cp <= '9')
5068 {
5069 int8 digit = (*cp - '0');
5070
5071 if (unlikely(pg_mul_s32_overflow(val, 10, &val)) ||
5073 ereport(ERROR,
5075 errmsg("number is out of range")));
5077 found = true;
5078 }
5079
5080 *ptr = cp;
5081 *value = val;
5082
5083 return found;
5084}
int8_t int8
Definition c.h:618
#define unlikely(x)
Definition c.h:438
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, fb(), 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 5110 of file varlena.c.

5113{
5114 const char *cp = start_ptr;
5115 int n;
5116
5117 /* set defaults for output parameters */
5118 *argpos = -1;
5119 *widthpos = -1;
5120 *flags = 0;
5121 *width = 0;
5122
5123 /* try to identify first number */
5125 {
5126 if (*cp != '$')
5127 {
5128 /* Must be just a width and a type, so we're done */
5129 *width = n;
5130 return cp;
5131 }
5132 /* The number was argument position */
5133 *argpos = n;
5134 /* Explicit 0 for argument index is immediately refused */
5135 if (n == 0)
5136 ereport(ERROR,
5138 errmsg("format specifies argument 0, but arguments are numbered from 1")));
5140 }
5141
5142 /* Handle flags (only minus is supported now) */
5143 while (*cp == '-')
5144 {
5145 *flags |= TEXT_FORMAT_FLAG_MINUS;
5147 }
5148
5149 if (*cp == '*')
5150 {
5151 /* Handle indirect width */
5154 {
5155 /* number in this position must be closed by $ */
5156 if (*cp != '$')
5157 ereport(ERROR,
5159 errmsg("width argument position must be ended by \"$\"")));
5160 /* The number was width argument position */
5161 *widthpos = n;
5162 /* Explicit 0 for argument index is immediately refused */
5163 if (n == 0)
5164 ereport(ERROR,
5166 errmsg("format specifies argument 0, but arguments are numbered from 1")));
5168 }
5169 else
5170 *widthpos = 0; /* width's argument position is unspecified */
5171 }
5172 else
5173 {
5174 /* Check for direct width specification */
5176 *width = n;
5177 }
5178
5179 /* cp should now be pointing at type character */
5180 return cp;
5181}
static bool text_format_parse_digits(const char **ptr, const char *end_ptr, int *value)
Definition varlena.c:5061

References ADVANCE_PARSE_POINTER, ereport, errcode(), errmsg, ERROR, fb(), 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 5187 of file varlena.c.

5191{
5192 char *str;
5193
5194 /* Handle NULL arguments before trying to stringify the value. */
5195 if (isNull)
5196 {
5197 if (conversion == 's')
5198 text_format_append_string(buf, "", flags, width);
5199 else if (conversion == 'L')
5200 text_format_append_string(buf, "NULL", flags, width);
5201 else if (conversion == 'I')
5202 ereport(ERROR,
5204 errmsg("null values cannot be formatted as an SQL identifier")));
5205 return;
5206 }
5207
5208 /* Stringify. */
5210
5211 /* Escape. */
5212 if (conversion == 'I')
5213 {
5214 /* quote_identifier may or may not allocate a new string. */
5216 }
5217 else if (conversion == 'L')
5218 {
5219 char *qstr = quote_literal_cstr(str);
5220
5221 text_format_append_string(buf, qstr, flags, width);
5222 /* quote_literal_cstr() always allocates a new string */
5223 pfree(qstr);
5224 }
5225 else
5226 text_format_append_string(buf, str, flags, width);
5227
5228 /* Cleanup. */
5229 pfree(str);
5230}
char * quote_literal_cstr(const char *rawstr)
Definition quote.c:101
const char * quote_identifier(const char *ident)
static void text_format_append_string(StringInfo buf, const char *str, int flags, int width)
Definition varlena.c:5236

References buf, ereport, errcode(), errmsg, ERROR, fb(), 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 1578 of file varlena.c.

1579{
1582 bool result;
1583
1585
1588
1590}

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

Referenced by gbt_textge().

◆ text_gt()

Datum text_gt ( PG_FUNCTION_ARGS  )

Definition at line 1563 of file varlena.c.

1564{
1567 bool result;
1568
1570
1573
1575}

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

Referenced by gbt_textgt().

◆ text_isequal()

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

Definition at line 3641 of file varlena.c.

3642{
3644 collid,
3647}
static bool DatumGetBool(Datum X)
Definition postgres.h:100
Datum texteq(PG_FUNCTION_ARGS)
Definition varlena.c:1429

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

Referenced by split_text_accum_result().

◆ text_larger()

Datum text_larger ( PG_FUNCTION_ARGS  )

Definition at line 2332 of file varlena.c.

2333{
2336 text *result;
2337
2338 result = ((text_cmp(arg1, arg2, PG_GET_COLLATION()) > 0) ? arg1 : arg2);
2339
2341}

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

◆ text_le()

Datum text_le ( PG_FUNCTION_ARGS  )

Definition at line 1548 of file varlena.c.

1549{
1552 bool result;
1553
1555
1558
1560}

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

Referenced by gbt_textle().

◆ text_left()

Datum text_left ( PG_FUNCTION_ARGS  )

Definition at line 4684 of file varlena.c.

4685{
4686 int n = PG_GETARG_INT32(1);
4687
4688 if (n < 0)
4689 {
4691 const char *p = VARDATA_ANY(str);
4692 int len = VARSIZE_ANY_EXHDR(str);
4693 int rlen;
4694
4695 n = pg_mbstrlen_with_len(p, len) + n;
4696 rlen = pg_mbcharcliplen(p, len, n);
4698 }
4699 else
4701}
int pg_mbstrlen_with_len(const char *mbstr, int limit)
Definition mbutils.c:1186
int pg_mbcharcliplen(const char *mbstr, int len, int limit)
Definition mbutils.c:1254
static text * text_substring(Datum str, int32 start, int32 length, bool length_not_specified)
Definition varlena.c:586

References cstring_to_text_with_len(), fb(), 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 410 of file varlena.c.

411{
412 /* fastpath when max encoding length is one */
415 else
416 {
417 text *t = DatumGetTextPP(str);
418
420 }
421}
Size toast_raw_datum_size(Datum value)
Definition detoast.c:545
#define DatumGetTextPP(X)
Definition fmgr.h:293

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

1534{
1537 bool result;
1538
1540
1543
1545}

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

Referenced by gbt_textlt().

◆ text_name()

Datum text_name ( PG_FUNCTION_ARGS  )

Definition at line 2681 of file varlena.c.

2682{
2683 text *s = PG_GETARG_TEXT_PP(0);
2684 Name result;
2685 int len;
2686
2688
2689 /* Truncate oversize input */
2690 if (len >= NAMEDATALEN)
2692
2693 /* We use palloc0 here to ensure result is zero-padded */
2696
2698}
NameData * Name
Definition c.h:833
#define PG_RETURN_NAME(x)
Definition fmgr.h:365
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition mbutils.c:1212
void * palloc0(Size size)
Definition mcxt.c:1420

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

◆ text_overlay()

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

Definition at line 856 of file varlena.c.

857{
858 text *result;
859 text *s1;
860 text *s2;
861 int sp_pl_sl;
862
863 /*
864 * Check for possible integer-overflow cases. For negative sp, throw a
865 * "substring length" error because that's what should be expected
866 * according to the spec's definition of OVERLAY().
867 */
868 if (sp <= 0)
871 errmsg("negative substring length not allowed")));
875 errmsg("integer out of range")));
876
877 s1 = text_substring(PointerGetDatum(t1), 1, sp - 1, false);
881
882 return result;
883}
static text * text_catenate(text *t1, text *t2)
Definition varlena.c:463

References ereport, errcode(), errmsg, ERROR, fb(), pg_add_s32_overflow(), PointerGetDatum, result, 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 2612 of file varlena.c.

2613{
2616 int result;
2617
2619
2622
2623 PG_RETURN_BOOL(result >= 0);
2624}

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

◆ text_pattern_gt()

Datum text_pattern_gt ( PG_FUNCTION_ARGS  )

Definition at line 2628 of file varlena.c.

2629{
2632 int result;
2633
2635
2638
2640}

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

◆ text_pattern_le()

Datum text_pattern_le ( PG_FUNCTION_ARGS  )

Definition at line 2596 of file varlena.c.

2597{
2600 int result;
2601
2603
2606
2607 PG_RETURN_BOOL(result <= 0);
2608}

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

◆ text_pattern_lt()

Datum text_pattern_lt ( PG_FUNCTION_ARGS  )

Definition at line 2580 of file varlena.c.

2581{
2584 int result;
2585
2587
2590
2592}

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

◆ text_position()

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

Definition at line 916 of file varlena.c.

917{
919 int result;
920
922
923 /* Empty needle always matches at position 1 */
924 if (VARSIZE_ANY_EXHDR(t2) < 1)
925 return 1;
926
927 /* Otherwise, can't match if haystack is shorter than needle */
929 pg_newlocale_from_collation(collid)->deterministic)
930 return 0;
931
933 /* don't need greedy mode here */
934 state.greedy = false;
935
937 result = 0;
938 else
941 return result;
942}
static int text_position_get_match_pos(TextPositionState *state)
Definition varlena.c:1295

References check_collation_set(), collid, fb(), pg_newlocale_from_collation(), result, 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 1319 of file varlena.c.

1320{
1321 /* no cleanup needed */
1322}

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

1296{
1297 /* Convert the byte position to char position. */
1298 state->refpos += pg_mbstrlen_with_len(state->refpoint,
1299 state->last_match - state->refpoint);
1300 state->refpoint = state->last_match;
1301 return state->refpos + 1;
1302}

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

1285{
1286 return state->last_match;
1287}

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

◆ text_position_next()

static bool text_position_next ( TextPositionState state)
static

Definition at line 1083 of file varlena.c.

1084{
1085 int needle_len = state->len2;
1086 char *start_ptr;
1087 char *matchptr;
1088
1089 if (needle_len <= 0)
1090 return false; /* result for empty pattern */
1091
1092 /* Start from the point right after the previous match. */
1093 if (state->last_match)
1094 start_ptr = state->last_match + state->last_match_len;
1095 else
1096 start_ptr = state->str1;
1097
1098retry:
1100
1101 if (!matchptr)
1102 return false;
1103
1104 /*
1105 * Found a match for the byte sequence. If this is a multibyte encoding,
1106 * where one character's byte sequence can appear inside a longer
1107 * multi-byte character, we need to verify that the match was at a
1108 * character boundary, not in the middle of a multi-byte character.
1109 */
1110 if (state->is_multibyte_char_in_char && state->locale->deterministic)
1111 {
1112 const char *haystack_end = state->str1 + state->len1;
1113
1114 /* Walk one character at a time, until we reach the match. */
1115
1116 /* the search should never move backwards. */
1117 Assert(state->refpoint <= matchptr);
1118
1119 while (state->refpoint < matchptr)
1120 {
1121 /* step to next character. */
1122 state->refpoint += pg_mblen_range(state->refpoint, haystack_end);
1123 state->refpos++;
1124
1125 /*
1126 * If we stepped over the match's start position, then it was a
1127 * false positive, where the byte sequence appeared in the middle
1128 * of a multi-byte character. Skip it, and continue the search at
1129 * the next character boundary.
1130 */
1131 if (state->refpoint > matchptr)
1132 {
1133 start_ptr = state->refpoint;
1134 goto retry;
1135 }
1136 }
1137 }
1138
1139 state->last_match = matchptr;
1140 state->last_match_len = state->last_match_len_tmp;
1141 return true;
1142}
static char * text_position_next_internal(char *start_ptr, TextPositionState *state)
Definition varlena.c:1150

References Assert, fb(), pg_mblen_range(), 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 1150 of file varlena.c.

1151{
1152 int haystack_len = state->len1;
1153 int needle_len = state->len2;
1154 int skiptablemask = state->skiptablemask;
1155 const char *haystack = state->str1;
1156 const char *needle = state->str2;
1157 const char *haystack_end = &haystack[haystack_len];
1158 const char *hptr;
1159
1161 Assert(needle_len > 0);
1162
1163 state->last_match_len_tmp = needle_len;
1164
1165 if (!state->locale->deterministic)
1166 {
1167 /*
1168 * With a nondeterministic collation, we have to use an unoptimized
1169 * route. We walk through the haystack and see if at each position
1170 * there is a substring of the remaining string that is equal to the
1171 * needle under the given collation.
1172 *
1173 * Note, the found substring could have a different length than the
1174 * needle. Callers that want to skip over the found string need to
1175 * read the length of the found substring from last_match_len rather
1176 * than just using the length of their needle.
1177 *
1178 * Most callers will require "greedy" semantics, meaning that we need
1179 * to find the longest such substring, not the shortest. For callers
1180 * that don't need greedy semantics, we can finish on the first match.
1181 *
1182 * This loop depends on the assumption that the needle is nonempty and
1183 * any matching substring must also be nonempty. (Even if the
1184 * collation would accept an empty match, returning one would send
1185 * callers that search for successive matches into an infinite loop.)
1186 */
1187 const char *result_hptr = NULL;
1188
1189 hptr = start_ptr;
1190 while (hptr < haystack_end)
1191 {
1192 const char *test_end;
1193
1194 /*
1195 * First check the common case that there is a match in the
1196 * haystack of exactly the length of the needle.
1197 */
1198 if (!state->greedy &&
1201 return (char *) hptr;
1202
1203 /*
1204 * Else check if any of the non-empty substrings starting at hptr
1205 * compare equal to the needle.
1206 */
1207 test_end = hptr;
1208 do
1209 {
1211 if (pg_strncoll(hptr, (test_end - hptr), needle, needle_len, state->locale) == 0)
1212 {
1213 state->last_match_len_tmp = (test_end - hptr);
1214 result_hptr = hptr;
1215 if (!state->greedy)
1216 break;
1217 }
1218 } while (test_end < haystack_end);
1219
1220 if (result_hptr)
1221 break;
1222
1224 }
1225
1226 return (char *) result_hptr;
1227 }
1228 else if (needle_len == 1)
1229 {
1230 /* No point in using B-M-H for a one-character needle */
1231 char nchar = *needle;
1232
1233 hptr = start_ptr;
1234 while (hptr < haystack_end)
1235 {
1236 if (*hptr == nchar)
1237 return (char *) hptr;
1238 hptr++;
1239 }
1240 }
1241 else
1242 {
1243 const char *needle_last = &needle[needle_len - 1];
1244
1245 /* Start at startpos plus the length of the needle */
1246 hptr = start_ptr + needle_len - 1;
1247 while (hptr < haystack_end)
1248 {
1249 /* Match the needle scanning *backward* */
1250 const char *nptr;
1251 const char *p;
1252
1253 nptr = needle_last;
1254 p = hptr;
1255 while (*nptr == *p)
1256 {
1257 /* Matched it all? If so, return 1-based position */
1258 if (nptr == needle)
1259 return (char *) p;
1260 nptr--, p--;
1261 }
1262
1263 /*
1264 * No match, so use the haystack char at hptr to decide how far to
1265 * advance. If the needle had any occurrence of that character
1266 * (or more precisely, one sharing the same skiptable entry)
1267 * before its last character, then we advance far enough to align
1268 * the last such needle character with that haystack position.
1269 * Otherwise we can advance by the whole needle length.
1270 */
1271 hptr += state->skiptable[(unsigned char) *hptr & skiptablemask];
1272 }
1273 }
1274
1275 return 0; /* not found */
1276}
int pg_strncoll(const char *arg1, size_t len1, const char *arg2, size_t len2, pg_locale_t locale)
Definition pg_locale.c:1400

References Assert, fb(), pg_mblen_range(), and pg_strncoll().

Referenced by text_position_next().

◆ text_position_reset()

static void text_position_reset ( TextPositionState state)
static

Definition at line 1311 of file varlena.c.

1312{
1313 state->last_match = NULL;
1314 state->refpoint = state->str1;
1315 state->refpos = 0;
1316}

References fb().

Referenced by split_part().

◆ text_position_setup()

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

Definition at line 962 of file varlena.c.

963{
964 int len1 = VARSIZE_ANY_EXHDR(t1);
965 int len2 = VARSIZE_ANY_EXHDR(t2);
966
968
970
971 /*
972 * Most callers need greedy mode, but some might want to unset this to
973 * optimize.
974 */
975 state->greedy = true;
976
977 Assert(len2 > 0);
978
979 /*
980 * Even with a multi-byte encoding, we perform the search using the raw
981 * byte sequence, ignoring multibyte issues. For UTF-8, that works fine,
982 * because in UTF-8 the byte sequence of one character cannot contain
983 * another character. For other multi-byte encodings, we do the search
984 * initially as a simple byte search, ignoring multibyte issues, but
985 * verify afterwards that the match we found is at a character boundary,
986 * and continue the search if it was a false match.
987 */
989 state->is_multibyte_char_in_char = false;
990 else if (GetDatabaseEncoding() == PG_UTF8)
991 state->is_multibyte_char_in_char = false;
992 else
993 state->is_multibyte_char_in_char = true;
994
995 state->str1 = VARDATA_ANY(t1);
996 state->str2 = VARDATA_ANY(t2);
997 state->len1 = len1;
998 state->len2 = len2;
999 state->last_match = NULL;
1000 state->refpoint = state->str1;
1001 state->refpos = 0;
1002
1003 /*
1004 * Prepare the skip table for Boyer-Moore-Horspool searching. In these
1005 * notes we use the terminology that the "haystack" is the string to be
1006 * searched (t1) and the "needle" is the pattern being sought (t2).
1007 *
1008 * If the needle is empty or bigger than the haystack then there is no
1009 * point in wasting cycles initializing the table. We also choose not to
1010 * use B-M-H for needles of length 1, since the skip table can't possibly
1011 * save anything in that case.
1012 *
1013 * (With nondeterministic collations, the search is already
1014 * multibyte-aware, so we don't need this.)
1015 */
1016 if (len1 >= len2 && len2 > 1 && state->locale->deterministic)
1017 {
1018 int searchlength = len1 - len2;
1019 int skiptablemask;
1020 int last;
1021 int i;
1022 const char *str2 = state->str2;
1023
1024 /*
1025 * First we must determine how much of the skip table to use. The
1026 * declaration of TextPositionState allows up to 256 elements, but for
1027 * short search problems we don't really want to have to initialize so
1028 * many elements --- it would take too long in comparison to the
1029 * actual search time. So we choose a useful skip table size based on
1030 * the haystack length minus the needle length. The closer the needle
1031 * length is to the haystack length the less useful skipping becomes.
1032 *
1033 * Note: since we use bit-masking to select table elements, the skip
1034 * table size MUST be a power of 2, and so the mask must be 2^N-1.
1035 */
1036 if (searchlength < 16)
1037 skiptablemask = 3;
1038 else if (searchlength < 64)
1039 skiptablemask = 7;
1040 else if (searchlength < 128)
1041 skiptablemask = 15;
1042 else if (searchlength < 512)
1043 skiptablemask = 31;
1044 else if (searchlength < 2048)
1045 skiptablemask = 63;
1046 else if (searchlength < 4096)
1047 skiptablemask = 127;
1048 else
1049 skiptablemask = 255;
1050 state->skiptablemask = skiptablemask;
1051
1052 /*
1053 * Initialize the skip table. We set all elements to the needle
1054 * length, since this is the correct skip distance for any character
1055 * not found in the needle.
1056 */
1057 for (i = 0; i <= skiptablemask; i++)
1058 state->skiptable[i] = len2;
1059
1060 /*
1061 * Now examine the needle. For each character except the last one,
1062 * set the corresponding table element to the appropriate skip
1063 * distance. Note that when two characters share the same skip table
1064 * entry, the one later in the needle must determine the skip
1065 * distance.
1066 */
1067 last = len2 - 1;
1068
1069 for (i = 0; i < last; i++)
1070 state->skiptable[(unsigned char) str2[i] & skiptablemask] = last - i;
1071 }
1072}
#define PG_UTF8
Definition mbprint.c:43
int GetDatabaseEncoding(void)
Definition mbutils.c:1389

References Assert, check_collation_set(), collid, fb(), 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 4729 of file varlena.c.

4730{
4732 const char *p = VARDATA_ANY(str);
4733 int len = VARSIZE_ANY_EXHDR(str);
4734 const char *endp = p + len;
4735 text *result;
4736 char *dst;
4737
4739 dst = (char *) VARDATA(result) + len;
4741
4743 {
4744 /* multibyte version */
4745 while (p < endp)
4746 {
4747 int sz;
4748
4749 sz = pg_mblen_range(p, endp);
4750 dst -= sz;
4751 memcpy(dst, p, sz);
4752 p += sz;
4753 }
4754 }
4755 else
4756 {
4757 /* single byte version */
4758 while (p < endp)
4759 *(--dst) = *p++;
4760 }
4761
4763}

References fb(), len, memcpy(), palloc(), pg_database_encoding_max_length(), PG_GETARG_TEXT_PP, pg_mblen_range(), PG_RETURN_TEXT_P, result, SET_VARSIZE(), str, VARDATA(), VARDATA_ANY(), VARHDRSZ, and VARSIZE_ANY_EXHDR().

◆ text_right()

Datum text_right ( PG_FUNCTION_ARGS  )

Definition at line 4708 of file varlena.c.

4709{
4711 const char *p = VARDATA_ANY(str);
4712 int len = VARSIZE_ANY_EXHDR(str);
4713 int n = PG_GETARG_INT32(1);
4714 int off;
4715
4716 if (n < 0)
4717 n = -n;
4718 else
4719 n = pg_mbstrlen_with_len(p, len) - n;
4720 off = pg_mbcharcliplen(p, len, n);
4721
4723}

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

2345{
2348 text *result;
2349
2350 result = ((text_cmp(arg1, arg2, PG_GET_COLLATION()) < 0) ? arg1 : arg2);
2351
2353}

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

◆ text_starts_with()

Datum text_starts_with ( PG_FUNCTION_ARGS  )

Definition at line 1593 of file varlena.c.

1594{
1599 bool result;
1600 Size len1,
1601 len2;
1602
1604
1606
1607 if (!mylocale->deterministic)
1608 ereport(ERROR,
1610 errmsg("nondeterministic collations are not supported for substring searches")));
1611
1612 len1 = toast_raw_datum_size(arg1);
1613 len2 = toast_raw_datum_size(arg2);
1614 if (len2 > len1)
1615 result = false;
1616 else
1617 {
1618 text *targ1 = text_substring(arg1, 1, len2, false);
1620
1622 VARSIZE_ANY_EXHDR(targ2)) == 0);
1623
1626 }
1627
1629}
size_t Size
Definition c.h:689

References check_collation_set(), collid, DatumGetTextPP, ereport, errcode(), errmsg, ERROR, fb(), PG_FREE_IF_COPY, PG_GET_COLLATION, PG_GETARG_DATUM, pg_newlocale_from_collation(), PG_RETURN_BOOL, result, 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 567 of file varlena.c.

568{
571 -1, true));
572}

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

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

References cstring_to_text(), DatumGetPointer(), DatumGetTextPSlice, elog, ereport, errcode(), errmsg, ERROR, fb(), i, Max, memcpy(), Min, palloc(), pfree(), pg_add_s32_overflow(), pg_database_encoding_max_length(), pg_mbcharcliplen_chars(), pg_mblen_unbounded(), 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 3655 of file varlena.c.

3656{
3658
3659 /* For array output, tstate should start as all zeroes */
3660 memset(&tstate, 0, sizeof(tstate));
3661
3662 if (!split_text(fcinfo, &tstate))
3664
3665 if (tstate.astate == NULL)
3667
3670}
#define PG_RETURN_ARRAYTYPE_P(x)
Definition array.h:265
ArrayType * construct_empty_array(Oid elmtype)
Datum makeArrayResult(ArrayBuildState *astate, MemoryContext rcontext)
#define PG_RETURN_DATUM(x)
Definition fmgr.h:354
static bool split_text(FunctionCallInfo fcinfo, SplitTextOutputData *tstate)
Definition varlena.c:3732

References construct_empty_array(), CurrentMemoryContext, fb(), 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 3681 of file varlena.c.

3682{
3683 return text_to_array(fcinfo);
3684}
Datum text_to_array(PG_FUNCTION_ARGS)
Definition varlena.c:3655

References text_to_array().

◆ text_to_cstring()

char * text_to_cstring ( const text t)

Definition at line 217 of file varlena.c.

218{
219 /* must cast away the const, unfortunately */
222 char *result;
223
224 result = (char *) palloc(len + 1);
226 result[len] = '\0';
227
228 if (tunpacked != t)
230
231 return result;
232}
#define unconstify(underlying_type, expr)
Definition c.h:1325
varlena * pg_detoast_datum_packed(varlena *datum)
Definition fmgr.c:1830

References fb(), len, memcpy(), palloc(), pfree(), pg_detoast_datum_packed(), result, 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(), ForeignServerConnectionString(), 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_advice_stash(), pg_create_restore_point(), pg_crypt(), pg_current_logfile(), pg_drop_advice_stash(), pg_get_advice_stash_contents(), 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_set_stashed_advice(), 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_mblen_func(), test_predtest(), test_slru_page_write(), test_text_to_wchars(), test_valid_server_encoding(), test_wchars_to_text(), 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 248 of file varlena.c.

249{
250 /* must cast away the const, unfortunately */
253
254 if (dst_len > 0)
255 {
256 dst_len--;
257 if (dst_len >= src_len)
259 else /* ensure truncation is encoding-safe */
262 dst[dst_len] = '\0';
263 }
264
265 if (srcunpacked != src)
267}

References fb(), memcpy(), 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 3692 of file varlena.c.

3693{
3694 ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
3696
3697 tstate.astate = NULL;
3699 tstate.tupstore = rsi->setResult;
3700 tstate.tupdesc = rsi->setDesc;
3701
3702 (void) split_text(fcinfo, &tstate);
3703
3704 return (Datum) 0;
3705}
void InitMaterializedSRF(FunctionCallInfo fcinfo, uint32 flags)
Definition funcapi.c:76
#define MAT_SRF_USE_EXPECTED_DESC
Definition funcapi.h:296
ArrayBuildState * astate
Definition varlena.c:110

References SplitTextOutputData::astate, fb(), 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 3716 of file varlena.c.

3717{
3718 return text_to_table(fcinfo);
3719}
Datum text_to_table(PG_FUNCTION_ARGS)
Definition varlena.c:3692

References text_to_table().

◆ textcat()

Datum textcat ( PG_FUNCTION_ARGS  )

Definition at line 448 of file varlena.c.

449{
452
454}

References fb(), PG_GETARG_TEXT_PP, PG_RETURN_TEXT_P, and text_catenate().

◆ texteq()

Datum texteq ( PG_FUNCTION_ARGS  )

Definition at line 1429 of file varlena.c.

1430{
1433 bool result;
1434
1436
1438
1439 if (mylocale->deterministic)
1440 {
1443 Size len1,
1444 len2;
1445
1446 /*
1447 * Since we only care about equality or not-equality, we can avoid all
1448 * the expense of strcoll() here, and just do bitwise comparison. In
1449 * fact, we don't even have to do a bitwise comparison if we can show
1450 * the lengths of the strings are unequal; which might save us from
1451 * having to detoast one or both values.
1452 */
1453 len1 = toast_raw_datum_size(arg1);
1454 len2 = toast_raw_datum_size(arg2);
1455 if (len1 != len2)
1456 result = false;
1457 else
1458 {
1461
1463 len1 - VARHDRSZ) == 0);
1464
1467 }
1468 }
1469 else
1470 {
1473
1474 result = (text_cmp(arg1, arg2, collid) == 0);
1475
1478 }
1479
1481}

References check_collation_set(), collid, DatumGetTextPP, fb(), PG_FREE_IF_COPY, PG_GET_COLLATION, PG_GETARG_DATUM, PG_GETARG_TEXT_PP, pg_newlocale_from_collation(), PG_RETURN_BOOL, result, 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 2386 of file varlena.c.

2387{
2390 size_t len1 = VARSIZE_ANY_EXHDR(arg1);
2391 size_t len2 = strlen(NameStr(*arg2));
2393 bool result;
2394
2396
2397 if (collid == C_COLLATION_OID)
2398 result = (len1 == len2 &&
2399 memcmp(VARDATA_ANY(arg1), NameStr(*arg2), len1) == 0);
2400 else
2402 NameStr(*arg2), len2,
2403 collid) == 0);
2404
2406
2408}

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

◆ textgename()

Datum textgename ( PG_FUNCTION_ARGS  )

Definition at line 2541 of file varlena.c.

2542{
2544}
Datum bttextnamecmp(PG_FUNCTION_ARGS)
Definition varlena.c:2477

References bttextnamecmp(), CmpCall, and PG_RETURN_BOOL.

◆ textgtname()

Datum textgtname ( PG_FUNCTION_ARGS  )

Definition at line 2535 of file varlena.c.

2536{
2538}

References bttextnamecmp(), CmpCall, and PG_RETURN_BOOL.

◆ textin()

Datum textin ( PG_FUNCTION_ARGS  )

Definition at line 278 of file varlena.c.

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

References cstring_to_text(), fb(), PG_GETARG_CSTRING, and PG_RETURN_TEXT_P.

Referenced by ExecEvalJsonExprPath().

◆ textlen()

Datum textlen ( PG_FUNCTION_ARGS  )

Definition at line 392 of file varlena.c.

393{
395
396 /* try to avoid decompressing argument */
398}
static int32 text_length(Datum str)
Definition varlena.c:410

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

◆ textlename()

Datum textlename ( PG_FUNCTION_ARGS  )

Definition at line 2529 of file varlena.c.

2530{
2532}

References bttextnamecmp(), CmpCall, and PG_RETURN_BOOL.

◆ textltname()

Datum textltname ( PG_FUNCTION_ARGS  )

Definition at line 2523 of file varlena.c.

2524{
2526}

References bttextnamecmp(), CmpCall, and PG_RETURN_BOOL.

◆ textne()

Datum textne ( PG_FUNCTION_ARGS  )

Definition at line 1484 of file varlena.c.

1485{
1488 bool result;
1489
1491
1493
1494 if (mylocale->deterministic)
1495 {
1498 Size len1,
1499 len2;
1500
1501 /* See comment in texteq() */
1502 len1 = toast_raw_datum_size(arg1);
1503 len2 = toast_raw_datum_size(arg2);
1504 if (len1 != len2)
1505 result = true;
1506 else
1507 {
1510
1512 len1 - VARHDRSZ) != 0);
1513
1516 }
1517 }
1518 else
1519 {
1522
1523 result = (text_cmp(arg1, arg2, collid) != 0);
1524
1527 }
1528
1530}

References check_collation_set(), collid, DatumGetTextPP, fb(), PG_FREE_IF_COPY, PG_GET_COLLATION, PG_GETARG_DATUM, PG_GETARG_TEXT_PP, pg_newlocale_from_collation(), PG_RETURN_BOOL, result, text_cmp(), toast_raw_datum_size(), VARDATA_ANY(), and VARHDRSZ.

◆ textnename()

Datum textnename ( PG_FUNCTION_ARGS  )

Definition at line 2436 of file varlena.c.

2437{
2440 size_t len1 = VARSIZE_ANY_EXHDR(arg1);
2441 size_t len2 = strlen(NameStr(*arg2));
2443 bool result;
2444
2446
2447 if (collid == C_COLLATION_OID)
2448 result = !(len1 == len2 &&
2449 memcmp(VARDATA_ANY(arg1), NameStr(*arg2), len1) == 0);
2450 else
2451 result = !(varstr_cmp(VARDATA_ANY(arg1), len1,
2452 NameStr(*arg2), len2,
2453 collid) == 0);
2454
2456
2458}

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

◆ textoctetlen()

Datum textoctetlen ( PG_FUNCTION_ARGS  )

Definition at line 429 of file varlena.c.

430{
432
433 /* We need not detoast the input at all */
435}

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

◆ textout()

Datum textout ( PG_FUNCTION_ARGS  )

Definition at line 289 of file varlena.c.

290{
292
294}
#define TextDatumGetCString(d)
Definition builtins.h:99
#define PG_RETURN_CSTRING(x)
Definition fmgr.h:364

References fb(), PG_GETARG_DATUM, PG_RETURN_CSTRING, and TextDatumGetCString.

Referenced by pg_node_tree_out().

◆ textoverlay()

Datum textoverlay ( PG_FUNCTION_ARGS  )

Definition at line 833 of file varlena.c.

834{
837 int sp = PG_GETARG_INT32(2); /* substring start position */
838 int sl = PG_GETARG_INT32(3); /* substring length */
839
841}
static text * text_overlay(text *t1, text *t2, int sp, int sl)
Definition varlena.c:856

References fb(), 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 844 of file varlena.c.

845{
848 int sp = PG_GETARG_INT32(2); /* substring start position */
849 int sl;
850
851 sl = text_length(PointerGetDatum(t2)); /* defaults to length(t2) */
853}

References fb(), 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 893 of file varlena.c.

894{
897
899}
static int text_position(text *t1, text *t2, Oid collid)
Definition varlena.c:916

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

◆ textrecv()

Datum textrecv ( PG_FUNCTION_ARGS  )

Definition at line 300 of file varlena.c.

301{
303 text *result;
304 char *str;
305 int nbytes;
306
307 str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
308
310 pfree(str);
312}
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(), result, and str.

◆ textsend()

Datum textsend ( PG_FUNCTION_ARGS  )

Definition at line 318 of file varlena.c.

319{
320 text *t = PG_GETARG_TEXT_PP(0);
322
326}
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 2722 of file varlena.c.

2723{
2724 char *rawname;
2725 List *result = NIL;
2726 List *namelist;
2727 ListCell *l;
2728
2729 /* Convert to C string (handles possible detoasting). */
2730 /* Note we rely on being able to modify rawname below. */
2731 rawname = text_to_cstring(textval);
2732
2734 ereport(ERROR,
2736 errmsg("invalid name syntax")));
2737
2738 if (namelist == NIL)
2739 ereport(ERROR,
2741 errmsg("invalid name syntax")));
2742
2743 foreach(l, namelist)
2744 {
2745 char *curname = (char *) lfirst(l);
2746
2748 }
2749
2750 pfree(rawname);
2752
2753 return result;
2754}
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:2870

References ereport, errcode(), errmsg, ERROR, fb(), lappend(), lfirst, list_free(), makeString(), NIL, pfree(), pstrdup(), result, 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 4102 of file varlena.c.

4103{
4105
4107}
uint32_t uint32
Definition c.h:624
static text * convert_to_base(uint64 value, int base)
Definition varlena.c:4076

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

◆ to_bin64()

Datum to_bin64 ( PG_FUNCTION_ARGS  )

Definition at line 4109 of file varlena.c.

4110{
4112
4114}
#define PG_GETARG_INT64(n)
Definition fmgr.h:284

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

◆ to_hex32()

Datum to_hex32 ( PG_FUNCTION_ARGS  )

Definition at line 4140 of file varlena.c.

4141{
4143
4145}

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

4148{
4150
4152}

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

◆ to_oct32()

Datum to_oct32 ( PG_FUNCTION_ARGS  )

Definition at line 4121 of file varlena.c.

4122{
4124
4126}

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

◆ to_oct64()

Datum to_oct64 ( PG_FUNCTION_ARGS  )

Definition at line 4128 of file varlena.c.

4129{
4131
4133}

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

◆ unicode_assigned()

Datum unicode_assigned ( PG_FUNCTION_ARGS  )

Definition at line 5463 of file varlena.c.

5464{
5466 unsigned char *p;
5467 int size;
5468
5470 ereport(ERROR,
5471 (errmsg("Unicode categorization can only be performed if server encoding is UTF8")));
5472
5473 /* convert to char32_t */
5475 p = (unsigned char *) VARDATA_ANY(input);
5476 for (int i = 0; i < size; i++)
5477 {
5478 char32_t uchar = utf8_to_unicode(p);
5479 int category = unicode_category(uchar);
5480
5481 if (category == PG_U_UNASSIGNED)
5482 PG_RETURN_BOOL(false);
5483
5484 p += pg_utf_mblen(p);
5485 }
5486
5487 PG_RETURN_BOOL(true);
5488}
FILE * input
static char32_t utf8_to_unicode(const unsigned char *c)
Definition mbprint.c:53
#define pg_utf_mblen
Definition pg_wchar.h:486
pg_unicode_category unicode_category(char32_t code)
@ PG_U_UNASSIGNED

References ereport, errmsg, ERROR, fb(), 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 5557 of file varlena.c.

5558{
5562 size_t size;
5563 char32_t *input_chars;
5564 char32_t *output_chars;
5565 unsigned char *p;
5566 size_t i;
5567 UnicodeNormalizationQC quickcheck;
5568 size_t output_size;
5569 bool result;
5570
5572
5573 /* convert to char32_t */
5575 input_chars = palloc_array(char32_t, size + 1);
5576 p = (unsigned char *) VARDATA_ANY(input);
5577 for (i = 0; i < size; i++)
5578 {
5580 p += pg_utf_mblen(p);
5581 }
5582 input_chars[i] = (char32_t) '\0';
5583 Assert((char *) p == VARDATA_ANY(input) + VARSIZE_ANY_EXHDR(input));
5584
5585 /* quick check (see UAX #15) */
5587 if (quickcheck == UNICODE_NORM_QC_YES)
5588 PG_RETURN_BOOL(true);
5589 else if (quickcheck == UNICODE_NORM_QC_NO)
5590 PG_RETURN_BOOL(false);
5591
5592 /* normalize and compare with original */
5594
5595 output_size = 0;
5596 for (char32_t *wp = output_chars; *wp; wp++)
5597 output_size++;
5598
5599 result = (size == output_size) &&
5600 (memcmp(input_chars, output_chars, size * sizeof(char32_t)) == 0);
5601
5603}
uint32_t char32_t
Definition c.h:1504
#define palloc_array(type, count)
Definition fe_memutils.h:91
UnicodeNormalizationQC unicode_is_normalized_quickcheck(UnicodeNormalizationForm form, const char32_t *input)
char32_t * unicode_normalize(UnicodeNormalizationForm form, const char32_t *input)
UnicodeNormalizationForm
UnicodeNormalizationQC
@ UNICODE_NORM_QC_YES
@ UNICODE_NORM_QC_NO
static UnicodeNormalizationForm unicode_norm_form_from_string(const char *formstr)
Definition varlena.c:5402

References Assert, fb(), i, input, palloc_array, PG_GETARG_TEXT_PP, pg_mbstrlen_with_len(), PG_RETURN_BOOL, pg_utf_mblen, result, 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 5402 of file varlena.c.

5403{
5405
5406 /*
5407 * Might as well check this while we're here.
5408 */
5410 ereport(ERROR,
5412 errmsg("Unicode normalization can only be performed if server encoding is UTF8")));
5413
5414 if (pg_strcasecmp(formstr, "NFC") == 0)
5415 form = UNICODE_NFC;
5416 else if (pg_strcasecmp(formstr, "NFD") == 0)
5417 form = UNICODE_NFD;
5418 else if (pg_strcasecmp(formstr, "NFKC") == 0)
5420 else if (pg_strcasecmp(formstr, "NFKD") == 0)
5422 else
5423 ereport(ERROR,
5425 errmsg("invalid normalization form: %s", formstr)));
5426
5427 return form;
5428}
int pg_strcasecmp(const char *s1, const char *s2)
@ UNICODE_NFKD
@ UNICODE_NFD
@ UNICODE_NFC
@ UNICODE_NFKC

References ereport, errcode(), errmsg, ERROR, fb(), 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 5491 of file varlena.c.

5492{
5496 size_t size;
5497 char32_t *input_chars;
5498 char32_t *output_chars;
5499 unsigned char *p;
5500 text *result;
5501 size_t i;
5502
5504
5505 /* convert to char32_t */
5507 input_chars = palloc_array(char32_t, size + 1);
5508 p = (unsigned char *) VARDATA_ANY(input);
5509 for (i = 0; i < size; i++)
5510 {
5512 p += pg_utf_mblen(p);
5513 }
5514 input_chars[i] = (char32_t) '\0';
5515 Assert((char *) p == VARDATA_ANY(input) + VARSIZE_ANY_EXHDR(input));
5516
5517 /* action */
5519
5520 /* convert back to UTF-8 string */
5521 size = 0;
5522 for (char32_t *wp = output_chars; *wp; wp++)
5523 {
5524 unsigned char buf[4];
5525
5527 size += pg_utf_mblen(buf);
5528 }
5529
5530 result = palloc(size + VARHDRSZ);
5531 SET_VARSIZE(result, size + VARHDRSZ);
5532
5533 p = (unsigned char *) VARDATA_ANY(result);
5534 for (char32_t *wp = output_chars; *wp; wp++)
5535 {
5536 unicode_to_utf8(*wp, p);
5537 p += pg_utf_mblen(p);
5538 }
5539 Assert((char *) p == (char *) result + size + VARHDRSZ);
5540
5542}
static unsigned char * unicode_to_utf8(char32_t c, unsigned char *utf8string)
Definition pg_wchar.h:428

References Assert, buf, fb(), i, input, palloc(), palloc_array, PG_GETARG_TEXT_PP, pg_mbstrlen_with_len(), PG_RETURN_TEXT_P, pg_utf_mblen, result, 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 5439 of file varlena.c.

5440{
5442}
#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 5649 of file varlena.c.

5650{
5652 char *instr;
5653 int len;
5655 text *result;
5656 char16_t pair_first = 0;
5658
5659 instr = VARDATA_ANY(input_text);
5661
5663
5664 while (len > 0)
5665 {
5666 if (instr[0] == '\\')
5667 {
5668 if (len >= 2 &&
5669 instr[1] == '\\')
5670 {
5671 if (pair_first)
5672 goto invalid_pair;
5673 appendStringInfoChar(&str, '\\');
5674 instr += 2;
5675 len -= 2;
5676 }
5677 else if ((len >= 5 && isxdigits_n(instr + 1, 4)) ||
5678 (len >= 6 && instr[1] == 'u' && isxdigits_n(instr + 2, 4)))
5679 {
5680 char32_t unicode;
5681 int offset = instr[1] == 'u' ? 2 : 1;
5682
5683 unicode = hexval_n(instr + offset, 4);
5684
5686 ereport(ERROR,
5688 errmsg("invalid Unicode code point: %04X", unicode));
5689
5690 if (pair_first)
5691 {
5693 {
5695 pair_first = 0;
5696 }
5697 else
5698 goto invalid_pair;
5699 }
5701 goto invalid_pair;
5702
5705 else
5706 {
5707 pg_unicode_to_server(unicode, (unsigned char *) cbuf);
5709 }
5710
5711 instr += 4 + offset;
5712 len -= 4 + offset;
5713 }
5714 else if (len >= 8 && instr[1] == '+' && isxdigits_n(instr + 2, 6))
5715 {
5716 char32_t unicode;
5717
5718 unicode = hexval_n(instr + 2, 6);
5719
5721 ereport(ERROR,
5723 errmsg("invalid Unicode code point: %04X", unicode));
5724
5725 if (pair_first)
5726 {
5728 {
5730 pair_first = 0;
5731 }
5732 else
5733 goto invalid_pair;
5734 }
5736 goto invalid_pair;
5737
5740 else
5741 {
5742 pg_unicode_to_server(unicode, (unsigned char *) cbuf);
5744 }
5745
5746 instr += 8;
5747 len -= 8;
5748 }
5749 else if (len >= 10 && instr[1] == 'U' && isxdigits_n(instr + 2, 8))
5750 {
5751 char32_t unicode;
5752
5753 unicode = hexval_n(instr + 2, 8);
5754
5756 ereport(ERROR,
5758 errmsg("invalid Unicode code point: %04X", unicode));
5759
5760 if (pair_first)
5761 {
5763 {
5765 pair_first = 0;
5766 }
5767 else
5768 goto invalid_pair;
5769 }
5771 goto invalid_pair;
5772
5775 else
5776 {
5777 pg_unicode_to_server(unicode, (unsigned char *) cbuf);
5779 }
5780
5781 instr += 10;
5782 len -= 10;
5783 }
5784 else
5785 ereport(ERROR,
5787 errmsg("invalid Unicode escape"),
5788 errhint("Unicode escapes must be \\XXXX, \\+XXXXXX, \\uXXXX, or \\UXXXXXXXX.")));
5789 }
5790 else
5791 {
5792 if (pair_first)
5793 goto invalid_pair;
5794
5795 appendStringInfoChar(&str, *instr++);
5796 len--;
5797 }
5798 }
5799
5800 /* unfinished surrogate pair? */
5801 if (pair_first)
5802 goto invalid_pair;
5803
5805 pfree(str.data);
5806
5808
5810 ereport(ERROR,
5812 errmsg("invalid Unicode surrogate pair")));
5813 PG_RETURN_NULL(); /* keep compiler quiet */
5814}
void pg_unicode_to_server(char32_t c, unsigned char *s)
Definition mbutils.c:875
static bool is_utf16_surrogate_first(char32_t c)
Definition pg_wchar.h:378
static bool is_utf16_surrogate_second(char32_t c)
Definition pg_wchar.h:384
static char32_t surrogate_pair_to_codepoint(char16_t first, char16_t second)
Definition pg_wchar.h:390
#define MAX_UNICODE_EQUIVALENT_STRING
Definition pg_wchar.h:182
static bool is_valid_unicode_codepoint(char32_t c)
Definition pg_wchar.h:372
static unsigned int hexval_n(const char *instr, size_t n)
Definition varlena.c:5635
static bool isxdigits_n(const char *instr, size_t n)
Definition varlena.c:5609

References appendStringInfoChar(), appendStringInfoString(), cstring_to_text_with_len(), ereport, errcode(), errhint(), errmsg, ERROR, fb(), 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(), result, str, surrogate_pair_to_codepoint(), VARDATA_ANY(), and VARSIZE_ANY_EXHDR().

◆ unknownin()

Datum unknownin ( PG_FUNCTION_ARGS  )

Definition at line 333 of file varlena.c.

334{
335 char *str = PG_GETARG_CSTRING(0);
336
337 /* representation is same as cstring */
339}

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

◆ unknownout()

Datum unknownout ( PG_FUNCTION_ARGS  )

Definition at line 345 of file varlena.c.

346{
347 /* representation is same as cstring */
348 char *str = PG_GETARG_CSTRING(0);
349
351}

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

◆ unknownrecv()

Datum unknownrecv ( PG_FUNCTION_ARGS  )

Definition at line 357 of file varlena.c.

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

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

◆ unknownsend()

Datum unknownsend ( PG_FUNCTION_ARGS  )

Definition at line 372 of file varlena.c.

373{
374 /* representation is same as cstring */
375 char *str = PG_GETARG_CSTRING(0);
377
381}

References buf, fb(), 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 5354 of file varlena.c.

5355{
5356 int dist;
5357
5358 Assert(state);
5359
5360 if (state->source == NULL || state->source[0] == '\0' ||
5361 candidate == NULL || candidate[0] == '\0')
5362 return;
5363
5364 /*
5365 * To avoid ERROR-ing, we check the lengths here instead of setting
5366 * 'trusted' to false in the call to varstr_levenshtein_less_equal().
5367 */
5368 if (strlen(state->source) > MAX_LEVENSHTEIN_STRLEN ||
5370 return;
5371
5373 candidate, strlen(candidate), 1, 1, 1,
5374 state->max_d, true);
5375 if (dist <= state->max_d &&
5376 dist <= strlen(state->source) / 2 &&
5377 (state->min_d == -1 || dist < state->min_d))
5378 {
5379 state->min_d = dist;
5380 state->match = candidate;
5381 }
5382}
#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, fb(), 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 1890 of file varlena.c.

1891{
1894 char *a1p,
1895 *a2p;
1896 int len1,
1897 len2,
1898 result;
1899
1900 a1p = VARDATA_ANY(arg1);
1901 a2p = VARDATA_ANY(arg2);
1902
1903 len1 = VARSIZE_ANY_EXHDR(arg1);
1904 len2 = VARSIZE_ANY_EXHDR(arg2);
1905
1906 result = varstrfastcmp_locale(a1p, len1, a2p, len2, ssup);
1907
1908 /* We can't afford to leak memory here. */
1909 if (PointerGetDatum(arg1) != x)
1910 pfree(arg1);
1911 if (PointerGetDatum(arg2) != y)
1912 pfree(arg2);
1913
1914 return result;
1915}
#define DatumGetVarStringPP(X)
Definition varlena.c:122

References DatumGetVarStringPP, fb(), pfree(), PointerGetDatum, result, 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 2202 of file varlena.c.

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

References SortSupportData::abbreviate, Assert, elog, estimateHyperLogLog(), fb(), LOG, 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 2035 of file varlena.c.

2036{
2037 const size_t max_prefix_bytes = sizeof(Datum);
2041
2042 /* working state */
2043 Datum res;
2044 char *pres;
2045 int len;
2046 uint32 hash;
2047
2048 pres = (char *) &res;
2049 /* memset(), so any non-overwritten bytes are NUL */
2052
2053 /* Get number of bytes, ignoring trailing spaces */
2054 if (sss->typid == BPCHAROID)
2056
2057 /*
2058 * If we're using the C collation, use memcpy(), rather than strxfrm(), to
2059 * abbreviate keys. The full comparator for the C locale is also
2060 * memcmp(). This should be faster than strxfrm().
2061 */
2062 if (sss->collate_c)
2064 else
2065 {
2066 Size bsize;
2067
2068 /*
2069 * We're not using the C collation, so fall back on strxfrm or ICU
2070 * analogs.
2071 */
2072
2073 /* By convention, we use buffer 1 to store and NUL-terminate */
2074 if (len >= sss->buflen1)
2075 {
2076 sss->buflen1 = Max(len + 1, Min(sss->buflen1 * 2, MaxAllocSize));
2077 sss->buf1 = repalloc(sss->buf1, sss->buflen1);
2078 }
2079
2080 /* Might be able to reuse strxfrm() blob from last call */
2081 if (sss->last_len1 == len && sss->cache_blob &&
2082 memcmp(sss->buf1, authoritative_data, len) == 0)
2083 {
2084 memcpy(pres, sss->buf2, Min(max_prefix_bytes, sss->last_len2));
2085 /* No change affecting cardinality, so no hashing required */
2086 goto done;
2087 }
2088
2090
2091 /*
2092 * pg_strxfrm() and pg_strxfrm_prefix expect NUL-terminated strings.
2093 */
2094 sss->buf1[len] = '\0';
2095 sss->last_len1 = len;
2096
2097 if (pg_strxfrm_prefix_enabled(sss->locale))
2098 {
2099 if (sss->buflen2 < max_prefix_bytes)
2100 {
2101 sss->buflen2 = Max(max_prefix_bytes,
2102 Min(sss->buflen2 * 2, MaxAllocSize));
2103 sss->buf2 = repalloc(sss->buf2, sss->buflen2);
2104 }
2105
2106 bsize = pg_strxfrm_prefix(sss->buf2, sss->buf1,
2107 max_prefix_bytes, sss->locale);
2108 sss->last_len2 = bsize;
2109 }
2110 else
2111 {
2112 /*
2113 * Loop: Call pg_strxfrm(), possibly enlarge buffer, and try
2114 * again. The pg_strxfrm() function leaves the result buffer
2115 * content undefined if the result did not fit, so we need to
2116 * retry until everything fits, even though we only need the first
2117 * few bytes in the end.
2118 */
2119 for (;;)
2120 {
2121 bsize = pg_strxfrm(sss->buf2, sss->buf1, sss->buflen2,
2122 sss->locale);
2123
2124 sss->last_len2 = bsize;
2125 if (bsize < sss->buflen2)
2126 break;
2127
2128 /*
2129 * Grow buffer and retry.
2130 */
2131 sss->buflen2 = Max(bsize + 1,
2132 Min(sss->buflen2 * 2, MaxAllocSize));
2133 sss->buf2 = repalloc(sss->buf2, sss->buflen2);
2134 }
2135 }
2136
2137 /*
2138 * Every Datum byte is always compared. This is safe because the
2139 * strxfrm() blob is itself NUL terminated, leaving no danger of
2140 * misinterpreting any NUL bytes not intended to be interpreted as
2141 * logically representing termination.
2142 */
2144 }
2145
2146 /*
2147 * Maintain approximate cardinality of both abbreviated keys and original,
2148 * authoritative keys using HyperLogLog. Used as cheap insurance against
2149 * the worst case, where we do many string transformations for no saving
2150 * in full strcoll()-based comparisons. These statistics are used by
2151 * varstr_abbrev_abort().
2152 *
2153 * First, Hash key proper, or a significant fraction of it. Mix in length
2154 * in order to compensate for cases where differences are past
2155 * PG_CACHE_LINE_SIZE bytes, so as to limit the overhead of hashing.
2156 */
2157 hash = DatumGetUInt32(hash_any((unsigned char *) authoritative_data,
2159
2160 if (len > PG_CACHE_LINE_SIZE)
2162
2163 addHyperLogLog(&sss->full_card, hash);
2164
2165 /* Hash abbreviated key */
2166 {
2167 uint32 tmp;
2168
2169 tmp = DatumGetUInt32(res) ^ (uint32) (DatumGetUInt64(res) >> 32);
2171 }
2172
2173 addHyperLogLog(&sss->abbr_card, hash);
2174
2175 /* Cache result, perhaps saving an expensive strxfrm() call next time */
2176 sss->cache_blob = true;
2177done:
2178
2179 /*
2180 * Byteswap on little-endian machines.
2181 *
2182 * This is needed so that ssup_datum_unsigned_cmp() (an unsigned integer
2183 * 3-way comparator) works correctly on all platforms. If we didn't do
2184 * this, the comparator would have to call memcmp() with a pair of
2185 * pointers to the first byte of each abbreviated key, which is slower.
2186 */
2187 res = DatumBigEndianToNative(res);
2188
2189 /* Don't leak memory here */
2190 if (PointerGetDatum(authoritative) != original)
2192
2193 return res;
2194}
#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)
void * repalloc(void *pointer, Size size)
Definition mcxt.c:1635
#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:1465
size_t pg_strxfrm(char *dest, const char *src, size_t destsize, pg_locale_t locale)
Definition pg_locale.c:1430
size_t pg_strxfrm_prefix(char *dest, const char *src, size_t destsize, pg_locale_t locale)
Definition pg_locale.c:1476
static uint32 DatumGetUInt32(Datum X)
Definition postgres.h:222
static uint64 DatumGetUInt64(Datum X)
Definition postgres.h:436
static unsigned hash(unsigned *uv, int n)
Definition rege_dfa.c:724

References addHyperLogLog(), bpchartruelen(), DatumBigEndianToNative, DatumGetUInt32(), DatumGetUInt64(), DatumGetVarStringPP, fb(), hash(), hash_any(), hash_uint32(), len, Max, MaxAllocSize, memcpy(), Min, pfree(), PG_CACHE_LINE_SIZE, pg_strxfrm(), pg_strxfrm_prefix(), pg_strxfrm_prefix_enabled(), PointerGetDatum, repalloc(), SortSupportData::ssup_extra, 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 1355 of file varlena.c.

1356{
1357 int result;
1359
1361
1363
1364 if (mylocale->collate_is_c)
1365 {
1366 result = memcmp(arg1, arg2, Min(len1, len2));
1367 if ((result == 0) && (len1 != len2))
1368 result = (len1 < len2) ? -1 : 1;
1369 }
1370 else
1371 {
1372 /*
1373 * memcmp() can't tell us which of two unequal strings sorts first,
1374 * but it's a cheap way to tell if they're equal. Testing shows that
1375 * memcmp() followed by strcoll() is only trivially slower than
1376 * strcoll() by itself, so we don't lose much if this doesn't work out
1377 * very often, and if it does - for example, because there are many
1378 * equal strings in the input - then we win big by avoiding expensive
1379 * collation-aware comparisons.
1380 */
1381 if (len1 == len2 && memcmp(arg1, arg2, len1) == 0)
1382 return 0;
1383
1384 result = pg_strncoll(arg1, len1, arg2, len2, mylocale);
1385
1386 /* Break tie if necessary. */
1387 if (result == 0 && mylocale->deterministic)
1388 {
1389 result = memcmp(arg1, arg2, Min(len1, len2));
1390 if ((result == 0) && (len1 != len2))
1391 result = (len1 < len2) ? -1 : 1;
1392 }
1393 }
1394
1395 return result;
1396}

References check_collation_set(), collid, fb(), Min, pg_newlocale_from_collation(), pg_strncoll(), and result.

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

1673{
1674 bool abbreviate = ssup->abbreviate;
1675 bool collate_c = false;
1677 pg_locale_t locale;
1678
1680
1682
1683 /*
1684 * If possible, set ssup->comparator to a function which can be used to
1685 * directly compare two datums. If we can do this, we'll avoid the
1686 * overhead of a trip through the fmgr layer for every comparison, which
1687 * can be substantial.
1688 *
1689 * Most typically, we'll set the comparator to varlenafastcmp_locale,
1690 * which uses strcoll() to perform comparisons. We use that for the
1691 * BpChar case too, but type NAME uses namefastcmp_locale. However, if
1692 * LC_COLLATE = C, we can make things quite a bit faster with
1693 * varstrfastcmp_c, bpcharfastcmp_c, or namefastcmp_c, all of which use
1694 * memcmp() rather than strcoll().
1695 */
1696 if (locale->collate_is_c)
1697 {
1698 if (typid == BPCHAROID)
1700 else if (typid == NAMEOID)
1701 {
1702 ssup->comparator = namefastcmp_c;
1703 /* Not supporting abbreviation with type NAME, for now */
1704 abbreviate = false;
1705 }
1706 else
1708
1709 collate_c = true;
1710 }
1711 else
1712 {
1713 /*
1714 * We use varlenafastcmp_locale except for type NAME.
1715 */
1716 if (typid == NAMEOID)
1717 {
1719 /* Not supporting abbreviation with type NAME, for now */
1720 abbreviate = false;
1721 }
1722 else
1724
1725 /*
1726 * Unfortunately, it seems that abbreviation for non-C collations is
1727 * broken on many common platforms; see pg_strxfrm_enabled().
1728 *
1729 * Even apart from the risk of broken locales, it's possible that
1730 * there are platforms where the use of abbreviated keys should be
1731 * disabled at compile time. For example, macOS's strxfrm()
1732 * implementation is known to not effectively concentrate a
1733 * significant amount of entropy from the original string in earlier
1734 * transformed blobs. It's possible that other supported platforms
1735 * are similarly encumbered. So, if we ever get past disabling this
1736 * categorically, we may still want or need to disable it for
1737 * particular platforms.
1738 */
1739 if (!pg_strxfrm_enabled(locale))
1740 abbreviate = false;
1741 }
1742
1743 /*
1744 * If we're using abbreviated keys, or if we're using a locale-aware
1745 * comparison, we need to initialize a VarStringSortSupport object. Both
1746 * cases will make use of the temporary buffers we initialize here for
1747 * scratch space (and to detect requirement for BpChar semantics from
1748 * caller), and the abbreviation case requires additional state.
1749 */
1750 if (abbreviate || !collate_c)
1751 {
1753 sss->buf1 = palloc(TEXTBUFLEN);
1754 sss->buflen1 = TEXTBUFLEN;
1755 sss->buf2 = palloc(TEXTBUFLEN);
1756 sss->buflen2 = TEXTBUFLEN;
1757 /* Start with invalid values */
1758 sss->last_len1 = -1;
1759 sss->last_len2 = -1;
1760 /* Initialize */
1761 sss->last_returned = 0;
1762 if (collate_c)
1763 sss->locale = NULL;
1764 else
1765 sss->locale = locale;
1766
1767 /*
1768 * To avoid somehow confusing a strxfrm() blob and an original string,
1769 * constantly keep track of the variety of data that buf1 and buf2
1770 * currently contain.
1771 *
1772 * Comparisons may be interleaved with conversion calls. Frequently,
1773 * conversions and comparisons are batched into two distinct phases,
1774 * but the correctness of caching cannot hinge upon this. For
1775 * comparison caching, buffer state is only trusted if cache_blob is
1776 * found set to false, whereas strxfrm() caching only trusts the state
1777 * when cache_blob is found set to true.
1778 *
1779 * Arbitrarily initialize cache_blob to true.
1780 */
1781 sss->cache_blob = true;
1782 sss->collate_c = collate_c;
1783 sss->typid = typid;
1784 ssup->ssup_extra = sss;
1785
1786 /*
1787 * If possible, plan to use the abbreviated keys optimization. The
1788 * core code may switch back to authoritative comparator should
1789 * abbreviation be aborted.
1790 */
1791 if (abbreviate)
1792 {
1793 sss->prop_card = 0.20;
1794 initHyperLogLog(&sss->abbr_card, 10);
1795 initHyperLogLog(&sss->full_card, 10);
1796 ssup->abbrev_full_comparator = ssup->comparator;
1800 }
1801 }
1802}
#define palloc_object(type)
Definition fe_memutils.h:89
void initHyperLogLog(hyperLogLogState *cState, uint8 bwidth)
Definition hyperloglog.c:66
bool pg_strxfrm_enabled(pg_locale_t locale)
Definition pg_locale.c:1414
int(* comparator)(Datum x, Datum y, SortSupport ssup)
Datum(* abbrev_converter)(Datum original, SortSupport ssup)
int(* abbrev_full_comparator)(Datum x, Datum y, SortSupport ssup)
bool(* abbrev_abort)(int memtupcount, SortSupport ssup)
int ssup_datum_unsigned_cmp(Datum x, Datum y, SortSupport ssup)
Definition tuplesort.c:3450
static bool varstr_abbrev_abort(int memtupcount, SortSupport ssup)
Definition varlena.c:2202
static int varlenafastcmp_locale(Datum x, Datum y, SortSupport ssup)
Definition varlena.c:1890
static int bpcharfastcmp_c(Datum x, Datum y, SortSupport ssup)
Definition varlena.c:1845
static int namefastcmp_c(Datum x, Datum y, SortSupport ssup)
Definition varlena.c:1878
static int namefastcmp_locale(Datum x, Datum y, SortSupport ssup)
Definition varlena.c:1921
static Datum varstr_abbrev_convert(Datum original, SortSupport ssup)
Definition varlena.c:2035
static int varstrfastcmp_c(Datum x, Datum y, SortSupport ssup)
Definition varlena.c:1808
#define TEXTBUFLEN
Definition varlena.c:119

References SortSupportData::abbrev_abort, SortSupportData::abbrev_converter, SortSupportData::abbrev_full_comparator, SortSupportData::abbreviate, bpcharfastcmp_c(), check_collation_set(), pg_locale_struct::collate_is_c, collid, SortSupportData::comparator, fb(), initHyperLogLog(), namefastcmp_c(), namefastcmp_locale(), palloc(), palloc_object, pg_newlocale_from_collation(), pg_strxfrm_enabled(), ssup_datum_unsigned_cmp(), SortSupportData::ssup_extra, TEXTBUFLEN, varlenafastcmp_locale(), varstr_abbrev_abort(), varstr_abbrev_convert(), and varstrfastcmp_c().

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

◆ varstrfastcmp_c()

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

Definition at line 1808 of file varlena.c.

1809{
1812 char *a1p,
1813 *a2p;
1814 int len1,
1815 len2,
1816 result;
1817
1818 a1p = VARDATA_ANY(arg1);
1819 a2p = VARDATA_ANY(arg2);
1820
1821 len1 = VARSIZE_ANY_EXHDR(arg1);
1822 len2 = VARSIZE_ANY_EXHDR(arg2);
1823
1824 result = memcmp(a1p, a2p, Min(len1, len2));
1825 if ((result == 0) && (len1 != len2))
1826 result = (len1 < len2) ? -1 : 1;
1827
1828 /* We can't afford to leak memory here. */
1829 if (PointerGetDatum(arg1) != x)
1830 pfree(arg1);
1831 if (PointerGetDatum(arg2) != y)
1832 pfree(arg2);
1833
1834 return result;
1835}

References DatumGetVarStringPP, fb(), Min, pfree(), PointerGetDatum, result, 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 1935 of file varlena.c.

1936{
1938 int result;
1939 bool arg1_match;
1940
1941 /* Fast pre-check for equality, as discussed in varstr_cmp() */
1942 if (len1 == len2 && memcmp(a1p, a2p, len1) == 0)
1943 {
1944 /*
1945 * No change in buf1 or buf2 contents, so avoid changing last_len1 or
1946 * last_len2. Existing contents of buffers might still be used by
1947 * next call.
1948 *
1949 * It's fine to allow the comparison of BpChar padding bytes here,
1950 * even though that implies that the memcmp() will usually be
1951 * performed for BpChar callers (though multibyte characters could
1952 * still prevent that from occurring). The memcmp() is still very
1953 * cheap, and BpChar's funny semantics have us remove trailing spaces
1954 * (not limited to padding), so we need make no distinction between
1955 * padding space characters and "real" space characters.
1956 */
1957 return 0;
1958 }
1959
1960 if (sss->typid == BPCHAROID)
1961 {
1962 /* Get true number of bytes, ignoring trailing spaces */
1963 len1 = bpchartruelen(a1p, len1);
1964 len2 = bpchartruelen(a2p, len2);
1965 }
1966
1967 if (len1 >= sss->buflen1)
1968 {
1969 sss->buflen1 = Max(len1 + 1, Min(sss->buflen1 * 2, MaxAllocSize));
1970 sss->buf1 = repalloc(sss->buf1, sss->buflen1);
1971 }
1972 if (len2 >= sss->buflen2)
1973 {
1974 sss->buflen2 = Max(len2 + 1, Min(sss->buflen2 * 2, MaxAllocSize));
1975 sss->buf2 = repalloc(sss->buf2, sss->buflen2);
1976 }
1977
1978 /*
1979 * We're likely to be asked to compare the same strings repeatedly, and
1980 * memcmp() is so much cheaper than strcoll() that it pays to try to cache
1981 * comparisons, even though in general there is no reason to think that
1982 * that will work out (every string datum may be unique). Caching does
1983 * not slow things down measurably when it doesn't work out, and can speed
1984 * things up by rather a lot when it does. In part, this is because the
1985 * memcmp() compares data from cachelines that are needed in L1 cache even
1986 * when the last comparison's result cannot be reused.
1987 */
1988 arg1_match = true;
1989 if (len1 != sss->last_len1 || memcmp(sss->buf1, a1p, len1) != 0)
1990 {
1991 arg1_match = false;
1992 memcpy(sss->buf1, a1p, len1);
1993 sss->buf1[len1] = '\0';
1994 sss->last_len1 = len1;
1995 }
1996
1997 /*
1998 * If we're comparing the same two strings as last time, we can return the
1999 * same answer without calling strcoll() again. This is more likely than
2000 * it seems (at least with moderate to low cardinality sets), because
2001 * quicksort compares the same pivot against many values.
2002 */
2003 if (len2 != sss->last_len2 || memcmp(sss->buf2, a2p, len2) != 0)
2004 {
2005 memcpy(sss->buf2, a2p, len2);
2006 sss->buf2[len2] = '\0';
2007 sss->last_len2 = len2;
2008 }
2009 else if (arg1_match && !sss->cache_blob)
2010 {
2011 /* Use result cached following last actual strcoll() call */
2012 return sss->last_returned;
2013 }
2014
2015 result = pg_strcoll(sss->buf1, sss->buf2, sss->locale);
2016
2017 /* Break tie if necessary. */
2018 if (result == 0 && sss->locale->deterministic)
2019 result = strcmp(sss->buf1, sss->buf2);
2020
2021 /* Cache result, perhaps saving an expensive strcoll() call next time */
2022 sss->cache_blob = false;
2023 sss->last_returned = result;
2024 return result;
2025}
int pg_strcoll(const char *arg1, const char *arg2, pg_locale_t locale)
Definition pg_locale.c:1381

References bpchartruelen(), fb(), Max, MaxAllocSize, memcpy(), Min, pg_strcoll(), repalloc(), result, and SortSupportData::ssup_extra.

Referenced by namefastcmp_locale(), and varlenafastcmp_locale().