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 "catalog/pg_collation.h"
#include "catalog/pg_type.h"
#include "common/hashfn.h"
#include "common/int.h"
#include "common/unicode_category.h"
#include "common/unicode_norm.h"
#include "common/unicode_version.h"
#include "funcapi.h"
#include "lib/hyperloglog.h"
#include "libpq/pqformat.h"
#include "miscadmin.h"
#include "nodes/execnodes.h"
#include "parser/scansup.h"
#include "port/pg_bswap.h"
#include "regex/regex.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/pg_locale.h"
#include "utils/sortsupport.h"
#include "utils/varlena.h"
#include "levenshtein.c"
Include dependency graph for varlena.c:

Go to the source code of this file.

Data Structures

struct  TextPositionState
 
struct  VarStringSortSupport
 
struct  SplitTextOutputData
 

Macros

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

Typedefs

typedef 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)
 
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:874
int errmsg(const char *fmt,...)
Definition elog.c:1093
int errhint(const char *fmt,...) pg_attribute_printf(1
#define ERROR
Definition elog.h:39
static int fb(int x)

Definition at line 4757 of file varlena.c.

4758 { \
4759 if (++(ptr) >= (end_ptr)) \
4760 ereport(ERROR, \
4762 errmsg("unterminated format() type specifier"), \
4763 errhint("For a single \"%%\" use \"%%%%\"."))); \
4764 } while (0)

◆ CmpCall

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

Definition at line 2489 of file varlena.c.

◆ DatumGetVarStringP

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

Definition at line 119 of file varlena.c.

◆ DatumGetVarStringPP

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

Definition at line 120 of file varlena.c.

◆ LEVENSHTEIN_LESS_EQUAL

#define LEVENSHTEIN_LESS_EQUAL

Definition at line 5297 of file varlena.c.

◆ TEXT_FORMAT_FLAG_MINUS

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

Definition at line 4755 of file varlena.c.

◆ TEXTBUFLEN

#define TEXTBUFLEN   1024

Definition at line 117 of file varlena.c.

Typedef Documentation

◆ VarString

Definition at line 45 of file varlena.c.

Function Documentation

◆ appendStringInfoRegexpSubstr()

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

Definition at line 3233 of file varlena.c.

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

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

3897{
3900
3902}
#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:3938
char * text_to_cstring(const text *t)
Definition varlena.c:215

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

3940{
3941 text *result;
3942 int nitems,
3943 *dims,
3944 ndims;
3945 Oid element_type;
3946 int typlen;
3947 bool typbyval;
3948 char typalign;
3949 uint8 typalignby;
3951 bool printed = false;
3952 char *p;
3953 bits8 *bitmap;
3954 int bitmask;
3955 int i;
3957
3958 ndims = ARR_NDIM(v);
3959 dims = ARR_DIMS(v);
3960 nitems = ArrayGetNItems(ndims, dims);
3961
3962 /* if there are no elements, return an empty string */
3963 if (nitems == 0)
3964 return cstring_to_text_with_len("", 0);
3965
3966 element_type = ARR_ELEMTYPE(v);
3968
3969 /*
3970 * We arrange to look up info about element type, including its output
3971 * conversion proc, only once per series of calls, assuming the element
3972 * type doesn't change underneath us.
3973 */
3974 my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
3975 if (my_extra == NULL)
3976 {
3977 fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
3978 sizeof(ArrayMetaState));
3979 my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
3980 my_extra->element_type = ~element_type;
3981 }
3982
3983 if (my_extra->element_type != element_type)
3984 {
3985 /*
3986 * Get info about element type, including its output conversion proc
3987 */
3988 get_type_io_data(element_type, IOFunc_output,
3989 &my_extra->typlen, &my_extra->typbyval,
3990 &my_extra->typalign, &my_extra->typdelim,
3991 &my_extra->typioparam, &my_extra->typiofunc);
3992 fmgr_info_cxt(my_extra->typiofunc, &my_extra->proc,
3993 fcinfo->flinfo->fn_mcxt);
3994 my_extra->element_type = element_type;
3995 }
3996 typlen = my_extra->typlen;
3997 typbyval = my_extra->typbyval;
3998 typalign = my_extra->typalign;
3999 typalignby = typalign_to_alignby(typalign);
4000
4001 p = ARR_DATA_PTR(v);
4002 bitmap = ARR_NULLBITMAP(v);
4003 bitmask = 1;
4004
4005 for (i = 0; i < nitems; i++)
4006 {
4008 char *value;
4009
4010 /* Get source element, checking for NULL */
4011 if (bitmap && (*bitmap & bitmask) == 0)
4012 {
4013 /* if null_string is NULL, we just ignore null elements */
4014 if (null_string != NULL)
4015 {
4016 if (printed)
4018 else
4020 printed = true;
4021 }
4022 }
4023 else
4024 {
4025 itemvalue = fetch_att(p, typbyval, typlen);
4026
4028
4029 if (printed)
4030 appendStringInfo(&buf, "%s%s", fldsep, value);
4031 else
4033 printed = true;
4034
4035 p = att_addlength_pointer(p, typlen, p);
4036 p = (char *) att_nominal_alignby(p, typalignby);
4037 }
4038
4039 /* advance bitmap pointer if any */
4040 if (bitmap)
4041 {
4042 bitmask <<= 1;
4043 if (bitmask == 0x100)
4044 {
4045 bitmap++;
4046 bitmask = 1;
4047 }
4048 }
4049 }
4050
4051 result = cstring_to_text_with_len(buf.data, buf.len);
4052 pfree(buf.data);
4053
4054 return result;
4055}
#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:556
uint8 bits8
Definition c.h:565
void fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
Definition fmgr.c:138
char * OutputFunctionCall(FmgrInfo *flinfo, Datum val)
Definition fmgr.c:1683
#define nitems(x)
Definition indent.h:31
static struct @174 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:2475
@ IOFunc_output
Definition lsyscache.h:37
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition mcxt.c:1232
void pfree(void *pointer)
Definition mcxt.c:1616
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:718
#define att_nominal_alignby(cur_offset, attalignby)
Definition tupmacs.h:189
#define att_addlength_pointer(cur_offset, attlen, attptr)
Definition tupmacs.h:209
static uint8 typalign_to_alignby(char typalign)
Definition tupmacs.h:80
static Datum fetch_att(const void *T, bool attbyval, int attlen)
Definition tupmacs.h:50
text * cstring_to_text_with_len(const char *s, int len)
Definition varlena.c:194

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

3913{
3914 ArrayType *v;
3915 char *fldsep;
3916 char *null_string;
3917
3918 /* returns NULL when first or second parameter is NULL */
3919 if (PG_ARGISNULL(0) || PG_ARGISNULL(1))
3921
3922 v = PG_GETARG_ARRAYTYPE_P(0);
3924
3925 /* NULL null string is passed through as a null pointer */
3926 if (!PG_ARGISNULL(2))
3928 else
3929 null_string = NULL;
3930
3932}
#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 1842 of file varlena.c.

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

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

Referenced by varstr_sortsupport().

◆ btnametextcmp()

Datum btnametextcmp ( PG_FUNCTION_ARGS  )

Definition at line 2458 of file varlena.c.

2459{
2462 int32 result;
2463
2464 result = varstr_cmp(NameStr(*arg1), strlen(NameStr(*arg1)),
2467
2469
2470 PG_RETURN_INT32(result);
2471}
#define NameStr(name)
Definition c.h:777
int32_t int32
Definition c.h:554
#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:772
int varstr_cmp(const char *arg1, int len1, const char *arg2, int len2, Oid collid)
Definition varlena.c:1353

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

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

◆ bttext_pattern_cmp()

Datum bttext_pattern_cmp ( PG_FUNCTION_ARGS  )

Definition at line 2641 of file varlena.c.

2642{
2645 int result;
2646
2648
2651
2652 PG_RETURN_INT32(result);
2653}
static int internal_text_pattern_compare(text *arg1, text *arg2)
Definition varlena.c:2555

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

◆ bttext_pattern_sortsupport()

Datum bttext_pattern_sortsupport ( PG_FUNCTION_ARGS  )

Definition at line 2657 of file varlena.c.

2658{
2660 MemoryContext oldcontext;
2661
2662 oldcontext = MemoryContextSwitchTo(ssup->ssup_cxt);
2663
2664 /* Use generic string SortSupport, forcing "C" collation */
2666
2667 MemoryContextSwitchTo(oldcontext);
2668
2670}
#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:124
struct SortSupportData * SortSupport
Definition sortsupport.h:58
MemoryContext ssup_cxt
Definition sortsupport.h:66
void varstr_sortsupport(SortSupport ssup, Oid typid, Oid collid)
Definition varlena.c:1669

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

◆ bttextcmp()

Datum bttextcmp ( PG_FUNCTION_ARGS  )

Definition at line 1629 of file varlena.c.

1630{
1633 int32 result;
1634
1635 result = text_cmp(arg1, arg2, PG_GET_COLLATION());
1636
1639
1640 PG_RETURN_INT32(result);
1641}
static int text_cmp(text *arg1, text *arg2, Oid collid)
Definition varlena.c:1401

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

Referenced by gbt_text_ssup_cmp(), and gbt_textcmp().

◆ bttextnamecmp()

Datum bttextnamecmp ( PG_FUNCTION_ARGS  )

◆ bttextsortsupport()

Datum bttextsortsupport ( PG_FUNCTION_ARGS  )

Definition at line 1644 of file varlena.c.

1645{
1647 Oid collid = ssup->ssup_collation;
1648 MemoryContext oldcontext;
1649
1650 oldcontext = MemoryContextSwitchTo(ssup->ssup_cxt);
1651
1652 /* Use generic string SortSupport */
1654
1655 MemoryContextSwitchTo(oldcontext);
1656
1658}
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 2313 of file varlena.c.

2314{
2315#ifdef NOT_USED
2316 Oid opcintype = PG_GETARG_OID(0);
2317#endif
2319 pg_locale_t locale;
2320
2322
2324
2326}
#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:1324

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

4517{
4519 int i;
4520
4521 /* We keep the info in fn_mcxt so it survives across calls */
4523 PG_NARGS() * sizeof(FmgrInfo));
4524
4525 for (i = argidx; i < PG_NARGS(); i++)
4526 {
4527 Oid valtype;
4528 Oid typOutput;
4529 bool typIsVarlena;
4530
4531 valtype = get_fn_expr_argtype(fcinfo->flinfo, i);
4532 if (!OidIsValid(valtype))
4533 elog(ERROR, "could not determine data type of concat() input");
4534
4537 }
4538
4539 fcinfo->flinfo->fn_extra = foutcache;
4540
4541 return foutcache;
4542}
#define OidIsValid(objectId)
Definition c.h:800
#define elog(elevel,...)
Definition elog.h:226
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition fmgr.c:1875
#define PG_NARGS()
Definition fmgr.h:203
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition lsyscache.c:3059

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

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

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

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

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

