PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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 chargetClosestMatch (ClosestMatchState *state)
 

Typedef Documentation

◆ ClosestMatchState

Function Documentation

◆ getClosestMatch()

const char * getClosestMatch ( ClosestMatchState state)
extern

Definition at line 5377 of file varlena.c.

5378{
5379 Assert(state);
5380
5381 return state->match;
5382}
#define Assert(condition)
Definition c.h:945

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 
)
extern

Definition at line 5322 of file varlena.c.

5323{
5324 Assert(state);
5325 Assert(max_d >= 0);
5326
5327 state->source = source;
5328 state->min_d = -1;
5329 state->max_d = max_d;
5330 state->match = NULL;
5331}
static rewind_source * source
Definition pg_rewind.c:89
static int fb(int x)

References Assert, fb(), 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 
)
extern

Definition at line 3335 of file varlena.c.

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

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

◆ SplitDirectoriesString()

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

Definition at line 2904 of file varlena.c.

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

Definition at line 3025 of file varlena.c.

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

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 
)
extern

Definition at line 2777 of file varlena.c.

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

◆ textToQualifiedNameList()

List * textToQualifiedNameList ( text textval)
extern

Definition at line 2719 of file varlena.c.

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

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

◆ updateClosestMatch()

void updateClosestMatch ( ClosestMatchState state,
const char candidate 
)
extern

Definition at line 5342 of file varlena.c.

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

◆ varstr_cmp()

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

Definition at line 1355 of file varlena.c.

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

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_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 
)
extern

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

References ereport, errcode(), errmsg, ERROR, fb(), i, j, MAX_LEVENSHTEIN_STRLEN, Min, palloc(), pg_mblen_range(), pg_mbstrlen_with_len(), rest_of_char_same(), send, 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 
)
extern

◆ varstr_sortsupport()

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

Definition at line 1671 of file varlena.c.

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

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

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