PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
varlena.h File Reference
#include "nodes/pg_list.h"
#include "utils/sortsupport.h"
Include dependency graph for varlena.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  ClosestMatchState
 

Typedefs

typedef struct ClosestMatchState ClosestMatchState
 

Functions

int varstr_cmp (const char *arg1, int len1, const char *arg2, int len2, Oid collid)
 
void varstr_sortsupport (SortSupport ssup, Oid typid, Oid collid)
 
int varstr_levenshtein (const char *source, int slen, const char *target, int tlen, int ins_c, int del_c, int sub_c, bool trusted)
 
int varstr_levenshtein_less_equal (const char *source, int slen, const char *target, int tlen, int ins_c, int del_c, int sub_c, int max_d, bool trusted)
 
ListtextToQualifiedNameList (text *textval)
 
bool SplitIdentifierString (char *rawstring, char separator, List **namelist)
 
bool SplitDirectoriesString (char *rawstring, char separator, List **namelist)
 
bool SplitGUCList (char *rawstring, char separator, List **namelist)
 
textreplace_text_regexp (text *src_text, text *pattern_text, text *replace_text, int cflags, Oid collation, int search_start, int n)
 
void initClosestMatch (ClosestMatchState *state, const char *source, int max_d)
 
void updateClosestMatch (ClosestMatchState *state, const char *candidate)
 
const char * getClosestMatch (ClosestMatchState *state)
 

Typedef Documentation

◆ ClosestMatchState

Function Documentation

◆ getClosestMatch()

const char * getClosestMatch ( ClosestMatchState state)

Definition at line 6445 of file varlena.c.

6446{
6447 Assert(state);
6448
6449 return state->match;
6450}
Assert(PointerIsAligned(start, uint64))
Definition: regguts.h:323

References Assert().

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

◆ initClosestMatch()

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

Definition at line 6390 of file varlena.c.

6391{
6392 Assert(state);
6393 Assert(max_d >= 0);
6394
6395 state->source = source;
6396 state->min_d = -1;
6397 state->max_d = max_d;
6398 state->match = NULL;
6399}
static rewind_source * source
Definition: pg_rewind.c:89

References Assert(), and source.

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

◆ replace_text_regexp()

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

Definition at line 4408 of file varlena.c.

