PostgreSQL Source Code  git master
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 6274 of file varlena.c.

6275 {
6276  Assert(state);
6277 
6278  return state->match;
6279 }
Assert(fmt[strlen(fmt) - 1] !='\n')
Definition: regguts.h:318

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

6220 {
6221  Assert(state);
6222  Assert(max_d >= 0);
6223 
6224  state->source = source;
6225  state->min_d = -1;
6226  state->max_d = max_d;
6227  state->match = NULL;
6228 }
static rewind_source * source
Definition: pg_rewind.c:81

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

4465 {
4466  text *ret_text;
4467  regex_t *re;
4468  int src_text_len = VARSIZE_ANY_EXHDR(src_text);
4469  int nmatches = 0;
4471  regmatch_t pmatch[10]; /* main match, plus \1 to \9 */
4472  int nmatch = lengthof(pmatch);
4473  pg_wchar *data;
4474  size_t data_len;
4475  int data_pos;
4476  char *start_ptr;
4477  int escape_status;
4478 
4479  initStringInfo(&buf);
4480 
4481  /* Convert data string to wide characters. */
4482  data = (pg_wchar *) palloc((src_text_len + 1) * sizeof(pg_wchar));
4483  data_len = pg_mb2wchar_with_len(VARDATA_ANY(src_text), data, src_text_len);
4484 
4485  /* Check whether replace_text has escapes, especially regexp submatches. */
4487 
4488  /* If no regexp submatches, we can use REG_NOSUB. */
4489  if (escape_status < 2)
4490  {
4491  cflags |= REG_NOSUB;
4492  /* Also tell pg_regexec we only want the whole-match location. */
4493  nmatch = 1;
4494  }
4495 
4496  /* Prepare the regexp. */
4497  re = RE_compile_and_cache(pattern_text, cflags, collation);
4498 
4499  /* start_ptr points to the data_pos'th character of src_text */
4500  start_ptr = (char *) VARDATA_ANY(src_text);
4501  data_pos = 0;
4502 
4503  while (search_start <= data_len)
4504  {
4505  int regexec_result;
4506 
4508 
4509  regexec_result = pg_regexec(re,
4510  data,
4511  data_len,
4512  search_start,
4513  NULL, /* no details */
4514  nmatch,
4515  pmatch,
4516  0);
4517 
4518  if (regexec_result == REG_NOMATCH)
4519  break;
4520 
4521  if (regexec_result != REG_OKAY)
4522  {
4523  char errMsg[100];
4524 
4526  pg_regerror(regexec_result, re, errMsg, sizeof(errMsg));
4527  ereport(ERROR,
4528  (errcode(ERRCODE_INVALID_REGULAR_EXPRESSION),
4529  errmsg("regular expression failed: %s", errMsg)));
4530  }
4531 
4532  /*
4533  * Count matches, and decide whether to replace this match.
4534  */
4535  nmatches++;
4536  if (n > 0 && nmatches != n)
4537  {
4538  /*
4539  * No, so advance search_start, but not start_ptr/data_pos. (Thus,
4540  * we treat the matched text as if it weren't matched, and copy it
4541  * to the output later.)
4542  */
4543  search_start = pmatch[0].rm_eo;
4544  if (pmatch[0].rm_so == pmatch[0].rm_eo)
4545  search_start++;
4546  continue;
4547  }
4548 
4549  /*
4550  * Copy the text to the left of the match position. Note we are given
4551  * character not byte indexes.
4552  */
4553  if (pmatch[0].rm_so - data_pos > 0)
4554  {
4555  int chunk_len;
4556 
4557  chunk_len = charlen_to_bytelen(start_ptr,
4558  pmatch[0].rm_so - data_pos);
4559  appendBinaryStringInfo(&buf, start_ptr, chunk_len);
4560 
4561  /*
4562  * Advance start_ptr over that text, to avoid multiple rescans of
4563  * it if the replace_text contains multiple back-references.
4564  */
4565  start_ptr += chunk_len;
4566  data_pos = pmatch[0].rm_so;
4567  }
4568 
4569  /*
4570  * Copy the replace_text, processing escapes if any are present.
4571  */
4572  if (escape_status > 0)
4574  start_ptr, data_pos);
4575  else
4577 
4578  /* Advance start_ptr and data_pos over the matched text. */
4579  start_ptr += charlen_to_bytelen(start_ptr,
4580  pmatch[0].rm_eo - data_pos);
4581  data_pos = pmatch[0].rm_eo;
4582 
4583  /*
4584  * If we only want to replace one occurrence, we're done.
4585  */
4586  if (n > 0)
4587  break;
4588 
4589  /*
4590  * Advance search position. Normally we start the next search at the
4591  * end of the previous match; but if the match was of zero length, we
4592  * have to advance by one character, or we'd just find the same match
4593  * again.
4594  */
4595  search_start = data_pos;
4596  if (pmatch[0].rm_so == pmatch[0].rm_eo)
4597  search_start++;
4598  }
4599 
4600  /*
4601  * Copy the text to the right of the last match.
4602  */
4603  if (data_pos < data_len)
4604  {
4605  int chunk_len;
4606 
4607  chunk_len = ((char *) src_text + VARSIZE_ANY(src_text)) - start_ptr;
4608  appendBinaryStringInfo(&buf, start_ptr, chunk_len);
4609  }
4610 
4611  ret_text = cstring_to_text_with_len(buf.data, buf.len);
4612  pfree(buf.data);
4613  pfree(data);
4614 
4615  return ret_text;
4616 }
#define lengthof(array)
Definition: c.h:724
int errcode(int sqlerrcode)
Definition: elog.c:695
int errmsg(const char *fmt,...)
Definition: elog.c:906
#define ERROR
Definition: elog.h:35
#define ereport(elevel,...)
Definition: elog.h:145
unsigned int pg_wchar
Definition: mbprint.c:31
int pg_mb2wchar_with_len(const char *from, pg_wchar *to, int len)
Definition: mbutils.c:929
void pfree(void *pointer)
Definition: mcxt.c:1306
void * palloc(Size size)
Definition: mcxt.c:1199
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
const void * data
static char * buf
Definition: pg_test_fsync.c:67
#define VARSIZE_ANY(PTR)
Definition: postgres.h:349
#define VARDATA_ANY(PTR)
Definition: postgres.h:362
#define VARSIZE_ANY_EXHDR(PTR)
Definition: postgres.h:355
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:138
#define REG_OKAY
Definition: regex.h:137
#define REG_NOSUB
Definition: regex.h:107
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:138
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:227
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
Definition: regex.h:56
regoff_t rm_eo
Definition: regex.h:86
regoff_t rm_so
Definition: regex.h:85
Definition: c.h:623
static void appendStringInfoText(StringInfo str, const text *t)
Definition: varlena.c:4237
static int check_replace_text_has_escape(const text *replace_text)
Definition: varlena.c:4328
static void appendStringInfoRegexpSubstr(StringInfo str, text *replace_text, regmatch_t *pmatch, char *start_ptr, int data_pos)
Definition: varlena.c:4361
static int charlen_to_bytelen(const char *p, int n)
Definition: varlena.c:786
text * cstring_to_text_with_len(const char *s, int len)
Definition: varlena.c:201
Datum replace_text(PG_FUNCTION_ARGS)
Definition: varlena.c:4251

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, replace_text(), regmatch_t::rm_eo, regmatch_t::rm_so, 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 3839 of file varlena.c.

