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 "catalog/pg_control.h"
#include "mb/pg_wchar.h"
#include "utils/builtins.h"
#include "utils/formatting.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 MAX_L10N_DATA   80
 
#define LC_ENV_BUFSIZE   (NAMEDATALEN + 20)
 

Functions

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)
 
void check_strxfrm_bug (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)
 
pg_locale_t pg_newlocale_from_collation (Oid collid)
 
char * get_collation_actual_version (char collprovider, const char *collcollate)
 
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
 
char * localized_abbrev_days [7]
 
char * localized_full_days [7]
 
char * localized_abbrev_months [12]
 
char * localized_full_months [12]
 
static bool CurrentLocaleConvValid = false
 
static bool CurrentLCTimeValid = false
 
static char lc_collate_envbuf [LC_ENV_BUFSIZE]
 
static char lc_ctype_envbuf [LC_ENV_BUFSIZE]
 
static char lc_monetary_envbuf [LC_ENV_BUFSIZE]
 
static char lc_numeric_envbuf [LC_ENV_BUFSIZE]
 
static char lc_time_envbuf [LC_ENV_BUFSIZE]
 
static HTABcollation_cache = NULL
 

Macro Definition Documentation

◆ LC_ENV_BUFSIZE

#define LC_ENV_BUFSIZE   (NAMEDATALEN + 20)

Definition at line 111 of file pg_locale.c.

Referenced by pg_perm_setlocale().

◆ MAX_L10N_DATA

#define MAX_L10N_DATA   80

Definition at line 90 of file pg_locale.c.

Referenced by cache_locale_time(), and PGLC_localeconv().

Function Documentation

◆ assign_locale_messages()

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

Definition at line 385 of file pg_locale.c.

References pg_perm_setlocale().

386 {
387  /*
388  * LC_MESSAGES category does not exist everywhere, but accept it anyway.
389  * We ignore failure, as per comment above.
390  */
391 #ifdef LC_MESSAGES
392  (void) pg_perm_setlocale(LC_MESSAGES, newval);
393 #endif
394 }
char * pg_perm_setlocale(int category, const char *locale)
Definition: pg_locale.c:160
#define newval

◆ assign_locale_monetary()

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

Definition at line 322 of file pg_locale.c.

References CurrentLocaleConvValid.

323 {
324  CurrentLocaleConvValid = false;
325 }
static bool CurrentLocaleConvValid
Definition: pg_locale.c:106

◆ assign_locale_numeric()

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

Definition at line 334 of file pg_locale.c.

References CurrentLocaleConvValid.

335 {
336  CurrentLocaleConvValid = false;
337 }
static bool CurrentLocaleConvValid
Definition: pg_locale.c:106

◆ assign_locale_time()

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

Definition at line 346 of file pg_locale.c.

References CurrentLCTimeValid.

347 {
348  CurrentLCTimeValid = false;
349 }
static bool CurrentLCTimeValid
Definition: pg_locale.c:107

◆ cache_locale_time()

void cache_locale_time ( void  )

Definition at line 774 of file pg_locale.c.

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_strcasecmp(), PG_UTF8, pstrdup(), setlocale, tm, and wchar2char().

Referenced by DCH_to_char().

