PostgreSQL Source Code  git master
pg_locale.c File Reference
#include "postgres.h"
#include <time.h>
#include "access/htup_details.h"
#include "catalog/pg_collation.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "utils/builtins.h"
#include "utils/formatting.h"
#include "utils/guc_hooks.h"
#include "utils/hsearch.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/pg_locale.h"
#include "utils/syscache.h"
Include dependency graph for pg_locale.c:

Go to the source code of this file.

Data Structures

struct  collation_cache_entry
 

Macros

#define PGLOCALE_SUPPORT_ERROR(provider)    elog(ERROR, "unsupported collprovider for %s: %c", __func__, provider)
 
#define TEXTBUFLEN   1024
 
#define MAX_L10N_DATA   80
 

Functions

static size_t mbstowcs_l (wchar_t *dest, const char *src, size_t n, locale_t loc)
 
static size_t wcstombs_l (char *dest, const wchar_t *src, size_t n, locale_t loc)
 
char * pg_perm_setlocale (int category, const char *locale)
 
bool check_locale (int category, const char *locale, char **canonname)
 
bool check_locale_monetary (char **newval, void **extra, GucSource source)
 
void assign_locale_monetary (const char *newval, void *extra)
 
bool check_locale_numeric (char **newval, void **extra, GucSource source)
 
void assign_locale_numeric (const char *newval, void *extra)
 
bool check_locale_time (char **newval, void **extra, GucSource source)
 
void assign_locale_time (const char *newval, void *extra)
 
bool check_locale_messages (char **newval, void **extra, GucSource source)
 
void assign_locale_messages (const char *newval, void *extra)
 
static void free_struct_lconv (struct lconv *s)
 
static bool struct_lconv_is_valid (struct lconv *s)
 
static void db_encoding_convert (int encoding, char **str)
 
struct lconv * PGLC_localeconv (void)
 
static void cache_single_string (char **dst, const char *src, int encoding)
 
void cache_locale_time (void)
 
static collation_cache_entrylookup_collation_cache (Oid collation, bool set_flags)
 
bool lc_collate_is_c (Oid collation)
 
bool lc_ctype_is_c (Oid collation)
 
void make_icu_collator (const char *iculocstr, const char *icurules, struct pg_locale_struct *resultp)
 
static void report_newlocale_failure (const char *localename)
 
bool pg_locale_deterministic (pg_locale_t locale)
 
pg_locale_t pg_newlocale_from_collation (Oid collid)
 
char * get_collation_actual_version (char collprovider, const char *collcollate)
 
static int pg_strcoll_libc (const char *arg1, const char *arg2, pg_locale_t locale)
 
static int pg_strncoll_libc (const char *arg1, size_t len1, const char *arg2, size_t len2, pg_locale_t locale)
 
int pg_strcoll (const char *arg1, const char *arg2, pg_locale_t locale)
 
int pg_strncoll (const char *arg1, size_t len1, const char *arg2, size_t len2, pg_locale_t locale)
 
static size_t pg_strxfrm_libc (char *dest, const char *src, size_t destsize, pg_locale_t locale)
 
static size_t pg_strnxfrm_libc (char *dest, const char *src, size_t srclen, size_t destsize, pg_locale_t locale)
 
bool pg_strxfrm_enabled (pg_locale_t locale)
 
size_t pg_strxfrm (char *dest, const char *src, size_t destsize, pg_locale_t locale)
 
size_t pg_strnxfrm (char *dest, size_t destsize, const char *src, size_t srclen, pg_locale_t locale)
 
bool pg_strxfrm_prefix_enabled (pg_locale_t locale)
 
size_t pg_strxfrm_prefix (char *dest, const char *src, size_t destsize, pg_locale_t locale)
 
size_t pg_strnxfrm_prefix (char *dest, size_t destsize, const char *src, size_t srclen, pg_locale_t locale)
 
int builtin_locale_encoding (const char *locale)
 
const char * builtin_validate_locale (int encoding, const char *locale)
 
char * icu_language_tag (const char *loc_str, int elevel)
 
void icu_validate_locale (const char *loc_str)
 
size_t wchar2char (char *to, const wchar_t *from, size_t tolen, pg_locale_t locale)
 
size_t char2wchar (wchar_t *to, size_t tolen, const char *from, size_t fromlen, pg_locale_t locale)
 

Variables

char * locale_messages
 
char * locale_monetary
 
char * locale_numeric
 
char * locale_time
 
int icu_validation_level = WARNING
 
char * localized_abbrev_days [7+1]
 
char * localized_full_days [7+1]
 
char * localized_abbrev_months [12+1]
 
char * localized_full_months [12+1]
 
bool database_ctype_is_c = false
 
static bool CurrentLocaleConvValid = false
 
static bool CurrentLCTimeValid = false
 
static HTABcollation_cache = NULL
 
struct pg_locale_struct default_locale
 

Macro Definition Documentation

◆ MAX_L10N_DATA

#define MAX_L10N_DATA   80

Definition at line 93 of file pg_locale.c.

◆ PGLOCALE_SUPPORT_ERROR

#define PGLOCALE_SUPPORT_ERROR (   provider)     elog(ERROR, "unsupported collprovider for %s: %c", __func__, provider)

Definition at line 84 of file pg_locale.c.

◆ TEXTBUFLEN

#define TEXTBUFLEN   1024

Definition at line 91 of file pg_locale.c.

Function Documentation

◆ assign_locale_messages()

void assign_locale_messages ( const char *  newval,
void *  extra 
)

Definition at line 427 of file pg_locale.c.

428 {
429  /*
430  * LC_MESSAGES category does not exist everywhere, but accept it anyway.
431  * We ignore failure, as per comment above.
432  */
433 #ifdef LC_MESSAGES
434  (void) pg_perm_setlocale(LC_MESSAGES, newval);
435 #endif
436 }
#define newval
char * pg_perm_setlocale(int category, const char *locale)
Definition: pg_locale.c:212

References newval, and pg_perm_setlocale().

◆ assign_locale_monetary()

void assign_locale_monetary ( const char *  newval,
void *  extra 
)

Definition at line 364 of file pg_locale.c.

365 {
366  CurrentLocaleConvValid = false;
367 }
static bool CurrentLocaleConvValid
Definition: pg_locale.c:120

References CurrentLocaleConvValid.

◆ assign_locale_numeric()

void assign_locale_numeric ( const char *  newval,
void *  extra 
)

Definition at line 376 of file pg_locale.c.

377 {
378  CurrentLocaleConvValid = false;
379 }

References CurrentLocaleConvValid.

◆ assign_locale_time()

void assign_locale_time ( const char *  newval,
void *  extra 
)

Definition at line 388 of file pg_locale.c.

389 {
390  CurrentLCTimeValid = false;
391 }
static bool CurrentLCTimeValid
Definition: pg_locale.c:121

References CurrentLCTimeValid.

◆ builtin_locale_encoding()

int builtin_locale_encoding ( const char *  locale)

Definition at line 2506 of file pg_locale.c.

2507 {
2508  if (strcmp(locale, "C") != 0)
2509  ereport(ERROR,
2510  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2511  errmsg("invalid locale name \"%s\" for builtin provider",
2512  locale)));
2513 
2514  return -1;
2515 }
int errcode(int sqlerrcode)
Definition: elog.c:859
int errmsg(const char *fmt,...)
Definition: elog.c:1072
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
static char * locale
Definition: initdb.c:140

References ereport, errcode(), errmsg(), ERROR, and locale.

Referenced by DefineCollation().

◆ builtin_validate_locale()

const char* builtin_validate_locale ( int  encoding,
const char *  locale 
)

Definition at line 2526 of file pg_locale.c.

2527 {
2528  if (strcmp(locale, "C") != 0)
2529  ereport(ERROR,
2530  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2531  errmsg("invalid locale name \"%s\" for builtin provider",
2532  locale)));
2533 
2534  return "C";
2535 }

References ereport, errcode(), errmsg(), ERROR, and locale.

Referenced by CheckMyDatabase(), createdb(), DefineCollation(), and pg_newlocale_from_collation().

◆ cache_locale_time()

void cache_locale_time ( void  )

Definition at line 806 of file pg_locale.c.