4412{
4413 text *ret_text;
4414 regex_t *re;
4415 int src_text_len = VARSIZE_ANY_EXHDR(src_text);
4416 int nmatches = 0;
4418 regmatch_t pmatch[10]; /* main match, plus \1 to \9 */
4419 int nmatch = lengthof(pmatch);
4420 pg_wchar *data;
4421 size_t data_len;
4422 int data_pos;
4423 char *start_ptr;
4424 int escape_status;
4425
4427
4428 /* Convert data string to wide characters. */
4429 data = (pg_wchar *) palloc((src_text_len + 1) * sizeof(pg_wchar));
4430 data_len = pg_mb2wchar_with_len(VARDATA_ANY(src_text), data, src_text_len);
4431
4432 /* Check whether replace_text has escapes, especially regexp submatches. */
4434
4435 /* If no regexp submatches, we can use REG_NOSUB. */
4436 if (escape_status < 2)
4437 {
4438 cflags |= REG_NOSUB;
4439 /* Also tell pg_regexec we only want the whole-match location. */
4440 nmatch = 1;
4441 }
4442
4443 /* Prepare the regexp. */
4444 re = RE_compile_and_cache(pattern_text, cflags, collation);
4445
4446 /* start_ptr points to the data_pos'th character of src_text */
4447 start_ptr = (char *) VARDATA_ANY(src_text);
4448 data_pos = 0;
4449
4450 while (search_start <= data_len)
4451 {
4452 int regexec_result;
4453
4455
4456 regexec_result = pg_regexec(re,
4457 data,
4458 data_len,
4459 search_start,
4460 NULL, /* no details */
4461 nmatch,
4462 pmatch,
4463 0);
4464
4465 if (regexec_result == REG_NOMATCH)
4466 break;
4467
4468 if (regexec_result != REG_OKAY)
4469 {
4470 char errMsg[100];
4471
4472 pg_regerror(regexec_result, re, errMsg, sizeof(errMsg));
4473 ereport(ERROR,
4474 (errcode(ERRCODE_INVALID_REGULAR_EXPRESSION),
4475 errmsg("regular expression failed: %s", errMsg)));
4476 }
4477
4478 /*
4479 * Count matches, and decide whether to replace this match.
4480 */
4481 nmatches++;
4482 if (n > 0 && nmatches != n)
4483 {
4484 /*
4485 * No, so advance search_start, but not start_ptr/data_pos. (Thus,
4486 * we treat the matched text as if it weren't matched, and copy it
4487 * to the output later.)
4488 */
4489 search_start = pmatch[0].rm_eo;
4490 if (pmatch[0].rm_so == pmatch[0].rm_eo)
4491 search_start++;
4492 continue;
4493 }
4494
4495 /*
4496 * Copy the text to the left of the match position. Note we are given
4497 * character not byte indexes.
4498 */
4499 if (pmatch[0].rm_so - data_pos > 0)
4500 {
4501 int chunk_len;
4502
4503 chunk_len = charlen_to_bytelen(start_ptr,
4504 pmatch[0].rm_so - data_pos);
4505 appendBinaryStringInfo(&buf, start_ptr, chunk_len);
4506
4507 /*
4508 * Advance start_ptr over that text, to avoid multiple rescans of
4509 * it if the replace_text contains multiple back-references.
4510 */
4511 start_ptr += chunk_len;
4512 data_pos = pmatch[0].rm_so;
4513 }
4514
4515 /*
4516 * Copy the replace_text, processing escapes if any are present.
4517 */
4518 if (escape_status > 0)
4520 start_ptr, data_pos);
4521 else
4523
4524 /* Advance start_ptr and data_pos over the matched text. */
4525 start_ptr += charlen_to_bytelen(start_ptr,
4526 pmatch[0].rm_eo - data_pos);
4527 data_pos = pmatch[0].rm_eo;
4528
4529 /*
4530 * If we only want to replace one occurrence, we're done.
4531 */
4532 if (n > 0)
4533 break;
4534
4535 /*
4536 * Advance search position. Normally we start the next search at the
4537 * end of the previous match; but if the match was of zero length, we
4538 * have to advance by one character, or we'd just find the same match
4539 * again.
4540 */
4541 search_start = data_pos;
4542 if (pmatch[0].rm_so == pmatch[0].rm_eo)
4543 search_start++;
4544 }
4545
4546 /*
4547 * Copy the text to the right of the last match.
4548 */
4549 if (data_pos < data_len)
4550 {
4551 int chunk_len;
4552
4553 chunk_len = ((char *) src_text + VARSIZE_ANY(src_text)) - start_ptr;
4554 appendBinaryStringInfo(&buf, start_ptr, chunk_len);
4555 }
4556
4557 ret_text = cstring_to_text_with_len(buf.data, buf.len);
4558 pfree(buf.data);
4559 pfree(data);
4560
4561 return ret_text;
4562}
#define lengthof(array)
Definition: c.h:759
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
unsigned int pg_wchar
Definition: mbprint.c:31
int pg_mb2wchar_with_len(const char *from, pg_wchar *to, int len)
Definition: mbutils.c:986
void pfree(void *pointer)
Definition: mcxt.c:1524
void * palloc(Size size)
Definition: mcxt.c:1317
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
const void * data
static char * buf
Definition: pg_test_fsync.c:72
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:658
#define VARSIZE_ANY(PTR)
Definition: varatt.h:311
#define VARDATA_ANY(PTR)
Definition: varatt.h:324
#define VARSIZE_ANY_EXHDR(PTR)
Definition: varatt.h:317
static void appendStringInfoText(StringInfo str, const text *t)
Definition: varlena.c:4184
static int check_replace_text_has_escape(const text *replace_text)
Definition: varlena.c:4275
text * cstring_to_text_with_len(const char *s, int len)
Definition: varlena.c:204
static void appendStringInfoRegexpSubstr(StringInfo str, text *replace_text, regmatch_t *pmatch, char *start_ptr, int data_pos)
Definition: varlena.c:4308
static int charlen_to_bytelen(const char *p, int n)
Definition: varlena.c:814
Datum replace_text(PG_FUNCTION_ARGS)
Definition: varlena.c:4198

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

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