775 {
776  char buf[(2 * 7 + 2 * 12) * MAX_L10N_DATA];
777  char *bufptr;
778  time_t timenow;
779  struct tm *timeinfo;
780  bool strftimefail = false;
781  int encoding;
782  int i;
783  char *save_lc_time;
784 #ifdef WIN32
785  char *save_lc_ctype;
786 #endif
787 
788  /* did we do this already? */
789  if (CurrentLCTimeValid)
790  return;
791 
792  elog(DEBUG3, "cache_locale_time() executed; locale: \"%s\"", locale_time);
793 
794  /*
795  * As in PGLC_localeconv(), it's critical that we not throw error while
796  * libc's locale settings have nondefault values. Hence, we just call
797  * strftime() within the critical section, and then convert and save its
798  * results afterwards.
799  */
800 
801  /* Save prevailing value of time locale */
802  save_lc_time = setlocale(LC_TIME, NULL);
803  if (!save_lc_time)
804  elog(ERROR, "setlocale(NULL) failed");
805  save_lc_time = pstrdup(save_lc_time);
806 
807 #ifdef WIN32
808 
809  /*
810  * On Windows, it appears that wcsftime() internally uses LC_CTYPE, so we
811  * must set it here. This code looks the same as what PGLC_localeconv()
812  * does, but the underlying reason is different: this does NOT determine
813  * the encoding we'll get back from strftime_win32().
814  */
815 
816  /* Save prevailing value of ctype locale */
817  save_lc_ctype = setlocale(LC_CTYPE, NULL);
818  if (!save_lc_ctype)
819  elog(ERROR, "setlocale(NULL) failed");
820  save_lc_ctype = pstrdup(save_lc_ctype);
821 
822  /* use lc_time to set the ctype */
823  setlocale(LC_CTYPE, locale_time);
824 #endif
825 
826  setlocale(LC_TIME, locale_time);
827 
828  /* We use times close to current time as data for strftime(). */
829  timenow = time(NULL);
830  timeinfo = localtime(&timenow);
831 
832  /* Store the strftime results in MAX_L10N_DATA-sized portions of buf[] */
833  bufptr = buf;
834 
835  /*
836  * MAX_L10N_DATA is sufficient buffer space for every known locale, and
837  * POSIX defines no strftime() errors. (Buffer space exhaustion is not an
838  * error.) An implementation might report errors (e.g. ENOMEM) by
839  * returning 0 (or, less plausibly, a negative value) and setting errno.
840  * Report errno just in case the implementation did that, but clear it in
841  * advance of the calls so we don't emit a stale, unrelated errno.
842  */
843  errno = 0;
844 
845  /* localized days */
846  for (i = 0; i < 7; i++)
847  {
848  timeinfo->tm_wday = i;
849  if (strftime(bufptr, MAX_L10N_DATA, "%a", timeinfo) <= 0)
850  strftimefail = true;
851  bufptr += MAX_L10N_DATA;
852  if (strftime(bufptr, MAX_L10N_DATA, "%A", timeinfo) <= 0)
853  strftimefail = true;
854  bufptr += MAX_L10N_DATA;
855  }
856 
857  /* localized months */
858  for (i = 0; i < 12; i++)
859  {
860  timeinfo->tm_mon = i;
861  timeinfo->tm_mday = 1; /* make sure we don't have invalid date */
862  if (strftime(bufptr, MAX_L10N_DATA, "%b", timeinfo) <= 0)
863  strftimefail = true;
864  bufptr += MAX_L10N_DATA;
865  if (strftime(bufptr, MAX_L10N_DATA, "%B", timeinfo) <= 0)
866  strftimefail = true;
867  bufptr += MAX_L10N_DATA;
868  }
869 
870  /*
871  * Restore the prevailing locale settings; as in PGLC_localeconv(),
872  * failure to do so is fatal.
873  */
874 #ifdef WIN32
875  if (!setlocale(LC_CTYPE, save_lc_ctype))
876  elog(FATAL, "failed to restore LC_CTYPE to \"%s\"", save_lc_ctype);
877 #endif
878  if (!setlocale(LC_TIME, save_lc_time))
879  elog(FATAL, "failed to restore LC_TIME to \"%s\"", save_lc_time);
880 
881  /*
882  * At this point we've done our best to clean up, and can throw errors, or
883  * call functions that might throw errors, with a clean conscience.
884  */
885  if (strftimefail)
886  elog(ERROR, "strftime() failed: %m");
887 
888  /* Release the pstrdup'd locale names */
889  pfree(save_lc_time);
890 #ifdef WIN32
891  pfree(save_lc_ctype);
892 #endif
893 
894 #ifndef WIN32
895 
896  /*
897  * As in PGLC_localeconv(), we must convert strftime()'s output from the
898  * encoding implied by LC_TIME to the database encoding. If we can't
899  * identify the LC_TIME encoding, just perform encoding validation.
900  */
901  encoding = pg_get_encoding_from_locale(locale_time, true);
902  if (encoding < 0)
903  encoding = PG_SQL_ASCII;
904 
905 #else
906 
907  /*
908  * On Windows, strftime_win32() always returns UTF8 data, so convert from
909  * that if necessary.
910  */
911  encoding = PG_UTF8;
912 
913 #endif /* WIN32 */
914 
915  bufptr = buf;
916 
917  /* localized days */
918  for (i = 0; i < 7; i++)
919  {
920  cache_single_string(&localized_abbrev_days[i], bufptr, encoding);
921  bufptr += MAX_L10N_DATA;
922  cache_single_string(&localized_full_days[i], bufptr, encoding);
923  bufptr += MAX_L10N_DATA;
924  }
925 
926  /* localized months */
927  for (i = 0; i < 12; i++)
928  {
929  cache_single_string(&localized_abbrev_months[i], bufptr, encoding);
930  bufptr += MAX_L10N_DATA;
931  cache_single_string(&localized_full_months[i], bufptr, encoding);
932  bufptr += MAX_L10N_DATA;
933  }
934 
935  CurrentLCTimeValid = true;
936 }
#define setlocale(a, b)
Definition: win32_port.h:408
#define DEBUG3
Definition: elog.h:23
char * pstrdup(const char *in)
Definition: mcxt.c:1186
char * localized_abbrev_months[12]
Definition: pg_locale.c:102
static struct pg_tm tm
Definition: localtime.c:108
void pfree(void *pointer)
Definition: mcxt.c:1056
#define MAX_L10N_DATA
Definition: pg_locale.c:90
#define ERROR
Definition: elog.h:43
#define FATAL
Definition: elog.h:52
static char * buf
Definition: pg_test_fsync.c:67
int pg_get_encoding_from_locale(const char *ctype, bool write_message)
Definition: chklocale.c:433
char * localized_full_days[7]
Definition: pg_locale.c:101
static void cache_single_string(char **dst, const char *src, int encoding)
Definition: pg_locale.c:751
int32 encoding
Definition: pg_database.h:41
#define elog(elevel,...)
Definition: elog.h:228
int i
char * localized_full_months[12]
Definition: pg_locale.c:103
char * localized_abbrev_days[7]
Definition: pg_locale.c:100
char * locale_time
Definition: pg_locale.c:97
static bool CurrentLCTimeValid
Definition: pg_locale.c:107

◆ cache_single_string()

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

Definition at line 751 of file pg_locale.c.

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

Referenced by cache_locale_time().

752 {
753  char *ptr;
754  char *olddst;
755 
756  /* Convert the string to the database encoding, or validate it's OK */
757  ptr = pg_any_to_server(src, strlen(src), encoding);
758 
759  /* Store the string in long-lived storage, replacing any previous value */
760  olddst = *dst;
762  if (olddst)
763  pfree(olddst);
764 
765  /* Might as well clean up any palloc'd conversion result, too */
766  if (ptr != src)
767  pfree(ptr);
768 }
void pfree(void *pointer)
Definition: mcxt.c:1056
MemoryContext TopMemoryContext
Definition: mcxt.c:44
int32 encoding
Definition: pg_database.h:41
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1173
char * pg_any_to_server(const char *s, int len, int encoding)
Definition: mbutils.c:581

◆ char2wchar()

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

Definition at line 1836 of file pg_locale.c.

References Assert, elog, ereport, errcode(), errhint(), errmsg(), ERROR, GetDatabaseEncoding(), pg_locale_struct::info, locale_t, mbstowcs_l, pfree(), PG_UTF8, pg_verifymbstr(), pnstrdup(), pg_locale_struct::provider, and generate_unaccent_rules::str.

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