807 {
808  char buf[(2 * 7 + 2 * 12) * MAX_L10N_DATA];
809  char *bufptr;
810  time_t timenow;
811  struct tm *timeinfo;
812  bool strftimefail = false;
813  int encoding;
814  int i;
815  char *save_lc_time;
816 #ifdef WIN32
817  char *save_lc_ctype;
818 #endif
819 
820  /* did we do this already? */
821  if (CurrentLCTimeValid)
822  return;
823 
824  elog(DEBUG3, "cache_locale_time() executed; locale: \"%s\"", locale_time);
825 
826  /*
827  * As in PGLC_localeconv(), it's critical that we not throw error while
828  * libc's locale settings have nondefault values. Hence, we just call
829  * strftime() within the critical section, and then convert and save its
830  * results afterwards.
831  */
832 
833  /* Save prevailing value of time locale */
834  save_lc_time = setlocale(LC_TIME, NULL);
835  if (!save_lc_time)
836  elog(ERROR, "setlocale(NULL) failed");
837  save_lc_time = pstrdup(save_lc_time);
838 
839 #ifdef WIN32
840 
841  /*
842  * On Windows, it appears that wcsftime() internally uses LC_CTYPE, so we
843  * must set it here. This code looks the same as what PGLC_localeconv()
844  * does, but the underlying reason is different: this does NOT determine
845  * the encoding we'll get back from strftime_win32().
846  */
847 
848  /* Save prevailing value of ctype locale */
849  save_lc_ctype = setlocale(LC_CTYPE, NULL);
850  if (!save_lc_ctype)
851  elog(ERROR, "setlocale(NULL) failed");
852  save_lc_ctype = pstrdup(save_lc_ctype);
853 
854  /* use lc_time to set the ctype */
855  setlocale(LC_CTYPE, locale_time);
856 #endif
857 
858  setlocale(LC_TIME, locale_time);
859 
860  /* We use times close to current time as data for strftime(). */
861  timenow = time(NULL);
862  timeinfo = localtime(&timenow);
863 
864  /* Store the strftime results in MAX_L10N_DATA-sized portions of buf[] */
865  bufptr = buf;
866 
867  /*
868  * MAX_L10N_DATA is sufficient buffer space for every known locale, and
869  * POSIX defines no strftime() errors. (Buffer space exhaustion is not an
870  * error.) An implementation might report errors (e.g. ENOMEM) by
871  * returning 0 (or, less plausibly, a negative value) and setting errno.
872  * Report errno just in case the implementation did that, but clear it in
873  * advance of the calls so we don't emit a stale, unrelated errno.
874  */
875  errno = 0;
876 
877  /* localized days */
878  for (i = 0; i < 7; i++)
879  {
880  timeinfo->tm_wday = i;
881  if (strftime(bufptr, MAX_L10N_DATA, "%a", timeinfo) <= 0)
882  strftimefail = true;
883  bufptr += MAX_L10N_DATA;
884  if (strftime(bufptr, MAX_L10N_DATA, "%A", timeinfo) <= 0)
885  strftimefail = true;
886  bufptr += MAX_L10N_DATA;
887  }
888 
889  /* localized months */
890  for (i = 0; i < 12; i++)
891  {
892  timeinfo->tm_mon = i;
893  timeinfo->tm_mday = 1; /* make sure we don't have invalid date */
894  if (strftime(bufptr, MAX_L10N_DATA, "%b", timeinfo) <= 0)
895  strftimefail = true;
896  bufptr += MAX_L10N_DATA;
897  if (strftime(bufptr, MAX_L10N_DATA, "%B", timeinfo) <= 0)
898  strftimefail = true;
899  bufptr += MAX_L10N_DATA;
900  }
901 
902  /*
903  * Restore the prevailing locale settings; as in PGLC_localeconv(),
904  * failure to do so is fatal.
905  */
906 #ifdef WIN32
907  if (!setlocale(LC_CTYPE, save_lc_ctype))
908  elog(FATAL, "failed to restore LC_CTYPE to \"%s\"", save_lc_ctype);
909 #endif
910  if (!setlocale(LC_TIME, save_lc_time))
911  elog(FATAL, "failed to restore LC_TIME to \"%s\"", save_lc_time);
912 
913  /*
914  * At this point we've done our best to clean up, and can throw errors, or
915  * call functions that might throw errors, with a clean conscience.
916  */
917  if (strftimefail)
918  elog(ERROR, "strftime() failed: %m");
919 
920  /* Release the pstrdup'd locale names */
921  pfree(save_lc_time);
922 #ifdef WIN32
923  pfree(save_lc_ctype);
924 #endif
925 
926 #ifndef WIN32
927 
928  /*
929  * As in PGLC_localeconv(), we must convert strftime()'s output from the
930  * encoding implied by LC_TIME to the database encoding. If we can't
931  * identify the LC_TIME encoding, just perform encoding validation.
932  */
934  if (encoding < 0)
936 
937 #else
938 
939  /*
940  * On Windows, strftime_win32() always returns UTF8 data, so convert from
941  * that if necessary.
942  */
943  encoding = PG_UTF8;
944 
945 #endif /* WIN32 */
946 
947  bufptr = buf;
948 
949  /* localized days */
950  for (i = 0; i < 7; i++)
951  {
953  bufptr += MAX_L10N_DATA;
955  bufptr += MAX_L10N_DATA;
956  }
957  localized_abbrev_days[7] = NULL;
958  localized_full_days[7] = NULL;
959 
960  /* localized months */
961  for (i = 0; i < 12; i++)
962  {
964  bufptr += MAX_L10N_DATA;
966  bufptr += MAX_L10N_DATA;
967  }
968  localized_abbrev_months[12] = NULL;
969  localized_full_months[12] = NULL;
970 
971  CurrentLCTimeValid = true;
972 }
#define DEBUG3
Definition: elog.h:28
#define FATAL
Definition: elog.h:41
#define elog(elevel,...)
Definition: elog.h:224
int i
Definition: isn.c:73
static struct pg_tm tm
Definition: localtime.c:104
char * pstrdup(const char *in)
Definition: mcxt.c:1683
void pfree(void *pointer)
Definition: mcxt.c:1508
int32 encoding
Definition: pg_database.h:41
char * localized_full_months[12+1]
Definition: pg_locale.c:114
char * locale_time
Definition: pg_locale.c:100
static void cache_single_string(char **dst, const char *src, int encoding)
Definition: pg_locale.c:783
#define MAX_L10N_DATA
Definition: pg_locale.c:93
char * localized_abbrev_months[12+1]
Definition: pg_locale.c:113
char * localized_full_days[7+1]
Definition: pg_locale.c:112
char * localized_abbrev_days[7+1]
Definition: pg_locale.c:111
static char * buf
Definition: pg_test_fsync.c:73
@ PG_SQL_ASCII
Definition: pg_wchar.h:226
@ PG_UTF8
Definition: pg_wchar.h:232
int pg_get_encoding_from_locale(const char *ctype, bool write_message)
Definition: chklocale.c:428
#define setlocale(a, b)
Definition: win32_port.h:467

References buf, cache_single_string(), CurrentLCTimeValid, DEBUG3, elog, encoding, ERROR, FATAL, i, locale_time, localized_abbrev_days, localized_abbrev_months, localized_full_days, localized_full_months, MAX_L10N_DATA, pfree(), pg_get_encoding_from_locale(), PG_SQL_ASCII, PG_UTF8, pstrdup(), setlocale, and tm.

Referenced by DCH_from_char(), and DCH_to_char().

◆ cache_single_string()

static void cache_single_string ( char **  dst,
const char *  src,
int  encoding 
)
static

Definition at line 783 of file pg_locale.c.

784 {
785  char *ptr;
786  char *olddst;
787 
788  /* Convert the string to the database encoding, or validate it's OK */
789  ptr = pg_any_to_server(src, strlen(src), encoding);
790 
791  /* Store the string in long-lived storage, replacing any previous value */
792  olddst = *dst;
794  if (olddst)
795  pfree(olddst);
796 
797  /* Might as well clean up any palloc'd conversion result, too */
798  if (ptr != src)
799  pfree(ptr);
800 }
char * pg_any_to_server(const char *s, int len, int encoding)
Definition: mbutils.c:676
MemoryContext TopMemoryContext
Definition: mcxt.c:137
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1670

References encoding, MemoryContextStrdup(), pfree(), pg_any_to_server(), and TopMemoryContext.

Referenced by cache_locale_time().

◆ char2wchar()

size_t char2wchar ( wchar_t *  to,
size_t  tolen,
const char *  from,
size_t  fromlen,
pg_locale_t  locale 
)

Definition at line 3081 of file pg_locale.c.

3083 {
3084  size_t result;
3085 
3086  Assert(!locale || locale->provider == COLLPROVIDER_LIBC);
3087 
3088  if (tolen == 0)
3089  return 0;
3090 
3091 #ifdef WIN32
3092  /* See WIN32 "Unicode" comment above */
3093  if (GetDatabaseEncoding() == PG_UTF8)
3094  {
3095  /* Win32 API does not work for zero-length input */
3096  if (fromlen == 0)
3097  result = 0;
3098  else
3099  {
3100  result = MultiByteToWideChar(CP_UTF8, 0, from, fromlen, to, tolen - 1);
3101  /* A zero return is failure */
3102  if (result == 0)
3103  result = -1;
3104  }
3105 
3106  if (result != -1)
3107  {
3108  Assert(result < tolen);
3109  /* Append trailing null wchar (MultiByteToWideChar() does not) */
3110  to[result] = 0;
3111  }
3112  }
3113  else
3114 #endif /* WIN32 */
3115  {
3116  /* mbstowcs requires ending '\0' */
3117  char *str = pnstrdup(from, fromlen);
3118 
3119  if (locale == (pg_locale_t) 0)
3120  {
3121  /* Use mbstowcs directly for the default locale */
3122  result = mbstowcs(to, str, tolen);
3123  }
3124  else
3125  {
3126  /* Use mbstowcs_l for nondefault locales */
3127  result = mbstowcs_l(to, str, tolen, locale->info.lt);
3128  }
3129 
3130  pfree(str);
3131  }
3132 
3133  if (result == -1)
3134  {
3135  /*
3136  * Invalid multibyte character encountered. We try to give a useful
3137  * error message by letting pg_verifymbstr check the string. But it's
3138  * possible that the string is OK to us, and not OK to mbstowcs ---
3139  * this suggests that the LC_CTYPE locale is different from the
3140  * database encoding. Give a generic error message if pg_verifymbstr
3141  * can't find anything wrong.
3142  */
3143  pg_verifymbstr(from, fromlen, false); /* might not return */
3144  /* but if it does ... */
3145  ereport(ERROR,
3146  (errcode(ERRCODE_CHARACTER_NOT_IN_REPERTOIRE),
3147  errmsg("invalid multibyte character for locale"),
3148  errhint("The server's LC_CTYPE locale is probably incompatible with the database encoding.")));
3149  }
3150 
3151  return result;
3152 }
int errhint(const char *fmt,...)
Definition: elog.c:1319
Assert(fmt[strlen(fmt) - 1] !='\n')
int GetDatabaseEncoding(void)
Definition: mbutils.c:1261
bool pg_verifymbstr(const char *mbstr, int len, bool noError)
Definition: mbutils.c:1556
char * pnstrdup(const char *in, Size len)
Definition: mcxt.c:1694
static size_t mbstowcs_l(wchar_t *dest, const char *src, size_t n, locale_t loc)
Definition: pg_locale.c:166

References Assert(), ereport, errcode(), errhint(), errmsg(), ERROR, GetDatabaseEncoding(), locale, mbstowcs_l(), pfree(), PG_UTF8, pg_verifymbstr(), pnstrdup(), and generate_unaccent_rules::str.

Referenced by lowerstr_with_len(), str_initcap(), str_tolower(), str_toupper(), t_isalnum(), t_isalpha(), t_isdigit(), t_isprint(), t_isspace(), and TParserInit().

◆ check_locale()

bool check_locale ( int  category,
const char *  locale,
char **  canonname 
)

Definition at line 315 of file pg_locale.c.

316 {
317  char *save;
318  char *res;
319 
320  if (canonname)
321  *canonname = NULL; /* in case of failure */
322 
323  save = setlocale(category, NULL);
324  if (!save)
325  return false; /* won't happen, we hope */
326 
327  /* save may be pointing at a modifiable scratch variable, see above. */
328  save = pstrdup(save);
329 
330  /* set the locale with setlocale, to see if it accepts it. */
331  res = setlocale(category, locale);
332 
333  /* save canonical name if requested. */
334  if (res && canonname)
335  *canonname = pstrdup(res);
336 
337  /* restore old value. */
338  if (!setlocale(category, save))
339  elog(WARNING, "failed to restore old locale \"%s\"", save);
340  pfree(save);
341 
342  return (res != NULL);
343 }
#define WARNING
Definition: elog.h:36

References elog, locale, pfree(), pstrdup(), res, setlocale, and WARNING.

Referenced by check_locale_messages(), check_locale_monetary(), check_locale_numeric(), check_locale_time(), and createdb().

◆ check_locale_messages()

bool check_locale_messages ( char **  newval,
void **  extra,
GucSource  source 
)

Definition at line 404 of file pg_locale.c.

405 {
406  if (**newval == '\0')
407  {
408  if (source == PGC_S_DEFAULT)
409  return true;
410  else
411  return false;
412  }
413 
414  /*
415  * LC_MESSAGES category does not exist everywhere, but accept it anyway
416  *
417  * On Windows, we can't even check the value, so accept blindly
418  */
419 #if defined(LC_MESSAGES) && !defined(WIN32)
420  return check_locale(LC_MESSAGES, *newval, NULL);
421 #else
422  return true;
423 #endif
424 }
@ PGC_S_DEFAULT
Definition: guc.h:109
bool check_locale(int category, const char *locale, char **canonname)
Definition: pg_locale.c:315
static rewind_source * source
Definition: pg_rewind.c:89

