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)
 
charscan_quoted_identifier (char **endp, char **nextp)
 
charscan_identifier (char **endp, char **nextp, char separator, bool downcase_unquoted)
 
bool SplitIdentifierString (char *rawstring, char separator, List **namelist)
 
bool SplitDirectoriesString (char *rawstring, char separator, List **namelist)
 
bool SplitGUCList (char *rawstring, char separator, List **namelist)
 
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 5389 of file varlena.c.

5390{
5391 Assert(state);
5392
5393 return state->match;
5394}
#define Assert(condition)
Definition c.h:943

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

5335{
5336 Assert(state);
5337 Assert(max_d >= 0);
5338
5339 state->source = source;
5340 state->min_d = -1;
5341 state->max_d = max_d;
5342 state->match = NULL;
5343}
static rewind_source * source
Definition pg_rewind.c:89
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 3347 of file varlena.c.

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

References appendBinaryStringInfo(), 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().

◆ scan_identifier()

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

Definition at line 2805 of file varlena.c.

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

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

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

◆ scan_quoted_identifier()

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

Definition at line 2770 of file varlena.c.

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

References fb(), and token.

Referenced by scan_identifier(), and SplitDirectoriesString().

◆ SplitDirectoriesString()

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

Definition at line 2953 of file varlena.c.

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

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

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

◆ SplitGUCList()

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

Definition at line 3063 of file varlena.c.

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

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

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

◆ SplitIdentifierString()

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

Definition at line 2870 of file varlena.c.

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

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

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

◆ textToQualifiedNameList()

List * textToQualifiedNameList ( text textval)
extern

Definition at line 2722 of file varlena.c.

2723{
2724 char *rawname;
2725 List *result = NIL;
2726 List *namelist;
2727 ListCell *l;
2728
2729 /* Convert to C string (handles possible detoasting). */
2730 /* Note we rely on being able to modify rawname below. */
2731 rawname = text_to_cstring(textval);
2732
2734 ereport(ERROR,
2736 errmsg("invalid name syntax")));
2737
2738 if (namelist == NIL)
2739 ereport(ERROR,
2741 errmsg("invalid name syntax")));
2742
2743 foreach(l, namelist)
2744 {
2745 char *curname = (char *) lfirst(l);
2746
2748 }
2749
2750 pfree(rawname);
2752
2753 return result;
2754}
uint32 result
void list_free(List *list)
Definition list.c:1546
#define lfirst(lc)
Definition pg_list.h:172
Definition pg_list.h:54
String * makeString(char *str)
Definition value.c:63
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition varlena.c:2870
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(), result, SplitIdentifierString(), and text_to_cstring().

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

◆ updateClosestMatch()

void updateClosestMatch ( ClosestMatchState state,
const char candidate 
)
extern

Definition at line 5354 of file varlena.c.

5355{
5356 int dist;
5357
5358 Assert(state);
5359
5360 if (state->source == NULL || state->source[0] == '\0' ||
5361 candidate == NULL || candidate[0] == '\0')
5362 return;
5363
5364 /*
5365 * To avoid ERROR-ing, we check the lengths here instead of setting
5366 * 'trusted' to false in the call to varstr_levenshtein_less_equal().
5367 */
5368 if (strlen(state->source) > MAX_LEVENSHTEIN_STRLEN ||
5370 return;
5371
5373 candidate, strlen(candidate), 1, 1, 1,
5374 state->max_d, true);
5375 if (dist <= state->max_d &&
5376 dist <= strlen(state->source) / 2 &&
5377 (state->min_d == -1 || dist < state->min_d))
5378 {
5379 state->min_d = dist;
5380 state->match = candidate;
5381 }
5382}
#define MAX_LEVENSHTEIN_STRLEN
Definition levenshtein.c:26
int varstr_levenshtein_less_equal(const char *source, int slen, const char *target, int tlen, int ins_c, int del_c, int sub_c, int max_d, bool trusted)

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

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

◆ 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:1091
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(), pg_strncoll(), and result.

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

◆ varstr_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:1186
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:5298
#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 1672 of file varlena.c.

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

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

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