1838 {
1839  size_t result;
1840 
1841  Assert(!locale || locale->provider == COLLPROVIDER_LIBC);
1842 
1843  if (tolen == 0)
1844  return 0;
1845 
1846 #ifdef WIN32
1847  /* See WIN32 "Unicode" comment above */
1848  if (GetDatabaseEncoding() == PG_UTF8)
1849  {
1850  /* Win32 API does not work for zero-length input */
1851  if (fromlen == 0)
1852  result = 0;
1853  else
1854  {
1855  result = MultiByteToWideChar(CP_UTF8, 0, from, fromlen, to, tolen - 1);
1856  /* A zero return is failure */
1857  if (result == 0)
1858  result = -1;
1859  }
1860 
1861  if (result != -1)
1862  {
1863  Assert(result < tolen);
1864  /* Append trailing null wchar (MultiByteToWideChar() does not) */
1865  to[result] = 0;
1866  }
1867  }
1868  else
1869 #endif /* WIN32 */
1870  {
1871  /* mbstowcs requires ending '\0' */
1872  char *str = pnstrdup(from, fromlen);
1873 
1874  if (locale == (pg_locale_t) 0)
1875  {
1876  /* Use mbstowcs directly for the default locale */
1877  result = mbstowcs(to, str, tolen);
1878  }
1879  else
1880  {
1881 #ifdef HAVE_LOCALE_T
1882 #ifdef HAVE_MBSTOWCS_L
1883  /* Use mbstowcs_l for nondefault locales */
1884  result = mbstowcs_l(to, str, tolen, locale->info.lt);
1885 #else /* !HAVE_MBSTOWCS_L */
1886  /* We have to temporarily set the locale as current ... ugh */
1887  locale_t save_locale = uselocale(locale->info.lt);
1888 
1889  result = mbstowcs(to, str, tolen);
1890 
1891  uselocale(save_locale);
1892 #endif /* HAVE_MBSTOWCS_L */
1893 #else /* !HAVE_LOCALE_T */
1894  /* Can't have locale != 0 without HAVE_LOCALE_T */
1895  elog(ERROR, "mbstowcs_l is not available");
1896  result = 0; /* keep compiler quiet */
1897 #endif /* HAVE_LOCALE_T */
1898  }
1899 
1900  pfree(str);
1901  }
1902 
1903  if (result == -1)
1904  {
1905  /*
1906  * Invalid multibyte character encountered. We try to give a useful
1907  * error message by letting pg_verifymbstr check the string. But it's
1908  * possible that the string is OK to us, and not OK to mbstowcs ---
1909  * this suggests that the LC_CTYPE locale is different from the
1910  * database encoding. Give a generic error message if pg_verifymbstr
1911  * can't find anything wrong.
1912  */
1913  pg_verifymbstr(from, fromlen, false); /* might not return */
1914  /* but if it does ... */
1915  ereport(ERROR,
1916  (errcode(ERRCODE_CHARACTER_NOT_IN_REPERTOIRE),
1917  errmsg("invalid multibyte character for locale"),
1918  errhint("The server's LC_CTYPE locale is probably incompatible with the database encoding.")));
1919  }
1920 
1921  return result;
1922 }
union pg_locale_struct::@144 info
int errhint(const char *fmt,...)
Definition: elog.c:1071
char * pnstrdup(const char *in, Size len)
Definition: mcxt.c:1197
int errcode(int sqlerrcode)
Definition: elog.c:608
void pfree(void *pointer)
Definition: mcxt.c:1056
#define ERROR
Definition: elog.h:43
#define locale_t
Definition: win32_port.h:363
#define ereport(elevel, rest)
Definition: elog.h:141
int GetDatabaseEncoding(void)
Definition: mbutils.c:1046
#define Assert(condition)
Definition: c.h:733
#define mbstowcs_l
Definition: win32_port.h:390
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define elog(elevel,...)
Definition: elog.h:228
bool pg_verifymbstr(const char *mbstr, int len, bool noError)
Definition: wchar.c:1914

◆ check_locale()

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

Definition at line 273 of file pg_locale.c.

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

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

274 {
275  char *save;
276  char *res;
277 
278  if (canonname)
279  *canonname = NULL; /* in case of failure */
280 
281  save = setlocale(category, NULL);
282  if (!save)
283  return false; /* won't happen, we hope */
284 
285  /* save may be pointing at a modifiable scratch variable, see above. */
286  save = pstrdup(save);
287 
288  /* set the locale with setlocale, to see if it accepts it. */
289  res = setlocale(category, locale);
290 
291  /* save canonical name if requested. */
292  if (res && canonname)
293  *canonname = pstrdup(res);
294 
295  /* restore old value. */
296  if (!setlocale(category, save))
297  elog(WARNING, "failed to restore old locale \"%s\"", save);
298  pfree(save);
299 
300  return (res != NULL);
301 }
#define setlocale(a, b)
Definition: win32_port.h:408
char * pstrdup(const char *in)
Definition: mcxt.c:1186
void pfree(void *pointer)
Definition: mcxt.c:1056
#define WARNING
Definition: elog.h:40
#define elog(elevel,...)
Definition: elog.h:228
static char * locale
Definition: initdb.c:125

◆ check_locale_messages()

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

Definition at line 362 of file pg_locale.c.

References check_locale(), and PGC_S_DEFAULT.

363 {
364  if (**newval == '\0')
365  {
366  if (source == PGC_S_DEFAULT)
367  return true;
368  else
369  return false;
370  }
371 
372  /*
373  * LC_MESSAGES category does not exist everywhere, but accept it anyway
374  *
375  * On Windows, we can't even check the value, so accept blindly
376  */
377 #if defined(LC_MESSAGES) && !defined(WIN32)
378  return check_locale(LC_MESSAGES, *newval, NULL);
379 #else
380  return true;
381 #endif
382 }
bool check_locale(int category, const char *locale, char **canonname)
Definition: pg_locale.c:273
#define newval

◆ check_locale_monetary()

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

Definition at line 316 of file pg_locale.c.

References check_locale().

317 {
318  return check_locale(LC_MONETARY, *newval, NULL);
319 }
bool check_locale(int category, const char *locale, char **canonname)
Definition: pg_locale.c:273
#define newval

◆ check_locale_numeric()

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

Definition at line 328 of file pg_locale.c.

References check_locale().

329 {
330  return check_locale(LC_NUMERIC, *newval, NULL);
331 }
bool check_locale(int category, const char *locale, char **canonname)
Definition: pg_locale.c:273
#define newval

◆ check_locale_time()

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

Definition at line 340 of file pg_locale.c.

References check_locale().

341 {
342  return check_locale(LC_TIME, *newval, NULL);
343 }
bool check_locale(int category, const char *locale, char **canonname)
Definition: pg_locale.c:273
#define newval

◆ check_strxfrm_bug()

void check_strxfrm_bug ( void  )

Definition at line 1041 of file pg_locale.c.

References buf, ereport, errcode(), errhint(), errmsg_internal(), ERROR, and setlocale.

Referenced by CheckMyDatabase(), and main().