References check_locale(), newval, PGC_S_DEFAULT, and source.

◆ check_locale_monetary()

bool check_locale_monetary ( char **  newval,
void **  extra,
GucSource  source 
)

Definition at line 358 of file pg_locale.c.

359 {
360  return check_locale(LC_MONETARY, *newval, NULL);
361 }

References check_locale(), and newval.

◆ check_locale_numeric()

bool check_locale_numeric ( char **  newval,
void **  extra,
GucSource  source 
)

Definition at line 370 of file pg_locale.c.

371 {
372  return check_locale(LC_NUMERIC, *newval, NULL);
373 }

References check_locale(), and newval.

◆ check_locale_time()

bool check_locale_time ( char **  newval,
void **  extra,
GucSource  source 
)

Definition at line 382 of file pg_locale.c.

383 {
384  return check_locale(LC_TIME, *newval, NULL);
385 }

References check_locale(), and newval.

◆ db_encoding_convert()

static void db_encoding_convert ( int  encoding,
char **  str 
)
static

Definition at line 494 of file pg_locale.c.

495 {
496  char *pstr;
497  char *mstr;
498 
499  /* convert the string to the database encoding */
500  pstr = pg_any_to_server(*str, strlen(*str), encoding);
501  if (pstr == *str)
502  return; /* no conversion happened */
503 
504  /* need it malloc'd not palloc'd */
505  mstr = strdup(pstr);
506  if (mstr == NULL)
507  ereport(ERROR,
508  (errcode(ERRCODE_OUT_OF_MEMORY),
509  errmsg("out of memory")));
510 
511  /* replace old string */
512  free(*str);
513  *str = mstr;
514 
515  pfree(pstr);
516 }
#define free(a)
Definition: header.h:65

References encoding, ereport, errcode(), errmsg(), ERROR, free, pfree(), pg_any_to_server(), and generate_unaccent_rules::str.

Referenced by PGLC_localeconv().

◆ free_struct_lconv()

static void free_struct_lconv ( struct lconv *  s)
static

Definition at line 444 of file pg_locale.c.

445 {
446  free(s->decimal_point);
447  free(s->thousands_sep);
448  free(s->grouping);
449  free(s->int_curr_symbol);
450  free(s->currency_symbol);
451  free(s->mon_decimal_point);
452  free(s->mon_thousands_sep);
453  free(s->mon_grouping);
454  free(s->positive_sign);
455  free(s->negative_sign);
456 }

References free.

Referenced by PGLC_localeconv().

◆ get_collation_actual_version()

char* get_collation_actual_version ( char  collprovider,
const char *  collcollate 
)

Definition at line 1724 of file pg_locale.c.

1725 {
1726  char *collversion = NULL;
1727 
1728  /* the builtin collation provider is not versioned */
1729  if (collprovider == COLLPROVIDER_BUILTIN)
1730  return NULL;
1731 
1732 #ifdef USE_ICU
1733  if (collprovider == COLLPROVIDER_ICU)
1734  {
1735  UCollator *collator;
1736  UVersionInfo versioninfo;
1737  char buf[U_MAX_VERSION_STRING_LENGTH];
1738 
1739  collator = pg_ucol_open(collcollate);
1740 
1741  ucol_getVersion(collator, versioninfo);
1742  ucol_close(collator);
1743 
1744  u_versionToString(versioninfo, buf);
1745  collversion = pstrdup(buf);
1746  }
1747  else
1748 #endif
1749  if (collprovider == COLLPROVIDER_LIBC &&
1750  pg_strcasecmp("C", collcollate) != 0 &&
1751  pg_strncasecmp("C.", collcollate, 2) != 0 &&
1752  pg_strcasecmp("POSIX", collcollate) != 0)
1753  {
1754 #if defined(__GLIBC__)
1755  /* Use the glibc version because we don't have anything better. */
1756  collversion = pstrdup(gnu_get_libc_version());
1757 #elif defined(LC_VERSION_MASK)
1758  locale_t loc;
1759 
1760  /* Look up FreeBSD collation version. */
1761  loc = newlocale(LC_COLLATE, collcollate, NULL);
1762  if (loc)
1763  {
1764  collversion =
1765  pstrdup(querylocale(LC_COLLATE_MASK | LC_VERSION_MASK, loc));
1766  freelocale(loc);
1767  }
1768  else
1769  ereport(ERROR,
1770  (errmsg("could not load locale \"%s\"", collcollate)));
1771 #elif defined(WIN32)
1772  /*
1773  * If we are targeting Windows Vista and above, we can ask for a name
1774  * given a collation name (earlier versions required a location code
1775  * that we don't have).
1776  */
1777  NLSVERSIONINFOEX version = {sizeof(NLSVERSIONINFOEX)};
1778  WCHAR wide_collcollate[LOCALE_NAME_MAX_LENGTH];
1779 
1780  MultiByteToWideChar(CP_ACP, 0, collcollate, -1, wide_collcollate,
1781  LOCALE_NAME_MAX_LENGTH);
1782  if (!GetNLSVersionEx(COMPARE_STRING, wide_collcollate, &version))
1783  {
1784  /*
1785  * GetNLSVersionEx() wants a language tag such as "en-US", not a
1786  * locale name like "English_United States.1252". Until those
1787  * values can be prevented from entering the system, or 100%
1788  * reliably converted to the more useful tag format, tolerate the
1789  * resulting error and report that we have no version data.
1790  */
1791  if (GetLastError() == ERROR_INVALID_PARAMETER)
1792  return NULL;
1793 
1794  ereport(ERROR,
1795  (errmsg("could not get collation version for locale \"%s\": error code %lu",
1796  collcollate,
1797  GetLastError())));
1798  }
1799  collversion = psprintf("%lu.%lu,%lu.%lu",
1800  (version.dwNLSVersion >> 8) & 0xFFFF,
1801  version.dwNLSVersion & 0xFF,
1802  (version.dwDefinedVersion >> 8) & 0xFFFF,
1803  version.dwDefinedVersion & 0xFF);
1804 #endif
1805  }
1806 
1807  return collversion;
1808 }
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
int pg_strncasecmp(const char *s1, const char *s2, size_t n)
Definition: pgstrcasecmp.c:69
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
#define locale_t
Definition: win32_port.h:424

References buf, ereport, errmsg(), ERROR, locale_t, pg_strcasecmp(), pg_strncasecmp(), psprintf(), and pstrdup().

Referenced by AlterCollation(), AlterDatabaseRefreshColl(), CheckMyDatabase(), createdb(), DefineCollation(), pg_collation_actual_version(), pg_database_collation_actual_version(), pg_import_system_collations(), and pg_newlocale_from_collation().

◆ icu_language_tag()

char* icu_language_tag ( const char *  loc_str,
int  elevel 
)

Definition at line 2887 of file pg_locale.c.

2888 {
2889 #ifdef USE_ICU
2890  UErrorCode status;
2891  char *langtag;
2892  size_t buflen = 32; /* arbitrary starting buffer size */
2893  const bool strict = true;
2894 
2895  /*
2896  * A BCP47 language tag doesn't have a clearly-defined upper limit (cf.
2897  * RFC5646 section 4.4). Additionally, in older ICU versions,
2898  * uloc_toLanguageTag() doesn't always return the ultimate length on the
2899  * first call, necessitating a loop.
2900  */
2901  langtag = palloc(buflen);
2902  while (true)
2903  {
2904  status = U_ZERO_ERROR;
2905  uloc_toLanguageTag(loc_str, langtag, buflen, strict, &status);
2906 
2907  /* try again if the buffer is not large enough */
2908  if ((status == U_BUFFER_OVERFLOW_ERROR ||
2909  status == U_STRING_NOT_TERMINATED_WARNING) &&
2910  buflen < MaxAllocSize)
2911  {
2912  buflen = Min(buflen * 2, MaxAllocSize);
2913  langtag = repalloc(langtag, buflen);
2914  continue;
2915  }
2916 
2917  break;
2918  }
2919 
2920  if (U_FAILURE(status))
2921  {
2922  pfree(langtag);
2923 
2924  if (elevel > 0)
2925  ereport(elevel,
2926  (errmsg("could not convert locale name \"%s\" to language tag: %s",
2927  loc_str, u_errorName(status))));
2928  return NULL;
2929  }
2930 
2931  return langtag;
2932 #else /* not USE_ICU */
2933  ereport(ERROR,
2934  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2935  errmsg("ICU is not supported in this build")));
2936  return NULL; /* keep compiler quiet */
2937 #endif /* not USE_ICU */
2938 }
#define Min(x, y)
Definition: c.h:991
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1528
void * palloc(Size size)
Definition: mcxt.c:1304
#define MaxAllocSize
Definition: memutils.h:40

References ereport, errcode(), errmsg(), ERROR, MaxAllocSize, Min, palloc(), pfree(), and repalloc().

Referenced by createdb(), DefineCollation(), and pg_import_system_collations().

◆ icu_validate_locale()

void icu_validate_locale ( const char *  loc_str)

Definition at line 2944 of file pg_locale.c.

2945 {
2946 #ifdef USE_ICU
2947  UCollator *collator;
2948  UErrorCode status;
2949  char lang[ULOC_LANG_CAPACITY];
2950  bool found = false;
2951  int elevel = icu_validation_level;
2952 
2953  /* no validation */
2954  if (elevel < 0)
2955  return;
2956 
2957  /* downgrade to WARNING during pg_upgrade */
2958  if (IsBinaryUpgrade && elevel > WARNING)
2959  elevel = WARNING;
2960 
2961  /* validate that we can extract the language */
2962  status = U_ZERO_ERROR;
2963  uloc_getLanguage(loc_str, lang, ULOC_LANG_CAPACITY, &status);
2964  if (U_FAILURE(status) || status == U_STRING_NOT_TERMINATED_WARNING)
2965  {
2966  ereport(elevel,
2967  (errmsg("could not get language from ICU locale \"%s\": %s",
2968  loc_str, u_errorName(status)),
2969  errhint("To disable ICU locale validation, set the parameter %s to \"%s\".",
2970  "icu_validation_level", "disabled")));
2971  return;
2972  }
2973 
2974  /* check for special language name */
2975  if (strcmp(lang, "") == 0 ||
2976  strcmp(lang, "root") == 0 || strcmp(lang, "und") == 0)
2977  found = true;
2978 
2979  /* search for matching language within ICU */
2980  for (int32_t i = 0; !found && i < uloc_countAvailable(); i++)
2981  {
2982  const char *otherloc = uloc_getAvailable(i);
2983  char otherlang[ULOC_LANG_CAPACITY];
2984 
2985  status = U_ZERO_ERROR;
2986  uloc_getLanguage(otherloc, otherlang, ULOC_LANG_CAPACITY, &status);
2987  if (U_FAILURE(status) || status == U_STRING_NOT_TERMINATED_WARNING)
2988  continue;
2989 
2990  if (strcmp(lang, otherlang) == 0)
2991  found = true;
2992  }
2993 
2994  if (!found)
2995  ereport(elevel,
2996  (errmsg("ICU locale \"%s\" has unknown language \"%s\"",
2997  loc_str, lang),
2998  errhint("To disable ICU locale validation, set the parameter %s to \"%s\".",
2999  "icu_validation_level", "disabled")));
3000 
3001  /* check that it can be opened */
3002  collator = pg_ucol_open(loc_str);
3003  ucol_close(collator);
3004 #else /* not USE_ICU */
3005  /* could get here if a collation was created by a build with ICU */
3006  ereport(ERROR,
3007  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3008  errmsg("ICU is not supported in this build")));
3009 #endif /* not USE_ICU */
3010 }
bool IsBinaryUpgrade
Definition: globals.c:118
int icu_validation_level
Definition: pg_locale.c:102