3201{
3202 int result = 0;
3203 const char *p = VARDATA_ANY(replace_text);
3204 const char *p_end = p + VARSIZE_ANY_EXHDR(replace_text);
3205
3206 while (p < p_end)
3207 {
3208 /* Find next escape char, if any. */
3209 p = memchr(p, '\\', p_end - p);
3210 if (p == NULL)
3211 break;
3212 p++;
3213 /* Note: a backslash at the end doesn't require extra processing. */
3214 if (p < p_end)
3215 {
3216 if (*p >= '1' && *p <= '9')
3217 return 2; /* Found a submatch specifier, so done */
3218 result = 1; /* Found some other sequence, keep looking */
3219 p++;
3220 }
3221 }
3222 return result;
3223}

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

Referenced by replace_text_regexp().

◆ concat_internal()

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

Definition at line 4554 of file varlena.c.

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

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

4063{
4064 const char *digits = "0123456789abcdef";
4065
4066 /* We size the buffer for to_bin's longest possible return value. */
4067 char buf[sizeof(uint64) * BITS_PER_BYTE];
4068 char *const end = buf + sizeof(buf);
4069 char *ptr = end;
4070
4071 Assert(base > 1);
4072 Assert(base <= 16);
4073
4074 do
4075 {
4076 *--ptr = digits[value % base];
4077 value /= base;
4078 } while (ptr > buf && value);
4079
4080 return cstring_to_text_with_len(ptr, end - ptr);
4081}
uint64_t uint64
Definition c.h:559
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 182 of file varlena.c.

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

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(), quote_ident(), quote_ident_cstr(), quote_nullable(), sepgsql_getcon(), sepgsql_mcstrans_in(), sepgsql_mcstrans_out(), set_config_by_name(), show_all_file_settings(), show_config_by_name(), show_config_by_name_missing_ok(), ShowAllGUCConfig(), soundex(), split_part(), ssl_cipher(), ssl_client_dn(), ssl_issuer_dn(), ssl_version(), string_to_text(), test_canonicalize_path(), test_custom_stats_var_report(), test_slru_page_read(), test_slru_page_readonly(), text_substring(), textin(), timeofday(), timetz_at_local(), tsquerytree(), unaccent_dict(), unicode_version(), upper(), xml_encode_special_chars(), xml_in(), and xml_recv().

◆ cstring_to_text_with_len()

text * cstring_to_text_with_len ( const char s,
int  len 
)

Definition at line 194 of file varlena.c.

195{
196 text *result = (text *) palloc(len + VARHDRSZ);
197
198 SET_VARSIZE(result, len + VARHDRSZ);
199 memcpy(VARDATA(result), s, len);
200
201 return result;
202}
#define VARHDRSZ
Definition c.h:723
void * palloc(Size size)
Definition mcxt.c:1387
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 fb(), len, palloc(), SET_VARSIZE(), VARDATA(), and VARHDRSZ.

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

◆ getClosestMatch()

const char * getClosestMatch ( ClosestMatchState state)

Definition at line 5375 of file varlena.c.

5376{
5377 Assert(state);
5378
5379 return state->match;
5380}

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

5606{
5607 if (c >= '0' && c <= '9')
5608 return c - '0';
5609 if (c >= 'a' && c <= 'f')
5610 return c - 'a' + 0xA;
5611 if (c >= 'A' && c <= 'F')
5612 return c - 'A' + 0xA;
5613 elog(ERROR, "invalid hexadecimal digit");
5614 return 0; /* not reached */
5615}
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 5621 of file varlena.c.

5622{
5623 unsigned int result = 0;
5624
5625 for (size_t i = 0; i < n; i++)
5626 result += hexval(instr[i]) << (4 * (n - i - 1));
5627
5628 return result;
5629}
static unsigned int hexval(unsigned char c)
Definition varlena.c:5605

References hexval(), and i.

Referenced by unistr().

◆ icu_unicode_version()

Datum icu_unicode_version ( PG_FUNCTION_ARGS  )

Definition at line 5434 of file varlena.c.

5435{
5436 const char *version = pg_icu_unicode_version();
5437
5438 if (version)
5440 else
5442}
const char * pg_icu_unicode_version()
Definition pg_locale.c:1653
text * cstring_to_text(const char *s)
Definition varlena.c:182

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

5321{
5322 Assert(state);
5323 Assert(max_d >= 0);
5324
5325 state->source = source;
5326 state->min_d = -1;
5327 state->max_d = max_d;
5328 state->match = NULL;
5329}
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 2555 of file varlena.c.

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

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

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

◆ isxdigits_n()

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

Definition at line 5595 of file varlena.c.

5596{
5597 for (size_t i = 0; i < n; i++)
5598 if (!isxdigit((unsigned char) instr[i]))
5599 return false;
5600
5601 return true;
5602}

References fb(), and i.

Referenced by unistr().

◆ makeStringAggState()

static StringInfo makeStringAggState ( FunctionCallInfo  fcinfo)
static

Definition at line 4294 of file varlena.c.

4295{
4297 MemoryContext aggcontext;
4298 MemoryContext oldcontext;
4299
4300 if (!AggCheckCallContext(fcinfo, &aggcontext))
4301 {
4302 /* cannot be called directly because of internal-type argument */
4303 elog(ERROR, "string_agg_transfn called in non-aggregate context");
4304 }
4305
4306 /*
4307 * Create state in aggregate context. It'll stay there across subsequent
4308 * calls.
4309 */
4310 oldcontext = MemoryContextSwitchTo(aggcontext);
4312 MemoryContextSwitchTo(oldcontext);
4313
4314 return state;
4315}
int AggCheckCallContext(FunctionCallInfo fcinfo, MemoryContext *aggcontext)
Definition nodeAgg.c:4607
StringInfo makeStringInfo(void)
Definition stringinfo.c:72

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

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

◆ name_text()

Datum name_text ( PG_FUNCTION_ARGS  )

Definition at line 2700 of file varlena.c.

2701{
2702 Name s = PG_GETARG_NAME(0);
2703
2705}

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

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

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

◆ namefastcmp_c()

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

Definition at line 1875 of file varlena.c.

1876{
1879
1881}
#define NAMEDATALEN
static Name DatumGetName(Datum X)
Definition postgres.h:390

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

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

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

Referenced by varstr_sortsupport().

◆ namegetext()

Datum namegetext ( PG_FUNCTION_ARGS  )

Definition at line 2514 of file varlena.c.

2515{
2517}
#define CmpCall(cmpfunc)
Definition varlena.c:2489
Datum btnametextcmp(PG_FUNCTION_ARGS)
Definition varlena.c:2458

References btnametextcmp(), CmpCall, and PG_RETURN_BOOL.

◆ namegttext()

Datum namegttext ( PG_FUNCTION_ARGS  )

Definition at line 2508 of file varlena.c.

2509{
2511}

References btnametextcmp(), CmpCall, and PG_RETURN_BOOL.

◆ nameletext()

Datum nameletext ( PG_FUNCTION_ARGS  )

Definition at line 2502 of file varlena.c.

2503{
2505}

References btnametextcmp(), CmpCall, and PG_RETURN_BOOL.

◆ namelttext()

Datum namelttext ( PG_FUNCTION_ARGS  )

Definition at line 2496 of file varlena.c.

2497{
2499}

References btnametextcmp(), CmpCall, and PG_RETURN_BOOL.

◆ namenetext()

Datum namenetext ( PG_FUNCTION_ARGS  )

Definition at line 2408 of file varlena.c.

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

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

◆ pg_column_compression()

Datum pg_column_compression ( PG_FUNCTION_ARGS  )

Definition at line 4193 of file varlena.c.

4194{
4195 int typlen;
4196 char *result;
4198
4199 /* On first call, get the input type's typlen, and save at *fn_extra */
4200 if (fcinfo->flinfo->fn_extra == NULL)
4201 {
4202 /* Lookup the datatype of the supplied argument */
4203 Oid argtypeid = get_fn_expr_argtype(fcinfo->flinfo, 0);
4204
4205 typlen = get_typlen(argtypeid);
4206 if (typlen == 0) /* should not happen */
4207 elog(ERROR, "cache lookup failed for type %u", argtypeid);
4208
4209 fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
4210 sizeof(int));
4211 *((int *) fcinfo->flinfo->fn_extra) = typlen;
4212 }
4213 else
4214 typlen = *((int *) fcinfo->flinfo->fn_extra);
4215
4216 if (typlen != -1)
4218
4219 /* get the compression method id stored in the compressed varlena */
4224
4225 /* convert compression method id to compression method name */
4226 switch (cmid)
4227 {
4229 result = "pglz";
4230 break;
4232 result = "lz4";
4233 break;
4234 default:
4235 elog(ERROR, "invalid compression method id %d", cmid);
4236 }
4237
4239}
int16 get_typlen(Oid typid)
Definition lsyscache.c:2347
static Pointer DatumGetPointer(Datum X)
Definition postgres.h:342
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, 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 4146 of file varlena.c.