3841 {
3842  char *nextp = rawstring;
3843  bool done = false;
3844 
3845  *namelist = NIL;
3846 
3847  while (scanner_isspace(*nextp))
3848  nextp++; /* skip leading whitespace */
3849 
3850  if (*nextp == '\0')
3851  return true; /* allow empty string */
3852 
3853  /* At the top of the loop, we are at start of a new directory. */
3854  do
3855  {
3856  char *curname;
3857  char *endp;
3858 
3859  if (*nextp == '"')
3860  {
3861  /* Quoted name --- collapse quote-quote pairs */
3862  curname = nextp + 1;
3863  for (;;)
3864  {
3865  endp = strchr(nextp + 1, '"');
3866  if (endp == NULL)
3867  return false; /* mismatched quotes */
3868  if (endp[1] != '"')
3869  break; /* found end of quoted name */
3870  /* Collapse adjacent quotes into one quote, and look again */
3871  memmove(endp, endp + 1, strlen(endp));
3872  nextp = endp;
3873  }
3874  /* endp now points at the terminating quote */
3875  nextp = endp + 1;
3876  }
3877  else
3878  {
3879  /* Unquoted name --- extends to separator or end of string */
3880  curname = endp = nextp;
3881  while (*nextp && *nextp != separator)
3882  {
3883  /* trailing whitespace should not be included in name */
3884  if (!scanner_isspace(*nextp))
3885  endp = nextp + 1;
3886  nextp++;
3887  }
3888  if (curname == endp)
3889  return false; /* empty unquoted name not allowed */
3890  }
3891 
3892  while (scanner_isspace(*nextp))
3893  nextp++; /* skip trailing whitespace */
3894 
3895  if (*nextp == separator)
3896  {
3897  nextp++;
3898  while (scanner_isspace(*nextp))
3899  nextp++; /* skip leading whitespace for next */
3900  /* we expect another name, so done remains false */
3901  }
3902  else if (*nextp == '\0')
3903  done = true;
3904  else
3905  return false; /* invalid syntax */
3906 
3907  /* Now safe to overwrite separator with a null */
3908  *endp = '\0';
3909 
3910  /* Truncate path if it's overlength */
3911  if (strlen(curname) >= MAXPGPATH)
3912  curname[MAXPGPATH - 1] = '\0';
3913 
3914  /*
3915  * Finished isolating current name --- add it to list
3916  */
3917  curname = pstrdup(curname);
3918  canonicalize_path(curname);
3919  *namelist = lappend(*namelist, curname);
3920 
3921  /* Loop back if we didn't reach end of string */
3922  } while (!done);
3923 
3924  return true;
3925 }
List * lappend(List *list, void *datum)
Definition: list.c:338
char * pstrdup(const char *in)
Definition: mcxt.c:1483
#define MAXPGPATH
#define NIL
Definition: pg_list.h:66
void canonicalize_path(char *path)
Definition: path.c:264
bool scanner_isspace(char ch)
Definition: scansup.c:117

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