1042 {
1043  char buf[32];
1044  const int canary = 0x7F;
1045  bool ok = true;
1046 
1047  /*
1048  * Given a two-byte ASCII string and length limit 7, 8 or 9, Solaris 10
1049  * 05/08 returns 18 and modifies 10 bytes. It respects limits above or
1050  * below that range.
1051  *
1052  * The bug is present in Solaris 8 as well; it is absent in Solaris 10
1053  * 01/13 and Solaris 11.2. Affected locales include is_IS.ISO8859-1,
1054  * en_US.UTF-8, en_US.ISO8859-1, and ru_RU.KOI8-R. Unaffected locales
1055  * include de_DE.UTF-8, de_DE.ISO8859-1, zh_TW.UTF-8, and C.
1056  */
1057  buf[7] = canary;
1058  (void) strxfrm(buf, "ab", 7);
1059  if (buf[7] != canary)
1060  ok = false;
1061 
1062  /*
1063  * illumos bug #1594 was present in the source tree from 2010-10-11 to
1064  * 2012-02-01. Given an ASCII string of any length and length limit 1,
1065  * affected systems ignore the length limit and modify a number of bytes
1066  * one less than the return value. The problem inputs for this bug do not
1067  * overlap those for the Solaris bug, hence a distinct test.
1068  *
1069  * Affected systems include smartos-20110926T021612Z. Affected locales
1070  * include en_US.ISO8859-1 and en_US.UTF-8. Unaffected locales include C.
1071  */
1072  buf[1] = canary;
1073  (void) strxfrm(buf, "a", 1);
1074  if (buf[1] != canary)
1075  ok = false;
1076 
1077  if (!ok)
1078  ereport(ERROR,
1079  (errcode(ERRCODE_SYSTEM_ERROR),
1080  errmsg_internal("strxfrm(), in locale \"%s\", writes past the specified array length",
1081  setlocale(LC_COLLATE, NULL)),
1082  errhint("Apply system library package updates.")));
1083 }
int errhint(const char *fmt,...)
Definition: elog.c:1071
#define setlocale(a, b)
Definition: win32_port.h:408
int errcode(int sqlerrcode)
Definition: elog.c:608
#define ERROR
Definition: elog.h:43
static char * buf
Definition: pg_test_fsync.c:67
#define ereport(elevel, rest)
Definition: elog.h:141
int errmsg_internal(const char *fmt,...)
Definition: elog.c:911

◆ db_encoding_convert()

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

Definition at line 462 of file pg_locale.c.

References ereport, errcode(), errmsg(), ERROR, free, pfree(), and pg_any_to_server().

Referenced by PGLC_localeconv().

463 {
464  char *pstr;
465  char *mstr;
466 
467  /* convert the string to the database encoding */
468  pstr = pg_any_to_server(*str, strlen(*str), encoding);
469  if (pstr == *str)
470  return; /* no conversion happened */
471 
472  /* need it malloc'd not palloc'd */
473  mstr = strdup(pstr);
474  if (mstr == NULL)
475  ereport(ERROR,
476  (errcode(ERRCODE_OUT_OF_MEMORY),
477  errmsg("out of memory")));
478 
479  /* replace old string */
480  free(*str);
481  *str = mstr;
482 
483  pfree(pstr);
484 }
int errcode(int sqlerrcode)
Definition: elog.c:608
void pfree(void *pointer)
Definition: mcxt.c:1056
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
#define free(a)
Definition: header.h:65
int32 encoding
Definition: pg_database.h:41
int errmsg(const char *fmt,...)
Definition: elog.c:822
char * pg_any_to_server(const char *s, int len, int encoding)
Definition: mbutils.c:581

◆ free_struct_lconv()

static void free_struct_lconv ( struct lconv *  s)
static

Definition at line 402 of file pg_locale.c.

References free.

Referenced by PGLC_localeconv().

403 {
404  if (s->decimal_point)
405  free(s->decimal_point);
406  if (s->thousands_sep)
407  free(s->thousands_sep);
408  if (s->grouping)
409  free(s->grouping);
410  if (s->int_curr_symbol)
411  free(s->int_curr_symbol);
412  if (s->currency_symbol)
413  free(s->currency_symbol);
414  if (s->mon_decimal_point)
415  free(s->mon_decimal_point);
416  if (s->mon_thousands_sep)
417  free(s->mon_thousands_sep);
418  if (s->mon_grouping)
419  free(s->mon_grouping);
420  if (s->positive_sign)
421  free(s->positive_sign);
422  if (s->negative_sign)
423  free(s->negative_sign);
424 }
#define free(a)
Definition: header.h:65

◆ get_collation_actual_version()

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

Definition at line 1504 of file pg_locale.c.

References asc_tolower(), buf, ereport, errmsg(), ERROR, get_encoding_name_for_icu(), GetDatabaseEncoding(), name, palloc(), pg_attribute_unused(), pstrdup(), status(), generate_unaccent_rules::str, and value.

Referenced by AlterCollation(), DefineCollation(), pg_collation_actual_version(), pg_import_system_collations(), and pg_newlocale_from_collation().

1505 {
1506  char *collversion = NULL;
1507 
1508 #ifdef USE_ICU
1509  if (collprovider == COLLPROVIDER_ICU)
1510  {
1511  UCollator *collator;
1512  UErrorCode status;
1513  UVersionInfo versioninfo;
1514  char buf[U_MAX_VERSION_STRING_LENGTH];
1515 
1516  status = U_ZERO_ERROR;
1517  collator = ucol_open(collcollate, &status);
1518  if (U_FAILURE(status))
1519  ereport(ERROR,
1520  (errmsg("could not open collator for locale \"%s\": %s",
1521  collcollate, u_errorName(status))));
1522  ucol_getVersion(collator, versioninfo);
1523  ucol_close(collator);
1524 
1525  u_versionToString(versioninfo, buf);
1526  collversion = pstrdup(buf);
1527  }
1528  else
1529 #endif
1530  if (collprovider == COLLPROVIDER_LIBC)
1531  {
1532 #if defined(__GLIBC__)
1533  /* Use the glibc version because we don't have anything better. */
1534  collversion = pstrdup(gnu_get_libc_version());
1535 #endif
1536  }
1537 
1538  return collversion;
1539 }
char * pstrdup(const char *in)
Definition: mcxt.c:1186
#define ERROR
Definition: elog.h:43
static char * buf
Definition: pg_test_fsync.c:67
#define ereport(elevel, rest)
Definition: elog.h:141
int errmsg(const char *fmt,...)
Definition: elog.c:822
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:226

◆ lc_collate_is_c()

bool lc_collate_is_c ( Oid  collation)

Definition at line 1176 of file pg_locale.c.

References elog, ERROR, lookup_collation_cache(), OidIsValid, and setlocale.

Referenced by bpchareq(), bpcharne(), 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().

