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

5376{
5377 Assert(state);
5378
5379 return state->match;
5380}
#define Assert(condition)
Definition c.h:885

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 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
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 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
int errcode(int sqlerrcode)
Definition elog.c:874
int errmsg(const char *fmt,...)
Definition elog.c:1093
#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
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:718
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:3109
static int check_replace_text_has_escape(const text *replace_text)
Definition varlena.c:3200
text * cstring_to_text_with_len(const char *s, int len)
Definition varlena.c:194
static void appendStringInfoRegexpSubstr(StringInfo str, text *replace_text, regmatch_t *pmatch, char *start_ptr, int data_pos)
Definition varlena.c:3233
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(), 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 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 
)
extern

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

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}
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 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
char * text_to_cstring(const text *t)
Definition varlena.c:215

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

◆ varstr_cmp()

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

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}
#define Min(x, y)
Definition c.h:1019
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:1324

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:5284
#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 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().