Referenced by load_libraries(), and PostmasterMain().

◆ SplitGUCList()

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

Definition at line 3960 of file varlena.c.

3962 {
3963  char *nextp = rawstring;
3964  bool done = false;
3965 
3966  *namelist = NIL;
3967 
3968  while (scanner_isspace(*nextp))
3969  nextp++; /* skip leading whitespace */
3970 
3971  if (*nextp == '\0')
3972  return true; /* allow empty string */
3973 
3974  /* At the top of the loop, we are at start of a new identifier. */
3975  do
3976  {
3977  char *curname;
3978  char *endp;
3979 
3980  if (*nextp == '"')
3981  {
3982  /* Quoted name --- collapse quote-quote pairs */
3983  curname = nextp + 1;
3984  for (;;)
3985  {
3986  endp = strchr(nextp + 1, '"');
3987  if (endp == NULL)
3988  return false; /* mismatched quotes */
3989  if (endp[1] != '"')
3990  break; /* found end of quoted name */
3991  /* Collapse adjacent quotes into one quote, and look again */
3992  memmove(endp, endp + 1, strlen(endp));
3993  nextp = endp;
3994  }
3995  /* endp now points at the terminating quote */
3996  nextp = endp + 1;
3997  }
3998  else
3999  {
4000  /* Unquoted name --- extends to separator or whitespace */
4001  curname = nextp;
4002  while (*nextp && *nextp != separator &&
4003  !scanner_isspace(*nextp))
4004  nextp++;
4005  endp = nextp;
4006  if (curname == nextp)
4007  return false; /* empty unquoted name not allowed */
4008  }
4009 
4010  while (scanner_isspace(*nextp))
4011  nextp++; /* skip trailing whitespace */
4012 
4013  if (*nextp == separator)
4014  {
4015  nextp++;
4016  while (scanner_isspace(*nextp))
4017  nextp++; /* skip leading whitespace for next */
4018  /* we expect another name, so done remains false */
4019  }
4020  else if (*nextp == '\0')
4021  done = true;
4022  else
4023  return false; /* invalid syntax */
4024 
4025  /* Now safe to overwrite separator with a null */
4026  *endp = '\0';
4027 
4028  /*
4029  * Finished isolating current name --- add it to list
4030  */
4031  *namelist = lappend(*namelist, curname);
4032 
4033  /* Loop back if we didn't reach end of string */
4034  } while (!done);
4035 
4036  return true;
4037 }

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

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

◆ SplitIdentifierString()

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

Definition at line 3712 of file varlena.c.

