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.

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)
 

Function Documentation

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

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

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

4499 {
4500  text *ret_text;
4501  regex_t *re;
4502  int src_text_len = VARSIZE_ANY_EXHDR(src_text);
4503  int nmatches = 0;
4505  regmatch_t pmatch[10]; /* main match, plus \1 to \9 */
4506  int nmatch = lengthof(pmatch);
4507  pg_wchar *data;
4508  size_t data_len;
4509  int data_pos;
4510  char *start_ptr;
4511  int escape_status;
4512 
4513  initStringInfo(&buf);
4514 
4515  /* Convert data string to wide characters. */
4516  data = (pg_wchar *) palloc((src_text_len + 1) * sizeof(pg_wchar));
4517  data_len = pg_mb2wchar_with_len(VARDATA_ANY(src_text), data, src_text_len);
4518 
4519  /* Check whether replace_text has escapes, especially regexp submatches. */
4520  escape_status = check_replace_text_has_escape(replace_text);
4521 
4522  /* If no regexp submatches, we can use REG_NOSUB. */
4523  if (escape_status < 2)
4524  {
4525  cflags |= REG_NOSUB;
4526  /* Also tell pg_regexec we only want the whole-match location. */
4527  nmatch = 1;
4528  }
4529 
4530  /* Prepare the regexp. */
4531  re = RE_compile_and_cache(pattern_text, cflags, collation);
4532 
4533  /* start_ptr points to the data_pos'th character of src_text */
4534  start_ptr = (char *) VARDATA_ANY(src_text);
4535  data_pos = 0;
4536 
4537  while (search_start <= data_len)
4538  {
4539  int regexec_result;
4540 
4542 
4543  regexec_result = pg_regexec(re,
4544  data,
4545  data_len,
4546  search_start,
4547  NULL, /* no details */
4548  nmatch,
4549  pmatch,
4550  0);
4551 
4552  if (regexec_result == REG_NOMATCH)
4553  break;
4554 
4555  if (regexec_result != REG_OKAY)
4556  {
4557  char errMsg[100];
4558 
4560  pg_regerror(regexec_result, re, errMsg, sizeof(errMsg));
4561  ereport(ERROR,
4562  (errcode(ERRCODE_INVALID_REGULAR_EXPRESSION),
4563  errmsg("regular expression failed: %s", errMsg)));
4564  }
4565 
4566  /*
4567  * Count matches, and decide whether to replace this match.
4568  */
4569  nmatches++;
4570  if (n > 0 && nmatches != n)
4571  {
4572  /*
4573  * No, so advance search_start, but not start_ptr/data_pos. (Thus,
4574  * we treat the matched text as if it weren't matched, and copy it
4575  * to the output later.)
4576  */
4577  search_start = pmatch[0].rm_eo;
4578  if (pmatch[0].rm_so == pmatch[0].rm_eo)
4579  search_start++;
4580  continue;
4581  }
4582 
4583  /*
4584  * Copy the text to the left of the match position. Note we are given
4585  * character not byte indexes.
4586  */
4587  if (pmatch[0].rm_so - data_pos > 0)
4588  {
4589  int chunk_len;
4590 
4591  chunk_len = charlen_to_bytelen(start_ptr,
4592  pmatch[0].rm_so - data_pos);
4593  appendBinaryStringInfo(&buf, start_ptr, chunk_len);
4594 
4595  /*
4596  * Advance start_ptr over that text, to avoid multiple rescans of
4597  * it if the replace_text contains multiple back-references.
4598  */
4599  start_ptr += chunk_len;
4600  data_pos = pmatch[0].rm_so;
4601  }
4602 
4603  /*
4604  * Copy the replace_text, processing escapes if any are present.
4605  */
4606  if (escape_status > 0)
4607  appendStringInfoRegexpSubstr(&buf, replace_text, pmatch,
4608  start_ptr, data_pos);
4609  else
4610  appendStringInfoText(&buf, replace_text);
4611 
4612  /* Advance start_ptr and data_pos over the matched text. */
4613  start_ptr += charlen_to_bytelen(start_ptr,
4614  pmatch[0].rm_eo - data_pos);
4615  data_pos = pmatch[0].rm_eo;
4616 
4617  /*
4618  * If we only want to replace one occurrence, we're done.
4619  */
4620  if (n > 0)
4621  break;
4622 
4623  /*
4624  * Advance search position. Normally we start the next search at the
4625  * end of the previous match; but if the match was of zero length, we
4626  * have to advance by one character, or we'd just find the same match
4627  * again.
4628  */
4629  search_start = data_pos;
4630  if (pmatch[0].rm_so == pmatch[0].rm_eo)
4631  search_start++;
4632  }
4633 
4634  /*
4635  * Copy the text to the right of the last match.
4636  */
4637  if (data_pos < data_len)
4638  {
4639  int chunk_len;
4640 
4641  chunk_len = ((char *) src_text + VARSIZE_ANY(src_text)) - start_ptr;
4642  appendBinaryStringInfo(&buf, start_ptr, chunk_len);
4643  }
4644 
4645  ret_text = cstring_to_text_with_len(buf.data, buf.len);
4646  pfree(buf.data);
4647  pfree(data);
4648 
4649  return ret_text;
4650 }
#define VARDATA_ANY(PTR)
Definition: postgres.h:361
regoff_t rm_so
Definition: regex.h:87
static int check_replace_text_has_escape(const text *replace_text)
Definition: varlena.c:4362
int errcode(int sqlerrcode)
Definition: elog.c:698
#define lengthof(array)
Definition: c.h:734
regoff_t rm_eo
Definition: regex.h:88
void pfree(void *pointer)
Definition: mcxt.c:1169
#define REG_OKAY
Definition: regex.h:139
#define ERROR
Definition: elog.h:46
static int charlen_to_bytelen(const char *p, int n)
Definition: varlena.c:786
static void appendStringInfoText(StringInfo str, const text *t)
Definition: varlena.c:4271
static char * buf
Definition: pg_test_fsync.c:68
text * cstring_to_text_with_len(const char *s, int len)
Definition: varlena.c:201
size_t pg_regerror(int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size)
Definition: regerror.c:60
unsigned int pg_wchar
Definition: mbprint.c:31
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
#define VARSIZE_ANY(PTR)
Definition: postgres.h:348
int pg_mb2wchar_with_len(const char *from, pg_wchar *to, int len)
Definition: mbutils.c:929
#define ereport(elevel,...)
Definition: elog.h:157
#define REG_NOSUB
Definition: regex.h:109
static void appendStringInfoRegexpSubstr(StringInfo str, text *replace_text, regmatch_t *pmatch, char *start_ptr, int data_pos)
Definition: varlena.c:4395
regex_t * RE_compile_and_cache(text *text_re, int cflags, Oid collation)
Definition: regexp.c:138
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:176
#define VARSIZE_ANY_EXHDR(PTR)
Definition: postgres.h:354
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define REG_NOMATCH
Definition: regex.h:140
Definition: c.h:621
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:227
Definition: regex.h:55