References ereport, errcode(), errhint(), errmsg(), ERROR, i, icu_validation_level, IsBinaryUpgrade, and WARNING.

Referenced by createdb(), and DefineCollation().

◆ lc_collate_is_c()

bool lc_collate_is_c ( Oid  collation)

Definition at line 1311 of file pg_locale.c.

1312 {
1313  /*
1314  * If we're asked about "collation 0", return false, so that the code will
1315  * go into the non-C path and report that the collation is bogus.
1316  */
1317  if (!OidIsValid(collation))
1318  return false;
1319 
1320  /*
1321  * If we're asked about the default collation, we have to inquire of the C
1322  * library. Cache the result so we only have to compute it once.
1323  */
1324  if (collation == DEFAULT_COLLATION_OID)
1325  {
1326  static int result = -1;
1327  const char *localeptr;
1328 
1329  if (result >= 0)
1330  return (bool) result;
1331 
1332  if (default_locale.provider == COLLPROVIDER_BUILTIN)
1333  {
1334  result = true;
1335  return (bool) result;
1336  }
1337  else if (default_locale.provider == COLLPROVIDER_ICU)
1338  {
1339  result = false;
1340  return (bool) result;
1341  }
1342  else if (default_locale.provider == COLLPROVIDER_LIBC)
1343  {
1344  localeptr = setlocale(LC_CTYPE, NULL);
1345  if (!localeptr)
1346  elog(ERROR, "invalid LC_CTYPE setting");
1347  }
1348  else
1349  elog(ERROR, "unexpected collation provider '%c'",
1351 
1352  if (strcmp(localeptr, "C") == 0)
1353  result = true;
1354  else if (strcmp(localeptr, "POSIX") == 0)
1355  result = true;
1356  else
1357  result = false;
1358  return (bool) result;
1359  }
1360 
1361  /*
1362  * If we're asked about the built-in C/POSIX collations, we know that.
1363  */
1364  if (collation == C_COLLATION_OID ||
1365  collation == POSIX_COLLATION_OID)
1366  return true;
1367 
1368  /*
1369  * Otherwise, we have to consult pg_collation, but we cache that.
1370  */
1371  return (lookup_collation_cache(collation, true))->collate_is_c;
1372 }
#define OidIsValid(objectId)
Definition: c.h:762
struct pg_locale_struct default_locale
Definition: pg_locale.c:1440
static collation_cache_entry * lookup_collation_cache(Oid collation, bool set_flags)
Definition: pg_locale.c:1230

References default_locale, elog, ERROR, lookup_collation_cache(), OidIsValid, pg_locale_struct::provider, and setlocale.

Referenced by bpchareq(), bpcharne(), btvarstrequalimage(), convert_string_datum(), DefineCollation(), hashbpchar(), hashbpcharextended(), hashtext(), hashtextextended(), make_greater_string(), match_pattern_prefix(), spg_text_inner_consistent(), text_position_setup(), text_starts_with(), texteq(), textne(), varstr_cmp(), and varstr_sortsupport().

◆ lc_ctype_is_c()

bool lc_ctype_is_c ( Oid  collation)

Definition at line 1378 of file pg_locale.c.

1379 {
1380  /*
1381  * If we're asked about "collation 0", return false, so that the code will
1382  * go into the non-C path and report that the collation is bogus.
1383  */
1384  if (!OidIsValid(collation))
1385  return false;
1386 
1387  /*
1388  * If we're asked about the default collation, we have to inquire of the C
1389  * library. Cache the result so we only have to compute it once.
1390  */
1391  if (collation == DEFAULT_COLLATION_OID)
1392  {
1393  static int result = -1;
1394  const char *localeptr;
1395 
1396  if (result >= 0)
1397  return (bool) result;
1398 
1399  if (default_locale.provider == COLLPROVIDER_BUILTIN)
1400  {
1401  localeptr = default_locale.info.builtin.locale;
1402  }
1403  else if (default_locale.provider == COLLPROVIDER_ICU)
1404  {
1405  result = false;
1406  return (bool) result;
1407  }
1408  else if (default_locale.provider == COLLPROVIDER_LIBC)
1409  {
1410  localeptr = setlocale(LC_CTYPE, NULL);
1411  if (!localeptr)
1412  elog(ERROR, "invalid LC_CTYPE setting");
1413  }
1414  else
1415  elog(ERROR, "unexpected collation provider '%c'",
1417 
1418  if (strcmp(localeptr, "C") == 0)
1419  result = true;
1420  else if (strcmp(localeptr, "POSIX") == 0)
1421  result = true;
1422  else
1423  result = false;
1424  return (bool) result;
1425  }
1426 
1427  /*
1428  * If we're asked about the built-in C/POSIX collations, we know that.
1429  */
1430  if (collation == C_COLLATION_OID ||
1431  collation == POSIX_COLLATION_OID)
1432  return true;
1433 
1434  /*
1435  * Otherwise, we have to consult pg_collation, but we cache that.
1436  */
1437  return (lookup_collation_cache(collation, true))->ctype_is_c;
1438 }
struct pg_locale_struct::@146::@147 builtin
union pg_locale_struct::@146 info

Referenced by DefineCollation(), Generic_Text_IC_like(), GenericMatchText(), like_fixed_prefix(), pg_set_regex_collation(), str_initcap(), str_tolower(), and str_toupper().

◆ lookup_collation_cache()

static collation_cache_entry* lookup_collation_cache ( Oid  collation,
bool  set_flags 
)
static

Definition at line 1230 of file pg_locale.c.

1231 {
1232  collation_cache_entry *cache_entry;
1233  bool found;
1234 
1235  Assert(OidIsValid(collation));
1236  Assert(collation != DEFAULT_COLLATION_OID);
1237 
1238  if (collation_cache == NULL)
1239  {
1240  /* First time through, initialize the hash table */
1241  HASHCTL ctl;
1242 
1243  ctl.keysize = sizeof(Oid);
1244  ctl.entrysize = sizeof(collation_cache_entry);
1245  collation_cache = hash_create("Collation cache", 100, &ctl,
1246  HASH_ELEM | HASH_BLOBS);
1247  }
1248 
1249  cache_entry = hash_search(collation_cache, &collation, HASH_ENTER, &found);
1250  if (!found)
1251  {
1252  /*
1253  * Make sure cache entry is marked invalid, in case we fail before
1254  * setting things.
1255  */
1256  cache_entry->flags_valid = false;
1257  cache_entry->locale = 0;
1258  }
1259 
1260  if (set_flags && !cache_entry->flags_valid)
1261  {
1262  /* Attempt to set the flags */
1263  HeapTuple tp;
1264  Form_pg_collation collform;
1265 
1266  tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
1267  if (!HeapTupleIsValid(tp))
1268  elog(ERROR, "cache lookup failed for collation %u", collation);
1269  collform = (Form_pg_collation) GETSTRUCT(tp);
1270 
1271  if (collform->collprovider == COLLPROVIDER_BUILTIN)
1272  {
1273  cache_entry->collate_is_c = true;
1274  cache_entry->ctype_is_c = true;
1275  }
1276  else if (collform->collprovider == COLLPROVIDER_LIBC)
1277  {
1278  Datum datum;
1279  const char *collcollate;
1280  const char *collctype;
1281 
1282  datum = SysCacheGetAttrNotNull(COLLOID, tp, Anum_pg_collation_collcollate);
1283  collcollate = TextDatumGetCString(datum);
1284  datum = SysCacheGetAttrNotNull(COLLOID, tp, Anum_pg_collation_collctype);
1285  collctype = TextDatumGetCString(datum);
1286 
1287  cache_entry->collate_is_c = ((strcmp(collcollate, "C") == 0) ||
1288  (strcmp(collcollate, "POSIX") == 0));
1289  cache_entry->ctype_is_c = ((strcmp(collctype, "C") == 0) ||
1290  (strcmp(collctype, "POSIX") == 0));
1291  }
1292  else
1293  {
1294  cache_entry->collate_is_c = false;
1295  cache_entry->ctype_is_c = false;
1296  }
1297 
1298  cache_entry->flags_valid = true;
1299 
1300  ReleaseSysCache(tp);
1301  }
1302 
1303  return cache_entry;
1304 }
#define TextDatumGetCString(d)
Definition: builtins.h:98
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:955
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:352
@ HASH_ENTER
Definition: hsearch.h:114
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_BLOBS
Definition: hsearch.h:97
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:58
static HTAB * collation_cache
Definition: pg_locale.c:134
uintptr_t Datum
Definition: postgres.h:64
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
unsigned int Oid
Definition: postgres_ext.h:31
Size keysize
Definition: hsearch.h:75
Size entrysize
Definition: hsearch.h:76
Definition: pg_locale.c:126
bool collate_is_c
Definition: pg_locale.c:128
pg_locale_t locale
Definition: pg_locale.c:131
bool flags_valid
Definition: pg_locale.c:130
bool ctype_is_c
Definition: pg_locale.c:129
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:266
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:218
Datum SysCacheGetAttrNotNull(int cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition: syscache.c:510

References Assert(), collation_cache_entry::collate_is_c, collation_cache, collation_cache_entry::ctype_is_c, elog, HASHCTL::entrysize, ERROR, collation_cache_entry::flags_valid, GETSTRUCT, HASH_BLOBS, hash_create(), HASH_ELEM, HASH_ENTER, hash_search(), HeapTupleIsValid, HASHCTL::keysize, collation_cache_entry::locale, ObjectIdGetDatum(), OidIsValid, ReleaseSysCache(), SearchSysCache1(), SysCacheGetAttrNotNull(), and TextDatumGetCString.

Referenced by lc_collate_is_c(), and pg_newlocale_from_collation().

◆ make_icu_collator()

void make_icu_collator ( const char *  iculocstr,
const char *  icurules,
struct pg_locale_struct resultp 
)

Definition at line 1443 of file pg_locale.c.

1446 {
1447 #ifdef USE_ICU
1448  UCollator *collator;
1449 
1450  collator = pg_ucol_open(iculocstr);
1451 
1452  /*
1453  * If rules are specified, we extract the rules of the standard collation,
1454  * add our own rules, and make a new collator with the combined rules.
1455  */
1456  if (icurules)
1457  {
1458  const UChar *default_rules;
1459  UChar *agg_rules;
1460  UChar *my_rules;
1461  UErrorCode status;
1462  int32_t length;
1463 
1464  default_rules = ucol_getRules(collator, &length);
1465  icu_to_uchar(&my_rules, icurules, strlen(icurules));
1466 
1467  agg_rules = palloc_array(UChar, u_strlen(default_rules) + u_strlen(my_rules) + 1);
1468  u_strcpy(agg_rules, default_rules);
1469  u_strcat(agg_rules, my_rules);
1470 
1471  ucol_close(collator);
1472 
1473  status = U_ZERO_ERROR;
1474  collator = ucol_openRules(agg_rules, u_strlen(agg_rules),
1475  UCOL_DEFAULT, UCOL_DEFAULT_STRENGTH, NULL, &status);
1476  if (U_FAILURE(status))
1477  ereport(ERROR,
1478  (errmsg("could not open collator for locale \"%s\" with rules \"%s\": %s",
1479  iculocstr, icurules, u_errorName(status))));
1480  }
1481 
1482  /* We will leak this string if the caller errors later :-( */
1483  resultp->info.icu.locale = MemoryContextStrdup(TopMemoryContext, iculocstr);
1484  resultp->info.icu.ucol = collator;
1485 #else /* not USE_ICU */
1486  /* could get here if a collation was created by a build with ICU */
1487  ereport(ERROR,
1488  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1489  errmsg("ICU is not supported in this build")));
1490 #endif /* not USE_ICU */
1491 }
#define palloc_array(type, count)
Definition: fe_memutils.h:64
const char * locale
Definition: pg_locale.h:81

References ereport, errcode(), errmsg(), ERROR, pg_locale_struct::info, pg_locale_struct::locale, MemoryContextStrdup(), palloc_array, and TopMemoryContext.

Referenced by CheckMyDatabase(), and pg_newlocale_from_collation().

◆ mbstowcs_l()

static size_t mbstowcs_l ( wchar_t *  dest,
const char *  src,
size_t  n,
locale_t  loc 
)
static

Definition at line 166 of file pg_locale.c.

167 {
168 #ifdef WIN32
169  return _mbstowcs_l(dest, src, n, loc);
170 #else
171  size_t result;
172  locale_t save_locale = uselocale(loc);
173 
174  result = mbstowcs(dest, src, n);
175  uselocale(save_locale);
176  return result;
177 #endif
178 }

References generate_unaccent_rules::dest, and locale_t.

Referenced by char2wchar().

◆ pg_locale_deterministic()

bool pg_locale_deterministic ( pg_locale_t  locale)

Definition at line 1525 of file pg_locale.c.

1526 {
1527  /* default locale must always be deterministic */
1528  if (locale == NULL)
1529  return true;
1530  else
1531  return locale->deterministic;
1532 }

References locale.

Referenced by bpchareq(), bpcharne(), Generic_Text_IC_like(), GenericMatchText(), hashbpchar(), hashbpcharextended(), hashtext(), hashtextextended(), pg_set_regex_collation(), text_position_setup(), text_starts_with(), texteq(), textne(), varstr_cmp(), and varstrfastcmp_locale().

◆ pg_newlocale_from_collation()

pg_locale_t pg_newlocale_from_collation ( Oid  collid)

Definition at line 1545 of file pg_locale.c.

1546 {
1547  collation_cache_entry *cache_entry;
1548 
1549  /* Callers must pass a valid OID */
1551 
1552  if (collid == DEFAULT_COLLATION_OID)
1553  {
1554  if (default_locale.provider == COLLPROVIDER_LIBC)
1555  return (pg_locale_t) 0;
1556  else
1557  return &default_locale;
1558  }
1559 
1560  cache_entry = lookup_collation_cache(collid, false);
1561 
1562  if (cache_entry->locale == 0)
1563  {
1564  /* We haven't computed this yet in this session, so do it */
1565  HeapTuple tp;
1566  Form_pg_collation collform;
1567  struct pg_locale_struct result;
1568  pg_locale_t resultp;
1569  Datum datum;
1570  bool isnull;
1571 
1572  tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collid));
1573  if (!HeapTupleIsValid(tp))
1574  elog(ERROR, "cache lookup failed for collation %u", collid);
1575  collform = (Form_pg_collation) GETSTRUCT(tp);
1576 
1577  /* We'll fill in the result struct locally before allocating memory */
1578  memset(&result, 0, sizeof(result));
1579  result.provider = collform->collprovider;
1580  result.deterministic = collform->collisdeterministic;
1581 
1582  if (collform->collprovider == COLLPROVIDER_BUILTIN)
1583  {
1584  const char *locstr;
1585 
1586  datum = SysCacheGetAttrNotNull(COLLOID, tp, Anum_pg_collation_colllocale);
1587  locstr = TextDatumGetCString(datum);
1588 
1590 
1591  result.info.builtin.locale = MemoryContextStrdup(TopMemoryContext,
1592  locstr);
1593  }
1594  else if (collform->collprovider == COLLPROVIDER_LIBC)
1595  {
1596  const char *collcollate;
1597  const char *collctype pg_attribute_unused();
1598  locale_t loc;
1599 
1600  datum = SysCacheGetAttrNotNull(COLLOID, tp, Anum_pg_collation_collcollate);
1601  collcollate = TextDatumGetCString(datum);
1602  datum = SysCacheGetAttrNotNull(COLLOID, tp, Anum_pg_collation_collctype);
1603  collctype = TextDatumGetCString(datum);
1604 
1605  if (strcmp(collcollate, collctype) == 0)
1606  {
1607  /* Normal case where they're the same */
1608  errno = 0;
1609 #ifndef WIN32
1610  loc = newlocale(LC_COLLATE_MASK | LC_CTYPE_MASK, collcollate,
1611  NULL);
1612 #else
1613  loc = _create_locale(LC_ALL, collcollate);
1614 #endif
1615  if (!loc)
1616  report_newlocale_failure(collcollate);
1617  }
1618  else
1619  {
1620 #ifndef WIN32
1621  /* We need two newlocale() steps */
1622  locale_t loc1;
1623 
1624  errno = 0;
1625  loc1 = newlocale(LC_COLLATE_MASK, collcollate, NULL);
1626  if (!loc1)
1627  report_newlocale_failure(collcollate);
1628  errno = 0;
1629  loc = newlocale(LC_CTYPE_MASK, collctype, loc1);
1630  if (!loc)
1631  report_newlocale_failure(collctype);
1632 #else
1633 
1634  /*
1635  * XXX The _create_locale() API doesn't appear to support
1636  * this. Could perhaps be worked around by changing
1637  * pg_locale_t to contain two separate fields.
1638  */
1639  ereport(ERROR,
1640  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1641  errmsg("collations with different collate and ctype values are not supported on this platform")));
1642 #endif
1643  }
1644 
1645  result.info.lt = loc;
1646  }
1647  else if (collform->collprovider == COLLPROVIDER_ICU)
1648  {
1649  const char *iculocstr;
1650  const char *icurules;
1651 
1652  datum = SysCacheGetAttrNotNull(COLLOID, tp, Anum_pg_collation_colllocale);
1653  iculocstr = TextDatumGetCString(datum);
1654 
1655  datum = SysCacheGetAttr(COLLOID, tp, Anum_pg_collation_collicurules, &isnull);
1656  if (!isnull)
1657  icurules = TextDatumGetCString(datum);
1658  else
1659  icurules = NULL;
1660 
1661  make_icu_collator(iculocstr, icurules, &result);
1662  }
1663 
1664  datum = SysCacheGetAttr(COLLOID, tp, Anum_pg_collation_collversion,
1665  &isnull);
1666  if (!isnull)
1667  {
1668  char *actual_versionstr;
1669  char *collversionstr;
1670 
1671  collversionstr = TextDatumGetCString(datum);
1672 
1673  Assert(collform->collprovider != COLLPROVIDER_BUILTIN);
1674  if (collform->collprovider == COLLPROVIDER_LIBC)
1675  datum = SysCacheGetAttrNotNull(COLLOID, tp, Anum_pg_collation_collcollate);
1676  else
1677  datum = SysCacheGetAttrNotNull(COLLOID, tp, Anum_pg_collation_colllocale);
1678 
1679  actual_versionstr = get_collation_actual_version(collform->collprovider,
1680  TextDatumGetCString(datum));
1681  if (!actual_versionstr)
1682  {
1683  /*
1684  * This could happen when specifying a version in CREATE
1685  * COLLATION but the provider does not support versioning, or
1686  * manually creating a mess in the catalogs.
1687  */
1688  ereport(ERROR,
1689  (errmsg("collation \"%s\" has no actual version, but a version was recorded",
1690  NameStr(collform->collname))));
1691  }
1692 
1693  if (strcmp(actual_versionstr, collversionstr) != 0)
1694  ereport(WARNING,
1695  (errmsg("collation \"%s\" has version mismatch",
1696  NameStr(collform->collname)),
1697  errdetail("The collation in the database was created using version %s, "
1698  "but the operating system provides version %s.",
1699  collversionstr, actual_versionstr),
1700  errhint("Rebuild all objects affected by this collation and run "
1701  "ALTER COLLATION %s REFRESH VERSION, "
1702  "or build PostgreSQL with the right library version.",
1703  quote_qualified_identifier(get_namespace_name(collform->collnamespace),
1704  NameStr(collform->collname)))));
1705  }
1706 
1707  ReleaseSysCache(tp);
1708 
1709  /* We'll keep the pg_locale_t structures in TopMemoryContext */
1710  resultp = MemoryContextAlloc(TopMemoryContext, sizeof(*resultp));
1711  *resultp = result;
1712 
1713  cache_entry->locale = resultp;
1714  }
1715 
1716  return cache_entry->locale;
1717 }
#define NameStr(name)
Definition: c.h:733
#define pg_attribute_unused()
Definition: c.h:123
Oid collid
int errdetail(const char *fmt,...)
Definition: elog.c:1205
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3322
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:1168
void make_icu_collator(const char *iculocstr, const char *icurules, struct pg_locale_struct *resultp)
Definition: pg_locale.c:1443
char * get_collation_actual_version(char collprovider, const char *collcollate)
Definition: pg_locale.c:1724
static void report_newlocale_failure(const char *localename)
Definition: pg_locale.c:1496
const char * builtin_validate_locale(int encoding, const char *locale)
Definition: pg_locale.c:2526
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:12071
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:479