3714 {
3715  char *nextp = rawstring;
3716  bool done = false;
3717 
3718  *namelist = NIL;
3719 
3720  while (scanner_isspace(*nextp))
3721  nextp++; /* skip leading whitespace */
3722 
3723  if (*nextp == '\0')
3724  return true; /* allow empty string */
3725 
3726  /* At the top of the loop, we are at start of a new identifier. */
3727  do
3728  {
3729  char *curname;
3730  char *endp;
3731 
3732  if (*nextp == '"')
3733  {
3734  /* Quoted name --- collapse quote-quote pairs, no downcasing */
3735  curname = nextp + 1;
3736  for (;;)
3737  {
3738  endp = strchr(nextp + 1, '"');
3739  if (endp == NULL)
3740  return false; /* mismatched quotes */
3741  if (endp[1] != '"')
3742  break; /* found end of quoted name */
3743  /* Collapse adjacent quotes into one quote, and look again */
3744  memmove(endp, endp + 1, strlen(endp));
3745  nextp = endp;
3746  }
3747  /* endp now points at the terminating quote */
3748  nextp = endp + 1;
3749  }
3750  else
3751  {
3752  /* Unquoted name --- extends to separator or whitespace */
3753  char *downname;
3754  int len;
3755 
3756  curname = nextp;
3757  while (*nextp && *nextp != separator &&
3758  !scanner_isspace(*nextp))
3759  nextp++;
3760  endp = nextp;
3761  if (curname == nextp)
3762  return false; /* empty unquoted name not allowed */
3763 
3764  /*
3765  * Downcase the identifier, using same code as main lexer does.
3766  *
3767  * XXX because we want to overwrite the input in-place, we cannot
3768  * support a downcasing transformation that increases the string
3769  * length. This is not a problem given the current implementation
3770  * of downcase_truncate_identifier, but we'll probably have to do
3771  * something about this someday.
3772  */
3773  len = endp - curname;
3774  downname = downcase_truncate_identifier(curname, len, false);
3775  Assert(strlen(downname) <= len);
3776  strncpy(curname, downname, len); /* strncpy is required here */
3777  pfree(downname);
3778  }
3779 
3780  while (scanner_isspace(*nextp))
3781  nextp++; /* skip trailing whitespace */
3782 
3783  if (*nextp == separator)
3784  {
3785  nextp++;
3786  while (scanner_isspace(*nextp))
3787  nextp++; /* skip leading whitespace for next */
3788  /* we expect another name, so done remains false */
3789  }
3790  else if (*nextp == '\0')
3791  done = true;
3792  else
3793  return false; /* invalid syntax */
3794 
3795  /* Now safe to overwrite separator with a null */
3796  *endp = '\0';
3797 
3798  /* Truncate name if it's overlength */
3799  truncate_identifier(curname, strlen(curname), false);
3800 
3801  /*
3802  * Finished isolating current name --- add it to list
3803  */
3804  *namelist = lappend(*namelist, curname);
3805 
3806  /* Loop back if we didn't reach end of string */
3807  } while (!done);
3808 
3809  return true;
3810 }
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_datestyle(), check_log_destination(), 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(), recomputeNamespacePath(), stringToQualifiedNameList(), and textToQualifiedNameList().

◆ textToQualifiedNameList()

List* textToQualifiedNameList ( text textval)

Definition at line 3654 of file varlena.c.

3655 {
3656  char *rawname;
3657  List *result = NIL;
3658  List *namelist;
3659  ListCell *l;
3660 
3661  /* Convert to C string (handles possible detoasting). */
3662  /* Note we rely on being able to modify rawname below. */
3663  rawname = text_to_cstring(textval);
3664 
3665  if (!SplitIdentifierString(rawname, '.', &namelist))
3666  ereport(ERROR,
3667  (errcode(ERRCODE_INVALID_NAME),
3668  errmsg("invalid name syntax")));
3669 
3670  if (namelist == NIL)
3671  ereport(ERROR,
3672  (errcode(ERRCODE_INVALID_NAME),
3673  errmsg("invalid name syntax")));
3674 
3675  foreach(l, namelist)
3676  {
3677  char *curname = (char *) lfirst(l);
3678 
3679  result = lappend(result, makeString(pstrdup(curname)));
3680  }
3681 
3682  pfree(rawname);
3683  list_free(namelist);
3684 
3685  return result;
3686 }
void list_free(List *list)
Definition: list.c:1545
#define lfirst(lc)
Definition: pg_list.h:170
Definition: pg_list.h:52
String * makeString(char *str)
Definition: value.c:63
char * text_to_cstring(const text *t)
Definition: varlena.c:222
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3712

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

Referenced by bt_metap(), 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 6239 of file varlena.c.

