PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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 (char *arg1, int len1, char *arg2, int len2, Oid collid)
 
void varstr_sortsupport (SortSupport ssup, Oid collid, bool bpchar)
 
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)
 
textreplace_text_regexp (text *src_text, void *regexp, text *replace_text, bool glob)
 

Function Documentation

text* replace_text_regexp ( text src_text,
void *  regexp,
text replace_text,
bool  glob 
)

Definition at line 3775 of file varlena.c.

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

Referenced by textregexreplace(), and textregexreplace_noopt().

3777 {
3778  text *ret_text;
3779  regex_t *re = (regex_t *) regexp;
3780  int src_text_len = VARSIZE_ANY_EXHDR(src_text);
3783  pg_wchar *data;
3784  size_t data_len;
3785  int search_start;
3786  int data_pos;
3787  char *start_ptr;
3788  bool have_escape;
3789 
3790  initStringInfo(&buf);
3791 
3792  /* Convert data string to wide characters. */
3793  data = (pg_wchar *) palloc((src_text_len + 1) * sizeof(pg_wchar));
3794  data_len = pg_mb2wchar_with_len(VARDATA_ANY(src_text), data, src_text_len);
3795 
3796  /* Check whether replace_text has escape char. */
3797  have_escape = check_replace_text_has_escape_char(replace_text);
3798 
3799  /* start_ptr points to the data_pos'th character of src_text */
3800  start_ptr = (char *) VARDATA_ANY(src_text);
3801  data_pos = 0;
3802 
3803  search_start = 0;
3804  while (search_start <= data_len)
3805  {
3806  int regexec_result;
3807 
3809 
3810  regexec_result = pg_regexec(re,
3811  data,
3812  data_len,
3813  search_start,
3814  NULL, /* no details */
3816  pmatch,
3817  0);
3818 
3819  if (regexec_result == REG_NOMATCH)
3820  break;
3821 
3822  if (regexec_result != REG_OKAY)
3823  {
3824  char errMsg[100];
3825 
3827  pg_regerror(regexec_result, re, errMsg, sizeof(errMsg));
3828  ereport(ERROR,
3829  (errcode(ERRCODE_INVALID_REGULAR_EXPRESSION),
3830  errmsg("regular expression failed: %s", errMsg)));
3831  }
3832 
3833  /*
3834  * Copy the text to the left of the match position. Note we are given
3835  * character not byte indexes.
3836  */
3837  if (pmatch[0].rm_so - data_pos > 0)
3838  {
3839  int chunk_len;
3840 
3841  chunk_len = charlen_to_bytelen(start_ptr,
3842  pmatch[0].rm_so - data_pos);
3843  appendBinaryStringInfo(&buf, start_ptr, chunk_len);
3844 
3845  /*
3846  * Advance start_ptr over that text, to avoid multiple rescans of
3847  * it if the replace_text contains multiple back-references.
3848  */
3849  start_ptr += chunk_len;
3850  data_pos = pmatch[0].rm_so;
3851  }
3852 
3853  /*
3854  * Copy the replace_text. Process back references when the
3855  * replace_text has escape characters.
3856  */
3857  if (have_escape)
3858  appendStringInfoRegexpSubstr(&buf, replace_text, pmatch,
3859  start_ptr, data_pos);
3860  else
3861  appendStringInfoText(&buf, replace_text);
3862 
3863  /* Advance start_ptr and data_pos over the matched text. */
3864  start_ptr += charlen_to_bytelen(start_ptr,
3865  pmatch[0].rm_eo - data_pos);
3866  data_pos = pmatch[0].rm_eo;
3867 
3868  /*
3869  * When global option is off, replace the first instance only.
3870  */
3871  if (!glob)
3872  break;
3873 
3874  /*
3875  * Advance search position. Normally we start the next search at the
3876  * end of the previous match; but if the match was of zero length, we
3877  * have to advance by one character, or we'd just find the same match
3878  * again.
3879  */
3880  search_start = data_pos;
3881  if (pmatch[0].rm_so == pmatch[0].rm_eo)
3882  search_start++;
3883  }
3884 
3885  /*
3886  * Copy the text to the right of the last match.
3887  */
3888  if (data_pos < data_len)
3889  {
3890  int chunk_len;
3891 
3892  chunk_len = ((char *) src_text + VARSIZE_ANY(src_text)) - start_ptr;
3893  appendBinaryStringInfo(&buf, start_ptr, chunk_len);
3894  }
3895 
3896  ret_text = cstring_to_text_with_len(buf.data, buf.len);
3897  pfree(buf.data);
3898  pfree(data);
3899 
3900  return ret_text;
3901 }
#define VARDATA_ANY(PTR)
Definition: postgres.h:349
regoff_t rm_so
Definition: regex.h:85
int errcode(int sqlerrcode)
Definition: elog.c:575
regoff_t rm_eo
Definition: regex.h:86
void pfree(void *pointer)
Definition: mcxt.c:992
#define REG_OKAY
Definition: regex.h:137
#define ERROR
Definition: elog.h:43
static bool check_replace_text_has_escape_char(const text *replace_text)
Definition: varlena.c:3637
static int charlen_to_bytelen(const char *p, int n)
Definition: varlena.c:737
static void appendStringInfoText(StringInfo str, const text *t)
Definition: varlena.c:3540
static char * buf
Definition: pg_test_fsync.c:65
text * cstring_to_text_with_len(const char *s, int len)
Definition: varlena.c:163
size_t pg_regerror(int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size)
Definition: regerror.c:60
#define ereport(elevel, rest)
Definition: elog.h:122
unsigned int pg_wchar
Definition: mbprint.c:31
void initStringInfo(StringInfo str)
Definition: stringinfo.c:65
#define REGEXP_REPLACE_BACKREF_CNT
Definition: varlena.c:3764
#define VARSIZE_ANY(PTR)
Definition: postgres.h:336
int pg_mb2wchar_with_len(const char *from, pg_wchar *to, int len)
Definition: mbutils.c:734
#define NULL
Definition: c.h:226
static void appendStringInfoRegexpSubstr(StringInfo str, text *replace_text, regmatch_t *pmatch, char *start_ptr, int data_pos)
Definition: varlena.c:3670
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:172
#define VARSIZE_ANY_EXHDR(PTR)
Definition: postgres.h:342
void * palloc(Size size)
Definition: mcxt.c:891
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define REG_NOMATCH
Definition: regex.h:138
Definition: c.h:435
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:240
Definition: regex.h:55
bool SplitDirectoriesString ( char *  rawstring,
char  separator,
List **  namelist 
)