References Assert(), pg_locale_struct::builtin, builtin_validate_locale(), collid, default_locale, pg_locale_struct::deterministic, elog, ereport, errcode(), errdetail(), errhint(), errmsg(), ERROR, get_collation_actual_version(), get_namespace_name(), GetDatabaseEncoding(), GETSTRUCT, HeapTupleIsValid, pg_locale_struct::info, collation_cache_entry::locale, locale_t, lookup_collation_cache(), pg_locale_struct::lt, make_icu_collator(), MemoryContextAlloc(), MemoryContextStrdup(), NameStr, ObjectIdGetDatum(), OidIsValid, pg_attribute_unused, pg_locale_struct::provider, quote_qualified_identifier(), ReleaseSysCache(), report_newlocale_failure(), SearchSysCache1(), SysCacheGetAttr(), SysCacheGetAttrNotNull(), TextDatumGetCString, TopMemoryContext, and WARNING.

Referenced by bpchareq(), bpcharne(), DefineCollation(), Generic_Text_IC_like(), GenericMatchText(), hashbpchar(), hashbpcharextended(), hashtext(), hashtextextended(), like_fixed_prefix(), pg_set_regex_collation(), str_initcap(), str_tolower(), str_toupper(), text_position_setup(), text_starts_with(), texteq(), textne(), varstr_cmp(), and varstr_sortsupport().