◆ SplitDirectoriesString()

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

Definition at line 3652 of file varlena.c.

3654{
3655 char *nextp = rawstring;
3656 bool done = false;
3657
3658 *namelist = NIL;
3659
3660 while (scanner_isspace(*nextp))
3661 nextp++; /* skip leading whitespace */
3662
3663 if (*nextp == '\0')
3664 return true; /* allow empty string */
3665
3666 /* At the top of the loop, we are at start of a new directory. */
3667 do
3668 {
3669 char *curname;
3670 char *endp;
3671
3672 if (*nextp == '"')
3673 {
3674 /* Quoted name --- collapse quote-quote pairs */
3675 curname = nextp + 1;
3676 for (;;)
3677 {
3678 endp = strchr(nextp + 1, '"');
3679 if (endp == NULL)
3680 return false; /* mismatched quotes */
3681 if (endp[1] != '"')
3682 break; /* found end of quoted name */
3683 /* Collapse adjacent quotes into one quote, and look again */
3684 memmove(endp, endp + 1, strlen(endp));
3685 nextp = endp;
3686 }
3687 /* endp now points at the terminating quote */
3688 nextp = endp + 1;
3689 }
3690 else
3691 {
3692 /* Unquoted name --- extends to separator or end of string */
3693 curname = endp = nextp;
3694 while (*nextp && *nextp != separator)
3695 {
3696 /* trailing whitespace should not be included in name */
3697 if (!scanner_isspace(*nextp))
3698 endp = nextp + 1;
3699 nextp++;
3700 }
3701 if (curname == endp)
3702 return false; /* empty unquoted name not allowed */
3703 }
3704
3705 while (scanner_isspace(*nextp))
3706 nextp++; /* skip trailing whitespace */
3707
3708 if (*nextp == separator)
3709 {
3710 nextp++;
3711 while (scanner_isspace(*nextp))
3712 nextp++; /* skip leading whitespace for next */
3713 /* we expect another name, so done remains false */
3714 }
3715 else if (*nextp == '\0')
3716 done = true;
3717 else
3718 return false; /* invalid syntax */
3719
3720 /* Now safe to overwrite separator with a null */
3721 *endp = '\0';
3722
3723 /* Truncate path if it's overlength */
3724 if (strlen(curname) >= MAXPGPATH)
3725 curname[MAXPGPATH - 1] = '\0';
3726
3727 /*
3728 * Finished isolating current name --- add it to list
3729 */
3730 curname = pstrdup(curname);
3731 canonicalize_path(curname);
3732 *namelist = lappend(*namelist, curname);
3733
3734 /* Loop back if we didn't reach end of string */
3735 } while (!done);
3736
3737 return true;
3738}
List * lappend(List *list, void *datum)
Definition: list.c:339
char * pstrdup(const char *in)
Definition: mcxt.c:1699
#define MAXPGPATH
#define NIL
Definition: pg_list.h:68
void canonicalize_path(char *path)
Definition: path.c:337
bool scanner_isspace(char ch)
Definition: scansup.c:117

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

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

◆ SplitGUCList()

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

Definition at line 3773 of file varlena.c.

