PostgreSQL Source Code git master
varlena.h File Reference
#include "nodes/pg_list.h"
#include "utils/sortsupport.h"
Include dependency graph for varlena.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  ClosestMatchState
 

Typedefs

typedef struct ClosestMatchState ClosestMatchState
 

Functions

int varstr_cmp (const char *arg1, int len1, const char *arg2, int len2, Oid collid)
 
void varstr_sortsupport (SortSupport ssup, Oid typid, Oid collid)
 
int varstr_levenshtein (const char *source, int slen, const char *target, int tlen, int ins_c, int del_c, int sub_c, bool trusted)
 
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)
 
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)
 
textreplace_text_regexp (text *src_text, text *pattern_text, text *replace_text, int cflags, Oid collation, int search_start, int n)
 
void initClosestMatch (ClosestMatchState *state, const char *source, int max_d)
 
void updateClosestMatch (ClosestMatchState *state, const char *candidate)
 
const char * getClosestMatch (ClosestMatchState *state)
 

Typedef Documentation

◆ ClosestMatchState

Function Documentation

◆ getClosestMatch()

const char * getClosestMatch ( ClosestMatchState state)

Definition at line 5350 of file varlena.c.

5351{
5352 Assert(state);
5353
5354 return state->match;
5355}
Assert(PointerIsAligned(start, uint64))
Definition: regguts.h:323

References Assert().

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

◆ initClosestMatch()

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

Definition at line 5295 of file varlena.c.

5296{
5297 Assert(state);
5298 Assert(max_d >= 0);
5299
5300 state->source = source;
5301 state->min_d = -1;
5302 state->max_d = max_d;
5303 state->match = NULL;
5304}
static rewind_source * source
Definition: pg_rewind.c:89

References Assert(), and source.

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

◆ replace_text_regexp()

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

Definition at line 3313 of file varlena.c.

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

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

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

◆ SplitDirectoriesString()

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

Definition at line 2882 of file varlena.c.

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

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

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

◆ SplitGUCList()

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

Definition at line 3003 of file varlena.c.

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

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

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

◆ SplitIdentifierString()

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

Definition at line 2755 of file varlena.c.

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

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

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

◆ textToQualifiedNameList()

List * textToQualifiedNameList ( text textval)

Definition at line 2697 of file varlena.c.

2698{
2699 char *rawname;
2700 List *result = NIL;
2701 List *namelist;
2702 ListCell *l;
2703
2704 /* Convert to C string (handles possible detoasting). */
2705 /* Note we rely on being able to modify rawname below. */
2706 rawname = text_to_cstring(textval);
2707
2708 if (!SplitIdentifierString(rawname, '.', &namelist))
2709 ereport(ERROR,
2710 (errcode(ERRCODE_INVALID_NAME),
2711 errmsg("invalid name syntax")));
2712
2713 if (namelist == NIL)
2714 ereport(ERROR,
2715 (errcode(ERRCODE_INVALID_NAME),
2716 errmsg("invalid name syntax")));
2717
2718 foreach(l, namelist)
2719 {
2720 char *curname = (char *) lfirst(l);
2721
2722 result = lappend(result, makeString(pstrdup(curname)));
2723 }
2724
2725 pfree(rawname);
2726 list_free(namelist);
2727
2728 return result;
2729}
void list_free(List *list)
Definition: list.c:1546
#define lfirst(lc)
Definition: pg_list.h:172
Definition: pg_list.h:54
String * makeString(char *str)
Definition: value.c:63
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:2755
char * text_to_cstring(const text *t)
Definition: varlena.c:214

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

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

◆ updateClosestMatch()

void updateClosestMatch ( ClosestMatchState state,
const char *  candidate 
)

Definition at line 5315 of file varlena.c.

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

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

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

◆ varstr_cmp()

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

Definition at line 1308 of file varlena.c.

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

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

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

◆ varstr_levenshtein()