◆ pg_perm_setlocale()

char* pg_perm_setlocale ( int  category,
const char *  locale 
)

Definition at line 212 of file pg_locale.c.

213 {
214  char *result;
215  const char *envvar;
216 
217 #ifndef WIN32
218  result = setlocale(category, locale);
219 #else
220 
221  /*
222  * On Windows, setlocale(LC_MESSAGES) does not work, so just assume that
223  * the given value is good and set it in the environment variables. We
224  * must ignore attempts to set to "", which means "keep using the old
225  * environment value".
226  */
227 #ifdef LC_MESSAGES
228  if (category == LC_MESSAGES)
229  {
230  result = (char *) locale;
231  if (locale == NULL || locale[0] == '\0')
232  return result;
233  }
234  else
235 #endif
236  result = setlocale(category, locale);
237 #endif /* WIN32 */
238 
239  if (result == NULL)
240  return result; /* fall out immediately on failure */
241 
242  /*
243  * Use the right encoding in translated messages. Under ENABLE_NLS, let
244  * pg_bind_textdomain_codeset() figure it out. Under !ENABLE_NLS, message
245  * format strings are ASCII, but database-encoding strings may enter the
246  * message via %s. This makes the overall message encoding equal to the
247  * database encoding.
248  */
249  if (category == LC_CTYPE)
250  {
251  static char save_lc_ctype[LOCALE_NAME_BUFLEN];
252 
253  /* copy setlocale() return value before callee invokes it again */
254  strlcpy(save_lc_ctype, result, sizeof(save_lc_ctype));
255  result = save_lc_ctype;
256 
257 #ifdef ENABLE_NLS
258  SetMessageEncoding(pg_bind_textdomain_codeset(textdomain(NULL)));
259 #else
261 #endif
262  }
263 
264  switch (category)
265  {
266  case LC_COLLATE:
267  envvar = "LC_COLLATE";
268  break;
269  case LC_CTYPE:
270  envvar = "LC_CTYPE";
271  break;
272 #ifdef LC_MESSAGES
273  case LC_MESSAGES:
274  envvar = "LC_MESSAGES";
275 #ifdef WIN32
276  result = IsoLocaleName(locale);
277  if (result == NULL)
278  result = (char *) locale;
279  elog(DEBUG3, "IsoLocaleName() executed; locale: \"%s\"", result);
280 #endif /* WIN32 */
281  break;
282 #endif /* LC_MESSAGES */
283  case LC_MONETARY:
284  envvar = "LC_MONETARY";
285  break;
286  case LC_NUMERIC:
287  envvar = "LC_NUMERIC";
288  break;
289  case LC_TIME:
290  envvar = "LC_TIME";
291  break;
292  default:
293  elog(FATAL, "unrecognized LC category: %d", category);
294  return NULL; /* keep compiler quiet */
295  }
296 
297  if (setenv(envvar, result, 1) != 0)
298  return NULL;
299 
300  return result;
301 }
void SetMessageEncoding(int encoding)
Definition: mbutils.c:1171
#define LOCALE_NAME_BUFLEN
Definition: pg_locale.h:36
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define setenv(x, y, z)
Definition: win32_port.h:537

References DEBUG3, elog, FATAL, GetDatabaseEncoding(), locale, LOCALE_NAME_BUFLEN, setenv, setlocale, SetMessageEncoding(), and strlcpy().

Referenced by assign_locale_messages(), CheckMyDatabase(), and init_locale().

◆ pg_strcoll()

int pg_strcoll ( const char *  arg1,
const char *  arg2,
pg_locale_t  locale 
)

Definition at line 2077 of file pg_locale.c.

2078 {
2079  int result;
2080 
2081  if (!locale || locale->provider == COLLPROVIDER_LIBC)
2082  result = pg_strcoll_libc(arg1, arg2, locale);
2083 #ifdef USE_ICU
2084  else if (locale->provider == COLLPROVIDER_ICU)
2085  result = pg_strncoll_icu(arg1, -1, arg2, -1, locale);
2086 #endif
2087  else
2088  /* shouldn't happen */
2089  PGLOCALE_SUPPORT_ERROR(locale->provider);
2090 
2091  return result;
2092 }
#define PGLOCALE_SUPPORT_ERROR(provider)
Definition: pg_locale.c:84
static int pg_strcoll_libc(const char *arg1, const char *arg2, pg_locale_t locale)
Definition: pg_locale.c:1895

References locale, pg_strcoll_libc(), and PGLOCALE_SUPPORT_ERROR.

Referenced by varstrfastcmp_locale().

◆ pg_strcoll_libc()

static int pg_strcoll_libc ( const char *  arg1,
const char *  arg2,
pg_locale_t  locale 
)
static

Definition at line 1895 of file pg_locale.c.

1896 {
1897  int result;
1898 
1899  Assert(!locale || locale->provider == COLLPROVIDER_LIBC);
1900 #ifdef WIN32
1901  if (GetDatabaseEncoding() == PG_UTF8)
1902  {
1903  size_t len1 = strlen(arg1);
1904  size_t len2 = strlen(arg2);
1905 
1906  result = pg_strncoll_libc_win32_utf8(arg1, len1, arg2, len2, locale);
1907  }
1908  else
1909 #endif /* WIN32 */
1910  if (locale)
1911  result = strcoll_l(arg1, arg2, locale->info.lt);
1912  else
1913  result = strcoll(arg1, arg2);
1914 
1915  return result;
1916 }
#define strcoll_l
Definition: win32_port.h:447

References Assert(), GetDatabaseEncoding(), locale, PG_UTF8, and strcoll_l.

Referenced by pg_strcoll(), and pg_strncoll_libc().

◆ pg_strncoll()

int pg_strncoll ( const char *  arg1,
size_t  len1,
const char *  arg2,
size_t  len2,
pg_locale_t  locale 
)

Definition at line 2112 of file pg_locale.c.

2114 {
2115  int result;
2116 
2117  if (!locale || locale->provider == COLLPROVIDER_LIBC)
2118  result = pg_strncoll_libc(arg1, len1, arg2, len2, locale);
2119 #ifdef USE_ICU
2120  else if (locale->provider == COLLPROVIDER_ICU)
2121  result = pg_strncoll_icu(arg1, len1, arg2, len2, locale);
2122 #endif
2123  else
2124  /* shouldn't happen */
2125  PGLOCALE_SUPPORT_ERROR(locale->provider);
2126 
2127  return result;
2128 }
static int pg_strncoll_libc(const char *arg1, size_t len1, const char *arg2, size_t len2, pg_locale_t locale)
Definition: pg_locale.c:1924

References locale, pg_strncoll_libc(), and PGLOCALE_SUPPORT_ERROR.

Referenced by varstr_cmp().

◆ pg_strncoll_libc()

static int pg_strncoll_libc ( const char *  arg1,
size_t  len1,
const char *  arg2,
size_t  len2,
pg_locale_t  locale 
)
static

Definition at line 1924 of file pg_locale.c.

1926 {
1927  char sbuf[TEXTBUFLEN];
1928  char *buf = sbuf;
1929  size_t bufsize1 = len1 + 1;
1930  size_t bufsize2 = len2 + 1;
1931  char *arg1n;
1932  char *arg2n;
1933  int result;
1934 
1935  Assert(!locale || locale->provider == COLLPROVIDER_LIBC);
1936 
1937 #ifdef WIN32
1938  /* check for this case before doing the work for nul-termination */
1939  if (GetDatabaseEncoding() == PG_UTF8)
1940  return pg_strncoll_libc_win32_utf8(arg1, len1, arg2, len2, locale);
1941 #endif /* WIN32 */
1942 
1943  if (bufsize1 + bufsize2 > TEXTBUFLEN)
1944  buf = palloc(bufsize1 + bufsize2);
1945 
1946  arg1n = buf;
1947  arg2n = buf + bufsize1;
1948 
1949  /* nul-terminate arguments */
1950  memcpy(arg1n, arg1, len1);
1951  arg1n[len1] = '\0';
1952  memcpy(arg2n, arg2, len2);
1953  arg2n[len2] = '\0';
1954 
1955  result = pg_strcoll_libc(arg1n, arg2n, locale);
1956 
1957  if (buf != sbuf)
1958  pfree(buf);
1959 
1960  return result;
1961 }
#define TEXTBUFLEN
Definition: pg_locale.c:91

References Assert(), buf, GetDatabaseEncoding(), locale, palloc(), pfree(), pg_strcoll_libc(), PG_UTF8, and TEXTBUFLEN.

Referenced by pg_strncoll().

◆ pg_strnxfrm()

size_t pg_strnxfrm ( char *  dest,
size_t  destsize,
const char *  src,
size_t  srclen,
pg_locale_t  locale 
)

Definition at line 2396 of file pg_locale.c.

2398 {
2399  size_t result = 0; /* keep compiler quiet */
2400 
2401  if (!locale || locale->provider == COLLPROVIDER_LIBC)
2402  result = pg_strnxfrm_libc(dest, src, srclen, destsize, locale);
2403 #ifdef USE_ICU
2404  else if (locale->provider == COLLPROVIDER_ICU)
2405  result = pg_strnxfrm_icu(dest, src, srclen, destsize, locale);
2406 #endif
2407  else
2408  /* shouldn't happen */
2409  PGLOCALE_SUPPORT_ERROR(locale->provider);
2410 
2411  return result;
2412 }
static size_t pg_strnxfrm_libc(char *dest, const char *src, size_t srclen, size_t destsize, pg_locale_t locale)
Definition: pg_locale.c:2150

References generate_unaccent_rules::dest, locale, pg_strnxfrm_libc(), and PGLOCALE_SUPPORT_ERROR.

Referenced by hashbpchar(), hashbpcharextended(), hashtext(), and hashtextextended().

◆ pg_strnxfrm_libc()

static size_t pg_strnxfrm_libc ( char *  dest,
const char *  src,
size_t  srclen,
size_t  destsize,
pg_locale_t  locale 
)
static

Definition at line 2150 of file pg_locale.c.

2152 {
2153  char sbuf[TEXTBUFLEN];
2154  char *buf = sbuf;
2155  size_t bufsize = srclen + 1;
2156  size_t result;
2157 
2158  Assert(!locale || locale->provider == COLLPROVIDER_LIBC);
2159 
2160  if (bufsize > TEXTBUFLEN)
2161  buf = palloc(bufsize);
2162 
2163  /* nul-terminate arguments */
2164  memcpy(buf, src, srclen);
2165  buf[srclen] = '\0';
2166 
2167  result = pg_strxfrm_libc(dest, buf, destsize, locale);
2168 
2169  if (buf != sbuf)
2170  pfree(buf);
2171 
2172  /* if dest is defined, it should be nul-terminated */
2173  Assert(result >= destsize || dest[result] == '\0');
2174 
2175  return result;
2176 }
#define bufsize
Definition: indent_globs.h:36
static size_t pg_strxfrm_libc(char *dest, const char *src, size_t destsize, pg_locale_t locale)
Definition: pg_locale.c:2132