1177 {
1178  /*
1179  * If we're asked about "collation 0", return false, so that the code will
1180  * go into the non-C path and report that the collation is bogus.
1181  */
1182  if (!OidIsValid(collation))
1183  return false;
1184 
1185  /*
1186  * If we're asked about the default collation, we have to inquire of the C
1187  * library. Cache the result so we only have to compute it once.
1188  */
1189  if (collation == DEFAULT_COLLATION_OID)
1190  {
1191  static int result = -1;
1192  char *localeptr;
1193 
1194  if (result >= 0)
1195  return (bool) result;
1196  localeptr = setlocale(LC_COLLATE, NULL);
1197  if (!localeptr)
1198  elog(ERROR, "invalid LC_COLLATE setting");
1199 
1200  if (strcmp(localeptr, "C") == 0)
1201  result = true;
1202  else if (strcmp(localeptr, "POSIX") == 0)
1203  result = true;
1204  else
1205  result = false;
1206  return (bool) result;
1207  }
1208 
1209  /*
1210  * If we're asked about the built-in C/POSIX collations, we know that.
1211  */
1212  if (collation == C_COLLATION_OID ||
1213  collation == POSIX_COLLATION_OID)
1214  return true;
1215 
1216  /*
1217  * Otherwise, we have to consult pg_collation, but we cache that.
1218  */
1219  return (lookup_collation_cache(collation, true))->collate_is_c;
1220 }
#define setlocale(a, b)
Definition: win32_port.h:408
#define OidIsValid(objectId)
Definition: c.h:639
#define ERROR
Definition: elog.h:43
#define elog(elevel,...)
Definition: elog.h:228
static collation_cache_entry * lookup_collation_cache(Oid collation, bool set_flags)
Definition: pg_locale.c:1111

◆ lc_ctype_is_c()

bool lc_ctype_is_c ( Oid  collation)

Definition at line 1226 of file pg_locale.c.

References elog, ereport, errcode(), errdetail(), errmsg(), ERROR, lookup_collation_cache(), OidIsValid, and setlocale.

Referenced by DefineCollation(), Generic_Text_IC_like(), GenericMatchText(), like_fixed_prefix(), lowerstr_with_len(), pg_set_regex_collation(), str_initcap(), str_tolower(), str_toupper(), t_isalpha(), t_isdigit(), t_isprint(), t_isspace(), and TParserInit().

1227 {
1228  /*
1229  * If we're asked about "collation 0", return false, so that the code will
1230  * go into the non-C path and report that the collation is bogus.
1231  */
1232  if (!OidIsValid(collation))
1233  return false;
1234 
1235  /*
1236  * If we're asked about the default collation, we have to inquire of the C
1237  * library. Cache the result so we only have to compute it once.
1238  */
1239  if (collation == DEFAULT_COLLATION_OID)
1240  {
1241  static int result = -1;
1242  char *localeptr;
1243 
1244  if (result >= 0)
1245  return (bool) result;
1246  localeptr = setlocale(LC_CTYPE, NULL);
1247  if (!localeptr)
1248  elog(ERROR, "invalid LC_CTYPE setting");
1249 
1250  if (strcmp(localeptr, "C") == 0)
1251  result = true;
1252  else if (strcmp(localeptr, "POSIX") == 0)
1253  result = true;
1254  else
1255  result = false;
1256  return (bool) result;
1257  }
1258 
1259  /*
1260  * If we're asked about the built-in C/POSIX collations, we know that.
1261  */
1262  if (collation == C_COLLATION_OID ||
1263  collation == POSIX_COLLATION_OID)
1264  return true;
1265 
1266  /*
1267  * Otherwise, we have to consult pg_collation, but we cache that.
1268  */
1269  return (lookup_collation_cache(collation, true))->ctype_is_c;
1270 }
#define setlocale(a, b)
Definition: win32_port.h:408
#define OidIsValid(objectId)
Definition: c.h:639
#define ERROR
Definition: elog.h:43
#define elog(elevel,...)
Definition: elog.h:228
static collation_cache_entry * lookup_collation_cache(Oid collation, bool set_flags)
Definition: pg_locale.c:1111

◆ lookup_collation_cache()

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

Definition at line 1111 of file pg_locale.c.

References Assert, collation_cache_entry::collate_is_c, COLLOID, 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, NameStr, ObjectIdGetDatum, OidIsValid, ReleaseSysCache(), and SearchSysCache1().

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

1112 {
1113  collation_cache_entry *cache_entry;
1114  bool found;
1115 
1116  Assert(OidIsValid(collation));
1117  Assert(collation != DEFAULT_COLLATION_OID);
1118 
1119  if (collation_cache == NULL)
1120  {
1121  /* First time through, initialize the hash table */
1122  HASHCTL ctl;
1123 
1124  memset(&ctl, 0, sizeof(ctl));
1125  ctl.keysize = sizeof(Oid);
1126  ctl.entrysize = sizeof(collation_cache_entry);
1127  collation_cache = hash_create("Collation cache", 100, &ctl,
1128  HASH_ELEM | HASH_BLOBS);
1129  }
1130 
1131  cache_entry = hash_search(collation_cache, &collation, HASH_ENTER, &found);
1132  if (!found)
1133  {
1134  /*
1135  * Make sure cache entry is marked invalid, in case we fail before
1136  * setting things.
1137  */
1138  cache_entry->flags_valid = false;
1139  cache_entry->locale = 0;
1140  }
1141 
1142  if (set_flags && !cache_entry->flags_valid)
1143  {
1144  /* Attempt to set the flags */
1145  HeapTuple tp;
1146  Form_pg_collation collform;
1147  const char *collcollate;
1148  const char *collctype;
1149 
1150  tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
1151  if (!HeapTupleIsValid(tp))
1152  elog(ERROR, "cache lookup failed for collation %u", collation);
1153  collform = (Form_pg_collation) GETSTRUCT(tp);
1154 
1155  collcollate = NameStr(collform->collcollate);
1156  collctype = NameStr(collform->collctype);
1157 
1158  cache_entry->collate_is_c = ((strcmp(collcollate, "C") == 0) ||
1159  (strcmp(collcollate, "POSIX") == 0));
1160  cache_entry->ctype_is_c = ((strcmp(collctype, "C") == 0) ||
1161  (strcmp(collctype, "POSIX") == 0));
1162 
1163  cache_entry->flags_valid = true;
1164 
1165  ReleaseSysCache(tp);
1166  }
1167 
1168  return cache_entry;
1169 }
bool flags_valid
Definition: pg_locale.c:130
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define HASH_ELEM
Definition: hsearch.h:87
bool ctype_is_c
Definition: pg_locale.c:129
Size entrysize
Definition: hsearch.h:73
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:906
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:639
bool collate_is_c
Definition: pg_locale.c:128
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
pg_locale_t locale
Definition: pg_locale.c:131
#define HASH_BLOBS
Definition: hsearch.h:88
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:316
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
Size keysize
Definition: hsearch.h:72
static HTAB * collation_cache
Definition: pg_locale.c:134
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:733
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:51
#define elog(elevel,...)
Definition: elog.h:228
#define NameStr(name)
Definition: c.h:610
Definition: pg_locale.c:125