◆ SplitDirectoriesString()

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

Definition at line 3873 of file varlena.c.

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

Referenced by load_libraries(), and PostmasterMain().

3875 {
3876  char *nextp = rawstring;
3877  bool done = false;
3878 
3879  *namelist = NIL;
3880 
3881  while (scanner_isspace(*nextp))
3882  nextp++; /* skip leading whitespace */
3883 
3884  if (*nextp == '\0')
3885  return true; /* allow empty string */
3886 
3887  /* At the top of the loop, we are at start of a new directory. */
3888  do
3889  {
3890  char *curname;
3891  char *endp;
3892 
3893  if (*nextp == '"')
3894  {
3895  /* Quoted name --- collapse quote-quote pairs */
3896  curname = nextp + 1;
3897  for (;;)
3898  {
3899  endp = strchr(nextp + 1, '"');
3900  if (endp == NULL)
3901  return false; /* mismatched quotes */
3902  if (endp[1] != '"')
3903  break; /* found end of quoted name */
3904  /* Collapse adjacent quotes into one quote, and look again */
3905  memmove(endp, endp + 1, strlen(endp));
3906  nextp = endp;
3907  }
3908  /* endp now points at the terminating quote */
3909  nextp = endp + 1;
3910  }
3911  else
3912  {
3913  /* Unquoted name --- extends to separator or end of string */
3914  curname = endp = nextp;
3915  while (*nextp && *nextp != separator)
3916  {
3917  /* trailing whitespace should not be included in name */
3918  if (!scanner_isspace(*nextp))
3919  endp = nextp + 1;
3920  nextp++;
3921  }
3922  if (curname == endp)
3923  return false; /* empty unquoted name not allowed */
3924  }
3925 
3926  while (scanner_isspace(*nextp))
3927  nextp++; /* skip trailing whitespace */
3928 
3929  if (*nextp == separator)
3930  {
3931  nextp++;
3932  while (scanner_isspace(*nextp))
3933  nextp++; /* skip leading whitespace for next */
3934  /* we expect another name, so done remains false */
3935  }
3936  else if (*nextp == '\0')
3937  done = true;
3938  else
3939  return false; /* invalid syntax */
3940 
3941  /* Now safe to overwrite separator with a null */
3942  *endp = '\0';
3943 
3944  /* Truncate path if it's overlength */
3945  if (strlen(curname) >= MAXPGPATH)
3946  curname[MAXPGPATH - 1] = '\0';
3947 
3948  /*
3949  * Finished isolating current name --- add it to list
3950  */
3951  curname = pstrdup(curname);
3952  canonicalize_path(curname);
3953  *namelist = lappend(*namelist, curname);
3954 
3955  /* Loop back if we didn't reach end of string */
3956  } while (!done);
3957 
3958  return true;
3959 }
#define NIL
Definition: pg_list.h:65
char * pstrdup(const char *in)
Definition: mcxt.c:1299
void canonicalize_path(char *path)
Definition: path.c:254
#define MAXPGPATH
List * lappend(List *list, void *datum)
Definition: list.c:336
bool scanner_isspace(char ch)
Definition: scansup.c:117