References Assert(), buf, bufsize, generate_unaccent_rules::dest, locale, palloc(), pfree(), pg_strxfrm_libc(), and TEXTBUFLEN.

Referenced by pg_strnxfrm().

◆ pg_strnxfrm_prefix()

size_t pg_strnxfrm_prefix ( char *  dest,
size_t  destsize,
const char *  src,
size_t  srclen,
pg_locale_t  locale 
)

Definition at line 2481 of file pg_locale.c.

2483 {
2484  size_t result = 0; /* keep compiler quiet */
2485 
2486  if (!locale)
2487  PGLOCALE_SUPPORT_ERROR(COLLPROVIDER_LIBC);
2488 #ifdef USE_ICU
2489  else if (locale->provider == COLLPROVIDER_ICU)
2490  result = pg_strnxfrm_prefix_icu(dest, src, -1, destsize, locale);
2491 #endif
2492  else
2493  PGLOCALE_SUPPORT_ERROR(locale->provider);
2494 
2495  return result;
2496 }

References generate_unaccent_rules::dest, locale, and PGLOCALE_SUPPORT_ERROR.

◆ pg_strxfrm()

size_t pg_strxfrm ( char *  dest,
const char *  src,
size_t  destsize,
pg_locale_t  locale 
)

Definition at line 2360 of file pg_locale.c.

2361 {
2362  size_t result = 0; /* keep compiler quiet */
2363 
2364  if (!locale || locale->provider == COLLPROVIDER_LIBC)
2365  result = pg_strxfrm_libc(dest, src, destsize, locale);
2366 #ifdef USE_ICU
2367  else if (locale->provider == COLLPROVIDER_ICU)
2368  result = pg_strnxfrm_icu(dest, src, -1, destsize, locale);
2369 #endif
2370  else
2371  /* shouldn't happen */
2372  PGLOCALE_SUPPORT_ERROR(locale->provider);
2373 
2374  return result;
2375 }

References generate_unaccent_rules::dest, locale, pg_strxfrm_libc(), and PGLOCALE_SUPPORT_ERROR.

Referenced by varstr_abbrev_convert().

◆ pg_strxfrm_enabled()

bool pg_strxfrm_enabled ( pg_locale_t  locale)

Definition at line 2328 of file pg_locale.c.

2329 {
2330  if (!locale || locale->provider == COLLPROVIDER_LIBC)
2331 #ifdef TRUST_STRXFRM
2332  return true;
2333 #else
2334  return false;
2335 #endif
2336  else if (locale->provider == COLLPROVIDER_ICU)
2337  return true;
2338  else
2339  /* shouldn't happen */
2340  PGLOCALE_SUPPORT_ERROR(locale->provider);
2341 
2342  return false; /* keep compiler quiet */
2343 }

References locale, and PGLOCALE_SUPPORT_ERROR.

Referenced by varstr_sortsupport().

◆ pg_strxfrm_libc()

static size_t pg_strxfrm_libc ( char *  dest,
const char *  src,
size_t  destsize,
pg_locale_t  locale 
)
static

Definition at line 2132 of file pg_locale.c.

2134 {
2135  Assert(!locale || locale->provider == COLLPROVIDER_LIBC);
2136 
2137 #ifdef TRUST_STRXFRM
2138  if (locale)
2139  return strxfrm_l(dest, src, destsize, locale->info.lt);
2140  else
2141  return strxfrm(dest, src, destsize);
2142 #else
2143  /* shouldn't happen */
2144  PGLOCALE_SUPPORT_ERROR(locale->provider);
2145  return 0; /* keep compiler quiet */
2146 #endif
2147 }
#define strxfrm_l
Definition: win32_port.h:448

References Assert(), generate_unaccent_rules::dest, locale, PGLOCALE_SUPPORT_ERROR, and strxfrm_l.

Referenced by pg_strnxfrm_libc(), and pg_strxfrm().

◆ pg_strxfrm_prefix()

size_t pg_strxfrm_prefix ( char *  dest,
const char *  src,
size_t  destsize,
pg_locale_t  locale 
)

Definition at line 2446 of file pg_locale.c.

2448 {
2449  size_t result = 0; /* keep compiler quiet */
2450 
2451  if (!locale)
2452  PGLOCALE_SUPPORT_ERROR(COLLPROVIDER_LIBC);
2453 #ifdef USE_ICU
2454  else if (locale->provider == COLLPROVIDER_ICU)
2455  result = pg_strnxfrm_prefix_icu(dest, src, -1, destsize, locale);
2456 #endif
2457  else
2458  PGLOCALE_SUPPORT_ERROR(locale->provider);
2459 
2460  return result;
2461 }

References generate_unaccent_rules::dest, locale, and PGLOCALE_SUPPORT_ERROR.

Referenced by varstr_abbrev_convert().

◆ pg_strxfrm_prefix_enabled()

bool pg_strxfrm_prefix_enabled ( pg_locale_t  locale)

Definition at line 2419 of file pg_locale.c.

2420 {
2421  if (!locale || locale->provider == COLLPROVIDER_LIBC)
2422  return false;
2423  else if (locale->provider == COLLPROVIDER_ICU)
2424  return true;
2425  else
2426  /* shouldn't happen */
2427  PGLOCALE_SUPPORT_ERROR(locale->provider);
2428 
2429  return false; /* keep compiler quiet */
2430 }

References locale, and PGLOCALE_SUPPORT_ERROR.

Referenced by varstr_abbrev_convert().

◆ PGLC_localeconv()

struct lconv* PGLC_localeconv ( void  )

Definition at line 524 of file pg_locale.c.

525 {
526  static struct lconv CurrentLocaleConv;
527  static bool CurrentLocaleConvAllocated = false;
528  struct lconv *extlconv;
529  struct lconv worklconv;
530  char *save_lc_monetary;
531  char *save_lc_numeric;
532 #ifdef WIN32
533  char *save_lc_ctype;
534 #endif
535 
536  /* Did we do it already? */
538  return &CurrentLocaleConv;
539 
540  /* Free any already-allocated storage */
541  if (CurrentLocaleConvAllocated)
542  {
543  free_struct_lconv(&CurrentLocaleConv);
544  CurrentLocaleConvAllocated = false;
545  }
546 
547  /*
548  * This is tricky because we really don't want to risk throwing error
549  * while the locale is set to other than our usual settings. Therefore,
550  * the process is: collect the usual settings, set locale to special
551  * setting, copy relevant data into worklconv using strdup(), restore
552  * normal settings, convert data to desired encoding, and finally stash
553  * the collected data in CurrentLocaleConv. This makes it safe if we
554  * throw an error during encoding conversion or run out of memory anywhere
555  * in the process. All data pointed to by struct lconv members is
556  * allocated with strdup, to avoid premature elog(ERROR) and to allow
557  * using a single cleanup routine.
558  */
559  memset(&worklconv, 0, sizeof(worklconv));
560 
561  /* Save prevailing values of monetary and numeric locales */
562  save_lc_monetary = setlocale(LC_MONETARY, NULL);
563  if (!save_lc_monetary)
564  elog(ERROR, "setlocale(NULL) failed");
565  save_lc_monetary = pstrdup(save_lc_monetary);
566 
567  save_lc_numeric = setlocale(LC_NUMERIC, NULL);
568  if (!save_lc_numeric)
569  elog(ERROR, "setlocale(NULL) failed");
570  save_lc_numeric = pstrdup(save_lc_numeric);
571 
572 #ifdef WIN32
573 
574  /*
575  * The POSIX standard explicitly says that it is undefined what happens if
576  * LC_MONETARY or LC_NUMERIC imply an encoding (codeset) different from
577  * that implied by LC_CTYPE. In practice, all Unix-ish platforms seem to
578  * believe that localeconv() should return strings that are encoded in the
579  * codeset implied by the LC_MONETARY or LC_NUMERIC locale name. Hence,
580  * once we have successfully collected the localeconv() results, we will
581  * convert them from that codeset to the desired server encoding.
582  *
583  * Windows, of course, resolutely does things its own way; on that
584  * platform LC_CTYPE has to match LC_MONETARY/LC_NUMERIC to get sane
585  * results. Hence, we must temporarily set that category as well.
586  */
587 
588  /* Save prevailing value of ctype locale */
589  save_lc_ctype = setlocale(LC_CTYPE, NULL);
590  if (!save_lc_ctype)
591  elog(ERROR, "setlocale(NULL) failed");
592  save_lc_ctype = pstrdup(save_lc_ctype);
593 
594  /* Here begins the critical section where we must not throw error */
595 
596  /* use numeric to set the ctype */
597  setlocale(LC_CTYPE, locale_numeric);
598 #endif
599 
600  /* Get formatting information for numeric */
601  setlocale(LC_NUMERIC, locale_numeric);
602  extlconv = localeconv();
603 
604  /* Must copy data now in case setlocale() overwrites it */
605  worklconv.decimal_point = strdup(extlconv->decimal_point);
606  worklconv.thousands_sep = strdup(extlconv->thousands_sep);
607  worklconv.grouping = strdup(extlconv->grouping);
608 
609 #ifdef WIN32
610  /* use monetary to set the ctype */
611  setlocale(LC_CTYPE, locale_monetary);
612 #endif
613 
614  /* Get formatting information for monetary */
615  setlocale(LC_MONETARY, locale_monetary);
616  extlconv = localeconv();
617 
618  /* Must copy data now in case setlocale() overwrites it */
619  worklconv.int_curr_symbol = strdup(extlconv->int_curr_symbol);
620  worklconv.currency_symbol = strdup(extlconv->currency_symbol);
621  worklconv.mon_decimal_point = strdup(extlconv->mon_decimal_point);
622  worklconv.mon_thousands_sep = strdup(extlconv->mon_thousands_sep);
623  worklconv.mon_grouping = strdup(extlconv->mon_grouping);
624  worklconv.positive_sign = strdup(extlconv->positive_sign);
625  worklconv.negative_sign = strdup(extlconv->negative_sign);
626  /* Copy scalar fields as well */
627  worklconv.int_frac_digits = extlconv->int_frac_digits;
628  worklconv.frac_digits = extlconv->frac_digits;
629  worklconv.p_cs_precedes = extlconv->p_cs_precedes;
630  worklconv.p_sep_by_space = extlconv->p_sep_by_space;
631  worklconv.n_cs_precedes = extlconv->n_cs_precedes;
632  worklconv.n_sep_by_space = extlconv->n_sep_by_space;
633  worklconv.p_sign_posn = extlconv->p_sign_posn;
634  worklconv.n_sign_posn = extlconv->n_sign_posn;
635 
636  /*
637  * Restore the prevailing locale settings; failure to do so is fatal.
638  * Possibly we could limp along with nondefault LC_MONETARY or LC_NUMERIC,
639  * but proceeding with the wrong value of LC_CTYPE would certainly be bad
640  * news; and considering that the prevailing LC_MONETARY and LC_NUMERIC
641  * are almost certainly "C", there's really no reason that restoring those
642  * should fail.
643  */
644 #ifdef WIN32
645  if (!setlocale(LC_CTYPE, save_lc_ctype))
646  elog(FATAL, "failed to restore LC_CTYPE to \"%s\"", save_lc_ctype);
647 #endif
648  if (!setlocale(LC_MONETARY, save_lc_monetary))
649  elog(FATAL, "failed to restore LC_MONETARY to \"%s\"", save_lc_monetary);
650  if (!setlocale(LC_NUMERIC, save_lc_numeric))
651  elog(FATAL, "failed to restore LC_NUMERIC to \"%s\"", save_lc_numeric);
652 
653  /*
654  * At this point we've done our best to clean up, and can call functions
655  * that might possibly throw errors with a clean conscience. But let's
656  * make sure we don't leak any already-strdup'd fields in worklconv.
657  */
658  PG_TRY();
659  {
660  int encoding;
661 
662  /* Release the pstrdup'd locale names */
663  pfree(save_lc_monetary);
664  pfree(save_lc_numeric);
665 #ifdef WIN32
666  pfree(save_lc_ctype);
667 #endif
668 
669  /* If any of the preceding strdup calls failed, complain now. */
670  if (!struct_lconv_is_valid(&worklconv))
671  ereport(ERROR,
672  (errcode(ERRCODE_OUT_OF_MEMORY),
673  errmsg("out of memory")));
674 
675  /*
676  * Now we must perform encoding conversion from whatever's associated
677  * with the locales into the database encoding. If we can't identify
678  * the encoding implied by LC_NUMERIC or LC_MONETARY (ie we get -1),
679  * use PG_SQL_ASCII, which will result in just validating that the
680  * strings are OK in the database encoding.
681  */
683  if (encoding < 0)
685 
686  db_encoding_convert(encoding, &worklconv.decimal_point);
687  db_encoding_convert(encoding, &worklconv.thousands_sep);
688  /* grouping is not text and does not require conversion */
689 
691  if (encoding < 0)
693 
694  db_encoding_convert(encoding, &worklconv.int_curr_symbol);
695  db_encoding_convert(encoding, &worklconv.currency_symbol);
696  db_encoding_convert(encoding, &worklconv.mon_decimal_point);
697  db_encoding_convert(encoding, &worklconv.mon_thousands_sep);
698  /* mon_grouping is not text and does not require conversion */
699  db_encoding_convert(encoding, &worklconv.positive_sign);
700  db_encoding_convert(encoding, &worklconv.negative_sign);
701  }
702  PG_CATCH();
703  {
704  free_struct_lconv(&worklconv);
705  PG_RE_THROW();
706  }
707  PG_END_TRY();
708 
709  /*
710  * Everything is good, so save the results.
711  */
712  CurrentLocaleConv = worklconv;
713  CurrentLocaleConvAllocated = true;
714  CurrentLocaleConvValid = true;
715  return &CurrentLocaleConv;
716 }
#define PG_RE_THROW()
Definition: elog.h:411
#define PG_TRY(...)
Definition: elog.h:370
#define PG_END_TRY(...)
Definition: elog.h:395
#define PG_CATCH(...)
Definition: elog.h:380
char * locale_numeric
Definition: pg_locale.c:99
static void db_encoding_convert(int encoding, char **str)
Definition: pg_locale.c:494
static void free_struct_lconv(struct lconv *s)
Definition: pg_locale.c:444
static bool struct_lconv_is_valid(struct lconv *s)
Definition: pg_locale.c:463
char * locale_monetary
Definition: pg_locale.c:98