3775{
3776 char *nextp = rawstring;
3777 bool done = false;
3778
3779 *namelist = NIL;
3780
3781 while (scanner_isspace(*nextp))
3782 nextp++; /* skip leading whitespace */
3783
3784 if (*nextp == '\0')
3785 return true; /* allow empty string */
3786
3787 /* At the top of the loop, we are at start of a new identifier. */
3788 do
3789 {
3790 char *curname;
3791 char *endp;
3792
3793 if (*nextp == '"')
3794 {
3795 /* Quoted name --- collapse quote-quote pairs */
3796 curname = nextp + 1;
3797 for (;;)
3798 {
3799 endp = strchr(nextp + 1, '"');
3800 if (endp == NULL)
3801 return false; /* mismatched quotes */
3802 if (endp[1] != '"')
3803 break; /* found end of quoted name */
3804 /* Collapse adjacent quotes into one quote, and look again */
3805 memmove(endp, endp + 1, strlen(endp));
3806 nextp = endp;
3807 }
3808 /* endp now points at the terminating quote */
3809 nextp = endp + 1;
3810 }
3811 else
3812 {
3813 /* Unquoted name --- extends to separator or whitespace */
3814 curname = nextp;
3815 while (*nextp && *nextp != separator &&
3816 !scanner_isspace(*nextp))
3817 nextp++;
3818 endp = nextp;
3819 if (curname == nextp)
3820 return false; /* empty unquoted name not allowed */
3821 }
3822
3823 while (scanner_isspace(*nextp))
3824 nextp++; /* skip trailing whitespace */
3825
3826 if (*nextp == separator)
3827 {
3828 nextp++;
3829 while (scanner_isspace(*nextp))
3830 nextp++; /* skip leading whitespace for next */
3831 /* we expect another name, so done remains false */
3832 }
3833 else if (*nextp == '\0')
3834 done = true;
3835 else
3836 return false; /* invalid syntax */
3837
3838 /* Now safe to overwrite separator with a null */
3839 *endp = '\0';
3840
3841 /*
3842 * Finished isolating current name --- add it to list
3843 */
3844 *namelist = lappend(*namelist, curname);
3845
3846 /* Loop back if we didn't reach end of string */
3847 } while (!done);
3848
3849 return true;
3850}

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

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

◆ SplitIdentifierString()

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

Definition at line 3525 of file varlena.c.

3527{
3528 char *nextp = rawstring;
3529 bool done = false;
3530
3531 *namelist = NIL;
3532
3533 while (scanner_isspace(*nextp))
3534 nextp++; /* skip leading whitespace */
3535
3536 if (*nextp == '\0')
3537 return true; /* allow empty string */
3538
3539 /* At the top of the loop, we are at start of a new identifier. */
3540 do
3541 {
3542 char *curname;
3543 char *endp;
3544
3545 if (*nextp == '"')
3546 {
3547 /* Quoted name --- collapse quote-quote pairs, no downcasing */
3548 curname = nextp + 1;
3549 for (;;)
3550 {
3551 endp = strchr(nextp + 1, '"');
3552 if (endp == NULL)
3553 return false; /* mismatched quotes */
3554 if (endp[1] != '"')
3555 break; /* found end of quoted name */
3556 /* Collapse adjacent quotes into one quote, and look again */
3557 memmove(endp, endp + 1, strlen(endp));
3558 nextp = endp;
3559 }
3560 /* endp now points at the terminating quote */
3561 nextp = endp + 1;
3562 }
3563 else
3564 {
3565 /* Unquoted name --- extends to separator or whitespace */
3566 char *downname;
3567 int len;
3568
3569 curname = nextp;
3570 while (*nextp && *nextp != separator &&
3571 !scanner_isspace(*nextp))
3572 nextp++;
3573 endp = nextp;
3574 if (curname == nextp)
3575 return false; /* empty unquoted name not allowed */
3576
3577 /*
3578 * Downcase the identifier, using same code as main lexer does.
3579 *
3580 * XXX because we want to overwrite the input in-place, we cannot
3581 * support a downcasing transformation that increases the string
3582 * length. This is not a problem given the current implementation
3583 * of downcase_truncate_identifier, but we'll probably have to do
3584 * something about this someday.
3585 */
3586 len = endp - curname;
3587 downname = downcase_truncate_identifier(curname, len, false);
3588 Assert(strlen(downname) <= len);
3589 strncpy(curname, downname, len); /* strncpy is required here */
3590 pfree(downname);
3591 }
3592
3593 while (scanner_isspace(*nextp))
3594 nextp++; /* skip trailing whitespace */
3595
3596 if (*nextp == separator)
3597 {
3598 nextp++;
3599 while (scanner_isspace(*nextp))
3600 nextp++; /* skip leading whitespace for next */
3601 /* we expect another name, so done remains false */
3602 }
3603 else if (*nextp == '\0')
3604 done = true;
3605 else
3606 return false; /* invalid syntax */
3607
3608 /* Now safe to overwrite separator with a null */
3609 *endp = '\0';
3610
3611 /* Truncate name if it's overlength */
3612 truncate_identifier(curname, strlen(curname), false);
3613
3614 /*
3615 * Finished isolating current name --- add it to list
3616 */
3617 *namelist = lappend(*namelist, curname);
3618
3619 /* Loop back if we didn't reach end of string */
3620 } while (!done);
3621
3622 return true;
3623}
const void size_t len
void truncate_identifier(char *ident, int len, bool warn)
Definition: scansup.c:93
char * downcase_truncate_identifier(const char *ident, int len, bool warn)
Definition: scansup.c:37

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

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