int varstr_levenshtein ( const char *  source,
int  slen,
const char *  target,
int  tlen,
int  ins_c,
int  del_c,
int  sub_c,
bool  trusted 
)

Definition at line 73 of file levenshtein.c.

78{
79 int m,
80 n;
81 int *prev;
82 int *curr;
83 int *s_char_len = NULL;
84 int j;
85 const char *y;
86
87 /*
88 * For varstr_levenshtein_less_equal, we have real variables called
89 * start_column and stop_column; otherwise it's just short-hand for 0 and
90 * m.
91 */
92#ifdef LEVENSHTEIN_LESS_EQUAL
93 int start_column,
94 stop_column;
95
96#undef START_COLUMN
97#undef STOP_COLUMN
98#define START_COLUMN start_column
99#define STOP_COLUMN stop_column
100#else
101#undef START_COLUMN
102#undef STOP_COLUMN
103#define START_COLUMN 0
104#define STOP_COLUMN m
105#endif
106
107 /* Convert string lengths (in bytes) to lengths in characters */
108 m = pg_mbstrlen_with_len(source, slen);
109 n = pg_mbstrlen_with_len(target, tlen);
110
111 /*
112 * We can transform an empty s into t with n insertions, or a non-empty t
113 * into an empty s with m deletions.
114 */
115 if (!m)
116 return n * ins_c;
117 if (!n)
118 return m * del_c;
119
120 /*
121 * For security concerns, restrict excessive CPU+RAM usage. (This
122 * implementation uses O(m) memory and has O(mn) complexity.) If
123 * "trusted" is true, caller is responsible for not making excessive
124 * requests, typically by using a small max_d along with strings that are
125 * bounded, though not necessarily to MAX_LEVENSHTEIN_STRLEN exactly.
126 */
127 if (!trusted &&
131 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
132 errmsg("levenshtein argument exceeds maximum length of %d characters",
134
135#ifdef LEVENSHTEIN_LESS_EQUAL
136 /* Initialize start and stop columns. */
137 start_column = 0;
138 stop_column = m + 1;
139
140 /*
141 * If max_d >= 0, determine whether the bound is impossibly tight. If so,
142 * return max_d + 1 immediately. Otherwise, determine whether it's tight
143 * enough to limit the computation we must perform. If so, figure out
144 * initial stop column.
145 */
146 if (max_d >= 0)
147 {
148 int min_theo_d; /* Theoretical minimum distance. */
149 int max_theo_d; /* Theoretical maximum distance. */
150 int net_inserts = n - m;
151
152 min_theo_d = net_inserts < 0 ?
153 -net_inserts * del_c : net_inserts * ins_c;
154 if (min_theo_d > max_d)
155 return max_d + 1;
156 if (ins_c + del_c < sub_c)
157 sub_c = ins_c + del_c;
158 max_theo_d = min_theo_d + sub_c * Min(m, n);
159 if (max_d >= max_theo_d)
160 max_d = -1;
161 else if (ins_c + del_c > 0)
162 {
163 /*
164 * Figure out how much of the first row of the notional matrix we
165 * need to fill in. If the string is growing, the theoretical
166 * minimum distance already incorporates the cost of deleting the
167 * number of characters necessary to make the two strings equal in
168 * length. Each additional deletion forces another insertion, so
169 * the best-case total cost increases by ins_c + del_c. If the
170 * string is shrinking, the minimum theoretical cost assumes no
171 * excess deletions; that is, we're starting no further right than
172 * column n - m. If we do start further right, the best-case
173 * total cost increases by ins_c + del_c for each move right.
174 */
175 int slack_d = max_d - min_theo_d;
176 int best_column = net_inserts < 0 ? -net_inserts : 0;
177
178 stop_column = best_column + (slack_d / (ins_c + del_c)) + 1;
179 if (stop_column > m)
180 stop_column = m + 1;
181 }
182 }
183#endif
184
185 /*
186 * In order to avoid calling pg_mblen() repeatedly on each character in s,
187 * we cache all the lengths before starting the main loop -- but if all
188 * the characters in both strings are single byte, then we skip this and
189 * use a fast-path in the main loop. If only one string contains
190 * multi-byte characters, we still build the array, so that the fast-path
191 * needn't deal with the case where the array hasn't been initialized.
192 */
193 if (m != slen || n != tlen)
194 {
195 int i;
196 const char *cp = source;
197
198 s_char_len = (int *) palloc((m + 1) * sizeof(int));
199 for (i = 0; i < m; ++i)
200 {
201 s_char_len[i] = pg_mblen(cp);
202 cp += s_char_len[i];
203 }
204 s_char_len[i] = 0;
205 }
206
207 /* One more cell for initialization column and row. */
208 ++m;
209 ++n;
210
211 /* Previous and current rows of notional array. */
212 prev = (int *) palloc(2 * m * sizeof(int));
213 curr = prev + m;
214
215 /*
216 * To transform the first i characters of s into the first 0 characters of
217 * t, we must perform i deletions.
218 */
219 for (int i = START_COLUMN; i < STOP_COLUMN; i++)
220 prev[i] = i * del_c;
221
222 /* Loop through rows of the notional array */
223 for (y = target, j = 1; j < n; j++)
224 {
225 int *temp;
226 const char *x = source;
227 int y_char_len = n != tlen + 1 ? pg_mblen(y) : 1;
228 int i;
229
230#ifdef LEVENSHTEIN_LESS_EQUAL
231
232 /*
233 * In the best case, values percolate down the diagonal unchanged, so
234 * we must increment stop_column unless it's already on the right end
235 * of the array. The inner loop will read prev[stop_column], so we
236 * have to initialize it even though it shouldn't affect the result.
237 */
238 if (stop_column < m)
239 {
240 prev[stop_column] = max_d + 1;
241 ++stop_column;
242 }
243
244 /*
245 * The main loop fills in curr, but curr[0] needs a special case: to
246 * transform the first 0 characters of s into the first j characters
247 * of t, we must perform j insertions. However, if start_column > 0,
248 * this special case does not apply.
249 */
250 if (start_column == 0)
251 {
252 curr[0] = j * ins_c;
253 i = 1;
254 }
255 else
256 i = start_column;
257#else
258 curr[0] = j * ins_c;
259 i = 1;
260#endif
261
262 /*
263 * This inner loop is critical to performance, so we include a
264 * fast-path to handle the (fairly common) case where no multibyte
265 * characters are in the mix. The fast-path is entitled to assume
266 * that if s_char_len is not initialized then BOTH strings contain
267 * only single-byte characters.
268 */
269 if (s_char_len != NULL)
270 {
271 for (; i < STOP_COLUMN; i++)
272 {
273 int ins;
274 int del;
275 int sub;
276 int x_char_len = s_char_len[i - 1];
277
278 /*
279 * Calculate costs for insertion, deletion, and substitution.
280 *
281 * When calculating cost for substitution, we compare the last
282 * character of each possibly-multibyte character first,
283 * because that's enough to rule out most mis-matches. If we
284 * get past that test, then we compare the lengths and the
285 * remaining bytes.
286 */
287 ins = prev[i] + ins_c;
288 del = curr[i - 1] + del_c;
289 if (x[x_char_len - 1] == y[y_char_len - 1]
290 && x_char_len == y_char_len &&
291 (x_char_len == 1 || rest_of_char_same(x, y, x_char_len)))
292 sub = prev[i - 1];
293 else
294 sub = prev[i - 1] + sub_c;
295
296 /* Take the one with minimum cost. */
297 curr[i] = Min(ins, del);
298 curr[i] = Min(curr[i], sub);
299
300 /* Point to next character. */
301 x += x_char_len;
302 }
303 }
304 else
305 {
306 for (; i < STOP_COLUMN; i++)
307 {
308 int ins;
309 int del;
310 int sub;
311
312 /* Calculate costs for insertion, deletion, and substitution. */
313 ins = prev[i] + ins_c;
314 del = curr[i - 1] + del_c;
315 sub = prev[i - 1] + ((*x == *y) ? 0 : sub_c);
316
317 /* Take the one with minimum cost. */
318 curr[i] = Min(ins, del);
319 curr[i] = Min(curr[i], sub);
320
321 /* Point to next character. */
322 x++;
323 }
324 }
325
326 /* Swap current row with previous row. */
327 temp = curr;
328 curr = prev;
329 prev = temp;
330
331 /* Point to next character. */
332 y += y_char_len;
333
334#ifdef LEVENSHTEIN_LESS_EQUAL
335
336 /*
337 * This chunk of code represents a significant performance hit if used
338 * in the case where there is no max_d bound. This is probably not
339 * because the max_d >= 0 test itself is expensive, but rather because
340 * the possibility of needing to execute this code prevents tight
341 * optimization of the loop as a whole.
342 */
343 if (max_d >= 0)
344 {
345 /*
346 * The "zero point" is the column of the current row where the
347 * remaining portions of the strings are of equal length. There
348 * are (n - 1) characters in the target string, of which j have
349 * been transformed. There are (m - 1) characters in the source
350 * string, so we want to find the value for zp where (n - 1) - j =
351 * (m - 1) - zp.
352 */
353 int zp = j - (n - m);
354
355 /* Check whether the stop column can slide left. */
356 while (stop_column > 0)
357 {
358 int ii = stop_column - 1;
359 int net_inserts = ii - zp;
360
361 if (prev[ii] + (net_inserts > 0 ? net_inserts * ins_c :
362 -net_inserts * del_c) <= max_d)
363 break;
364 stop_column--;
365 }
366
367 /* Check whether the start column can slide right. */
368 while (start_column < stop_column)
369 {
370 int net_inserts = start_column - zp;
371
372 if (prev[start_column] +
373 (net_inserts > 0 ? net_inserts * ins_c :
374 -net_inserts * del_c) <= max_d)
375 break;
376
377 /*
378 * We'll never again update these values, so we must make sure
379 * there's nothing here that could confuse any future
380 * iteration of the outer loop.
381 */
382 prev[start_column] = max_d + 1;
383 curr[start_column] = max_d + 1;
384 if (start_column != 0)
385 source += (s_char_len != NULL) ? s_char_len[start_column - 1] : 1;
386 start_column++;
387 }
388
389 /* If they cross, we're going to exceed the bound. */
390 if (start_column >= stop_column)
391 return max_d + 1;
392 }
393#endif
394 }
395
396 /*
397 * Because the final value was swapped from the previous row to the
398 * current row, that's where we'll find it.
399 */
400 return prev[m - 1];
401}
int y
Definition: isn.c:76
int x
Definition: isn.c:75
int j
Definition: isn.c:78
int i
Definition: isn.c:77
#define START_COLUMN
#define STOP_COLUMN
int pg_mbstrlen_with_len(const char *mbstr, int limit)
Definition: mbutils.c:1060
int pg_mblen(const char *mbstr)
Definition: mbutils.c:1026
static bool rest_of_char_same(const char *s1, const char *s2, int len)
Definition: varlena.c:5259

References ereport, errcode(), errmsg(), ERROR, i, j, MAX_LEVENSHTEIN_STRLEN, Min, palloc(), pg_mblen(), pg_mbstrlen_with_len(), rest_of_char_same(), source, START_COLUMN, STOP_COLUMN, x, and y.

Referenced by levenshtein(), and levenshtein_with_costs().

◆ varstr_levenshtein_less_equal()

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 
)

◆ varstr_sortsupport()

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

Definition at line 1626 of file varlena.c.

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

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

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