◆ SplitGUCList()

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

Definition at line 3994 of file varlena.c.

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

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

3996 {
3997  char *nextp = rawstring;
3998  bool done = false;
3999 
4000  *namelist = NIL;
4001 
4002  while (scanner_isspace(*nextp))
4003  nextp++; /* skip leading whitespace */
4004 
4005  if (*nextp == '\0')
4006  return true; /* allow empty string */
4007 
4008  /* At the top of the loop, we are at start of a new identifier. */
4009  do
4010  {
4011  char *curname;
4012  char *endp;
4013 
4014  if (*nextp == '"')
4015  {
4016  /* Quoted name --- collapse quote-quote pairs */
4017  curname = nextp + 1;
4018  for (;;)
4019  {
4020  endp = strchr(nextp + 1, '"');
4021  if (endp == NULL)
4022  return false; /* mismatched quotes */
4023  if (endp[1] != '"')
4024  break; /* found end of quoted name */
4025  /* Collapse adjacent quotes into one quote, and look again */
4026  memmove(endp, endp + 1, strlen(endp));
4027  nextp = endp;
4028  }
4029  /* endp now points at the terminating quote */
4030  nextp = endp + 1;
4031  }
4032  else
4033  {
4034  /* Unquoted name --- extends to separator or whitespace */
4035  curname = nextp;
4036  while (*nextp && *nextp != separator &&
4037  !scanner_isspace(*nextp))
4038  nextp++;
4039  endp = nextp;
4040  if (curname == nextp)
4041  return false; /* empty unquoted name not allowed */
4042  }
4043 
4044  while (scanner_isspace(*nextp))
4045  nextp++; /* skip trailing whitespace */
4046 
4047  if (*nextp == separator)
4048  {
4049  nextp++;
4050  while (scanner_isspace(*nextp))
4051  nextp++; /* skip leading whitespace for next */
4052  /* we expect another name, so done remains false */
4053  }
4054  else if (*nextp == '\0')
4055  done = true;
4056  else
4057  return false; /* invalid syntax */
4058 
4059  /* Now safe to overwrite separator with a null */
4060  *endp = '\0';
4061 
4062  /*
4063  * Finished isolating current name --- add it to list
4064  */
4065  *namelist = lappend(*namelist, curname);
4066 
4067  /* Loop back if we didn't reach end of string */
4068  } while (!done);
4069 
4070  return true;
4071 }
#define NIL
Definition: pg_list.h:65
List * lappend(List *list, void *datum)
Definition: list.c:336
bool scanner_isspace(char ch)
Definition: scansup.c:117