4147{
4149 int32 result;
4150 int typlen;
4151
4152 /* On first call, get the input type's typlen, and save at *fn_extra */
4153 if (fcinfo->flinfo->fn_extra == NULL)
4154 {
4155 /* Lookup the datatype of the supplied argument */
4156 Oid argtypeid = get_fn_expr_argtype(fcinfo->flinfo, 0);
4157
4158 typlen = get_typlen(argtypeid);
4159 if (typlen == 0) /* should not happen */
4160 elog(ERROR, "cache lookup failed for type %u", argtypeid);
4161
4162 fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
4163 sizeof(int));
4164 *((int *) fcinfo->flinfo->fn_extra) = typlen;
4165 }
4166 else
4167 typlen = *((int *) fcinfo->flinfo->fn_extra);
4168
4169 if (typlen == -1)
4170 {
4171 /* varlena type, possibly toasted */
4172 result = toast_datum_size(value);
4173 }
4174 else if (typlen == -2)
4175 {
4176 /* cstring */
4177 result = strlen(DatumGetCString(value)) + 1;
4178 }
4179 else
4180 {
4181 /* ordinary fixed-width type */
4182 result = typlen;
4183 }
4184
4185 PG_RETURN_INT32(result);
4186}
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, toast_datum_size(), and value.

◆ pg_column_toast_chunk_id()

Datum pg_column_toast_chunk_id ( PG_FUNCTION_ARGS  )

Definition at line 4246 of file varlena.c.

4247{
4248 int typlen;
4249 varlena *attr;
4250 varatt_external toast_pointer;
4251
4252 /* On first call, get the input type's typlen, and save at *fn_extra */
4253 if (fcinfo->flinfo->fn_extra == NULL)
4254 {
4255 /* Lookup the datatype of the supplied argument */
4256 Oid argtypeid = get_fn_expr_argtype(fcinfo->flinfo, 0);
4257
4258 typlen = get_typlen(argtypeid);
4259 if (typlen == 0) /* should not happen */
4260 elog(ERROR, "cache lookup failed for type %u", argtypeid);
4261
4262 fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
4263 sizeof(int));
4264 *((int *) fcinfo->flinfo->fn_extra) = typlen;
4265 }
4266 else
4267 typlen = *((int *) fcinfo->flinfo->fn_extra);
4268
4269 if (typlen != -1)
4271
4273
4274 if (!VARATT_IS_EXTERNAL_ONDISK(attr))
4276
4277 VARATT_EXTERNAL_GET_POINTER(toast_pointer, attr);
4278
4279 PG_RETURN_OID(toast_pointer.va_valueid);
4280}
#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 802 of file varlena.c.

803{
804 int nch = 0;
805 int l;
806
807 Assert(len > 0);
808 Assert(limit > 0);
810
811 while (len > 0 && *mbstr)
812 {
814 nch++;
815 if (nch == limit)
816 break;
817 len -= l;
818 mbstr += l;
819 }
820 return nch;
821}
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 3123 of file varlena.c.

3124{
3128 int src_text_len;
3131 text *ret_text;
3132 int chunk_len;
3133 char *curr_ptr;
3134 char *start_ptr;
3136 bool found;
3137
3140
3141 /* Return unmodified source string if empty source or pattern */
3142 if (src_text_len < 1 || from_sub_text_len < 1)
3143 {
3145 }
3146
3148
3149 found = text_position_next(&state);
3150
3151 /* When the from_sub_text is not found, there is nothing to do. */
3152 if (!found)
3153 {
3156 }
3159
3161
3162 do
3163 {
3165
3166 /* copy the data skipped over by last text_position_next() */
3169
3171
3172 start_ptr = curr_ptr + state.last_match_len;
3173
3174 found = text_position_next(&state);
3175 if (found)
3177 }
3178 while (found);
3179
3180 /* copy trailing data */
3183
3185
3187 pfree(str.data);
3188
3190}
#define CHECK_FOR_INTERRUPTS()
Definition miscadmin.h:123
static Size VARSIZE_ANY(const void *PTR)
Definition varatt.h:460
static void text_position_setup(text *t1, text *t2, Oid collid, TextPositionState *state)
Definition varlena.c:960
static void text_position_cleanup(TextPositionState *state)
Definition varlena.c:1317
static void appendStringInfoText(StringInfo str, const text *t)
Definition varlena.c:3109
static char * text_position_get_match_ptr(TextPositionState *state)
Definition varlena.c:1282
static bool text_position_next(TextPositionState *state)
Definition varlena.c:1081

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

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

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

5285{
5286 while (len > 0)
5287 {
5288 len--;
5289 if (s1[len] != s2[len])
5290 return false;
5291 }
5292 return true;
5293}
char * s1
char * s2

References len, s1, and s2.

Referenced by varstr_levenshtein().

◆ split_part()

Datum split_part ( PG_FUNCTION_ARGS  )

Definition at line 3495 of file varlena.c.

3496{
3499 int fldnum = PG_GETARG_INT32(2);
3500 int inputstring_len;
3501 int fldsep_len;
3503 char *start_ptr;
3504 char *end_ptr;
3506 bool found;
3507
3508 /* field number is 1 based */
3509 if (fldnum == 0)
3510 ereport(ERROR,
3512 errmsg("field position must not be zero")));
3513
3516
3517 /* return empty string for empty input string */
3518 if (inputstring_len < 1)
3520
3521 /* handle empty field separator */
3522 if (fldsep_len < 1)
3523 {
3524 /* if first or last field, return input string, else empty string */
3525 if (fldnum == 1 || fldnum == -1)
3527 else
3529 }
3530
3531 /* find the first field separator */
3533
3534 found = text_position_next(&state);
3535
3536 /* special case if fldsep not found at all */
3537 if (!found)
3538 {
3540 /* if first or last field, return input string, else empty string */
3541 if (fldnum == 1 || fldnum == -1)
3543 else
3545 }
3546
3547 /*
3548 * take care of a negative field number (i.e. count from the right) by
3549 * converting to a positive field number; we need total number of fields
3550 */
3551 if (fldnum < 0)
3552 {
3553 /* we found a fldsep, so there are at least two fields */
3554 int numfields = 2;
3555
3556 while (text_position_next(&state))
3557 numfields++;
3558
3559 /* special case of last field does not require an extra pass */
3560 if (fldnum == -1)
3561 {
3562 start_ptr = text_position_get_match_ptr(&state) + state.last_match_len;
3566 end_ptr - start_ptr));
3567 }
3568
3569 /* else, convert fldnum to positive notation */
3570 fldnum += numfields + 1;
3571
3572 /* if nonexistent field, return empty string */
3573 if (fldnum <= 0)
3574 {
3577 }
3578
3579 /* reset to pointing at first match, but now with positive fldnum */
3581 found = text_position_next(&state);
3582 Assert(found);
3583 }
3584
3585 /* identify bounds of first field */
3588
3589 while (found && --fldnum > 0)
3590 {
3591 /* identify bounds of next field */
3592 start_ptr = end_ptr + state.last_match_len;
3593 found = text_position_next(&state);
3594 if (found)
3596 }
3597
3599
3600 if (fldnum > 0)
3601 {
3602 /* N'th field separator not found */
3603 /* if last field requested, return it, else empty string */
3604 if (fldnum == 1)
3605 {
3607
3610 }
3611 else
3613 }
3614 else
3615 {
3616 /* non-last field requested */
3618 }
3619
3621}
#define PG_GETARG_INT32(n)
Definition fmgr.h:269
static void text_position_reset(TextPositionState *state)
Definition varlena.c:1309

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

◆ split_text()

static bool split_text ( FunctionCallInfo  fcinfo,
SplitTextOutputData tstate 
)
static

Definition at line 3718 of file varlena.c.

3719{
3721 text *fldsep;
3723 Oid collation = PG_GET_COLLATION();
3724 int inputstring_len;
3725 int fldsep_len;
3726 char *start_ptr;
3728
3729 /* when input string is NULL, then result is NULL too */
3730 if (PG_ARGISNULL(0))
3731 return false;
3732
3734
3735 /* fldsep can be NULL */
3736 if (!PG_ARGISNULL(1))
3738 else
3739 fldsep = NULL;
3740
3741 /* null_string can be NULL or omitted */
3742 if (PG_NARGS() > 2 && !PG_ARGISNULL(2))
3744 else
3745 null_string = NULL;
3746
3747 if (fldsep != NULL)
3748 {
3749 /*
3750 * Normal case with non-null fldsep. Use the text_position machinery
3751 * to search for occurrences of fldsep.
3752 */
3754
3757
3758 /* return empty set for empty input string */
3759 if (inputstring_len < 1)
3760 return true;
3761
3762 /* empty field separator: return input string as a one-element set */
3763 if (fldsep_len < 1)
3764 {
3766 null_string, collation);
3767 return true;
3768 }
3769
3771
3773
3774 for (;;)
3775 {
3776 bool found;
3777 char *end_ptr;
3778 int chunk_len;
3779
3781
3782 found = text_position_next(&state);
3783 if (!found)
3784 {
3785 /* fetch last field */
3787 end_ptr = NULL; /* not used, but some compilers complain */
3788 }
3789 else
3790 {
3791 /* fetch non-last field */
3794 }
3795
3796 /* build a temp text datum to pass to split_text_accum_result */
3798
3799 /* stash away this field */
3801 null_string, collation);
3802
3804
3805 if (!found)
3806 break;
3807
3808 start_ptr = end_ptr + state.last_match_len;
3809 }
3810
3812 }
3813 else
3814 {
3815 const char *end_ptr;
3816
3817 /*
3818 * When fldsep is NULL, each character in the input string becomes a
3819 * separate element in the result set. The separator is effectively
3820 * the space between characters.
3821 */
3823
3826
3827 while (inputstring_len > 0)
3828 {
3830
3832
3833 /* build a temp text datum to pass to split_text_accum_result */
3835
3836 /* stash away this field */
3838 null_string, collation);
3839
3841
3844 }
3845 }
3846
3847 return true;
3848}
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:3857

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