◆ pg_newlocale_from_collation()

pg_locale_t pg_newlocale_from_collation ( Oid  collid)

Definition at line 1323 of file pg_locale.c.

References Assert, COLLOID, pg_locale_struct::deterministic, elog, ereport, errcode(), errdetail(), errhint(), errmsg(), ERROR, get_collation_actual_version(), get_namespace_name(), GETSTRUCT, HeapTupleIsValid, pg_locale_struct::info, collation_cache_entry::locale, locale_t, lookup_collation_cache(), MemoryContextAlloc(), MemoryContextStrdup(), NameStr, ObjectIdGetDatum, OidIsValid, pg_attribute_unused(), pg_locale_struct::provider, quote_qualified_identifier(), ReleaseSysCache(), SearchSysCache1(), status(), SysCacheGetAttr(), 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().

1324 {
1325  collation_cache_entry *cache_entry;
1326 
1327  /* Callers must pass a valid OID */
1328  Assert(OidIsValid(collid));
1329 
1330  /* Return 0 for "default" collation, just in case caller forgets */
1331  if (collid == DEFAULT_COLLATION_OID)
1332  return (pg_locale_t) 0;
1333 
1334  cache_entry = lookup_collation_cache(collid, false);
1335 
1336  if (cache_entry->locale == 0)
1337  {
1338  /* We haven't computed this yet in this session, so do it */
1339  HeapTuple tp;
1340  Form_pg_collation collform;
1341  const char *collcollate;
1342  const char *collctype pg_attribute_unused();
1343  struct pg_locale_struct result;
1344  pg_locale_t resultp;
1345  Datum collversion;
1346  bool isnull;
1347 
1348  tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collid));
1349  if (!HeapTupleIsValid(tp))
1350  elog(ERROR, "cache lookup failed for collation %u", collid);
1351  collform = (Form_pg_collation) GETSTRUCT(tp);
1352 
1353  collcollate = NameStr(collform->collcollate);
1354  collctype = NameStr(collform->collctype);
1355 
1356  /* We'll fill in the result struct locally before allocating memory */
1357  memset(&result, 0, sizeof(result));
1358  result.provider = collform->collprovider;
1359  result.deterministic = collform->collisdeterministic;
1360 
1361  if (collform->collprovider == COLLPROVIDER_LIBC)
1362  {
1363 #ifdef HAVE_LOCALE_T
1364  locale_t loc;
1365 
1366  if (strcmp(collcollate, collctype) == 0)
1367  {
1368  /* Normal case where they're the same */
1369  errno = 0;
1370 #ifndef WIN32
1371  loc = newlocale(LC_COLLATE_MASK | LC_CTYPE_MASK, collcollate,
1372  NULL);
1373 #else
1374  loc = _create_locale(LC_ALL, collcollate);
1375 #endif
1376  if (!loc)
1377  report_newlocale_failure(collcollate);
1378  }
1379  else
1380  {
1381 #ifndef WIN32
1382  /* We need two newlocale() steps */
1383  locale_t loc1;
1384 
1385  errno = 0;
1386  loc1 = newlocale(LC_COLLATE_MASK, collcollate, NULL);
1387  if (!loc1)
1388  report_newlocale_failure(collcollate);
1389  errno = 0;
1390  loc = newlocale(LC_CTYPE_MASK, collctype, loc1);
1391  if (!loc)
1392  report_newlocale_failure(collctype);
1393 #else
1394 
1395  /*
1396  * XXX The _create_locale() API doesn't appear to support
1397  * this. Could perhaps be worked around by changing
1398  * pg_locale_t to contain two separate fields.
1399  */
1400  ereport(ERROR,
1401  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1402  errmsg("collations with different collate and ctype values are not supported on this platform")));
1403 #endif
1404  }
1405 
1406  result.info.lt = loc;
1407 #else /* not HAVE_LOCALE_T */
1408  /* platform that doesn't support locale_t */
1409  ereport(ERROR,
1410  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1411  errmsg("collation provider LIBC is not supported on this platform")));
1412 #endif /* not HAVE_LOCALE_T */
1413  }
1414  else if (collform->collprovider == COLLPROVIDER_ICU)
1415  {
1416 #ifdef USE_ICU
1417  UCollator *collator;
1418  UErrorCode status;
1419 
1420  if (strcmp(collcollate, collctype) != 0)
1421  ereport(ERROR,
1422  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1423  errmsg("collations with different collate and ctype values are not supported by ICU")));
1424 
1425  status = U_ZERO_ERROR;
1426  collator = ucol_open(collcollate, &status);
1427  if (U_FAILURE(status))
1428  ereport(ERROR,
1429  (errmsg("could not open collator for locale \"%s\": %s",
1430  collcollate, u_errorName(status))));
1431 
1432  if (U_ICU_VERSION_MAJOR_NUM < 54)
1433  icu_set_collation_attributes(collator, collcollate);
1434 
1435  /* We will leak this string if we get an error below :-( */
1436  result.info.icu.locale = MemoryContextStrdup(TopMemoryContext,
1437  collcollate);
1438  result.info.icu.ucol = collator;
1439 #else /* not USE_ICU */
1440  /* could get here if a collation was created by a build with ICU */
1441  ereport(ERROR,
1442  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1443  errmsg("ICU is not supported in this build"), \
1444  errhint("You need to rebuild PostgreSQL using --with-icu.")));
1445 #endif /* not USE_ICU */
1446  }
1447 
1448  collversion = SysCacheGetAttr(COLLOID, tp, Anum_pg_collation_collversion,
1449  &isnull);
1450  if (!isnull)
1451  {
1452  char *actual_versionstr;
1453  char *collversionstr;
1454 
1455  actual_versionstr = get_collation_actual_version(collform->collprovider, collcollate);
1456  if (!actual_versionstr)
1457  {
1458  /*
1459  * This could happen when specifying a version in CREATE
1460  * COLLATION for a libc locale, or manually creating a mess in
1461  * the catalogs.
1462  */
1463  ereport(ERROR,
1464  (errmsg("collation \"%s\" has no actual version, but a version was specified",
1465  NameStr(collform->collname))));
1466  }
1467  collversionstr = TextDatumGetCString(collversion);
1468 
1469  if (strcmp(actual_versionstr, collversionstr) != 0)
1470  ereport(WARNING,
1471  (errmsg("collation \"%s\" has version mismatch",
1472  NameStr(collform->collname)),
1473  errdetail("The collation in the database was created using version %s, "
1474  "but the operating system provides version %s.",
1475  collversionstr, actual_versionstr),
1476  errhint("Rebuild all objects affected by this collation and run "
1477  "ALTER COLLATION %s REFRESH VERSION, "
1478  "or build PostgreSQL with the right library version.",
1479  quote_qualified_identifier(get_namespace_name(collform->collnamespace),
1480  NameStr(collform->collname)))));
1481  }
1482 
1483  ReleaseSysCache(tp);
1484 
1485  /* We'll keep the pg_locale_t structures in TopMemoryContext */
1486  resultp = MemoryContextAlloc(TopMemoryContext, sizeof(*resultp));
1487  *resultp = result;
1488 
1489  cache_entry->locale = resultp;
1490  }
1491 
1492  return cache_entry->locale;
1493 }
int errhint(const char *fmt,...)
Definition: elog.c:1071
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
int errcode(int sqlerrcode)
Definition: elog.c:608
#define OidIsValid(objectId)
Definition: c.h:639
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
int errdetail(const char *fmt,...)
Definition: elog.c:957
#define locale_t
Definition: win32_port.h:363
#define ereport(elevel, rest)
Definition: elog.h:141
MemoryContext TopMemoryContext
Definition: mcxt.c:44
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10724
#define WARNING
Definition: elog.h:40
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
pg_locale_t locale
Definition: pg_locale.c:131
#define TextDatumGetCString(d)
Definition: builtins.h:84
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1377
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:733
pg_attribute_unused()
Definition: isn.c:63
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:51
int errmsg(const char *fmt,...)
Definition: elog.c:822
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1173
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:796
#define elog(elevel,...)
Definition: elog.h:228
#define NameStr(name)
Definition: c.h:610
static collation_cache_entry * lookup_collation_cache(Oid collation, bool set_flags)
Definition: pg_locale.c:1111
Definition: pg_locale.c:125
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:226
char * get_collation_actual_version(char collprovider, const char *collcollate)
Definition: pg_locale.c:1504