6240 {
6241  int dist;
6242 
6243  Assert(state);
6244 
6245  if (state->source == NULL || state->source[0] == '\0' ||
6246  candidate == NULL || candidate[0] == '\0')
6247  return;
6248 
6249  /*
6250  * To avoid ERROR-ing, we check the lengths here instead of setting
6251  * 'trusted' to false in the call to varstr_levenshtein_less_equal().
6252  */
6253  if (strlen(state->source) > MAX_LEVENSHTEIN_STRLEN ||
6254  strlen(candidate) > MAX_LEVENSHTEIN_STRLEN)
6255  return;
6256 
6257  dist = varstr_levenshtein_less_equal(state->source, strlen(state->source),
6258  candidate, strlen(candidate), 1, 1, 1,
6259  state->max_d, true);
6260  if (dist <= state->max_d &&
6261  dist <= strlen(state->source) / 2 &&
6262  (state->min_d == -1 || dist < state->min_d))
6263  {
6264  state->min_d = dist;
6265  state->match = candidate;
6266  }
6267 }
#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 1518 of file varlena.c.

1519 {
1520  int result;
1521 
1522  check_collation_set(collid);
1523 
1524  /*
1525  * Unfortunately, there is no strncoll(), so in the non-C locale case we
1526  * have to do some memory copying. This turns out to be significantly
1527  * slower, so we optimize the case where LC_COLLATE is C. We also try to
1528  * optimize relatively-short strings by avoiding palloc/pfree overhead.
1529  */
1530  if (lc_collate_is_c(collid))
1531  {
1532  result = memcmp(arg1, arg2, Min(len1, len2));
1533  if ((result == 0) && (len1 != len2))
1534  result = (len1 < len2) ? -1 : 1;
1535  }
1536  else
1537  {
1538  char a1buf[TEXTBUFLEN];
1539  char a2buf[TEXTBUFLEN];
1540  char *a1p,
1541  *a2p;
1542  pg_locale_t mylocale;
1543 
1544  mylocale = pg_newlocale_from_collation(collid);
1545 
1546  /*
1547  * memcmp() can't tell us which of two unequal strings sorts first,
1548  * but it's a cheap way to tell if they're equal. Testing shows that
1549  * memcmp() followed by strcoll() is only trivially slower than
1550  * strcoll() by itself, so we don't lose much if this doesn't work out
1551  * very often, and if it does - for example, because there are many
1552  * equal strings in the input - then we win big by avoiding expensive
1553  * collation-aware comparisons.
1554  */
1555  if (len1 == len2 && memcmp(arg1, arg2, len1) == 0)
1556  return 0;
1557 
1558 #ifdef WIN32
1559  /* Win32 does not have UTF-8, so we need to map to UTF-16 */
1560  if (GetDatabaseEncoding() == PG_UTF8
1561  && (!mylocale || mylocale->provider == COLLPROVIDER_LIBC))
1562  {
1563  int a1len;
1564  int a2len;
1565  int r;
1566 
1567  if (len1 >= TEXTBUFLEN / 2)
1568  {
1569  a1len = len1 * 2 + 2;
1570  a1p = palloc(a1len);
1571  }
1572  else
1573  {
1574  a1len = TEXTBUFLEN;
1575  a1p = a1buf;
1576  }
1577  if (len2 >= TEXTBUFLEN / 2)
1578  {
1579  a2len = len2 * 2 + 2;
1580  a2p = palloc(a2len);
1581  }
1582  else
1583  {
1584  a2len = TEXTBUFLEN;
1585  a2p = a2buf;
1586  }
1587 
1588  /* stupid Microsloth API does not work for zero-length input */
1589  if (len1 == 0)
1590  r = 0;
1591  else
1592  {
1593  r = MultiByteToWideChar(CP_UTF8, 0, arg1, len1,
1594  (LPWSTR) a1p, a1len / 2);
1595  if (!r)
1596  ereport(ERROR,
1597  (errmsg("could not convert string to UTF-16: error code %lu",
1598  GetLastError())));
1599  }
1600  ((LPWSTR) a1p)[r] = 0;
1601 
1602  if (len2 == 0)
1603  r = 0;
1604  else
1605  {
1606  r = MultiByteToWideChar(CP_UTF8, 0, arg2, len2,
1607  (LPWSTR) a2p, a2len / 2);
1608  if (!r)
1609  ereport(ERROR,
1610  (errmsg("could not convert string to UTF-16: error code %lu",
1611  GetLastError())));
1612  }
1613  ((LPWSTR) a2p)[r] = 0;
1614 
1615  errno = 0;
1616 #ifdef HAVE_LOCALE_T
1617  if (mylocale)
1618  result = wcscoll_l((LPWSTR) a1p, (LPWSTR) a2p, mylocale->info.lt);
1619  else
1620 #endif
1621  result = wcscoll((LPWSTR) a1p, (LPWSTR) a2p);
1622  if (result == 2147483647) /* _NLSCMPERROR; missing from mingw
1623  * headers */
1624  ereport(ERROR,
1625  (errmsg("could not compare Unicode strings: %m")));
1626 
1627  /* Break tie if necessary. */
1628  if (result == 0 &&
1629  (!mylocale || mylocale->deterministic))
1630  {
1631  result = memcmp(arg1, arg2, Min(len1, len2));
1632  if ((result == 0) && (len1 != len2))
1633  result = (len1 < len2) ? -1 : 1;
1634  }
1635 
1636  if (a1p != a1buf)
1637  pfree(a1p);
1638  if (a2p != a2buf)
1639  pfree(a2p);
1640 
1641  return result;
1642  }
1643 #endif /* WIN32 */
1644 
1645  if (len1 >= TEXTBUFLEN)
1646  a1p = (char *) palloc(len1 + 1);
1647  else
1648  a1p = a1buf;
1649  if (len2 >= TEXTBUFLEN)
1650  a2p = (char *) palloc(len2 + 1);
1651  else
1652  a2p = a2buf;
1653 
1654  memcpy(a1p, arg1, len1);
1655  a1p[len1] = '\0';
1656  memcpy(a2p, arg2, len2);
1657  a2p[len2] = '\0';
1658 
1659  if (mylocale)
1660  {
1661  if (mylocale->provider == COLLPROVIDER_ICU)
1662  {
1663 #ifdef USE_ICU
1664 #ifdef HAVE_UCOL_STRCOLLUTF8
1665  if (GetDatabaseEncoding() == PG_UTF8)
1666  {
1667  UErrorCode status;
1668 
1669  status = U_ZERO_ERROR;
1670  result = ucol_strcollUTF8(mylocale->info.icu.ucol,
1671  arg1, len1,
1672  arg2, len2,
1673  &status);
1674  if (U_FAILURE(status))
1675  ereport(ERROR,
1676  (errmsg("collation failed: %s", u_errorName(status))));
1677  }
1678  else
1679 #endif
1680  {
1681  int32_t ulen1,
1682  ulen2;
1683  UChar *uchar1,
1684  *uchar2;
1685 
1686  ulen1 = icu_to_uchar(&uchar1, arg1, len1);
1687  ulen2 = icu_to_uchar(&uchar2, arg2, len2);
1688 
1689  result = ucol_strcoll(mylocale->info.icu.ucol,
1690  uchar1, ulen1,
1691  uchar2, ulen2);
1692 
1693  pfree(uchar1);
1694  pfree(uchar2);
1695  }
1696 #else /* not USE_ICU */
1697  /* shouldn't happen */
1698  elog(ERROR, "unsupported collprovider: %c", mylocale->provider);
1699 #endif /* not USE_ICU */
1700  }
1701  else
1702  {
1703 #ifdef HAVE_LOCALE_T
1704  result = strcoll_l(a1p, a2p, mylocale->info.lt);
1705 #else
1706  /* shouldn't happen */
1707  elog(ERROR, "unsupported collprovider: %c", mylocale->provider);
1708 #endif
1709  }
1710  }
1711  else
1712  result = strcoll(a1p, a2p);
1713 
1714  /* Break tie if necessary. */
1715  if (result == 0 &&
1716  (!mylocale || mylocale->deterministic))
1717  result = strcmp(a1p, a2p);
1718 
1719  if (a1p != a1buf)
1720  pfree(a1p);
1721  if (a2p != a2buf)
1722  pfree(a2p);
1723  }
1724 
1725  return result;
1726 }
#define Min(x, y)
Definition: c.h:937
int GetDatabaseEncoding(void)
Definition: mbutils.c:1210
bool lc_collate_is_c(Oid collation)
Definition: pg_locale.c:1299
pg_locale_t pg_newlocale_from_collation(Oid collid)
Definition: pg_locale.c:1481
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:225
@ PG_UTF8
Definition: pg_wchar.h:232
union pg_locale_struct::@142 info
bool deterministic
Definition: pg_locale.h:76
static void check_collation_set(Oid collid)
Definition: varlena.c:1489
#define TEXTBUFLEN
Definition: varlena.c:113
#define strcoll_l
Definition: win32_port.h:442
#define wcscoll_l
Definition: win32_port.h:444