3861{
3862 bool is_null = false;
3863
3864 if (null_string && text_isequal(field_value, null_string, collation))
3865 is_null = true;
3866
3867 if (tstate->tupstore)
3868 {
3869 Datum values[1];
3870 bool nulls[1];
3871
3873 nulls[0] = is_null;
3874
3875 tuplestore_putvalues(tstate->tupstore,
3876 tstate->tupdesc,
3877 values,
3878 nulls);
3879 }
3880 else
3881 {
3882 tstate->astate = accumArrayResult(tstate->astate,
3884 is_null,
3885 TEXTOID,
3887 }
3888}
ArrayBuildState * accumArrayResult(ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
static Datum values[MAXATTR]
Definition bootstrap.c:147
MemoryContext CurrentMemoryContext
Definition mcxt.c:160
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, const Datum *values, const bool *isnull)
Definition tuplestore.c:784
static bool text_isequal(text *txt1, text *txt2, Oid collid)
Definition varlena.c:3627

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

2904{
2905 char *nextp = rawstring;
2906 bool done = false;
2907
2908 *namelist = NIL;
2909
2910 while (scanner_isspace(*nextp))
2911 nextp++; /* skip leading whitespace */
2912
2913 if (*nextp == '\0')
2914 return true; /* empty string represents empty list */
2915
2916 /* At the top of the loop, we are at start of a new directory. */
2917 do
2918 {
2919 char *curname;
2920 char *endp;
2921
2922 if (*nextp == '"')
2923 {
2924 /* Quoted name --- collapse quote-quote pairs */
2925 curname = nextp + 1;
2926 for (;;)
2927 {
2928 endp = strchr(nextp + 1, '"');
2929 if (endp == NULL)
2930 return false; /* mismatched quotes */
2931 if (endp[1] != '"')
2932 break; /* found end of quoted name */
2933 /* Collapse adjacent quotes into one quote, and look again */
2934 memmove(endp, endp + 1, strlen(endp));
2935 nextp = endp;
2936 }
2937 /* endp now points at the terminating quote */
2938 nextp = endp + 1;
2939 }
2940 else
2941 {
2942 /* Unquoted name --- extends to separator or end of string */
2943 curname = endp = nextp;
2944 while (*nextp && *nextp != separator)
2945 {
2946 /* trailing whitespace should not be included in name */
2947 if (!scanner_isspace(*nextp))
2948 endp = nextp + 1;
2949 nextp++;
2950 }
2951 if (curname == endp)
2952 return false; /* empty unquoted name not allowed */
2953 }
2954
2955 while (scanner_isspace(*nextp))
2956 nextp++; /* skip trailing whitespace */
2957
2958 if (*nextp == separator)
2959 {
2960 nextp++;
2961 while (scanner_isspace(*nextp))
2962 nextp++; /* skip leading whitespace for next */
2963 /* we expect another name, so done remains false */
2964 }
2965 else if (*nextp == '\0')
2966 done = true;
2967 else
2968 return false; /* invalid syntax */
2969
2970 /* Now safe to overwrite separator with a null */
2971 *endp = '\0';
2972
2973 /* Truncate path if it's overlength */
2974 if (strlen(curname) >= MAXPGPATH)
2975 curname[MAXPGPATH - 1] = '\0';
2976
2977 /*
2978 * Finished isolating current name --- add it to list
2979 */
2983
2984 /* Loop back if we didn't reach end of string */
2985 } while (!done);
2986
2987 return true;
2988}
List * lappend(List *list, void *datum)
Definition list.c:339
char * pstrdup(const char *in)
Definition mcxt.c:1781
#define MAXPGPATH
#define NIL
Definition pg_list.h:68
void canonicalize_path(char *path)
Definition path.c:337
bool scanner_isspace(char ch)
Definition scansup.c:105

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

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

◆ SplitGUCList()

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

Definition at line 3023 of file varlena.c.

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

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

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

◆ SplitIdentifierString()

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

Definition at line 2775 of file varlena.c.

2777{
2778 char *nextp = rawstring;
2779 bool done = false;
2780
2781 *namelist = NIL;
2782
2783 while (scanner_isspace(*nextp))
2784 nextp++; /* skip leading whitespace */
2785
2786 if (*nextp == '\0')
2787 return true; /* empty string represents empty list */
2788
2789 /* At the top of the loop, we are at start of a new identifier. */
2790 do
2791 {
2792 char *curname;
2793 char *endp;
2794
2795 if (*nextp == '"')
2796 {
2797 /* Quoted name --- collapse quote-quote pairs, no downcasing */
2798 curname = nextp + 1;
2799 for (;;)
2800 {
2801 endp = strchr(nextp + 1, '"');
2802 if (endp == NULL)
2803 return false; /* mismatched quotes */
2804 if (endp[1] != '"')
2805 break; /* found end of quoted name */
2806 /* Collapse adjacent quotes into one quote, and look again */
2807 memmove(endp, endp + 1, strlen(endp));
2808 nextp = endp;
2809 }
2810 /* endp now points at the terminating quote */
2811 nextp = endp + 1;
2812 }
2813 else
2814 {
2815 /* Unquoted name --- extends to separator or whitespace */
2816 char *downname;
2817 int len;
2818
2819 curname = nextp;
2820 while (*nextp && *nextp != separator &&
2822 nextp++;
2823 endp = nextp;
2824 if (curname == nextp)
2825 return false; /* empty unquoted name not allowed */
2826
2827 /*
2828 * Downcase the identifier, using same code as main lexer does.
2829 *
2830 * XXX because we want to overwrite the input in-place, we cannot
2831 * support a downcasing transformation that increases the string
2832 * length. This is not a problem given the current implementation
2833 * of downcase_truncate_identifier, but we'll probably have to do
2834 * something about this someday.
2835 */
2836 len = endp - curname;
2839 strncpy(curname, downname, len); /* strncpy is required here */
2840 pfree(downname);
2841 }
2842
2843 while (scanner_isspace(*nextp))
2844 nextp++; /* skip trailing whitespace */
2845
2846 if (*nextp == separator)
2847 {
2848 nextp++;
2849 while (scanner_isspace(*nextp))
2850 nextp++; /* skip leading whitespace for next */
2851 /* we expect another name, so done remains false */
2852 }
2853 else if (*nextp == '\0')
2854 done = true;
2855 else
2856 return false; /* invalid syntax */
2857
2858 /* Now safe to overwrite separator with a null */
2859 *endp = '\0';
2860
2861 /* Truncate name if it's overlength */
2863
2864 /*
2865 * Finished isolating current name --- add it to list
2866 */
2868
2869 /* Loop back if we didn't reach end of string */
2870 } while (!done);
2871
2872 return true;
2873}
void truncate_identifier(char *ident, int len, bool warn)
Definition scansup.c:81
char * downcase_truncate_identifier(const char *ident, int len, bool warn)
Definition scansup.c:38

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

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

◆ string_agg_combine()

Datum string_agg_combine ( PG_FUNCTION_ARGS  )

Definition at line 4373 of file varlena.c.

4374{
4377 MemoryContext agg_context;
4378
4379 if (!AggCheckCallContext(fcinfo, &agg_context))
4380 elog(ERROR, "aggregate function called in non-aggregate context");
4381
4384
4385 if (state2 == NULL)
4386 {
4387 /*
4388 * NULL state2 is easy, just return state1, which we know is already
4389 * in the agg_context
4390 */
4391 if (state1 == NULL)
4394 }
4395
4396 if (state1 == NULL)
4397 {
4398 /* We must copy state2's data into the agg_context */
4400
4401 old_context = MemoryContextSwitchTo(agg_context);
4402 state1 = makeStringAggState(fcinfo);
4404 state1->cursor = state2->cursor;
4406 }
4407 else if (state2->len > 0)
4408 {
4409 /* Combine ... state1->cursor does not change in this case */
4411 }
4412
4414}
#define PG_RETURN_POINTER(x)
Definition fmgr.h:363
struct StringInfoData * StringInfo
Definition string.h:15
static StringInfo makeStringAggState(FunctionCallInfo fcinfo)
Definition varlena.c:4294

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

4455{
4456 bytea *sstate;
4457 StringInfo result;
4459 char *data;
4460 int datalen;
4461
4462 /* cannot be called directly because of internal-type argument */
4464
4465 sstate = PG_GETARG_BYTEA_PP(0);
4466
4467 /*
4468 * Initialize a StringInfo so that we can "receive" it using the standard
4469 * recv-function infrastructure.
4470 */
4472 VARSIZE_ANY_EXHDR(sstate));
4473
4474 result = makeStringAggState(fcinfo);
4475
4476 /* cursor */
4477 result->cursor = pq_getmsgint(&buf, 4);
4478
4479 /* data */
4480 datalen = VARSIZE_ANY_EXHDR(sstate) - 4;
4481 data = (char *) pq_getmsgbytes(&buf, datalen);
4482 appendBinaryStringInfo(result, data, datalen);
4483
4484 pq_getmsgend(&buf);
4485
4486 PG_RETURN_POINTER(result);
4487}
#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, StringInfoData::cursor, data, fb(), initReadOnlyStringInfo(), makeStringAggState(), PG_GETARG_BYTEA_PP, PG_RETURN_POINTER, pq_getmsgbytes(), pq_getmsgend(), pq_getmsgint(), VARDATA_ANY(), and VARSIZE_ANY_EXHDR().

◆ string_agg_finalfn()

Datum string_agg_finalfn ( PG_FUNCTION_ARGS  )

Definition at line 4490 of file varlena.c.

4491{
4493
4494 /* cannot be called directly because of internal-type argument */
4496
4498
4499 if (state != NULL)
4500 {
4501 /* As per comment in transfn, strip data before the cursor position */
4503 state->len - state->cursor));
4504 }
4505 else
4507}

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