Definition at line 3254 of file varlena.c.

References canonicalize_path(), lappend(), MAXPGPATH, memmove, NIL, NULL, and pstrdup().

Referenced by PostmasterMain().

3256 {
3257  char *nextp = rawstring;
3258  bool done = false;
3259 
3260  *namelist = NIL;
3261 
3262  while (isspace((unsigned char) *nextp))
3263  nextp++; /* skip leading whitespace */
3264 
3265  if (*nextp == '\0')
3266  return true; /* allow empty string */
3267 
3268  /* At the top of the loop, we are at start of a new directory. */
3269  do
3270  {
3271  char *curname;
3272  char *endp;
3273 
3274  if (*nextp == '"')
3275  {
3276  /* Quoted name --- collapse quote-quote pairs */
3277  curname = nextp + 1;
3278  for (;;)
3279  {
3280  endp = strchr(nextp + 1, '"');
3281  if (endp == NULL)
3282  return false; /* mismatched quotes */
3283  if (endp[1] != '"')
3284  break; /* found end of quoted name */
3285  /* Collapse adjacent quotes into one quote, and look again */
3286  memmove(endp, endp + 1, strlen(endp));
3287  nextp = endp;
3288  }
3289  /* endp now points at the terminating quote */
3290  nextp = endp + 1;
3291  }
3292  else
3293  {
3294  /* Unquoted name --- extends to separator or end of string */
3295  curname = endp = nextp;
3296  while (*nextp && *nextp != separator)
3297  {
3298  /* trailing whitespace should not be included in name */
3299  if (!isspace((unsigned char) *nextp))
3300  endp = nextp + 1;
3301  nextp++;
3302  }
3303  if (curname == endp)
3304  return false; /* empty unquoted name not allowed */
3305  }
3306 
3307  while (isspace((unsigned char) *nextp))
3308  nextp++; /* skip trailing whitespace */
3309 
3310  if (*nextp == separator)
3311  {
3312  nextp++;
3313  while (isspace((unsigned char) *nextp))
3314  nextp++; /* skip leading whitespace for next */
3315  /* we expect another name, so done remains false */
3316  }
3317  else if (*nextp == '\0')
3318  done = true;
3319  else
3320  return false; /* invalid syntax */
3321 
3322  /* Now safe to overwrite separator with a null */
3323  *endp = '\0';
3324 
3325  /* Truncate path if it's overlength */
3326  if (strlen(curname) >= MAXPGPATH)
3327  curname[MAXPGPATH - 1] = '\0';
3328 
3329  /*
3330  * Finished isolating current name --- add it to list
3331  */
3332  curname = pstrdup(curname);
3333  canonicalize_path(curname);
3334  *namelist = lappend(*namelist, curname);
3335 
3336  /* Loop back if we didn't reach end of string */
3337  } while (!done);
3338 
3339  return true;
3340 }
#define NIL
Definition: pg_list.h:69
char * pstrdup(const char *in)
Definition: mcxt.c:1165
void canonicalize_path(char *path)
Definition: path.c:254
#define MAXPGPATH
#define memmove(d, s, c)
Definition: c.h:1058
List * lappend(List *list, void *datum)
Definition: list.c:128
#define NULL
Definition: c.h:226
bool SplitIdentifierString ( char *  rawstring,
char  separator,
List **  namelist 
)