◆ textToQualifiedNameList()

List * textToQualifiedNameList ( text textval)

Definition at line 3467 of file varlena.c.

3468{
3469 char *rawname;
3470 List *result = NIL;
3471 List *namelist;
3472 ListCell *l;
3473
3474 /* Convert to C string (handles possible detoasting). */
3475 /* Note we rely on being able to modify rawname below. */
3476 rawname = text_to_cstring(textval);
3477
3478 if (!SplitIdentifierString(rawname, '.', &namelist))
3479 ereport(ERROR,
3480 (errcode(ERRCODE_INVALID_NAME),
3481 errmsg("invalid name syntax")));
3482
3483 if (namelist == NIL)
3484 ereport(ERROR,
3485 (errcode(ERRCODE_INVALID_NAME),
3486 errmsg("invalid name syntax")));
3487
3488 foreach(l, namelist)
3489 {
3490 char *curname = (char *) lfirst(l);
3491
3492 result = lappend(result, makeString(pstrdup(curname)));
3493 }
3494
3495 pfree(rawname);
3496 list_free(namelist);
3497
3498 return result;
3499}
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:3525
char * text_to_cstring(const text *t)
Definition: varlena.c:225

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

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

◆ updateClosestMatch()

void updateClosestMatch ( ClosestMatchState state,
const char *  candidate 
)

Definition at line 6410 of file varlena.c.

6411{
6412 int dist;
6413
6414 Assert(state);
6415
6416 if (state->source == NULL || state->source[0] == '\0' ||
6417 candidate == NULL || candidate[0] == '\0')
6418 return;
6419
6420 /*
6421 * To avoid ERROR-ing, we check the lengths here instead of setting
6422 * 'trusted' to false in the call to varstr_levenshtein_less_equal().
6423 */
6424 if (strlen(state->source) > MAX_LEVENSHTEIN_STRLEN ||
6425 strlen(candidate) > MAX_LEVENSHTEIN_STRLEN)
6426 return;
6427
6428 dist = varstr_levenshtein_less_equal(state->source, strlen(state->source),
6429 candidate, strlen(candidate), 1, 1, 1,
6430 state->max_d, true);
6431 if (dist <= state->max_d &&
6432 dist <= strlen(state->source) / 2 &&
6433 (state->min_d == -1 || dist < state->min_d))
6434 {
6435 state->min_d = dist;
6436 state->match = candidate;
6437 }
6438}
#define MAX_LEVENSHTEIN_STRLEN
Definition: levenshtein.c:26
int varstr_levenshtein_less_equal(const char *source, int slen, const char *target, int tlen, int ins_c, int del_c, int sub_c, int max_d, bool trusted)

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

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

◆ varstr_cmp()

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

Definition at line 1610 of file varlena.c.