4424{
4427 bytea *result;
4428
4429 /* cannot be called directly because of internal-type argument */
4431
4433
4435
4436 /* cursor */
4437 pq_sendint(&buf, state->cursor, 4);
4438
4439 /* data */
4440 pq_sendbytes(&buf, state->data, state->len);
4441
4442 result = pq_endtypsend(&buf);
4443
4444 PG_RETURN_BYTEA_P(result);
4445}
#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(), and pq_sendint().

◆ string_agg_transfn()

Datum string_agg_transfn ( PG_FUNCTION_ARGS  )

Definition at line 4318 of file varlena.c.

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

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

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

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

Referenced by text_overlay(), and textcat().

◆ text_cmp()

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

Definition at line 1401 of file varlena.c.

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

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

4635{
4636 text *result;
4637
4638 result = concat_internal("", 0, fcinfo);
4639 if (result == NULL)
4641 PG_RETURN_TEXT_P(result);
4642}
static text * concat_internal(const char *sepstr, int argidx, FunctionCallInfo fcinfo)
Definition varlena.c:4554

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

◆ text_concat_ws()

Datum text_concat_ws ( PG_FUNCTION_ARGS  )

Definition at line 4649 of file varlena.c.

4650{
4651 char *sep;
4652 text *result;
4653
4654 /* return NULL when separator is NULL */
4655 if (PG_ARGISNULL(0))
4658
4659 result = concat_internal(sep, 1, fcinfo);
4660 if (result == NULL)
4662 PG_RETURN_TEXT_P(result);
4663}

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

◆ text_format()

Datum text_format ( PG_FUNCTION_ARGS  )

Definition at line 4770 of file varlena.c.

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

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

5224{
5225 bool align_to_left = false;
5226 int len;
5227
5228 /* fast path for typical easy case */
5229 if (width == 0)
5230 {
5232 return;
5233 }
5234
5235 if (width < 0)
5236 {
5237 /* Negative width: implicit '-' flag, then take absolute value */
5238 align_to_left = true;
5239 /* -INT_MIN is undefined */
5240 if (width <= INT_MIN)
5241 ereport(ERROR,
5243 errmsg("number is out of range")));
5244 width = -width;
5245 }
5246 else if (flags & TEXT_FORMAT_FLAG_MINUS)
5247 align_to_left = true;
5248
5249 len = pg_mbstrlen(str);
5250 if (align_to_left)
5251 {
5252 /* left justify */
5254 if (len < width)
5255 appendStringInfoSpaces(buf, width - len);
5256 }
5257 else
5258 {
5259 /* right justify */
5260 if (len < width)
5261 appendStringInfoSpaces(buf, width - len);
5263 }
5264}
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:4755

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

5275{
5276 return text_format(fcinfo);
5277}
Datum text_format(PG_FUNCTION_ARGS)
Definition varlena.c:4770

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

5048{
5049 bool found = false;
5050 const char *cp = *ptr;
5051 int val = 0;
5052
5053 while (*cp >= '0' && *cp <= '9')
5054 {
5055 int8 digit = (*cp - '0');
5056
5057 if (unlikely(pg_mul_s32_overflow(val, 10, &val)) ||
5059 ereport(ERROR,
5061 errmsg("number is out of range")));
5063 found = true;
5064 }
5065
5066 *ptr = cp;
5067 *value = val;
5068
5069 return found;
5070}
int8_t int8
Definition c.h:552
#define unlikely(x)
Definition c.h:424
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 5096 of file varlena.c.

5099{
5100 const char *cp = start_ptr;
5101 int n;
5102
5103 /* set defaults for output parameters */
5104 *argpos = -1;
5105 *widthpos = -1;
5106 *flags = 0;
5107 *width = 0;
5108
5109 /* try to identify first number */
5111 {
5112 if (*cp != '$')
5113 {
5114 /* Must be just a width and a type, so we're done */
5115 *width = n;
5116 return cp;
5117 }
5118 /* The number was argument position */
5119 *argpos = n;
5120 /* Explicit 0 for argument index is immediately refused */
5121 if (n == 0)
5122 ereport(ERROR,
5124 errmsg("format specifies argument 0, but arguments are numbered from 1")));
5126 }
5127
5128 /* Handle flags (only minus is supported now) */
5129 while (*cp == '-')
5130 {
5131 *flags |= TEXT_FORMAT_FLAG_MINUS;
5133 }
5134
5135 if (*cp == '*')
5136 {
5137 /* Handle indirect width */
5140 {
5141 /* number in this position must be closed by $ */
5142 if (*cp != '$')
5143 ereport(ERROR,
5145 errmsg("width argument position must be ended by \"$\"")));
5146 /* The number was width argument position */
5147 *widthpos = n;
5148 /* Explicit 0 for argument index is immediately refused */
5149 if (n == 0)
5150 ereport(ERROR,
5152 errmsg("format specifies argument 0, but arguments are numbered from 1")));
5154 }
5155 else
5156 *widthpos = 0; /* width's argument position is unspecified */
5157 }
5158 else
5159 {
5160 /* Check for direct width specification */
5162 *width = n;
5163 }
5164
5165 /* cp should now be pointing at type character */
5166 return cp;
5167}
static bool text_format_parse_digits(const char **ptr, const char *end_ptr, int *value)
Definition varlena.c:5047

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

5177{
5178 char *str;
5179
5180 /* Handle NULL arguments before trying to stringify the value. */
5181 if (isNull)
5182 {
5183 if (conversion == 's')
5184 text_format_append_string(buf, "", flags, width);
5185 else if (conversion == 'L')
5186 text_format_append_string(buf, "NULL", flags, width);
5187 else if (conversion == 'I')
5188 ereport(ERROR,
5190 errmsg("null values cannot be formatted as an SQL identifier")));
5191 return;
5192 }
5193
5194 /* Stringify. */
5196
5197 /* Escape. */
5198 if (conversion == 'I')
5199 {
5200 /* quote_identifier may or may not allocate a new string. */
5202 }
5203 else if (conversion == 'L')
5204 {
5205 char *qstr = quote_literal_cstr(str);
5206
5207 text_format_append_string(buf, qstr, flags, width);
5208 /* quote_literal_cstr() always allocates a new string */
5209 pfree(qstr);
5210 }
5211 else
5212 text_format_append_string(buf, str, flags, width);
5213
5214 /* Cleanup. */
5215 pfree(str);
5216}
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:5222

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

1576{
1579 bool result;
1580
1581 result = (text_cmp(arg1, arg2, PG_GET_COLLATION()) >= 0);
1582
1585
1586 PG_RETURN_BOOL(result);
1587}

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

Referenced by gbt_textge().

◆ text_gt()

Datum text_gt ( PG_FUNCTION_ARGS  )

Definition at line 1560 of file varlena.c.

1561{
1564 bool result;
1565
1566 result = (text_cmp(arg1, arg2, PG_GET_COLLATION()) > 0);
1567
1570
1571 PG_RETURN_BOOL(result);
1572}

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

Referenced by gbt_textgt().

◆ text_isequal()

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

Definition at line 3627 of file varlena.c.

3628{
3630 collid,
3633}
static bool DatumGetBool(Datum X)
Definition postgres.h:100
Datum texteq(PG_FUNCTION_ARGS)
Definition varlena.c:1426

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

2330{
2333 text *result;
2334
2335 result = ((text_cmp(arg1, arg2, PG_GET_COLLATION()) > 0) ? arg1 : arg2);
2336
2337 PG_RETURN_TEXT_P(result);
2338}

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

◆ text_le()

Datum text_le ( PG_FUNCTION_ARGS  )

Definition at line 1545 of file varlena.c.

1546{
1549 bool result;
1550
1551 result = (text_cmp(arg1, arg2, PG_GET_COLLATION()) <= 0);
1552
1555
1556 PG_RETURN_BOOL(result);
1557}

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

Referenced by gbt_textle().

◆ text_left()

Datum text_left ( PG_FUNCTION_ARGS  )

Definition at line 4670 of file varlena.c.

4671{
4672 int n = PG_GETARG_INT32(1);
4673
4674 if (n < 0)
4675 {
4677 const char *p = VARDATA_ANY(str);
4678 int len = VARSIZE_ANY_EXHDR(str);
4679 int rlen;
4680
4681 n = pg_mbstrlen_with_len(p, len) + n;
4682 rlen = pg_mbcharcliplen(p, len, n);
4684 }
4685 else
4687}
int pg_mbstrlen_with_len(const char *mbstr, int limit)
Definition mbutils.c:1185
int pg_mbcharcliplen(const char *mbstr, int len, int limit)
Definition mbutils.c:1253
static text * text_substring(Datum str, int32 start, int32 length, bool length_not_specified)
Definition varlena.c:584

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

409{
410 /* fastpath when max encoding length is one */
413 else
414 {
415 text *t = DatumGetTextPP(str);
416
418 }
419}
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 1530 of file varlena.c.

1531{
1534 bool result;
1535
1536 result = (text_cmp(arg1, arg2, PG_GET_COLLATION()) < 0);
1537
1540
1541 PG_RETURN_BOOL(result);
1542}

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

Referenced by gbt_textlt().

◆ text_name()

Datum text_name ( PG_FUNCTION_ARGS  )

Definition at line 2677 of file varlena.c.