References check_collation_set(), pg_locale_struct::deterministic, elog(), ereport, errmsg(), ERROR, GetDatabaseEncoding(), pg_locale_struct::info, lc_collate_is_c(), Min, palloc(), pfree(), pg_newlocale_from_collation(), PG_UTF8, pg_locale_struct::provider, status(), strcoll_l, TEXTBUFLEN, and wcscoll_l.

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 &&
128  (m > MAX_LEVENSHTEIN_STRLEN ||
130  ereport(ERROR,
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:72
int x
Definition: isn.c:71
int j
Definition: isn.c:74
int i
Definition: isn.c:73
#define START_COLUMN
#define STOP_COLUMN
int pg_mbstrlen_with_len(const char *mbstr, int limit)
Definition: mbutils.c:1000
int pg_mblen(const char *mbstr)
Definition: mbutils.c:966
static bool rest_of_char_same(const char *s1, const char *s2, int len)
Definition: varlena.c:6183

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

2013 {
2014  bool abbreviate = ssup->abbreviate;
2015  bool collate_c = false;
2016  VarStringSortSupport *sss;
2017  pg_locale_t locale = 0;
2018 
2019  check_collation_set(collid);
2020 
2021  /*
2022  * If possible, set ssup->comparator to a function which can be used to
2023  * directly compare two datums. If we can do this, we'll avoid the
2024  * overhead of a trip through the fmgr layer for every comparison, which
2025  * can be substantial.
2026  *
2027  * Most typically, we'll set the comparator to varlenafastcmp_locale,
2028  * which uses strcoll() to perform comparisons. We use that for the
2029  * BpChar case too, but type NAME uses namefastcmp_locale. However, if
2030  * LC_COLLATE = C, we can make things quite a bit faster with
2031  * varstrfastcmp_c, bpcharfastcmp_c, or namefastcmp_c, all of which use
2032  * memcmp() rather than strcoll().
2033  */
2034  if (lc_collate_is_c(collid))
2035  {
2036  if (typid == BPCHAROID)
2037  ssup->comparator = bpcharfastcmp_c;
2038  else if (typid == NAMEOID)
2039  {
2040  ssup->comparator = namefastcmp_c;
2041  /* Not supporting abbreviation with type NAME, for now */
2042  abbreviate = false;
2043  }
2044  else
2045  ssup->comparator = varstrfastcmp_c;
2046 
2047  collate_c = true;
2048  }
2049  else
2050  {
2051  /*
2052  * We need a collation-sensitive comparison. To make things faster,
2053  * we'll figure out the collation based on the locale id and cache the
2054  * result.
2055  */
2057 
2058  /*
2059  * There is a further exception on Windows. When the database
2060  * encoding is UTF-8 and we are not using the C collation, complex
2061  * hacks are required. We don't currently have a comparator that
2062  * handles that case, so we fall back on the slow method of having the
2063  * sort code invoke bttextcmp() (in the case of text) via the fmgr
2064  * trampoline. ICU locales work just the same on Windows, however.
2065  */
2066 #ifdef WIN32
2067  if (GetDatabaseEncoding() == PG_UTF8 &&
2068  !(locale && locale->provider == COLLPROVIDER_ICU))
2069  return;
2070 #endif
2071 
2072  /*
2073  * We use varlenafastcmp_locale except for type NAME.
2074  */
2075  if (typid == NAMEOID)
2076  {
2078  /* Not supporting abbreviation with type NAME, for now */
2079  abbreviate = false;
2080  }
2081  else
2083  }
2084 
2085  /*
2086  * Unfortunately, it seems that abbreviation for non-C collations is
2087  * broken on many common platforms; testing of multiple versions of glibc
2088  * reveals that, for many locales, strcoll() and strxfrm() do not return
2089  * consistent results, which is fatal to this optimization. While no
2090  * other libc other than Cygwin has so far been shown to have a problem,
2091  * we take the conservative course of action for right now and disable
2092  * this categorically. (Users who are certain this isn't a problem on
2093  * their system can define TRUST_STRXFRM.)
2094  *
2095  * Even apart from the risk of broken locales, it's possible that there
2096  * are platforms where the use of abbreviated keys should be disabled at
2097  * compile time. Having only 4 byte datums could make worst-case
2098  * performance drastically more likely, for example. Moreover, macOS's
2099  * strxfrm() implementation is known to not effectively concentrate a
2100  * significant amount of entropy from the original string in earlier
2101  * transformed blobs. It's possible that other supported platforms are
2102  * similarly encumbered. So, if we ever get past disabling this
2103  * categorically, we may still want or need to disable it for particular
2104  * platforms.
2105  */
2106 #ifndef TRUST_STRXFRM
2107  if (!collate_c && !(locale && locale->provider == COLLPROVIDER_ICU))
2108  abbreviate = false;
2109 #endif
2110 
2111  /*
2112  * If we're using abbreviated keys, or if we're using a locale-aware
2113  * comparison, we need to initialize a VarStringSortSupport object. Both
2114  * cases will make use of the temporary buffers we initialize here for
2115  * scratch space (and to detect requirement for BpChar semantics from
2116  * caller), and the abbreviation case requires additional state.
2117  */
2118  if (abbreviate || !collate_c)
2119  {
2120  sss = palloc(sizeof(VarStringSortSupport));
2121  sss->buf1 = palloc(TEXTBUFLEN);
2122  sss->buflen1 = TEXTBUFLEN;
2123  sss->buf2 = palloc(TEXTBUFLEN);
2124  sss->buflen2 = TEXTBUFLEN;
2125  /* Start with invalid values */
2126  sss->last_len1 = -1;
2127  sss->last_len2 = -1;
2128  /* Initialize */
2129  sss->last_returned = 0;
2130  sss->locale = locale;
2131 
2132  /*
2133  * To avoid somehow confusing a strxfrm() blob and an original string,
2134  * constantly keep track of the variety of data that buf1 and buf2
2135  * currently contain.
2136  *
2137  * Comparisons may be interleaved with conversion calls. Frequently,
2138  * conversions and comparisons are batched into two distinct phases,
2139  * but the correctness of caching cannot hinge upon this. For
2140  * comparison caching, buffer state is only trusted if cache_blob is
2141  * found set to false, whereas strxfrm() caching only trusts the state
2142  * when cache_blob is found set to true.
2143  *
2144  * Arbitrarily initialize cache_blob to true.
2145  */
2146  sss->cache_blob = true;
2147  sss->collate_c = collate_c;
2148  sss->typid = typid;
2149  ssup->ssup_extra = sss;
2150 
2151  /*
2152  * If possible, plan to use the abbreviated keys optimization. The
2153  * core code may switch back to authoritative comparator should
2154  * abbreviation be aborted.
2155  */
2156  if (abbreviate)
2157  {
2158  sss->prop_card = 0.20;
2159  initHyperLogLog(&sss->abbr_card, 10);
2160  initHyperLogLog(&sss->full_card, 10);
2161  ssup->abbrev_full_comparator = ssup->comparator;
2165  }
2166  }
2167 }
void initHyperLogLog(hyperLogLogState *cState, uint8 bwidth)
Definition: hyperloglog.c:66
static char * locale
Definition: initdb.c:129
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:95
hyperLogLogState full_card
Definition: varlena.c:93
hyperLogLogState abbr_card
Definition: varlena.c:92
int ssup_datum_unsigned_cmp(Datum x, Datum y, SortSupport ssup)
Definition: tuplesort.c:3177
static bool varstr_abbrev_abort(int memtupcount, SortSupport ssup)
Definition: varlena.c:2692
static int varlenafastcmp_locale(Datum x, Datum y, SortSupport ssup)
Definition: varlena.c:2255
static int bpcharfastcmp_c(Datum x, Datum y, SortSupport ssup)
Definition: varlena.c:2210
static int namefastcmp_c(Datum x, Datum y, SortSupport ssup)
Definition: varlena.c:2243
static int namefastcmp_locale(Datum x, Datum y, SortSupport ssup)
Definition: varlena.c:2286
static Datum varstr_abbrev_convert(Datum original, SortSupport ssup)
Definition: varlena.c:2454
static int varstrfastcmp_c(Datum x, Datum y, SortSupport ssup)
Definition: varlena.c:2173

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, SortSupportData::comparator, VarStringSortSupport::full_card, GetDatabaseEncoding(), initHyperLogLog(), VarStringSortSupport::last_len1, VarStringSortSupport::last_len2, VarStringSortSupport::last_returned, lc_collate_is_c(), VarStringSortSupport::locale, locale, namefastcmp_c(), namefastcmp_locale(), palloc(), pg_newlocale_from_collation(), PG_UTF8, 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().