Definition at line 3129 of file varlena.c.

References Assert, downcase_truncate_identifier(), lappend(), memmove, NIL, NULL, pfree(), and truncate_identifier().

Referenced by check_datestyle(), check_log_destination(), check_search_path(), check_temp_tablespaces(), check_wal_consistency_checking(), ExtractExtensionList(), load_libraries(), parse_extension_control_file(), parse_output_parameters(), plpgsql_extra_checks_check_hook(), PostmasterMain(), PrepareTempTablespaces(), recomputeNamespacePath(), stringToQualifiedNameList(), and textToQualifiedNameList().

3131 {
3132  char *nextp = rawstring;
3133  bool done = false;
3134 
3135  *namelist = NIL;
3136 
3137  while (isspace((unsigned char) *nextp))
3138  nextp++; /* skip leading whitespace */
3139 
3140  if (*nextp == '\0')
3141  return true; /* allow empty string */
3142 
3143  /* At the top of the loop, we are at start of a new identifier. */
3144  do
3145  {
3146  char *curname;
3147  char *endp;
3148 
3149  if (*nextp == '"')
3150  {
3151  /* Quoted name --- collapse quote-quote pairs, no downcasing */
3152  curname = nextp + 1;
3153  for (;;)
3154  {
3155  endp = strchr(nextp + 1, '"');
3156  if (endp == NULL)
3157  return false; /* mismatched quotes */
3158  if (endp[1] != '"')
3159  break; /* found end of quoted name */
3160  /* Collapse adjacent quotes into one quote, and look again */
3161  memmove(endp, endp + 1, strlen(endp));
3162  nextp = endp;
3163  }
3164  /* endp now points at the terminating quote */
3165  nextp = endp + 1;
3166  }
3167  else
3168  {
3169  /* Unquoted name --- extends to separator or whitespace */
3170  char *downname;
3171  int len;
3172 
3173  curname = nextp;
3174  while (*nextp && *nextp != separator &&
3175  !isspace((unsigned char) *nextp))
3176  nextp++;
3177  endp = nextp;
3178  if (curname == nextp)
3179  return false; /* empty unquoted name not allowed */
3180 
3181  /*
3182  * Downcase the identifier, using same code as main lexer does.
3183  *
3184  * XXX because we want to overwrite the input in-place, we cannot
3185  * support a downcasing transformation that increases the string
3186  * length. This is not a problem given the current implementation
3187  * of downcase_truncate_identifier, but we'll probably have to do
3188  * something about this someday.
3189  */
3190  len = endp - curname;
3191  downname = downcase_truncate_identifier(curname, len, false);
3192  Assert(strlen(downname) <= len);
3193  strncpy(curname, downname, len); /* strncpy is required here */
3194  pfree(downname);
3195  }
3196 
3197  while (isspace((unsigned char) *nextp))
3198  nextp++; /* skip trailing whitespace */
3199 
3200  if (*nextp == separator)
3201  {
3202  nextp++;
3203  while (isspace((unsigned char) *nextp))
3204  nextp++; /* skip leading whitespace for next */
3205  /* we expect another name, so done remains false */
3206  }
3207  else if (*nextp == '\0')
3208  done = true;
3209  else
3210  return false; /* invalid syntax */
3211 
3212  /* Now safe to overwrite separator with a null */
3213  *endp = '\0';
3214 
3215  /* Truncate name if it's overlength */
3216  truncate_identifier(curname, strlen(curname), false);
3217 
3218  /*
3219  * Finished isolating current name --- add it to list
3220  */
3221  *namelist = lappend(*namelist, curname);
3222 
3223  /* Loop back if we didn't reach end of string */
3224  } while (!done);
3225 
3226  return true;
3227 }
#define NIL
Definition: pg_list.h:69
char * downcase_truncate_identifier(const char *ident, int len, bool warn)
Definition: scansup.c:131
void truncate_identifier(char *ident, int len, bool warn)
Definition: scansup.c:187
void pfree(void *pointer)
Definition: mcxt.c:992
#define memmove(d, s, c)
Definition: c.h:1058
List * lappend(List *list, void *datum)
Definition: list.c:128
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
List* textToQualifiedNameList ( text textval)