2678{
2679 text *s = PG_GETARG_TEXT_PP(0);
2680 Name result;
2681 int len;
2682
2684
2685 /* Truncate oversize input */
2686 if (len >= NAMEDATALEN)
2688
2689 /* We use palloc0 here to ensure result is zero-padded */
2690 result = (Name) palloc0(NAMEDATALEN);
2691 memcpy(NameStr(*result), VARDATA_ANY(s), len);
2692
2693 PG_RETURN_NAME(result);
2694}
NameData * Name
Definition c.h:775
#define PG_RETURN_NAME(x)
Definition fmgr.h:365
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition mbutils.c:1211
void * palloc0(Size size)
Definition mcxt.c:1417

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

◆ text_overlay()

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

Definition at line 854 of file varlena.c.

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

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

Referenced by textoverlay(), and textoverlay_no_len().

◆ text_pattern_ge()

Datum text_pattern_ge ( PG_FUNCTION_ARGS  )

Definition at line 2609 of file varlena.c.

2610{
2613 int result;
2614
2616
2619
2620 PG_RETURN_BOOL(result >= 0);
2621}

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

◆ text_pattern_gt()

Datum text_pattern_gt ( PG_FUNCTION_ARGS  )

Definition at line 2625 of file varlena.c.

2626{
2629 int result;
2630
2632
2635
2636 PG_RETURN_BOOL(result > 0);
2637}

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

◆ text_pattern_le()

Datum text_pattern_le ( PG_FUNCTION_ARGS  )

Definition at line 2593 of file varlena.c.

2594{
2597 int result;
2598
2600
2603
2604 PG_RETURN_BOOL(result <= 0);
2605}

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

◆ text_pattern_lt()

Datum text_pattern_lt ( PG_FUNCTION_ARGS  )

Definition at line 2577 of file varlena.c.

2578{
2581 int result;
2582
2584
2587
2588 PG_RETURN_BOOL(result < 0);
2589}

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

◆ text_position()

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

Definition at line 914 of file varlena.c.

915{
917 int result;
918
920
921 /* Empty needle always matches at position 1 */
922 if (VARSIZE_ANY_EXHDR(t2) < 1)
923 return 1;
924
925 /* Otherwise, can't match if haystack is shorter than needle */
927 pg_newlocale_from_collation(collid)->deterministic)
928 return 0;
929
931 /* don't need greedy mode here */
932 state.greedy = false;
933
935 result = 0;
936 else
939 return result;
940}
static int text_position_get_match_pos(TextPositionState *state)
Definition varlena.c:1293

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

Referenced by textpos().

◆ text_position_cleanup()

static void text_position_cleanup ( TextPositionState state)
static

Definition at line 1317 of file varlena.c.

1318{
1319 /* no cleanup needed */
1320}

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

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

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

1283{
1284 return state->last_match;
1285}

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

◆ text_position_next()

static bool text_position_next ( TextPositionState state)
static

Definition at line 1081 of file varlena.c.

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

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

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

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

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

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

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

4716{
4718 const char *p = VARDATA_ANY(str);
4719 int len = VARSIZE_ANY_EXHDR(str);
4720 const char *endp = p + len;
4721 text *result;
4722 char *dst;
4723
4724 result = palloc(len + VARHDRSZ);
4725 dst = (char *) VARDATA(result) + len;
4726 SET_VARSIZE(result, len + VARHDRSZ);
4727
4729 {
4730 /* multibyte version */
4731 while (p < endp)
4732 {
4733 int sz;
4734
4735 sz = pg_mblen_range(p, endp);
4736 dst -= sz;
4737 memcpy(dst, p, sz);
4738 p += sz;
4739 }
4740 }
4741 else
4742 {
4743 /* single byte version */
4744 while (p < endp)
4745 *(--dst) = *p++;
4746 }
4747
4748 PG_RETURN_TEXT_P(result);
4749}

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

◆ text_right()

Datum text_right ( PG_FUNCTION_ARGS  )

Definition at line 4694 of file varlena.c.

4695{
4697 const char *p = VARDATA_ANY(str);
4698 int len = VARSIZE_ANY_EXHDR(str);
4699 int n = PG_GETARG_INT32(1);
4700 int off;
4701
4702 if (n < 0)
4703 n = -n;
4704 else
4705 n = pg_mbstrlen_with_len(p, len) - n;
4706 off = pg_mbcharcliplen(p, len, n);
4707
4709}

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

2342{
2345 text *result;
2346
2347 result = ((text_cmp(arg1, arg2, PG_GET_COLLATION()) < 0) ? arg1 : arg2);
2348
2349 PG_RETURN_TEXT_P(result);
2350}

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

◆ text_starts_with()

Datum text_starts_with ( PG_FUNCTION_ARGS  )

Definition at line 1590 of file varlena.c.

1591{
1596 bool result;
1597 Size len1,
1598 len2;
1599
1601
1603
1604 if (!mylocale->deterministic)
1605 ereport(ERROR,
1607 errmsg("nondeterministic collations are not supported for substring searches")));
1608
1609 len1 = toast_raw_datum_size(arg1);
1610 len2 = toast_raw_datum_size(arg2);
1611 if (len2 > len1)
1612 result = false;
1613 else
1614 {
1615 text *targ1 = text_substring(arg1, 1, len2, false);
1617
1619 VARSIZE_ANY_EXHDR(targ2)) == 0);
1620
1623 }
1624
1625 PG_RETURN_BOOL(result);
1626}
size_t Size
Definition c.h:631

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

566{
569 -1, true));
570}

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

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

References cstring_to_text(), DatumGetPointer(), DatumGetTextPSlice, elog, ereport, errcode(), errmsg(), ERROR, fb(), i, Max, 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 3641 of file varlena.c.

3642{
3644
3645 /* For array output, tstate should start as all zeroes */
3646 memset(&tstate, 0, sizeof(tstate));
3647
3648 if (!split_text(fcinfo, &tstate))
3650
3651 if (tstate.astate == NULL)
3653
3656}
#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:3718

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

3668{
3669 return text_to_array(fcinfo);
3670}
Datum text_to_array(PG_FUNCTION_ARGS)
Definition varlena.c:3641

References text_to_array().

◆ text_to_cstring()

char * text_to_cstring ( const text t)

Definition at line 215 of file varlena.c.

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

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

Referenced by array_to_text(), array_to_text_null(), binary_upgrade_add_sub_rel_state(), binary_upgrade_create_empty_extension(), binary_upgrade_replorigin_advance(), binary_upgrade_set_missing_value(), connectby_text(), connectby_text_serial(), convert_and_check_filename(), convert_any_priv_string(), convert_column_name(), convert_database_name(), convert_foreign_data_wrapper_name(), convert_function_name(), convert_language_name(), convert_schema_name(), convert_server_name(), convert_tablespace_name(), convert_type_name(), crosstab(), crosstab_hash(), cursor_to_xml(), cursor_to_xmlschema(), daitch_mokotoff(), database_to_xml(), database_to_xml_and_xmlschema(), database_to_xmlschema(), datetime_to_char_body(), dblink_cancel_query(), dblink_close(), dblink_connect(), dblink_disconnect(), dblink_error_message(), dblink_exec(), dblink_fetch(), dblink_get_notify(), dblink_is_busy(), dblink_open(), dblink_record_internal(), dblink_send_query(), deserialize_deflist(), difference(), dmetaphone(), dmetaphone_alt(), do_to_timestamp(), errno_from_string(), ExecAlterExtensionStmt(), execute_extension_script(), executeDateTimeMethod(), get_raw_page_fork(), get_raw_page_fork_1_9(), has_param_priv_byname(), has_sequence_privilege_id_name(), has_sequence_privilege_name(), has_sequence_privilege_name_name(), injection_points_attach(), injection_points_attach_func(), injection_points_cached(), injection_points_detach(), injection_points_load(), injection_points_run(), injection_points_wakeup(), json_object_field(), json_object_field_text(), jsonb_set_lax(), JsonItemFromDatum(), ltree_addtext(), ltree_textadd(), NUM_cache(), parse_datetime(), parse_ident(), pg_backup_start(), pg_create_restore_point(), pg_crypt(), pg_current_logfile(), pg_get_expr_worker(), pg_get_logical_snapshot_info(), pg_get_logical_snapshot_meta(), pg_get_publication_sequences(), pg_get_serial_sequence(), pg_index_column_has_property(), pg_index_has_property(), pg_indexam_has_property(), pg_input_is_valid_common(), pg_logical_emit_message_bytea(), pg_ls_replslotdir(), pg_notify(), pg_prewarm(), pg_relation_size(), pg_replication_origin_advance(), pg_replication_origin_create(), pg_replication_origin_drop(), pg_replication_origin_oid(), pg_replication_origin_progress(), pg_replication_origin_session_setup(), pg_size_bytes(), pg_split_walfile_name(), pg_stat_get_progress_info(), pg_stat_get_replication_slot(), pg_stat_have_stats(), pg_stat_reset_replication_slot(), pg_stat_reset_shared(), pg_stat_reset_slru(), pgxml_texttoxmlchar(), phraseto_tsquery_byid(), plainto_tsquery_byid(), postgres_fdw_disconnect(), query_to_xml(), query_to_xml_and_xmlschema(), query_to_xmlschema(), quote_ident(), quote_ident_cstr(), range_constructor3(), regress_setenv(), replorigin_by_oid(), schema_to_xml(), schema_to_xml_and_xmlschema(), schema_to_xmlschema(), sepgsql_mcstrans_in(), sepgsql_mcstrans_out(), soundex(), table_to_xml(), table_to_xml_and_xmlschema(), table_to_xmlschema(), test_canonicalize_path(), test_custom_stats_var_create(), test_custom_stats_var_drop(), test_custom_stats_var_report(), test_custom_stats_var_update(), test_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 246 of file varlena.c.

247{
248 /* must cast away the const, unfortunately */
251
252 if (dst_len > 0)
253 {
254 dst_len--;
255 if (dst_len >= src_len)
257 else /* ensure truncation is encoding-safe */
260 dst[dst_len] = '\0';
261 }
262
263 if (srcunpacked != src)
265}

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