1611{
1612 int result;
1613 pg_locale_t mylocale;
1614
1616
1618
1619 if (mylocale->collate_is_c)
1620 {
1621 result = memcmp(arg1, arg2, Min(len1, len2));
1622 if ((result == 0) && (len1 != len2))
1623 result = (len1 < len2) ? -1 : 1;
1624 }
1625 else
1626 {
1627 /*
1628 * memcmp() can't tell us which of two unequal strings sorts first,
1629 * but it's a cheap way to tell if they're equal. Testing shows that
1630 * memcmp() followed by strcoll() is only trivially slower than
1631 * strcoll() by itself, so we don't lose much if this doesn't work out
1632 * very often, and if it does - for example, because there are many
1633 * equal strings in the input - then we win big by avoiding expensive
1634 * collation-aware comparisons.
1635 */
1636 if (len1 == len2 && memcmp(arg1, arg2, len1) == 0)
1637 return 0;
1638
1639 result = pg_strncoll(arg1, len1, arg2, len2, mylocale);
1640
1641 /* Break tie if necessary. */
1642 if (result == 0 && mylocale->deterministic)
1643 {
1644 result = memcmp(arg1, arg2, Min(len1, len2));
1645 if ((result == 0) && (len1 != len2))
1646 result = (len1 < len2) ? -1 : 1;
1647 }
1648 }
1649
1650 return result;
1651}
#define Min(x, y)
Definition: c.h:975
Oid collid
pg_locale_t pg_newlocale_from_collation(Oid collid)
Definition: pg_locale.c:1188
int pg_strncoll(const char *arg1, ssize_t len1, const char *arg2, ssize_t len2, pg_locale_t locale)
Definition: pg_locale.c:1356
bool deterministic
Definition: pg_locale.h:99
static void check_collation_set(Oid collid)
Definition: varlena.c:1581

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

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

◆ varstr_levenshtein()

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

Definition at line 73 of file levenshtein.c.

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

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

Referenced by levenshtein(), and levenshtein_with_costs().

◆ varstr_levenshtein_less_equal()

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

◆ varstr_sortsupport()

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

Definition at line 1928 of file varlena.c.