Definition at line 3071 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(), bt_page_stats(), 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().

3072 {
3073  char *rawname;
3074  List *result = NIL;
3075  List *namelist;
3076  ListCell *l;
3077 
3078  /* Convert to C string (handles possible detoasting). */
3079  /* Note we rely on being able to modify rawname below. */
3080  rawname = text_to_cstring(textval);
3081 
3082  if (!SplitIdentifierString(rawname, '.', &namelist))
3083  ereport(ERROR,
3084  (errcode(ERRCODE_INVALID_NAME),
3085  errmsg("invalid name syntax")));
3086 
3087  if (namelist == NIL)
3088  ereport(ERROR,
3089  (errcode(ERRCODE_INVALID_NAME),
3090  errmsg("invalid name syntax")));
3091 
3092  foreach(l, namelist)
3093  {
3094  char *curname = (char *) lfirst(l);
3095 
3096  result = lappend(result, makeString(pstrdup(curname)));
3097  }
3098 
3099  pfree(rawname);
3100  list_free(namelist);
3101 
3102  return result;
3103 }
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:69
char * pstrdup(const char *in)
Definition: mcxt.c:1165
int errcode(int sqlerrcode)
Definition: elog.c:575
void pfree(void *pointer)
Definition: mcxt.c:992
#define ERROR
Definition: elog.h:43
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3129
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
#define lfirst(lc)
Definition: pg_list.h:106
char * text_to_cstring(const text *t)
Definition: varlena.c:184
int errmsg(const char *fmt,...)
Definition: elog.c:797
void list_free(List *list)
Definition: list.c:1133
Definition: pg_list.h:45
int varstr_cmp ( char *  arg1,
int  len1,
char *  arg2,
int  len2,
Oid  collid 
)

Definition at line 1384 of file varlena.c.

References DEFAULT_COLLATION_OID, ereport, errcode(), errhint(), errmsg(), ERROR, GetDatabaseEncoding(), lc_collate_is_c(), Min, OidIsValid, palloc(), pfree(), pg_newlocale_from_collation(), PG_UTF8, strcoll_l, TEXTBUFLEN, and wcscoll_l.

Referenced by bpchar_larger(), bpchar_smaller(), bpcharcmp(), bpcharge(), bpchargt(), bpcharle(), bpcharlt(), citextcmp(), compareJsonbScalarValue(), gin_compare_jsonb(), make_greater_string(), spg_text_leaf_consistent(), and text_cmp().