◆ pg_perm_setlocale()

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

Definition at line 160 of file pg_locale.c.

References elog, FATAL, GetDatabaseEncoding(), lc_collate_envbuf, lc_ctype_envbuf, LC_ENV_BUFSIZE, lc_monetary_envbuf, lc_numeric_envbuf, lc_time_envbuf, putenv, setlocale, SetMessageEncoding(), snprintf, and strlcpy().

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

161 {
162  char *result;
163  const char *envvar;
164  char *envbuf;
165 
166 #ifndef WIN32
167  result = setlocale(category, locale);
168 #else
169 
170  /*
171  * On Windows, setlocale(LC_MESSAGES) does not work, so just assume that
172  * the given value is good and set it in the environment variables. We
173  * must ignore attempts to set to "", which means "keep using the old
174  * environment value".
175  */
176 #ifdef LC_MESSAGES
177  if (category == LC_MESSAGES)
178  {
179  result = (char *) locale;
180  if (locale == NULL || locale[0] == '\0')
181  return result;
182  }
183  else
184 #endif
185  result = setlocale(category, locale);
186 #endif /* WIN32 */
187 
188  if (result == NULL)
189  return result; /* fall out immediately on failure */
190 
191  /*
192  * Use the right encoding in translated messages. Under ENABLE_NLS, let
193  * pg_bind_textdomain_codeset() figure it out. Under !ENABLE_NLS, message
194  * format strings are ASCII, but database-encoding strings may enter the
195  * message via %s. This makes the overall message encoding equal to the
196  * database encoding.
197  */
198  if (category == LC_CTYPE)
199  {
200  static char save_lc_ctype[LC_ENV_BUFSIZE];
201 
202  /* copy setlocale() return value before callee invokes it again */
203  strlcpy(save_lc_ctype, result, sizeof(save_lc_ctype));
204  result = save_lc_ctype;
205 
206 #ifdef ENABLE_NLS
207  SetMessageEncoding(pg_bind_textdomain_codeset(textdomain(NULL)));
208 #else
210 #endif
211  }
212 
213  switch (category)
214  {
215  case LC_COLLATE:
216  envvar = "LC_COLLATE";
217  envbuf = lc_collate_envbuf;
218  break;
219  case LC_CTYPE:
220  envvar = "LC_CTYPE";
221  envbuf = lc_ctype_envbuf;
222  break;
223 #ifdef LC_MESSAGES
224  case LC_MESSAGES:
225  envvar = "LC_MESSAGES";
226  envbuf = lc_messages_envbuf;
227 #ifdef WIN32
228  result = IsoLocaleName(locale);
229  if (result == NULL)
230  result = (char *) locale;
231 #endif /* WIN32 */
232  break;
233 #endif /* LC_MESSAGES */
234  case LC_MONETARY:
235  envvar = "LC_MONETARY";
236  envbuf = lc_monetary_envbuf;
237  break;
238  case LC_NUMERIC:
239  envvar = "LC_NUMERIC";
240  envbuf = lc_numeric_envbuf;
241  break;
242  case LC_TIME:
243  envvar = "LC_TIME";
244  envbuf = lc_time_envbuf;
245  break;
246  default:
247  elog(FATAL, "unrecognized LC category: %d", category);
248  envvar = NULL; /* keep compiler quiet */
249  envbuf = NULL;
250  return NULL;
251  }
252 
253  snprintf(envbuf, LC_ENV_BUFSIZE - 1, "%s=%s", envvar, result);
254 
255  if (putenv(envbuf))
256  return NULL;
257 
258  return result;
259 }
static char lc_numeric_envbuf[LC_ENV_BUFSIZE]
Definition: pg_locale.c:120
void SetMessageEncoding(int encoding)
Definition: mbutils.c:950
static char lc_monetary_envbuf[LC_ENV_BUFSIZE]
Definition: pg_locale.c:119
#define setlocale(a, b)
Definition: win32_port.h:408
#define LC_ENV_BUFSIZE
Definition: pg_locale.c:111
static char lc_time_envbuf[LC_ENV_BUFSIZE]
Definition: pg_locale.c:121
#define FATAL
Definition: elog.h:52
static char lc_ctype_envbuf[LC_ENV_BUFSIZE]
Definition: pg_locale.c:114
int GetDatabaseEncoding(void)
Definition: mbutils.c:1046
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define putenv(x)
Definition: win32_port.h:474
#define elog(elevel,...)
Definition: elog.h:228
static char * locale
Definition: initdb.c:125
static char lc_collate_envbuf[LC_ENV_BUFSIZE]
Definition: pg_locale.c:113
#define snprintf
Definition: port.h:192