3679{
3680 ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
3682
3683 tstate.astate = NULL;
3685 tstate.tupstore = rsi->setResult;
3686 tstate.tupdesc = rsi->setDesc;
3687
3688 (void) split_text(fcinfo, &tstate);
3689
3690 return (Datum) 0;
3691}
void InitMaterializedSRF(FunctionCallInfo fcinfo, bits32 flags)
Definition funcapi.c:76
#define MAT_SRF_USE_EXPECTED_DESC
Definition funcapi.h:296
ArrayBuildState * astate
Definition varlena.c:108

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

3703{
3704 return text_to_table(fcinfo);
3705}
Datum text_to_table(PG_FUNCTION_ARGS)
Definition varlena.c:3678

References text_to_table().

◆ textcat()

Datum textcat ( PG_FUNCTION_ARGS  )

Definition at line 446 of file varlena.c.

447{
450
452}

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

◆ texteq()

Datum texteq ( PG_FUNCTION_ARGS  )

Definition at line 1426 of file varlena.c.

1427{
1430 bool result;
1431
1433
1435
1436 if (mylocale->deterministic)
1437 {
1440 Size len1,
1441 len2;
1442
1443 /*
1444 * Since we only care about equality or not-equality, we can avoid all
1445 * the expense of strcoll() here, and just do bitwise comparison. In
1446 * fact, we don't even have to do a bitwise comparison if we can show
1447 * the lengths of the strings are unequal; which might save us from
1448 * having to detoast one or both values.
1449 */
1450 len1 = toast_raw_datum_size(arg1);
1451 len2 = toast_raw_datum_size(arg2);
1452 if (len1 != len2)
1453 result = false;
1454 else
1455 {
1458
1460 len1 - VARHDRSZ) == 0);
1461
1464 }
1465 }
1466 else
1467 {
1470
1471 result = (text_cmp(arg1, arg2, collid) == 0);
1472
1475 }
1476
1477 PG_RETURN_BOOL(result);
1478}

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

2384{
2387 size_t len1 = VARSIZE_ANY_EXHDR(arg1);
2388 size_t len2 = strlen(NameStr(*arg2));
2390 bool result;
2391
2393
2394 if (collid == C_COLLATION_OID)
2395 result = (len1 == len2 &&
2396 memcmp(VARDATA_ANY(arg1), NameStr(*arg2), len1) == 0);
2397 else
2398 result = (varstr_cmp(VARDATA_ANY(arg1), len1,
2399 NameStr(*arg2), len2,
2400 collid) == 0);
2401
2403
2404 PG_RETURN_BOOL(result);
2405}

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

◆ textgename()

Datum textgename ( PG_FUNCTION_ARGS  )

Definition at line 2538 of file varlena.c.

2539{
2541}
Datum bttextnamecmp(PG_FUNCTION_ARGS)
Definition varlena.c:2474

References bttextnamecmp(), CmpCall, and PG_RETURN_BOOL.

◆ textgtname()

Datum textgtname ( PG_FUNCTION_ARGS  )

Definition at line 2532 of file varlena.c.

2533{
2535}

References bttextnamecmp(), CmpCall, and PG_RETURN_BOOL.

◆ textin()

Datum textin ( PG_FUNCTION_ARGS  )

Definition at line 276 of file varlena.c.

277{
278 char *inputText = PG_GETARG_CSTRING(0);
279
281}
#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 390 of file varlena.c.

391{
393
394 /* try to avoid decompressing argument */
396}
static int32 text_length(Datum str)
Definition varlena.c:408

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

◆ textlename()

Datum textlename ( PG_FUNCTION_ARGS  )

Definition at line 2526 of file varlena.c.

2527{
2529}

References bttextnamecmp(), CmpCall, and PG_RETURN_BOOL.

◆ textltname()

Datum textltname ( PG_FUNCTION_ARGS  )

Definition at line 2520 of file varlena.c.

2521{
2523}

References bttextnamecmp(), CmpCall, and PG_RETURN_BOOL.

◆ textne()

Datum textne ( PG_FUNCTION_ARGS  )

Definition at line 1481 of file varlena.c.

1482{
1485 bool result;
1486
1488
1490
1491 if (mylocale->deterministic)
1492 {
1495 Size len1,
1496 len2;
1497
1498 /* See comment in texteq() */
1499 len1 = toast_raw_datum_size(arg1);
1500 len2 = toast_raw_datum_size(arg2);
1501 if (len1 != len2)
1502 result = true;
1503 else
1504 {
1507
1509 len1 - VARHDRSZ) != 0);
1510
1513 }
1514 }
1515 else
1516 {
1519
1520 result = (text_cmp(arg1, arg2, collid) != 0);
1521
1524 }
1525
1526 PG_RETURN_BOOL(result);
1527}

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, text_cmp(), toast_raw_datum_size(), VARDATA_ANY(), and VARHDRSZ.

◆ textnename()

Datum textnename ( PG_FUNCTION_ARGS  )

Definition at line 2433 of file varlena.c.

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

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

◆ textoctetlen()

Datum textoctetlen ( PG_FUNCTION_ARGS  )

Definition at line 427 of file varlena.c.

428{
430
431 /* We need not detoast the input at all */
433}

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

◆ textout()

Datum textout ( PG_FUNCTION_ARGS  )

Definition at line 287 of file varlena.c.

288{
290
292}
#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(), plsample_func_handler(), and plsample_trigger_handler().

◆ textoverlay()

Datum textoverlay ( PG_FUNCTION_ARGS  )

Definition at line 831 of file varlena.c.

832{
835 int sp = PG_GETARG_INT32(2); /* substring start position */
836 int sl = PG_GETARG_INT32(3); /* substring length */
837
839}
static text * text_overlay(text *t1, text *t2, int sp, int sl)
Definition varlena.c:854

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

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

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

892{
895
897}
static int text_position(text *t1, text *t2, Oid collid)
Definition varlena.c:914

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

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

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

◆ textsend()

Datum textsend ( PG_FUNCTION_ARGS  )

Definition at line 316 of file varlena.c.

317{
318 text *t = PG_GETARG_TEXT_PP(0);
320
324}
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 2717 of file varlena.c.

2718{
2719 char *rawname;
2720 List *result = NIL;
2721 List *namelist;
2722 ListCell *l;
2723
2724 /* Convert to C string (handles possible detoasting). */
2725 /* Note we rely on being able to modify rawname below. */
2727
2729 ereport(ERROR,
2731 errmsg("invalid name syntax")));
2732
2733 if (namelist == NIL)
2734 ereport(ERROR,
2736 errmsg("invalid name syntax")));
2737
2738 foreach(l, namelist)
2739 {
2740 char *curname = (char *) lfirst(l);
2741
2742 result = lappend(result, makeString(pstrdup(curname)));
2743 }
2744
2745 pfree(rawname);
2747
2748 return result;
2749}
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:2775

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

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

◆ to_bin32()

Datum to_bin32 ( PG_FUNCTION_ARGS  )

Definition at line 4088 of file varlena.c.

4089{
4091
4093}
uint32_t uint32
Definition c.h:558
static text * convert_to_base(uint64 value, int base)
Definition varlena.c:4062

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

◆ to_bin64()

Datum to_bin64 ( PG_FUNCTION_ARGS  )

Definition at line 4095 of file varlena.c.

4096{
4098
4100}
#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 4126 of file varlena.c.

4127{
4129
4131}

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

4134{
4136
4138}

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

◆ to_oct32()

Datum to_oct32 ( PG_FUNCTION_ARGS  )

Definition at line 4107 of file varlena.c.

4108{
4110
4112}

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

◆ to_oct64()

Datum to_oct64 ( PG_FUNCTION_ARGS  )

Definition at line 4114 of file varlena.c.

4115{
4117
4119}

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

◆ unicode_assigned()

Datum unicode_assigned ( PG_FUNCTION_ARGS  )

Definition at line 5449 of file varlena.c.

5450{
5452 unsigned char *p;
5453 int size;
5454
5456 ereport(ERROR,
5457 (errmsg("Unicode categorization can only be performed if server encoding is UTF8")));
5458
5459 /* convert to char32_t */
5461 p = (unsigned char *) VARDATA_ANY(input);
5462 for (int i = 0; i < size; i++)
5463 {
5464 char32_t uchar = utf8_to_unicode(p);
5465 int category = unicode_category(uchar);
5466
5467 if (category == PG_U_UNASSIGNED)
5468 PG_RETURN_BOOL(false);
5469
5470 p += pg_utf_mblen(p);
5471 }
5472
5473 PG_RETURN_BOOL(true);
5474}
FILE * input
static char32_t utf8_to_unicode(const unsigned char *c)
Definition mbprint.c:53
#define pg_utf_mblen
Definition pg_wchar.h:633
pg_unicode_category unicode_category(char32_t code)
@ PG_U_UNASSIGNED

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

5544{
5548 int size;
5549 char32_t *input_chars;
5550 char32_t *output_chars;
5551 unsigned char *p;
5552 int i;
5553 UnicodeNormalizationQC quickcheck;
5554 int output_size;
5555 bool result;
5556
5558
5559 /* convert to char32_t */
5561 input_chars = palloc((size + 1) * sizeof(char32_t));
5562 p = (unsigned char *) VARDATA_ANY(input);
5563 for (i = 0; i < size; i++)
5564 {
5566 p += pg_utf_mblen(p);
5567 }
5568 input_chars[i] = (char32_t) '\0';
5569 Assert((char *) p == VARDATA_ANY(input) + VARSIZE_ANY_EXHDR(input));
5570
5571 /* quick check (see UAX #15) */
5573 if (quickcheck == UNICODE_NORM_QC_YES)
5574 PG_RETURN_BOOL(true);
5575 else if (quickcheck == UNICODE_NORM_QC_NO)
5576 PG_RETURN_BOOL(false);
5577
5578 /* normalize and compare with original */
5580
5581 output_size = 0;
5582 for (char32_t *wp = output_chars; *wp; wp++)
5583 output_size++;
5584
5585 result = (size == output_size) &&
5586 (memcmp(input_chars, output_chars, size * sizeof(char32_t)) == 0);
5587
5588 PG_RETURN_BOOL(result);
5589}
uint32_t char32_t
Definition c.h:1428
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:5388

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