References CurrentLocaleConvValid, db_encoding_convert(), elog, encoding, ereport, errcode(), errmsg(), ERROR, FATAL, free_struct_lconv(), locale_monetary, locale_numeric, pfree(), PG_CATCH, PG_END_TRY, pg_get_encoding_from_locale(), PG_RE_THROW, PG_SQL_ASCII, PG_TRY, pstrdup(), setlocale, and struct_lconv_is_valid().

Referenced by cash_in(), cash_numeric(), cash_out(), int4_cash(), int8_cash(), NUM_prepare_locale(), and numeric_cash().

◆ report_newlocale_failure()

static void report_newlocale_failure ( const char *  localename)
static

Definition at line 1496 of file pg_locale.c.

1497 {
1498  int save_errno;
1499 
1500  /*
1501  * Windows doesn't provide any useful error indication from
1502  * _create_locale(), and BSD-derived platforms don't seem to feel they
1503  * need to set errno either (even though POSIX is pretty clear that
1504  * newlocale should do so). So, if errno hasn't been set, assume ENOENT
1505  * is what to report.
1506  */
1507  if (errno == 0)
1508  errno = ENOENT;
1509 
1510  /*
1511  * ENOENT means "no such locale", not "no such file", so clarify that
1512  * errno with an errdetail message.
1513  */
1514  save_errno = errno; /* auxiliary funcs might change errno */
1515  ereport(ERROR,
1516  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1517  errmsg("could not create locale \"%s\": %m",
1518  localename),
1519  (save_errno == ENOENT ?
1520  errdetail("The operating system could not find any locale data for the locale name \"%s\".",
1521  localename) : 0)));
1522 }

References ereport, errcode(), errdetail(), errmsg(), and ERROR.

Referenced by pg_newlocale_from_collation().

◆ struct_lconv_is_valid()

static bool struct_lconv_is_valid ( struct lconv *  s)
static

Definition at line 463 of file pg_locale.c.

464 {
465  if (s->decimal_point == NULL)
466  return false;
467  if (s->thousands_sep == NULL)
468  return false;
469  if (s->grouping == NULL)
470  return false;
471  if (s->int_curr_symbol == NULL)
472  return false;
473  if (s->currency_symbol == NULL)
474  return false;
475  if (s->mon_decimal_point == NULL)
476  return false;
477  if (s->mon_thousands_sep == NULL)
478  return false;
479  if (s->mon_grouping == NULL)
480  return false;
481  if (s->positive_sign == NULL)
482  return false;
483  if (s->negative_sign == NULL)
484  return false;
485  return true;
486 }

Referenced by PGLC_localeconv().

◆ wchar2char()

size_t wchar2char ( char *  to,
const wchar_t *  from,
size_t  tolen,
pg_locale_t  locale 
)

Definition at line 3025 of file pg_locale.c.

3026 {
3027  size_t result;
3028 
3029  Assert(!locale || locale->provider == COLLPROVIDER_LIBC);
3030 
3031  if (tolen == 0)
3032  return 0;
3033 
3034 #ifdef WIN32
3035 
3036  /*
3037  * On Windows, the "Unicode" locales assume UTF16 not UTF8 encoding, and
3038  * for some reason mbstowcs and wcstombs won't do this for us, so we use
3039  * MultiByteToWideChar().
3040  */
3041  if (GetDatabaseEncoding() == PG_UTF8)
3042  {
3043  result = WideCharToMultiByte(CP_UTF8, 0, from, -1, to, tolen,
3044  NULL, NULL);
3045  /* A zero return is failure */
3046  if (result <= 0)
3047  result = -1;
3048  else
3049  {
3050  Assert(result <= tolen);
3051  /* Microsoft counts the zero terminator in the result */
3052  result--;
3053  }
3054  }
3055  else
3056 #endif /* WIN32 */
3057  if (locale == (pg_locale_t) 0)
3058  {
3059  /* Use wcstombs directly for the default locale */
3060  result = wcstombs(to, from, tolen);
3061  }
3062  else
3063  {
3064  /* Use wcstombs_l for nondefault locales */
3065  result = wcstombs_l(to, from, tolen, locale->info.lt);
3066  }
3067 
3068  return result;
3069 }
static size_t wcstombs_l(char *dest, const wchar_t *src, size_t n, locale_t loc)
Definition: pg_locale.c:182

References Assert(), GetDatabaseEncoding(), locale, PG_UTF8, and wcstombs_l().

Referenced by lowerstr_with_len(), str_initcap(), str_tolower(), and str_toupper().

◆ wcstombs_l()

static size_t wcstombs_l ( char *  dest,
const wchar_t *  src,
size_t  n,
locale_t  loc 
)
static

Definition at line 182 of file pg_locale.c.

183 {
184 #ifdef WIN32
185  return _wcstombs_l(dest, src, n, loc);
186 #else
187  size_t result;
188  locale_t save_locale = uselocale(loc);
189 
190  result = wcstombs(dest, src, n);
191  uselocale(save_locale);
192  return result;
193 #endif
194 }

References generate_unaccent_rules::dest, and locale_t.

Referenced by wchar2char().

Variable Documentation

◆ collation_cache

HTAB* collation_cache = NULL
static

Definition at line 134 of file pg_locale.c.

Referenced by lookup_collation_cache().

◆ CurrentLCTimeValid

bool CurrentLCTimeValid = false
static

Definition at line 121 of file pg_locale.c.

Referenced by assign_locale_time(), and cache_locale_time().

◆ CurrentLocaleConvValid

bool CurrentLocaleConvValid = false
static

Definition at line 120 of file pg_locale.c.

Referenced by assign_locale_monetary(), assign_locale_numeric(), and PGLC_localeconv().

◆ database_ctype_is_c

bool database_ctype_is_c = false

◆ default_locale

struct pg_locale_struct default_locale

Definition at line 1378 of file pg_locale.c.

Referenced by CheckMyDatabase(), lc_collate_is_c(), and pg_newlocale_from_collation().

◆ icu_validation_level

int icu_validation_level = WARNING

Definition at line 102 of file pg_locale.c.

Referenced by createdb(), DefineCollation(), and icu_validate_locale().

◆ locale_messages

char* locale_messages

Definition at line 97 of file pg_locale.c.

◆ locale_monetary

char* locale_monetary

Definition at line 98 of file pg_locale.c.

Referenced by PGLC_localeconv().

◆ locale_numeric

char* locale_numeric

Definition at line 99 of file pg_locale.c.

Referenced by PGLC_localeconv().

◆ locale_time

char* locale_time

Definition at line 100 of file pg_locale.c.

Referenced by cache_locale_time().

◆ localized_abbrev_days

char* localized_abbrev_days[7+1]

Definition at line 111 of file pg_locale.c.

Referenced by cache_locale_time(), DCH_from_char(), and DCH_to_char().

◆ localized_abbrev_months

char* localized_abbrev_months[12+1]

Definition at line 113 of file pg_locale.c.

Referenced by cache_locale_time(), DCH_from_char(), and DCH_to_char().

◆ localized_full_days

char* localized_full_days[7+1]

Definition at line 112 of file pg_locale.c.

Referenced by cache_locale_time(), DCH_from_char(), and DCH_to_char().

◆ localized_full_months

char* localized_full_months[12+1]

Definition at line 114 of file pg_locale.c.

Referenced by cache_locale_time(), DCH_from_char(), and DCH_to_char().