◆ SplitIdentifierString()

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

Definition at line 3746 of file varlena.c.

References Assert, downcase_truncate_identifier(), lappend(), 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().

3748 {
3749  char *nextp = rawstring;
3750  bool done = false;
3751 
3752  *namelist = NIL;
3753 
3754  while (scanner_isspace(*nextp))
3755  nextp++; /* skip leading whitespace */
3756 
3757  if (*nextp == '\0')
3758  return true; /* allow empty string */
3759 
3760  /* At the top of the loop, we are at start of a new identifier. */
3761  do
3762  {
3763  char *curname;
3764  char *endp;
3765 
3766  if (*nextp == '"')
3767  {
3768  /* Quoted name --- collapse quote-quote pairs, no downcasing */
3769  curname = nextp + 1;
3770  for (;;)
3771  {
3772  endp = strchr(nextp + 1, '"');
3773  if (endp == NULL)
3774  return false; /* mismatched quotes */
3775  if (endp[1] != '"')
3776  break; /* found end of quoted name */
3777  /* Collapse adjacent quotes into one quote, and look again */
3778  memmove(endp, endp + 1, strlen(endp));
3779  nextp = endp;
3780  }
3781  /* endp now points at the terminating quote */
3782  nextp = endp + 1;
3783  }
3784  else
3785  {
3786  /* Unquoted name --- extends to separator or whitespace */
3787  char *downname;
3788  int len;
3789 
3790  curname = nextp;
3791  while (*nextp && *nextp != separator &&
3792  !scanner_isspace(*nextp))
3793  nextp++;
3794  endp = nextp;
3795  if (curname == nextp)
3796  return false; /* empty unquoted name not allowed */
3797 
3798  /*
3799  * Downcase the identifier, using same code as main lexer does.
3800  *
3801  * XXX because we want to overwrite the input in-place, we cannot
3802  * support a downcasing transformation that increases the string
3803  * length. This is not a problem given the current implementation
3804  * of downcase_truncate_identifier, but we'll probably have to do
3805  * something about this someday.
3806  */
3807  len = endp - curname;
3808  downname = downcase_truncate_identifier(curname, len, false);
3809  Assert(strlen(downname) <= len);
3810  strncpy(curname, downname, len); /* strncpy is required here */
3811  pfree(downname);
3812  }
3813 
3814  while (scanner_isspace(*nextp))
3815  nextp++; /* skip trailing whitespace */
3816 
3817  if (*nextp == separator)
3818  {
3819  nextp++;
3820  while (scanner_isspace(*nextp))
3821  nextp++; /* skip leading whitespace for next */
3822  /* we expect another name, so done remains false */
3823  }
3824  else if (*nextp == '\0')
3825  done = true;
3826  else
3827  return false; /* invalid syntax */
3828 
3829  /* Now safe to overwrite separator with a null */
3830  *endp = '\0';
3831 
3832  /* Truncate name if it's overlength */
3833  truncate_identifier(curname, strlen(curname), false);
3834 
3835  /*
3836  * Finished isolating current name --- add it to list
3837  */
3838  *namelist = lappend(*namelist, curname);
3839 
3840  /* Loop back if we didn't reach end of string */
3841  } while (!done);
3842 
3843  return true;
3844 }
#define NIL
Definition: pg_list.h:65
char * downcase_truncate_identifier(const char *ident, int len, bool warn)
Definition: scansup.c:37
void truncate_identifier(char *ident, int len, bool warn)
Definition: scansup.c:93
void pfree(void *pointer)
Definition: mcxt.c:1169
List * lappend(List *list, void *datum)
Definition: list.c:336
bool scanner_isspace(char ch)
Definition: scansup.c:117
#define Assert(condition)
Definition: c.h:804

◆ textToQualifiedNameList()

List* textToQualifiedNameList ( text textval)

Definition at line 3688 of file varlena.c.

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