◆ unicode_norm_form_from_string()

static UnicodeNormalizationForm unicode_norm_form_from_string ( const char formstr)
static

Definition at line 5388 of file varlena.c.

5389{
5391
5392 /*
5393 * Might as well check this while we're here.
5394 */
5396 ereport(ERROR,
5398 errmsg("Unicode normalization can only be performed if server encoding is UTF8")));
5399
5400 if (pg_strcasecmp(formstr, "NFC") == 0)
5401 form = UNICODE_NFC;
5402 else if (pg_strcasecmp(formstr, "NFD") == 0)
5403 form = UNICODE_NFD;
5404 else if (pg_strcasecmp(formstr, "NFKC") == 0)
5406 else if (pg_strcasecmp(formstr, "NFKD") == 0)
5408 else
5409 ereport(ERROR,
5411 errmsg("invalid normalization form: %s", formstr)));
5412
5413 return form;
5414}
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 5477 of file varlena.c.

5478{
5482 int size;
5483 char32_t *input_chars;
5484 char32_t *output_chars;
5485 unsigned char *p;
5486 text *result;
5487 int i;
5488
5490
5491 /* convert to char32_t */
5493 input_chars = palloc((size + 1) * sizeof(char32_t));
5494 p = (unsigned char *) VARDATA_ANY(input);
5495 for (i = 0; i < size; i++)
5496 {
5498 p += pg_utf_mblen(p);
5499 }
5500 input_chars[i] = (char32_t) '\0';
5501 Assert((char *) p == VARDATA_ANY(input) + VARSIZE_ANY_EXHDR(input));
5502
5503 /* action */
5505
5506 /* convert back to UTF-8 string */
5507 size = 0;
5508 for (char32_t *wp = output_chars; *wp; wp++)
5509 {
5510 unsigned char buf[4];
5511
5513 size += pg_utf_mblen(buf);
5514 }
5515
5516 result = palloc(size + VARHDRSZ);
5517 SET_VARSIZE(result, size + VARHDRSZ);
5518
5519 p = (unsigned char *) VARDATA_ANY(result);
5520 for (char32_t *wp = output_chars; *wp; wp++)
5521 {
5522 unicode_to_utf8(*wp, p);
5523 p += pg_utf_mblen(p);
5524 }
5525 Assert((char *) p == (char *) result + size + VARHDRSZ);
5526
5527 PG_RETURN_TEXT_P(result);
5528}
static unsigned char * unicode_to_utf8(char32_t c, unsigned char *utf8string)
Definition pg_wchar.h:575

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

◆ unicode_version()

Datum unicode_version ( PG_FUNCTION_ARGS  )

Definition at line 5425 of file varlena.c.

5426{
5428}
#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 5635 of file varlena.c.

5636{
5638 char *instr;
5639 int len;
5641 text *result;
5642 char16_t pair_first = 0;
5644
5645 instr = VARDATA_ANY(input_text);
5647
5649
5650 while (len > 0)
5651 {
5652 if (instr[0] == '\\')
5653 {
5654 if (len >= 2 &&
5655 instr[1] == '\\')
5656 {
5657 if (pair_first)
5658 goto invalid_pair;
5659 appendStringInfoChar(&str, '\\');
5660 instr += 2;
5661 len -= 2;
5662 }
5663 else if ((len >= 5 && isxdigits_n(instr + 1, 4)) ||
5664 (len >= 6 && instr[1] == 'u' && isxdigits_n(instr + 2, 4)))
5665 {
5666 char32_t unicode;
5667 int offset = instr[1] == 'u' ? 2 : 1;
5668
5669 unicode = hexval_n(instr + offset, 4);
5670
5672 ereport(ERROR,
5674 errmsg("invalid Unicode code point: %04X", unicode));
5675
5676 if (pair_first)
5677 {
5679 {
5681 pair_first = 0;
5682 }
5683 else
5684 goto invalid_pair;
5685 }
5687 goto invalid_pair;
5688
5691 else
5692 {
5693 pg_unicode_to_server(unicode, (unsigned char *) cbuf);
5695 }
5696
5697 instr += 4 + offset;
5698 len -= 4 + offset;
5699 }
5700 else if (len >= 8 && instr[1] == '+' && isxdigits_n(instr + 2, 6))
5701 {
5702 char32_t unicode;
5703
5704 unicode = hexval_n(instr + 2, 6);
5705
5707 ereport(ERROR,
5709 errmsg("invalid Unicode code point: %04X", unicode));
5710
5711 if (pair_first)
5712 {
5714 {
5716 pair_first = 0;
5717 }
5718 else
5719 goto invalid_pair;
5720 }
5722 goto invalid_pair;
5723
5726 else
5727 {
5728 pg_unicode_to_server(unicode, (unsigned char *) cbuf);
5730 }
5731
5732 instr += 8;
5733 len -= 8;
5734 }
5735 else if (len >= 10 && instr[1] == 'U' && isxdigits_n(instr + 2, 8))
5736 {
5737 char32_t unicode;
5738
5739 unicode = hexval_n(instr + 2, 8);
5740
5742 ereport(ERROR,
5744 errmsg("invalid Unicode code point: %04X", unicode));
5745
5746 if (pair_first)
5747 {
5749 {
5751 pair_first = 0;
5752 }
5753 else
5754 goto invalid_pair;
5755 }
5757 goto invalid_pair;
5758
5761 else
5762 {
5763 pg_unicode_to_server(unicode, (unsigned char *) cbuf);
5765 }
5766
5767 instr += 10;
5768 len -= 10;
5769 }
5770 else
5771 ereport(ERROR,
5773 errmsg("invalid Unicode escape"),
5774 errhint("Unicode escapes must be \\XXXX, \\+XXXXXX, \\uXXXX, or \\UXXXXXXXX.")));
5775 }
5776 else
5777 {
5778 if (pair_first)
5779 goto invalid_pair;
5780
5781 appendStringInfoChar(&str, *instr++);
5782 len--;
5783 }
5784 }
5785
5786 /* unfinished surrogate pair? */
5787 if (pair_first)
5788 goto invalid_pair;
5789
5790 result = cstring_to_text_with_len(str.data, str.len);
5791 pfree(str.data);
5792
5793 PG_RETURN_TEXT_P(result);
5794
5796 ereport(ERROR,
5798 errmsg("invalid Unicode surrogate pair")));
5799 PG_RETURN_NULL(); /* keep compiler quiet */
5800}
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:525
static bool is_utf16_surrogate_second(char32_t c)
Definition pg_wchar.h:531
static char32_t surrogate_pair_to_codepoint(char16_t first, char16_t second)
Definition pg_wchar.h:537
#define MAX_UNICODE_EQUIVALENT_STRING
Definition pg_wchar.h:329
static bool is_valid_unicode_codepoint(char32_t c)
Definition pg_wchar.h:519
static unsigned int hexval_n(const char *instr, size_t n)
Definition varlena.c:5621
static bool isxdigits_n(const char *instr, size_t n)
Definition varlena.c:5595

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(), str, surrogate_pair_to_codepoint(), VARDATA_ANY(), and VARSIZE_ANY_EXHDR().

◆ unknownin()

Datum unknownin ( PG_FUNCTION_ARGS  )

Definition at line 331 of file varlena.c.

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

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

◆ unknownout()

Datum unknownout ( PG_FUNCTION_ARGS  )

Definition at line 343 of file varlena.c.

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

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

◆ unknownrecv()

Datum unknownrecv ( PG_FUNCTION_ARGS  )

Definition at line 355 of file varlena.c.

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

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

◆ unknownsend()

Datum unknownsend ( PG_FUNCTION_ARGS  )

Definition at line 370 of file varlena.c.

371{
372 /* representation is same as cstring */
373 char *str = PG_GETARG_CSTRING(0);
375
379}

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

5341{
5342 int dist;
5343
5344 Assert(state);
5345
5346 if (state->source == NULL || state->source[0] == '\0' ||
5347 candidate == NULL || candidate[0] == '\0')
5348 return;
5349
5350 /*
5351 * To avoid ERROR-ing, we check the lengths here instead of setting
5352 * 'trusted' to false in the call to varstr_levenshtein_less_equal().
5353 */
5354 if (strlen(state->source) > MAX_LEVENSHTEIN_STRLEN ||
5356 return;
5357
5359 candidate, strlen(candidate), 1, 1, 1,
5360 state->max_d, true);
5361 if (dist <= state->max_d &&
5362 dist <= strlen(state->source) / 2 &&
5363 (state->min_d == -1 || dist < state->min_d))
5364 {
5365 state->min_d = dist;
5366 state->match = candidate;
5367 }
5368}
#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 1887 of file varlena.c.

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

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

Referenced by varstr_sortsupport().

◆ varstr_abbrev_abort()

static bool varstr_abbrev_abort ( int  memtupcount,
SortSupport  ssup 
)
static

Definition at line 2199 of file varlena.c.

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

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

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

References addHyperLogLog(), bpchartruelen(), DatumBigEndianToNative, DatumGetUInt32(), DatumGetUInt64(), DatumGetVarStringPP, fb(), hash(), hash_any(), hash_uint32(), len, Max, MaxAllocSize, 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 1353 of file varlena.c.

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

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

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

◆ varstr_sortsupport()

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

Definition at line 1669 of file varlena.c.

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

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

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

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

Referenced by varstr_sortsupport().

◆ varstrfastcmp_locale()

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

Definition at line 1932 of file varlena.c.

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

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

Referenced by namefastcmp_locale(), and varlenafastcmp_locale().