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

5387{
5388 Assert(state);
5389
5390 return state->match;
5391}
#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 5331 of file varlena.c.

5332{
5333 Assert(state);
5334 Assert(max_d >= 0);
5335
5336 state->source = source;
5337 state->min_d = -1;
5338 state->max_d = max_d;
5339 state->match = NULL;
5340}
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 3344 of file varlena.c.

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

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

2803{
2804 char *token;
2805
2806 if (**nextp == '"')
2808
2809 /* Unquoted identifier --- extends to separator or whitespace */
2810 token = *nextp;
2811
2812 while (**nextp && **nextp != separator && !scanner_isspace(**nextp))
2813 (*nextp)++;
2814
2815 if (*nextp == token)
2816 return NULL; /* empty token */
2817
2818 *endp = *nextp;
2819
2821 {
2822 /*
2823 * Downcase the identifier, using same code as main lexer does.
2824 *
2825 * XXX because we want to overwrite the input in-place, we cannot
2826 * support a downcasing transformation that increases the string
2827 * length. This is not a problem given the current implementation of
2828 * downcase_truncate_identifier, but we'll probably have to do
2829 * something about this someday.
2830 */
2831 int len = *endp - token;
2833
2835 strncpy(token, downname, len); /* strncpy is required here */
2836 pfree(downname);
2837 }
2838
2839 return token;
2840}
#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:2767

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

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

References fb(), and token.

Referenced by scan_identifier(), and SplitDirectoriesString().

◆ SplitDirectoriesString()

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

Definition at line 2950 of file varlena.c.

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

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

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

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

2869{
2870 char *nextp = rawstring;
2871 bool done = false;
2872
2873 *namelist = NIL;
2874
2875 while (scanner_isspace(*nextp))
2876 nextp++; /* skip leading whitespace */
2877
2878 if (*nextp == '\0')
2879 return true; /* empty string represents empty list */
2880
2881 /* At the top of the loop, we are at start of a new identifier. */
2882 do
2883 {
2884 char *curname;
2885 char *endp;
2886
2888 if (curname == NULL)
2889 return false; /* mismatched quotes or empty name */
2890
2891 while (scanner_isspace(*nextp))
2892 nextp++; /* skip trailing whitespace */
2893
2894 if (*nextp == separator)
2895 {
2896 nextp++;
2897 while (scanner_isspace(*nextp))
2898 nextp++; /* skip leading whitespace for next */
2899 /* we expect another name, so done remains false */
2900 }
2901 else if (*nextp == '\0')
2902 done = true;
2903 else
2904 return false; /* invalid syntax */
2905
2906 /* Now safe to overwrite separator with a null */
2907 *endp = '\0';
2908
2909 /* Truncate name if it's overlength */
2911
2912 /*
2913 * Finished isolating current name --- add it to list
2914 */
2916
2917 /* Loop back if we didn't reach end of string */
2918 } while (!done);
2919
2920 return true;
2921}
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 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. */
2728 rawname = text_to_cstring(textval);
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
2745 }
2746
2747 pfree(rawname);
2749
2750 return result;
2751}
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:2867
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 5351 of file varlena.c.

5352{
5353 int dist;
5354
5355 Assert(state);
5356
5357 if (state->source == NULL || state->source[0] == '\0' ||
5358 candidate == NULL || candidate[0] == '\0')
5359 return;
5360
5361 /*
5362 * To avoid ERROR-ing, we check the lengths here instead of setting
5363 * 'trusted' to false in the call to varstr_levenshtein_less_equal().
5364 */
5365 if (strlen(state->source) > MAX_LEVENSHTEIN_STRLEN ||
5367 return;
5368
5370 candidate, strlen(candidate), 1, 1, 1,
5371 state->max_d, true);
5372 if (dist <= state->max_d &&
5373 dist <= strlen(state->source) / 2 &&
5374 (state->min_d == -1 || dist < state->min_d))
5375 {
5376 state->min_d = dist;
5377 state->match = candidate;
5378 }
5379}
#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: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:5295
#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:3447
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().