1385 {
1386  int result;
1387 
1388  /*
1389  * Unfortunately, there is no strncoll(), so in the non-C locale case we
1390  * have to do some memory copying. This turns out to be significantly
1391  * slower, so we optimize the case where LC_COLLATE is C. We also try to
1392  * optimize relatively-short strings by avoiding palloc/pfree overhead.
1393  */
1394  if (lc_collate_is_c(collid))
1395  {
1396  result = memcmp(arg1, arg2, Min(len1, len2));
1397  if ((result == 0) && (len1 != len2))
1398  result = (len1 < len2) ? -1 : 1;
1399  }
1400  else
1401  {
1402  char a1buf[TEXTBUFLEN];
1403  char a2buf[TEXTBUFLEN];
1404  char *a1p,
1405  *a2p;
1406 
1407 #ifdef HAVE_LOCALE_T
1408  pg_locale_t mylocale = 0;
1409 #endif
1410 
1411  if (collid != DEFAULT_COLLATION_OID)
1412  {
1413  if (!OidIsValid(collid))
1414  {
1415  /*
1416  * This typically means that the parser could not resolve a
1417  * conflict of implicit collations, so report it that way.
1418  */
1419  ereport(ERROR,
1420  (errcode(ERRCODE_INDETERMINATE_COLLATION),
1421  errmsg("could not determine which collation to use for string comparison"),
1422  errhint("Use the COLLATE clause to set the collation explicitly.")));
1423  }
1424 #ifdef HAVE_LOCALE_T
1425  mylocale = pg_newlocale_from_collation(collid);
1426 #endif
1427  }
1428 
1429  /*
1430  * memcmp() can't tell us which of two unequal strings sorts first,
1431  * but it's a cheap way to tell if they're equal. Testing shows that
1432  * memcmp() followed by strcoll() is only trivially slower than
1433  * strcoll() by itself, so we don't lose much if this doesn't work out
1434  * very often, and if it does - for example, because there are many
1435  * equal strings in the input - then we win big by avoiding expensive
1436  * collation-aware comparisons.
1437  */
1438  if (len1 == len2 && memcmp(arg1, arg2, len1) == 0)
1439  return 0;
1440 
1441 #ifdef WIN32
1442  /* Win32 does not have UTF-8, so we need to map to UTF-16 */
1443  if (GetDatabaseEncoding() == PG_UTF8)
1444  {
1445  int a1len;
1446  int a2len;
1447  int r;
1448 
1449  if (len1 >= TEXTBUFLEN / 2)
1450  {
1451  a1len = len1 * 2 + 2;
1452  a1p = palloc(a1len);
1453  }
1454  else
1455  {
1456  a1len = TEXTBUFLEN;
1457  a1p = a1buf;
1458  }
1459  if (len2 >= TEXTBUFLEN / 2)
1460  {
1461  a2len = len2 * 2 + 2;
1462  a2p = palloc(a2len);
1463  }
1464  else
1465  {
1466  a2len = TEXTBUFLEN;
1467  a2p = a2buf;
1468  }
1469 
1470  /* stupid Microsloth API does not work for zero-length input */
1471  if (len1 == 0)
1472  r = 0;
1473  else
1474  {
1475  r = MultiByteToWideChar(CP_UTF8, 0, arg1, len1,
1476  (LPWSTR) a1p, a1len / 2);
1477  if (!r)
1478  ereport(ERROR,
1479  (errmsg("could not convert string to UTF-16: error code %lu",
1480  GetLastError())));
1481  }
1482  ((LPWSTR) a1p)[r] = 0;
1483 
1484  if (len2 == 0)
1485  r = 0;
1486  else
1487  {
1488  r = MultiByteToWideChar(CP_UTF8, 0, arg2, len2,
1489  (LPWSTR) a2p, a2len / 2);
1490  if (!r)
1491  ereport(ERROR,
1492  (errmsg("could not convert string to UTF-16: error code %lu",
1493  GetLastError())));
1494  }
1495  ((LPWSTR) a2p)[r] = 0;
1496 
1497  errno = 0;
1498 #ifdef HAVE_LOCALE_T
1499  if (mylocale)
1500  result = wcscoll_l((LPWSTR) a1p, (LPWSTR) a2p, mylocale);
1501  else
1502 #endif
1503  result = wcscoll((LPWSTR) a1p, (LPWSTR) a2p);
1504  if (result == 2147483647) /* _NLSCMPERROR; missing from mingw
1505  * headers */
1506  ereport(ERROR,
1507  (errmsg("could not compare Unicode strings: %m")));
1508 
1509  /*
1510  * In some locales wcscoll() can claim that nonidentical strings
1511  * are equal. Believing that would be bad news for a number of
1512  * reasons, so we follow Perl's lead and sort "equal" strings
1513  * according to strcmp (on the UTF-8 representation).
1514  */
1515  if (result == 0)
1516  {
1517  result = memcmp(arg1, arg2, Min(len1, len2));
1518  if ((result == 0) && (len1 != len2))
1519  result = (len1 < len2) ? -1 : 1;
1520  }
1521 
1522  if (a1p != a1buf)
1523  pfree(a1p);
1524  if (a2p != a2buf)
1525  pfree(a2p);
1526 
1527  return result;
1528  }
1529 #endif /* WIN32 */
1530 
1531  if (len1 >= TEXTBUFLEN)
1532  a1p = (char *) palloc(len1 + 1);
1533  else
1534  a1p = a1buf;
1535  if (len2 >= TEXTBUFLEN)
1536  a2p = (char *) palloc(len2 + 1);
1537  else
1538  a2p = a2buf;
1539 
1540  memcpy(a1p, arg1, len1);
1541  a1p[len1] = '\0';
1542  memcpy(a2p, arg2, len2);
1543  a2p[len2] = '\0';
1544 
1545 #ifdef HAVE_LOCALE_T
1546  if (mylocale)
1547  result = strcoll_l(a1p, a2p, mylocale);
1548  else
1549 #endif
1550  result = strcoll(a1p, a2p);
1551 
1552  /*
1553  * In some locales strcoll() can claim that nonidentical strings are
1554  * equal. Believing that would be bad news for a number of reasons,
1555  * so we follow Perl's lead and sort "equal" strings according to
1556  * strcmp().
1557  */
1558  if (result == 0)
1559  result = strcmp(a1p, a2p);
1560 
1561  if (a1p != a1buf)
1562  pfree(a1p);
1563  if (a2p != a2buf)
1564  pfree(a2p);
1565  }
1566 
1567  return result;
1568 }
int errhint(const char *fmt,...)
Definition: elog.c:987
#define Min(x, y)
Definition: c.h:802
int errcode(int sqlerrcode)
Definition: elog.c:575
#define OidIsValid(objectId)
Definition: c.h:534
int pg_locale_t
Definition: pg_locale.h:71
#define wcscoll_l
Definition: win32.h:358
void pfree(void *pointer)
Definition: mcxt.c:992
#define ERROR
Definition: elog.h:43
bool lc_collate_is_c(Oid collation)
Definition: pg_locale.c:1123
#define DEFAULT_COLLATION_OID
Definition: pg_collation.h:68
#define ereport(elevel, rest)
Definition: elog.h:122
pg_locale_t pg_newlocale_from_collation(Oid collid)
Definition: pg_locale.c:1260
int GetDatabaseEncoding(void)
Definition: mbutils.c:1015
#define TEXTBUFLEN
Definition: varlena.c:85
void * palloc(Size size)
Definition: mcxt.c:891
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define strcoll_l
Definition: win32.h:356
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, NULL, palloc(), pg_mblen(), pg_mbstrlen_with_len(), rest_of_char_same(), 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:802
int errcode(int sqlerrcode)
Definition: elog.c:575
int pg_mbstrlen_with_len(const char *mbstr, int limit)
Definition: mbutils.c:805
#define STOP_COLUMN
#define ERROR
Definition: elog.h:43
#define START_COLUMN
#define ereport(elevel, rest)
Definition: elog.h:122
#define NULL
Definition: c.h:226
#define MAX_LEVENSHTEIN_STRLEN
Definition: levenshtein.c:26
static bool rest_of_char_same(const char *s1, const char *s2, int len)
Definition: varlena.c:5327
int pg_mblen(const char *mbstr)
Definition: mbutils.c:771
void * palloc(Size size)
Definition: mcxt.c:891
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
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 
)
void varstr_sortsupport ( SortSupport  ssup,
Oid  collid,
bool  bpchar 
)