1929{
1930 bool abbreviate = ssup->abbreviate;
1931 bool collate_c = false;
1934
1936
1938
1939 /*
1940 * If possible, set ssup->comparator to a function which can be used to
1941 * directly compare two datums. If we can do this, we'll avoid the
1942 * overhead of a trip through the fmgr layer for every comparison, which
1943 * can be substantial.
1944 *
1945 * Most typically, we'll set the comparator to varlenafastcmp_locale,
1946 * which uses strcoll() to perform comparisons. We use that for the
1947 * BpChar case too, but type NAME uses namefastcmp_locale. However, if
1948 * LC_COLLATE = C, we can make things quite a bit faster with
1949 * varstrfastcmp_c, bpcharfastcmp_c, or namefastcmp_c, all of which use
1950 * memcmp() rather than strcoll().
1951 */
1952 if (locale->collate_is_c)
1953 {
1954 if (typid == BPCHAROID)
1956 else if (typid == NAMEOID)
1957 {
1958 ssup->comparator = namefastcmp_c;
1959 /* Not supporting abbreviation with type NAME, for now */
1960 abbreviate = false;
1961 }
1962 else
1964
1965 collate_c = true;
1966 }
1967 else
1968 {
1969 /*
1970 * We use varlenafastcmp_locale except for type NAME.
1971 */
1972 if (typid == NAMEOID)
1973 {
1975 /* Not supporting abbreviation with type NAME, for now */
1976 abbreviate = false;
1977 }
1978 else
1980
1981 /*
1982 * Unfortunately, it seems that abbreviation for non-C collations is
1983 * broken on many common platforms; see pg_strxfrm_enabled().
1984 *
1985 * Even apart from the risk of broken locales, it's possible that
1986 * there are platforms where the use of abbreviated keys should be
1987 * disabled at compile time. Having only 4 byte datums could make
1988 * worst-case performance drastically more likely, for example.
1989 * Moreover, macOS's strxfrm() implementation is known to not
1990 * effectively concentrate a significant amount of entropy from the
1991 * original string in earlier transformed blobs. It's possible that
1992 * other supported platforms are similarly encumbered. So, if we ever
1993 * get past disabling this categorically, we may still want or need to
1994 * disable it for particular platforms.
1995 */
1997 abbreviate = false;
1998 }
1999
2000 /*
2001 * If we're using abbreviated keys, or if we're using a locale-aware
2002 * comparison, we need to initialize a VarStringSortSupport object. Both
2003 * cases will make use of the temporary buffers we initialize here for
2004 * scratch space (and to detect requirement for BpChar semantics from
2005 * caller), and the abbreviation case requires additional state.
2006 */
2007 if (abbreviate || !collate_c)
2008 {
2009 sss = palloc(sizeof(VarStringSortSupport));
2010 sss->buf1 = palloc(TEXTBUFLEN);
2011 sss->buflen1 = TEXTBUFLEN;
2012 sss->buf2 = palloc(TEXTBUFLEN);
2013 sss->buflen2 = TEXTBUFLEN;
2014 /* Start with invalid values */
2015 sss->last_len1 = -1;
2016 sss->last_len2 = -1;
2017 /* Initialize */
2018 sss->last_returned = 0;
2019 if (collate_c)
2020 sss->locale = NULL;
2021 else
2022 sss->locale = locale;
2023
2024 /*
2025 * To avoid somehow confusing a strxfrm() blob and an original string,
2026 * constantly keep track of the variety of data that buf1 and buf2
2027 * currently contain.
2028 *
2029 * Comparisons may be interleaved with conversion calls. Frequently,
2030 * conversions and comparisons are batched into two distinct phases,
2031 * but the correctness of caching cannot hinge upon this. For
2032 * comparison caching, buffer state is only trusted if cache_blob is
2033 * found set to false, whereas strxfrm() caching only trusts the state
2034 * when cache_blob is found set to true.
2035 *
2036 * Arbitrarily initialize cache_blob to true.
2037 */
2038 sss->cache_blob = true;
2039 sss->collate_c = collate_c;
2040 sss->typid = typid;
2041 ssup->ssup_extra = sss;
2042
2043 /*
2044 * If possible, plan to use the abbreviated keys optimization. The
2045 * core code may switch back to authoritative comparator should
2046 * abbreviation be aborted.
2047 */
2048 if (abbreviate)
2049 {
2050 sss->prop_card = 0.20;
2051 initHyperLogLog(&sss->abbr_card, 10);
2052 initHyperLogLog(&sss->full_card, 10);
2053 ssup->abbrev_full_comparator = ssup->comparator;
2057 }
2058 }
2059}
void initHyperLogLog(hyperLogLogState *cState, uint8 bwidth)
Definition: hyperloglog.c:66
static char * locale
Definition: initdb.c:140
bool pg_strxfrm_enabled(pg_locale_t locale)
Definition: pg_locale.c:1370
int(* comparator)(Datum x, Datum y, SortSupport ssup)
Definition: sortsupport.h:106
Datum(* abbrev_converter)(Datum original, SortSupport ssup)
Definition: sortsupport.h:172
void * ssup_extra
Definition: sortsupport.h:87
int(* abbrev_full_comparator)(Datum x, Datum y, SortSupport ssup)
Definition: sortsupport.h:191
bool(* abbrev_abort)(int memtupcount, SortSupport ssup)
Definition: sortsupport.h:182
pg_locale_t locale
Definition: varlena.c:104
hyperLogLogState full_card
Definition: varlena.c:102
hyperLogLogState abbr_card
Definition: varlena.c:101
int ssup_datum_unsigned_cmp(Datum x, Datum y, SortSupport ssup)
Definition: tuplesort.c:3139
static bool varstr_abbrev_abort(int memtupcount, SortSupport ssup)
Definition: varlena.c:2490
static int varlenafastcmp_locale(Datum x, Datum y, SortSupport ssup)
Definition: varlena.c:2147
static int bpcharfastcmp_c(Datum x, Datum y, SortSupport ssup)
Definition: varlena.c:2102
static int namefastcmp_c(Datum x, Datum y, SortSupport ssup)
Definition: varlena.c:2135
static int namefastcmp_locale(Datum x, Datum y, SortSupport ssup)
Definition: varlena.c:2178
static Datum varstr_abbrev_convert(Datum original, SortSupport ssup)
Definition: varlena.c:2292
static int varstrfastcmp_c(Datum x, Datum y, SortSupport ssup)
Definition: varlena.c:2065
#define TEXTBUFLEN
Definition: varlena.c:122

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

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