3689 {
3690  char *rawname;
3691  List *result = NIL;
3692  List *namelist;
3693  ListCell *l;
3694 
3695  /* Convert to C string (handles possible detoasting). */
3696  /* Note we rely on being able to modify rawname below. */
3697  rawname = text_to_cstring(textval);
3698 
3699  if (!SplitIdentifierString(rawname, '.', &namelist))
3700  ereport(ERROR,
3701  (errcode(ERRCODE_INVALID_NAME),
3702  errmsg("invalid name syntax")));
3703 
3704  if (namelist == NIL)
3705  ereport(ERROR,
3706  (errcode(ERRCODE_INVALID_NAME),
3707  errmsg("invalid name syntax")));
3708 
3709  foreach(l, namelist)
3710  {
3711  char *curname = (char *) lfirst(l);
3712 
3713  result = lappend(result, makeString(pstrdup(curname)));
3714  }
3715 
3716  pfree(rawname);
3717  list_free(namelist);
3718 
3719  return result;
3720 }
#define NIL
Definition: pg_list.h:65
char * pstrdup(const char *in)
Definition: mcxt.c:1299
int errcode(int sqlerrcode)
Definition: elog.c:698
String * makeString(char *str)
Definition: value.c:51
void pfree(void *pointer)
Definition: mcxt.c:1169
#define ERROR
Definition: elog.h:46
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3746
List * lappend(List *list, void *datum)
Definition: list.c:336
#define ereport(elevel,...)
Definition: elog.h:157
#define lfirst(lc)
Definition: pg_list.h:169
char * text_to_cstring(const text *t)
Definition: varlena.c:222
int errmsg(const char *fmt,...)
Definition: elog.c:909
void list_free(List *list)
Definition: list.c:1391
Definition: pg_list.h:50

◆ varstr_cmp()

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

Definition at line 1535 of file varlena.c.

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

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

◆ 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.

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

Referenced by levenshtein(), and levenshtein_with_costs().