◆ PGLC_localeconv()

struct lconv* PGLC_localeconv ( void  )

Definition at line 492 of file pg_locale.c.

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

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

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

◆ struct_lconv_is_valid()

static bool struct_lconv_is_valid ( struct lconv *  s)
static

Definition at line 431 of file pg_locale.c.

Referenced by PGLC_localeconv().

432 {
433  if (s->decimal_point == NULL)
434  return false;
435  if (s->thousands_sep == NULL)
436  return false;
437  if (s->grouping == NULL)
438  return false;
439  if (s->int_curr_symbol == NULL)
440  return false;
441  if (s->currency_symbol == NULL)
442  return false;
443  if (s->mon_decimal_point == NULL)
444  return false;
445  if (s->mon_thousands_sep == NULL)
446  return false;
447  if (s->mon_grouping == NULL)
448  return false;
449  if (s->positive_sign == NULL)
450  return false;
451  if (s->negative_sign == NULL)
452  return false;
453  return true;
454 }

◆ wchar2char()

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

Definition at line 1765 of file pg_locale.c.

References Assert, elog, ERROR, GetDatabaseEncoding(), pg_locale_struct::info, locale_t, PG_UTF8, pg_locale_struct::provider, and wcstombs_l.

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

1766 {
1767  size_t result;
1768 
1769  Assert(!locale || locale->provider == COLLPROVIDER_LIBC);
1770 
1771  if (tolen == 0)
1772  return 0;
1773 
1774 #ifdef WIN32
1775 
1776  /*
1777  * On Windows, the "Unicode" locales assume UTF16 not UTF8 encoding, and
1778  * for some reason mbstowcs and wcstombs won't do this for us, so we use
1779  * MultiByteToWideChar().
1780  */
1781  if (GetDatabaseEncoding() == PG_UTF8)
1782  {
1783  result = WideCharToMultiByte(CP_UTF8, 0, from, -1, to, tolen,
1784  NULL, NULL);
1785  /* A zero return is failure */
1786  if (result <= 0)
1787  result = -1;
1788  else
1789  {
1790  Assert(result <= tolen);
1791  /* Microsoft counts the zero terminator in the result */
1792  result--;
1793  }
1794  }
1795  else
1796 #endif /* WIN32 */
1797  if (locale == (pg_locale_t) 0)
1798  {
1799  /* Use wcstombs directly for the default locale */
1800  result = wcstombs(to, from, tolen);
1801  }
1802  else
1803  {
1804 #ifdef HAVE_LOCALE_T
1805 #ifdef HAVE_WCSTOMBS_L
1806  /* Use wcstombs_l for nondefault locales */
1807  result = wcstombs_l(to, from, tolen, locale->info.lt);
1808 #else /* !HAVE_WCSTOMBS_L */
1809  /* We have to temporarily set the locale as current ... ugh */
1810  locale_t save_locale = uselocale(locale->info.lt);
1811 
1812  result = wcstombs(to, from, tolen);
1813 
1814  uselocale(save_locale);
1815 #endif /* HAVE_WCSTOMBS_L */
1816 #else /* !HAVE_LOCALE_T */
1817  /* Can't have locale != 0 without HAVE_LOCALE_T */
1818  elog(ERROR, "wcstombs_l is not available");
1819  result = 0; /* keep compiler quiet */
1820 #endif /* HAVE_LOCALE_T */
1821  }
1822 
1823  return result;
1824 }
union pg_locale_struct::@144 info
#define wcstombs_l
Definition: win32_port.h:389
#define ERROR
Definition: elog.h:43
#define locale_t
Definition: win32_port.h:363
int GetDatabaseEncoding(void)
Definition: mbutils.c:1046
#define Assert(condition)
Definition: c.h:733
#define elog(elevel,...)
Definition: elog.h:228

Variable Documentation

◆ collation_cache

HTAB* collation_cache = NULL
static

Definition at line 134 of file pg_locale.c.

◆ CurrentLCTimeValid

bool CurrentLCTimeValid = false
static

Definition at line 107 of file pg_locale.c.

Referenced by assign_locale_time(), and cache_locale_time().

◆ CurrentLocaleConvValid

bool CurrentLocaleConvValid = false
static

Definition at line 106 of file pg_locale.c.

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

◆ lc_collate_envbuf

char lc_collate_envbuf[LC_ENV_BUFSIZE]
static

Definition at line 113 of file pg_locale.c.

Referenced by pg_perm_setlocale().

◆ lc_ctype_envbuf

char lc_ctype_envbuf[LC_ENV_BUFSIZE]
static

Definition at line 114 of file pg_locale.c.

Referenced by pg_perm_setlocale().

◆ lc_monetary_envbuf

char lc_monetary_envbuf[LC_ENV_BUFSIZE]
static

Definition at line 119 of file pg_locale.c.

Referenced by pg_perm_setlocale().

◆ lc_numeric_envbuf

char lc_numeric_envbuf[LC_ENV_BUFSIZE]
static

Definition at line 120 of file pg_locale.c.

Referenced by pg_perm_setlocale().

◆ lc_time_envbuf

char lc_time_envbuf[LC_ENV_BUFSIZE]
static

Definition at line 121 of file pg_locale.c.

Referenced by pg_perm_setlocale().

◆ locale_messages

char* locale_messages

Definition at line 94 of file pg_locale.c.

◆ locale_monetary

char* locale_monetary

Definition at line 95 of file pg_locale.c.

Referenced by PGLC_localeconv().

◆ locale_numeric

char* locale_numeric

Definition at line 96 of file pg_locale.c.

Referenced by PGLC_localeconv().

◆ locale_time

char* locale_time

Definition at line 97 of file pg_locale.c.

Referenced by cache_locale_time().

◆ localized_abbrev_days

char* localized_abbrev_days[7]

Definition at line 100 of file pg_locale.c.

Referenced by cache_locale_time(), and DCH_to_char().

◆ localized_abbrev_months

char* localized_abbrev_months[12]

Definition at line 102 of file pg_locale.c.

Referenced by cache_locale_time(), and DCH_to_char().

◆ localized_full_days

char* localized_full_days[7]

Definition at line 101 of file pg_locale.c.

Referenced by cache_locale_time(), and DCH_to_char().

◆ localized_full_months

char* localized_full_months[12]

Definition at line 103 of file pg_locale.c.

Referenced by cache_locale_time(), and DCH_to_char().