Definition at line 1766 of file varlena.c.

References VarStringSortSupport::abbr_card, SortSupportData::abbrev_abort, SortSupportData::abbrev_converter, SortSupportData::abbrev_full_comparator, SortSupportData::abbreviate, VarStringSortSupport::bpchar, bpchar(), bpcharfastcmp_c(), VarStringSortSupport::buf1, VarStringSortSupport::buf2, VarStringSortSupport::buflen1, VarStringSortSupport::buflen2, VarStringSortSupport::cache_blob, VarStringSortSupport::collate_c, SortSupportData::comparator, DEFAULT_COLLATION_OID, ereport, errcode(), errhint(), errmsg(), ERROR, VarStringSortSupport::full_card, GetDatabaseEncoding(), initHyperLogLog(), VarStringSortSupport::last_len1, VarStringSortSupport::last_len2, VarStringSortSupport::last_returned, lc_collate_is_c(), locale, OidIsValid, palloc(), pg_newlocale_from_collation(), PG_UTF8, VarStringSortSupport::prop_card, SortSupportData::ssup_extra, TEXTBUFLEN, varstr_abbrev_abort(), varstr_abbrev_convert(), varstrcmp_abbrev(), varstrfastcmp_c(), and varstrfastcmp_locale().

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

1767 {
1768  bool abbreviate = ssup->abbreviate;
1769  bool collate_c = false;
1770  VarStringSortSupport *sss;
1771 
1772 #ifdef HAVE_LOCALE_T
1773  pg_locale_t locale = 0;
1774 #endif
1775 
1776  /*
1777  * If possible, set ssup->comparator to a function which can be used to
1778  * directly compare two datums. If we can do this, we'll avoid the
1779  * overhead of a trip through the fmgr layer for every comparison, which
1780  * can be substantial.
1781  *
1782  * Most typically, we'll set the comparator to varstrfastcmp_locale, which
1783  * uses strcoll() to perform comparisons and knows about the special
1784  * requirements of BpChar callers. However, if LC_COLLATE = C, we can
1785  * make things quite a bit faster with varstrfastcmp_c or bpcharfastcmp_c,
1786  * both of which use memcmp() rather than strcoll().
1787  *
1788  * There is a further exception on Windows. When the database encoding is
1789  * UTF-8 and we are not using the C collation, complex hacks are required.
1790  * We don't currently have a comparator that handles that case, so we fall
1791  * back on the slow method of having the sort code invoke bttextcmp() (in
1792  * the case of text) via the fmgr trampoline.
1793  */
1794  if (lc_collate_is_c(collid))
1795  {
1796  if (!bpchar)
1797  ssup->comparator = varstrfastcmp_c;
1798  else
1799  ssup->comparator = bpcharfastcmp_c;
1800 
1801  collate_c = true;
1802  }
1803 #ifdef WIN32
1804  else if (GetDatabaseEncoding() == PG_UTF8)
1805  return;
1806 #endif
1807  else
1808  {
1810 
1811  /*
1812  * We need a collation-sensitive comparison. To make things faster,
1813  * we'll figure out the collation based on the locale id and cache the
1814  * result.
1815  */
1816  if (collid != DEFAULT_COLLATION_OID)
1817  {
1818  if (!OidIsValid(collid))
1819  {
1820  /*
1821  * This typically means that the parser could not resolve a
1822  * conflict of implicit collations, so report it that way.
1823  */
1824  ereport(ERROR,
1825  (errcode(ERRCODE_INDETERMINATE_COLLATION),
1826  errmsg("could not determine which collation to use for string comparison"),
1827  errhint("Use the COLLATE clause to set the collation explicitly.")));
1828  }
1829 #ifdef HAVE_LOCALE_T
1830  locale = pg_newlocale_from_collation(collid);
1831 #endif
1832  }
1833  }
1834 
1835  /*
1836  * Unfortunately, it seems that abbreviation for non-C collations is
1837  * broken on many common platforms; testing of multiple versions of glibc
1838  * reveals that, for many locales, strcoll() and strxfrm() do not return
1839  * consistent results, which is fatal to this optimization. While no
1840  * other libc other than Cygwin has so far been shown to have a problem,
1841  * we take the conservative course of action for right now and disable
1842  * this categorically. (Users who are certain this isn't a problem on
1843  * their system can define TRUST_STRXFRM.)
1844  *
1845  * Even apart from the risk of broken locales, it's possible that there
1846  * are platforms where the use of abbreviated keys should be disabled at
1847  * compile time. Having only 4 byte datums could make worst-case
1848  * performance drastically more likely, for example. Moreover, macOS's
1849  * strxfrm() implementation is known to not effectively concentrate a
1850  * significant amount of entropy from the original string in earlier
1851  * transformed blobs. It's possible that other supported platforms are
1852  * similarly encumbered. So, if we ever get past disabling this
1853  * categorically, we may still want or need to disable it for particular
1854  * platforms.
1855  */
1856 #ifndef TRUST_STRXFRM
1857  if (!collate_c)
1858  abbreviate = false;
1859 #endif
1860 
1861  /*
1862  * If we're using abbreviated keys, or if we're using a locale-aware
1863  * comparison, we need to initialize a StringSortSupport object. Both
1864  * cases will make use of the temporary buffers we initialize here for
1865  * scratch space (and to detect requirement for BpChar semantics from
1866  * caller), and the abbreviation case requires additional state.
1867  */
1868  if (abbreviate || !collate_c)
1869  {
1870  sss = palloc(sizeof(VarStringSortSupport));
1871  sss->buf1 = palloc(TEXTBUFLEN);
1872  sss->buflen1 = TEXTBUFLEN;
1873  sss->buf2 = palloc(TEXTBUFLEN);
1874  sss->buflen2 = TEXTBUFLEN;
1875  /* Start with invalid values */
1876  sss->last_len1 = -1;
1877  sss->last_len2 = -1;
1878  /* Initialize */
1879  sss->last_returned = 0;
1880 #ifdef HAVE_LOCALE_T
1881  sss->locale = locale;
1882 #endif
1883 
1884  /*
1885  * To avoid somehow confusing a strxfrm() blob and an original string,
1886  * constantly keep track of the variety of data that buf1 and buf2
1887  * currently contain.
1888  *
1889  * Comparisons may be interleaved with conversion calls. Frequently,
1890  * conversions and comparisons are batched into two distinct phases,
1891  * but the correctness of caching cannot hinge upon this. For
1892  * comparison caching, buffer state is only trusted if cache_blob is
1893  * found set to false, whereas strxfrm() caching only trusts the state
1894  * when cache_blob is found set to true.
1895  *
1896  * Arbitrarily initialize cache_blob to true.
1897  */
1898  sss->cache_blob = true;
1899  sss->collate_c = collate_c;
1900  sss->bpchar = bpchar;
1901  ssup->ssup_extra = sss;
1902 
1903  /*
1904  * If possible, plan to use the abbreviated keys optimization. The
1905  * core code may switch back to authoritative comparator should
1906  * abbreviation be aborted.
1907  */
1908  if (abbreviate)
1909  {
1910  sss->prop_card = 0.20;
1911  initHyperLogLog(&sss->abbr_card, 10);
1912  initHyperLogLog(&sss->full_card, 10);
1913  ssup->abbrev_full_comparator = ssup->comparator;
1914  ssup->comparator = varstrcmp_abbrev;
1917  }
1918  }
1919 }
static int varstrfastcmp_locale(Datum x, Datum y, SortSupport ssup)
Definition: varlena.c:1995
int(* comparator)(Datum x, Datum y, SortSupport ssup)
Definition: sortsupport.h:107
static int bpcharfastcmp_c(Datum x, Datum y, SortSupport ssup)
Definition: varlena.c:1962
int errhint(const char *fmt,...)
Definition: elog.c:987
static Datum varstr_abbrev_convert(Datum original, SortSupport ssup)
Definition: varlena.c:2150
static int varstrcmp_abbrev(Datum x, Datum y, SortSupport ssup)
Definition: varlena.c:2125
int errcode(int sqlerrcode)
Definition: elog.c:575
#define OidIsValid(objectId)
Definition: c.h:534
static int varstrfastcmp_c(Datum x, Datum y, SortSupport ssup)
Definition: varlena.c:1925
int pg_locale_t
Definition: pg_locale.h:71
void initHyperLogLog(hyperLogLogState *cState, uint8 bwidth)
Definition: hyperloglog.c:65
#define ERROR
Definition: elog.h:43
bool lc_collate_is_c(Oid collation)
Definition: pg_locale.c:1123
hyperLogLogState abbr_card
Definition: varlena.c:73
#define DEFAULT_COLLATION_OID
Definition: pg_collation.h:68
int(* abbrev_full_comparator)(Datum x, Datum y, SortSupport ssup)
Definition: sortsupport.h:192
void * ssup_extra
Definition: sortsupport.h:87
#define ereport(elevel, rest)
Definition: elog.h:122
pg_locale_t pg_newlocale_from_collation(Oid collid)
Definition: pg_locale.c:1260
int GetDatabaseEncoding(void)
Definition: mbutils.c:1015
hyperLogLogState full_card
Definition: varlena.c:74
static bool varstr_abbrev_abort(int memtupcount, SortSupport ssup)
Definition: varlena.c:2328
#define TEXTBUFLEN
Definition: varlena.c:85
void * palloc(Size size)
Definition: mcxt.c:891
int errmsg(const char *fmt,...)
Definition: elog.c:797
static char * locale
Definition: initdb.c:122
Datum bpchar(PG_FUNCTION_ARGS)
Definition: varchar.c:267
bool(* abbrev_abort)(int memtupcount, SortSupport ssup)
Definition: sortsupport.h:183
Datum(* abbrev_converter)(Datum original, SortSupport ssup)
Definition: sortsupport.h:173