78 {
79  int m,
80  n;
81  int *prev;
82  int *curr;
83  int *s_char_len = NULL;
84  int i,
85  j;
86  const char *y;
87 
88  /*
89  * For varstr_levenshtein_less_equal, we have real variables called
90  * start_column and stop_column; otherwise it's just short-hand for 0 and
91  * m.
92  */
93 #ifdef LEVENSHTEIN_LESS_EQUAL
94  int start_column,
95  stop_column;
96 
97 #undef START_COLUMN
98 #undef STOP_COLUMN
99 #define START_COLUMN start_column
100 #define STOP_COLUMN stop_column
101 #else
102 #undef START_COLUMN
103 #undef STOP_COLUMN
104 #define START_COLUMN 0
105 #define STOP_COLUMN m
106 #endif
107 
108  /* Convert string lengths (in bytes) to lengths in characters */
109  m = pg_mbstrlen_with_len(source, slen);
110  n = pg_mbstrlen_with_len(target, tlen);
111 
112  /*
113  * We can transform an empty s into t with n insertions, or a non-empty t
114  * into an empty s with m deletions.
115  */
116  if (!m)
117  return n * ins_c;
118  if (!n)
119  return m * del_c;
120 
121  /*
122  * For security concerns, restrict excessive CPU+RAM usage. (This
123  * implementation uses O(m) memory and has O(mn) complexity.) If
124  * "trusted" is true, caller is responsible for not making excessive
125  * requests, typically by using a small max_d along with strings that are
126  * bounded, though not necessarily to MAX_LEVENSHTEIN_STRLEN exactly.
127  */
128  if (!trusted &&
129  (m > MAX_LEVENSHTEIN_STRLEN ||
131  ereport(ERROR,
132  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
133  errmsg("levenshtein argument exceeds maximum length of %d characters",
135 
136 #ifdef LEVENSHTEIN_LESS_EQUAL
137  /* Initialize start and stop columns. */
138  start_column = 0;
139  stop_column = m + 1;
140 
141  /*
142  * If max_d >= 0, determine whether the bound is impossibly tight. If so,
143  * return max_d + 1 immediately. Otherwise, determine whether it's tight
144  * enough to limit the computation we must perform. If so, figure out
145  * initial stop column.
146  */
147  if (max_d >= 0)
148  {
149  int min_theo_d; /* Theoretical minimum distance. */
150  int max_theo_d; /* Theoretical maximum distance. */
151  int net_inserts = n - m;
152 
153  min_theo_d = net_inserts < 0 ?
154  -net_inserts * del_c : net_inserts * ins_c;
155  if (min_theo_d > max_d)
156  return max_d + 1;
157  if (ins_c + del_c < sub_c)
158  sub_c = ins_c + del_c;
159  max_theo_d = min_theo_d + sub_c * Min(m, n);
160  if (max_d >= max_theo_d)
161  max_d = -1;
162  else if (ins_c + del_c > 0)
163  {
164  /*
165  * Figure out how much of the first row of the notional matrix we
166  * need to fill in. If the string is growing, the theoretical
167  * minimum distance already incorporates the cost of deleting the
168  * number of characters necessary to make the two strings equal in
169  * length. Each additional deletion forces another insertion, so
170  * the best-case total cost increases by ins_c + del_c. If the
171  * string is shrinking, the minimum theoretical cost assumes no
172  * excess deletions; that is, we're starting no further right than
173  * column n - m. If we do start further right, the best-case
174  * total cost increases by ins_c + del_c for each move right.
175  */
176  int slack_d = max_d - min_theo_d;
177  int best_column = net_inserts < 0 ? -net_inserts : 0;
178 
179  stop_column = best_column + (slack_d / (ins_c + del_c)) + 1;
180  if (stop_column > m)
181  stop_column = m + 1;
182  }
183  }
184 #endif
185 
186  /*
187  * In order to avoid calling pg_mblen() repeatedly on each character in s,
188  * we cache all the lengths before starting the main loop -- but if all
189  * the characters in both strings are single byte, then we skip this and
190  * use a fast-path in the main loop. If only one string contains
191  * multi-byte characters, we still build the array, so that the fast-path
192  * needn't deal with the case where the array hasn't been initialized.
193  */
194  if (m != slen || n != tlen)
195  {
196  int i;
197  const char *cp = source;
198 
199  s_char_len = (int *) palloc((m + 1) * sizeof(int));
200  for (i = 0; i < m; ++i)
201  {
202  s_char_len[i] = pg_mblen(cp);
203  cp += s_char_len[i];
204  }
205  s_char_len[i] = 0;
206  }
207 
208  /* One more cell for initialization column and row. */
209  ++m;
210  ++n;
211 
212  /* Previous and current rows of notional array. */
213  prev = (int *) palloc(2 * m * sizeof(int));
214  curr = prev + m;
215 
216  /*
217  * To transform the first i characters of s into the first 0 characters of
218  * t, we must perform i deletions.
219  */
220  for (i = START_COLUMN; i < STOP_COLUMN; i++)
221  prev[i] = i * del_c;
222 
223  /* Loop through rows of the notional array */
224  for (y = target, j = 1; j < n; j++)
225  {
226  int *temp;
227  const char *x = source;
228  int y_char_len = n != tlen + 1 ? pg_mblen(y) : 1;
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 }
#define Min(x, y)
Definition: c.h:986
int errcode(int sqlerrcode)
Definition: elog.c:698
int pg_mbstrlen_with_len(const char *mbstr, int limit)
Definition: mbutils.c:1000
#define STOP_COLUMN
#define ERROR
Definition: elog.h:46
#define START_COLUMN
#define ereport(elevel,...)
Definition: elog.h:157
#define MAX_LEVENSHTEIN_STRLEN
Definition: levenshtein.c:26
static rewind_source * source
Definition: pg_rewind.c:79
static bool rest_of_char_same(const char *s1, const char *s2, int len)
Definition: varlena.c:6238
int pg_mblen(const char *mbstr)
Definition: mbutils.c:966
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
int i

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

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, pg_locale_struct::provider, SortSupportData::ssup_extra, TEXTBUFLEN, VarStringSortSupport::typid, varlenafastcmp_locale(), varstr_abbrev_abort(), varstr_abbrev_convert(), varstrcmp_abbrev(), and varstrfastcmp_c().

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

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