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+1]
 
char * localized_full_days [7+1]
 
char * localized_abbrev_months [12+1]
 
char * localized_full_months [12+1]
 
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 108 of file pg_locale.c.

Referenced by pg_perm_setlocale().

◆ MAX_L10N_DATA

#define MAX_L10N_DATA   80

Definition at line 81 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 383 of file pg_locale.c.

References pg_perm_setlocale().

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

◆ assign_locale_monetary()

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

Definition at line 320 of file pg_locale.c.

References CurrentLocaleConvValid.

321 {
322  CurrentLocaleConvValid = false;
323 }
static bool CurrentLocaleConvValid
Definition: pg_locale.c:103

◆ assign_locale_numeric()

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

Definition at line 332 of file pg_locale.c.

References CurrentLocaleConvValid.

333 {
334  CurrentLocaleConvValid = false;
335 }
static bool CurrentLocaleConvValid
Definition: pg_locale.c:103

◆ assign_locale_time()

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

Definition at line 344 of file pg_locale.c.

References CurrentLCTimeValid.

345 {
346  CurrentLCTimeValid = false;
347 }
static bool CurrentLCTimeValid
Definition: pg_locale.c:104

◆ cache_locale_time()

void cache_locale_time ( void  )

Definition at line 772 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_mbstrlen(), PG_SQL_ASCII, pg_strcasecmp(), PG_UTF8, pstrdup(), setlocale, tm, and wchar2char().

Referenced by DCH_from_char(), and DCH_to_char().

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

◆ cache_single_string()

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

Definition at line 749 of file pg_locale.c.

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

Referenced by cache_locale_time().

750 {
751  char *ptr;
752  char *olddst;
753 
754  /* Convert the string to the database encoding, or validate it's OK */
755  ptr = pg_any_to_server(src, strlen(src), encoding);
756 
757  /* Store the string in long-lived storage, replacing any previous value */
758  olddst = *dst;
760  if (olddst)
761  pfree(olddst);
762 
763  /* Might as well clean up any palloc'd conversion result, too */
764  if (ptr != src)
765  pfree(ptr);
766 }
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:619

◆ char2wchar()

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

Definition at line 2052 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().

2054 {
2055  size_t result;
2056 
2057  Assert(!locale || locale->provider == COLLPROVIDER_LIBC);
2058 
2059  if (tolen == 0)
2060  return 0;
2061 
2062 #ifdef WIN32
2063  /* See WIN32 "Unicode" comment above */
2064  if (GetDatabaseEncoding() == PG_UTF8)
2065  {
2066  /* Win32 API does not work for zero-length input */
2067  if (fromlen == 0)
2068  result = 0;
2069  else
2070  {
2071  result = MultiByteToWideChar(CP_UTF8, 0, from, fromlen, to, tolen - 1);
2072  /* A zero return is failure */
2073  if (result == 0)
2074  result = -1;
2075  }
2076 
2077  if (result != -1)
2078  {
2079  Assert(result < tolen);
2080  /* Append trailing null wchar (MultiByteToWideChar() does not) */
2081  to[result] = 0;
2082  }
2083  }
2084  else
2085 #endif /* WIN32 */
2086  {
2087  /* mbstowcs requires ending '\0' */
2088  char *str = pnstrdup(from, fromlen);
2089 
2090  if (locale == (pg_locale_t) 0)
2091  {
2092  /* Use mbstowcs directly for the default locale */
2093  result = mbstowcs(to, str, tolen);
2094  }
2095  else
2096  {
2097 #ifdef HAVE_LOCALE_T
2098 #ifdef HAVE_MBSTOWCS_L
2099  /* Use mbstowcs_l for nondefault locales */
2100  result = mbstowcs_l(to, str, tolen, locale->info.lt);
2101 #else /* !HAVE_MBSTOWCS_L */
2102  /* We have to temporarily set the locale as current ... ugh */
2103  locale_t save_locale = uselocale(locale->info.lt);
2104 
2105  result = mbstowcs(to, str, tolen);
2106 
2107  uselocale(save_locale);
2108 #endif /* HAVE_MBSTOWCS_L */
2109 #else /* !HAVE_LOCALE_T */
2110  /* Can't have locale != 0 without HAVE_LOCALE_T */
2111  elog(ERROR, "mbstowcs_l is not available");
2112  result = 0; /* keep compiler quiet */
2113 #endif /* HAVE_LOCALE_T */
2114  }
2115 
2116  pfree(str);
2117  }
2118 
2119  if (result == -1)
2120  {
2121  /*
2122  * Invalid multibyte character encountered. We try to give a useful
2123  * error message by letting pg_verifymbstr check the string. But it's
2124  * possible that the string is OK to us, and not OK to mbstowcs ---
2125  * this suggests that the LC_CTYPE locale is different from the
2126  * database encoding. Give a generic error message if pg_verifymbstr
2127  * can't find anything wrong.
2128  */
2129  pg_verifymbstr(from, fromlen, false); /* might not return */
2130  /* but if it does ... */
2131  ereport(ERROR,
2132  (errcode(ERRCODE_CHARACTER_NOT_IN_REPERTOIRE),
2133  errmsg("invalid multibyte character for locale"),
2134  errhint("The server's LC_CTYPE locale is probably incompatible with the database encoding.")));
2135  }
2136 
2137  return result;
2138 }
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:610
void pfree(void *pointer)
Definition: mcxt.c:1056
#define ERROR
Definition: elog.h:43
#define locale_t
Definition: win32_port.h:363
int GetDatabaseEncoding(void)
Definition: mbutils.c:1151
bool pg_verifymbstr(const char *mbstr, int len, bool noError)
Definition: mbutils.c:1446
#define ereport(elevel,...)
Definition: elog.h:144
#define Assert(condition)
Definition: c.h:745
#define mbstowcs_l
Definition: win32_port.h:390
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define elog(elevel,...)
Definition: elog.h:214
union pg_locale_struct::@142 info

◆ check_locale()

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

Definition at line 271 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().

272 {
273  char *save;
274  char *res;
275 
276  if (canonname)
277  *canonname = NULL; /* in case of failure */
278 
279  save = setlocale(category, NULL);
280  if (!save)
281  return false; /* won't happen, we hope */
282 
283  /* save may be pointing at a modifiable scratch variable, see above. */
284  save = pstrdup(save);
285 
286  /* set the locale with setlocale, to see if it accepts it. */
287  res = setlocale(category, locale);
288 
289  /* save canonical name if requested. */
290  if (res && canonname)
291  *canonname = pstrdup(res);
292 
293  /* restore old value. */
294  if (!setlocale(category, save))
295  elog(WARNING, "failed to restore old locale \"%s\"", save);
296  pfree(save);
297 
298  return (res != NULL);
299 }
#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:214
static char * locale
Definition: initdb.c:125

◆ check_locale_messages()

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

Definition at line 360 of file pg_locale.c.

References check_locale(), and PGC_S_DEFAULT.

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

◆ check_locale_monetary()

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

Definition at line 314 of file pg_locale.c.

References check_locale().

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

◆ check_locale_numeric()

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

Definition at line 326 of file pg_locale.c.

References check_locale().

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

◆ check_locale_time()

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

Definition at line 338 of file pg_locale.c.

References check_locale().

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

◆ check_strxfrm_bug()

void check_strxfrm_bug ( void  )

Definition at line 1212 of file pg_locale.c.

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

Referenced by CheckMyDatabase(), and main().

1213 {
1214  char buf[32];
1215  const int canary = 0x7F;
1216  bool ok = true;
1217 
1218  /*
1219  * Given a two-byte ASCII string and length limit 7, 8 or 9, Solaris 10
1220  * 05/08 returns 18 and modifies 10 bytes. It respects limits above or
1221  * below that range.
1222  *
1223  * The bug is present in Solaris 8 as well; it is absent in Solaris 10
1224  * 01/13 and Solaris 11.2. Affected locales include is_IS.ISO8859-1,
1225  * en_US.UTF-8, en_US.ISO8859-1, and ru_RU.KOI8-R. Unaffected locales
1226  * include de_DE.UTF-8, de_DE.ISO8859-1, zh_TW.UTF-8, and C.
1227  */
1228  buf[7] = canary;
1229  (void) strxfrm(buf, "ab", 7);
1230  if (buf[7] != canary)
1231  ok = false;
1232 
1233  /*
1234  * illumos bug #1594 was present in the source tree from 2010-10-11 to
1235  * 2012-02-01. Given an ASCII string of any length and length limit 1,
1236  * affected systems ignore the length limit and modify a number of bytes
1237  * one less than the return value. The problem inputs for this bug do not
1238  * overlap those for the Solaris bug, hence a distinct test.
1239  *
1240  * Affected systems include smartos-20110926T021612Z. Affected locales
1241  * include en_US.ISO8859-1 and en_US.UTF-8. Unaffected locales include C.
1242  */
1243  buf[1] = canary;
1244  (void) strxfrm(buf, "a", 1);
1245  if (buf[1] != canary)
1246  ok = false;
1247 
1248  if (!ok)
1249  ereport(ERROR,
1250  (errcode(ERRCODE_SYSTEM_ERROR),
1251  errmsg_internal("strxfrm(), in locale \"%s\", writes past the specified array length",
1252  setlocale(LC_COLLATE, NULL)),
1253  errhint("Apply system library package updates.")));
1254 }
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:610
#define ERROR
Definition: elog.h:43
static char * buf
Definition: pg_test_fsync.c:67
#define ereport(elevel,...)
Definition: elog.h:144
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 460 of file pg_locale.c.

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

Referenced by PGLC_localeconv().

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

◆ free_struct_lconv()

static void free_struct_lconv ( struct lconv *  s)
static

Definition at line 400 of file pg_locale.c.

References free.

Referenced by PGLC_localeconv().

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

◆ get_collation_actual_version()

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

Definition at line 1671 of file pg_locale.c.

References asc_tolower(), buf, ereport, errcode(), errmsg(), ERROR, get_encoding_name_for_icu(), GetDatabaseEncoding(), name, palloc(), pfree(), pg_attribute_unused(), pg_encoding_to_char(), pg_strcasecmp(), psprintf(), 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().

1672 {
1673  char *collversion = NULL;
1674 
1675 #ifdef USE_ICU
1676  if (collprovider == COLLPROVIDER_ICU)
1677  {
1678  UCollator *collator;
1679  UErrorCode status;
1680  UVersionInfo versioninfo;
1681  char buf[U_MAX_VERSION_STRING_LENGTH];
1682 
1683  status = U_ZERO_ERROR;
1684  collator = ucol_open(collcollate, &status);
1685  if (U_FAILURE(status))
1686  ereport(ERROR,
1687  (errmsg("could not open collator for locale \"%s\": %s",
1688  collcollate, u_errorName(status))));
1689  ucol_getVersion(collator, versioninfo);
1690  ucol_close(collator);
1691 
1692  u_versionToString(versioninfo, buf);
1693  collversion = pstrdup(buf);
1694  }
1695  else
1696 #endif
1697  if (collprovider == COLLPROVIDER_LIBC)
1698  {
1699 #if defined(__GLIBC__)
1700  char *copy = pstrdup(collcollate);
1701  char *copy_suffix = strstr(copy, ".");
1702  bool need_version = true;
1703 
1704  /*
1705  * Check for names like C.UTF-8 by chopping off the encoding suffix on
1706  * our temporary copy, so we can skip the version.
1707  */
1708  if (copy_suffix)
1709  *copy_suffix = '\0';
1710  if (pg_strcasecmp("c", copy) == 0 ||
1711  pg_strcasecmp("posix", copy) == 0)
1712  need_version = false;
1713  pfree(copy);
1714  if (!need_version)
1715  return NULL;
1716 
1717  /* Use the glibc version because we don't have anything better. */
1718  collversion = pstrdup(gnu_get_libc_version());
1719 #elif defined(WIN32) && _WIN32_WINNT >= 0x0600
1720  /*
1721  * If we are targeting Windows Vista and above, we can ask for a name
1722  * given a collation name (earlier versions required a location code
1723  * that we don't have).
1724  */
1725  NLSVERSIONINFOEX version = {sizeof(NLSVERSIONINFOEX)};
1726  WCHAR wide_collcollate[LOCALE_NAME_MAX_LENGTH];
1727 
1728  /* These would be invalid arguments, but have no version. */
1729  if (pg_strcasecmp("c", collcollate) == 0 ||
1730  pg_strcasecmp("posix", collcollate) == 0)
1731  return NULL;
1732 
1733  /* For all other names, ask the OS. */
1734  MultiByteToWideChar(CP_ACP, 0, collcollate, -1, wide_collcollate,
1735  LOCALE_NAME_MAX_LENGTH);
1736  if (!GetNLSVersionEx(COMPARE_STRING, wide_collcollate, &version))
1737  ereport(ERROR,
1738  (errmsg("could not get collation version for locale \"%s\": error code %lu",
1739  collcollate,
1740  GetLastError())));
1741  collversion = psprintf("%d.%d,%d.%d",
1742  (version.dwNLSVersion >> 8) & 0xFFFF,
1743  version.dwNLSVersion & 0xFF,
1744  (version.dwDefinedVersion >> 8) & 0xFFFF,
1745  version.dwDefinedVersion & 0xFF);
1746 #endif
1747  }
1748 
1749  return collversion;
1750 }
char * pstrdup(const char *in)
Definition: mcxt.c:1186
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
void pfree(void *pointer)
Definition: mcxt.c:1056
#define ERROR
Definition: elog.h:43
static char * buf
Definition: pg_test_fsync.c:67
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg(const char *fmt,...)
Definition: elog.c:824
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:225

◆ lc_collate_is_c()

bool lc_collate_is_c ( Oid  collation)

Definition at line 1347 of file pg_locale.c.

References elog, ERROR, lookup_collation_cache(), OidIsValid, 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().

1348 {
1349  /*
1350  * If we're asked about "collation 0", return false, so that the code will
1351  * go into the non-C path and report that the collation is bogus.
1352  */
1353  if (!OidIsValid(collation))
1354  return false;
1355 
1356  /*
1357  * If we're asked about the default collation, we have to inquire of the C
1358  * library. Cache the result so we only have to compute it once.
1359  */
1360  if (collation == DEFAULT_COLLATION_OID)
1361  {
1362  static int result = -1;
1363  char *localeptr;
1364 
1365  if (result >= 0)
1366  return (bool) result;
1367  localeptr = setlocale(LC_COLLATE, NULL);
1368  if (!localeptr)
1369  elog(ERROR, "invalid LC_COLLATE setting");
1370 
1371  if (strcmp(localeptr, "C") == 0)
1372  result = true;
1373  else if (strcmp(localeptr, "POSIX") == 0)
1374  result = true;
1375  else
1376  result = false;
1377  return (bool) result;
1378  }
1379 
1380  /*
1381  * If we're asked about the built-in C/POSIX collations, we know that.
1382  */
1383  if (collation == C_COLLATION_OID ||
1384  collation == POSIX_COLLATION_OID)
1385  return true;
1386 
1387  /*
1388  * Otherwise, we have to consult pg_collation, but we cache that.
1389  */
1390  return (lookup_collation_cache(collation, true))->collate_is_c;
1391 }
#define setlocale(a, b)
Definition: win32_port.h:408
#define OidIsValid(objectId)
Definition: c.h:651
#define ERROR
Definition: elog.h:43
#define elog(elevel,...)
Definition: elog.h:214
static collation_cache_entry * lookup_collation_cache(Oid collation, bool set_flags)
Definition: pg_locale.c:1282

◆ lc_ctype_is_c()

bool lc_ctype_is_c ( Oid  collation)

Definition at line 1397 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().

1398 {
1399  /*
1400  * If we're asked about "collation 0", return false, so that the code will
1401  * go into the non-C path and report that the collation is bogus.
1402  */
1403  if (!OidIsValid(collation))
1404  return false;
1405 
1406  /*
1407  * If we're asked about the default collation, we have to inquire of the C
1408  * library. Cache the result so we only have to compute it once.
1409  */
1410  if (collation == DEFAULT_COLLATION_OID)
1411  {
1412  static int result = -1;
1413  char *localeptr;
1414 
1415  if (result >= 0)
1416  return (bool) result;
1417  localeptr = setlocale(LC_CTYPE, NULL);
1418  if (!localeptr)
1419  elog(ERROR, "invalid LC_CTYPE setting");
1420 
1421  if (strcmp(localeptr, "C") == 0)
1422  result = true;
1423  else if (strcmp(localeptr, "POSIX") == 0)
1424  result = true;
1425  else
1426  result = false;
1427  return (bool) result;
1428  }
1429 
1430  /*
1431  * If we're asked about the built-in C/POSIX collations, we know that.
1432  */
1433  if (collation == C_COLLATION_OID ||
1434  collation == POSIX_COLLATION_OID)
1435  return true;
1436 
1437  /*
1438  * Otherwise, we have to consult pg_collation, but we cache that.
1439  */
1440  return (lookup_collation_cache(collation, true))->ctype_is_c;
1441 }
#define setlocale(a, b)
Definition: win32_port.h:408
#define OidIsValid(objectId)
Definition: c.h:651
#define ERROR
Definition: elog.h:43
#define elog(elevel,...)
Definition: elog.h:214
static collation_cache_entry * lookup_collation_cache(Oid collation, bool set_flags)
Definition: pg_locale.c:1282

◆ lookup_collation_cache()

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

Definition at line 1282 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().

1283 {
1284  collation_cache_entry *cache_entry;
1285  bool found;
1286 
1287  Assert(OidIsValid(collation));
1288  Assert(collation != DEFAULT_COLLATION_OID);
1289 
1290  if (collation_cache == NULL)
1291  {
1292  /* First time through, initialize the hash table */
1293  HASHCTL ctl;
1294 
1295  memset(&ctl, 0, sizeof(ctl));
1296  ctl.keysize = sizeof(Oid);
1297  ctl.entrysize = sizeof(collation_cache_entry);
1298  collation_cache = hash_create("Collation cache", 100, &ctl,
1299  HASH_ELEM | HASH_BLOBS);
1300  }
1301 
1302  cache_entry = hash_search(collation_cache, &collation, HASH_ENTER, &found);
1303  if (!found)
1304  {
1305  /*
1306  * Make sure cache entry is marked invalid, in case we fail before
1307  * setting things.
1308  */
1309  cache_entry->flags_valid = false;
1310  cache_entry->locale = 0;
1311  }
1312 
1313  if (set_flags && !cache_entry->flags_valid)
1314  {
1315  /* Attempt to set the flags */
1316  HeapTuple tp;
1317  Form_pg_collation collform;
1318  const char *collcollate;
1319  const char *collctype;
1320 
1321  tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
1322  if (!HeapTupleIsValid(tp))
1323  elog(ERROR, "cache lookup failed for collation %u", collation);
1324  collform = (Form_pg_collation) GETSTRUCT(tp);
1325 
1326  collcollate = NameStr(collform->collcollate);
1327  collctype = NameStr(collform->collctype);
1328 
1329  cache_entry->collate_is_c = ((strcmp(collcollate, "C") == 0) ||
1330  (strcmp(collcollate, "POSIX") == 0));
1331  cache_entry->ctype_is_c = ((strcmp(collctype, "C") == 0) ||
1332  (strcmp(collctype, "POSIX") == 0));
1333 
1334  cache_entry->flags_valid = true;
1335 
1336  ReleaseSysCache(tp);
1337  }
1338 
1339  return cache_entry;
1340 }
bool flags_valid
Definition: pg_locale.c:127
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define HASH_ELEM
Definition: hsearch.h:87
bool ctype_is_c
Definition: pg_locale.c:126
Size entrysize
Definition: hsearch.h:73
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:927
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:651
bool collate_is_c
Definition: pg_locale.c:125
#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:128
#define HASH_BLOBS
Definition: hsearch.h:88
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:328
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
Size keysize
Definition: hsearch.h:72
static HTAB * collation_cache
Definition: pg_locale.c:131
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:745
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:51
#define elog(elevel,...)
Definition: elog.h:214
#define NameStr(name)
Definition: c.h:622
Definition: pg_locale.c:122

◆ pg_newlocale_from_collation()

pg_locale_t pg_newlocale_from_collation ( Oid  collid)

Definition at line 1494 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().

1495 {
1496  collation_cache_entry *cache_entry;
1497 
1498  /* Callers must pass a valid OID */
1499  Assert(OidIsValid(collid));
1500 
1501  /* Return 0 for "default" collation, just in case caller forgets */
1502  if (collid == DEFAULT_COLLATION_OID)
1503  return (pg_locale_t) 0;
1504 
1505  cache_entry = lookup_collation_cache(collid, false);
1506 
1507  if (cache_entry->locale == 0)
1508  {
1509  /* We haven't computed this yet in this session, so do it */
1510  HeapTuple tp;
1511  Form_pg_collation collform;
1512  const char *collcollate;
1513  const char *collctype pg_attribute_unused();
1514  struct pg_locale_struct result;
1515  pg_locale_t resultp;
1516  Datum collversion;
1517  bool isnull;
1518 
1519  tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collid));
1520  if (!HeapTupleIsValid(tp))
1521  elog(ERROR, "cache lookup failed for collation %u", collid);
1522  collform = (Form_pg_collation) GETSTRUCT(tp);
1523 
1524  collcollate = NameStr(collform->collcollate);
1525  collctype = NameStr(collform->collctype);
1526 
1527  /* We'll fill in the result struct locally before allocating memory */
1528  memset(&result, 0, sizeof(result));
1529  result.provider = collform->collprovider;
1530  result.deterministic = collform->collisdeterministic;
1531 
1532  if (collform->collprovider == COLLPROVIDER_LIBC)
1533  {
1534 #ifdef HAVE_LOCALE_T
1535  locale_t loc;
1536 
1537  if (strcmp(collcollate, collctype) == 0)
1538  {
1539  /* Normal case where they're the same */
1540  errno = 0;
1541 #ifndef WIN32
1542  loc = newlocale(LC_COLLATE_MASK | LC_CTYPE_MASK, collcollate,
1543  NULL);
1544 #else
1545  loc = _create_locale(LC_ALL, collcollate);
1546 #endif
1547  if (!loc)
1548  report_newlocale_failure(collcollate);
1549  }
1550  else
1551  {
1552 #ifndef WIN32
1553  /* We need two newlocale() steps */
1554  locale_t loc1;
1555 
1556  errno = 0;
1557  loc1 = newlocale(LC_COLLATE_MASK, collcollate, NULL);
1558  if (!loc1)
1559  report_newlocale_failure(collcollate);
1560  errno = 0;
1561  loc = newlocale(LC_CTYPE_MASK, collctype, loc1);
1562  if (!loc)
1563  report_newlocale_failure(collctype);
1564 #else
1565 
1566  /*
1567  * XXX The _create_locale() API doesn't appear to support
1568  * this. Could perhaps be worked around by changing
1569  * pg_locale_t to contain two separate fields.
1570  */
1571  ereport(ERROR,
1572  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1573  errmsg("collations with different collate and ctype values are not supported on this platform")));
1574 #endif
1575  }
1576 
1577  result.info.lt = loc;
1578 #else /* not HAVE_LOCALE_T */
1579  /* platform that doesn't support locale_t */
1580  ereport(ERROR,
1581  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1582  errmsg("collation provider LIBC is not supported on this platform")));
1583 #endif /* not HAVE_LOCALE_T */
1584  }
1585  else if (collform->collprovider == COLLPROVIDER_ICU)
1586  {
1587 #ifdef USE_ICU
1588  UCollator *collator;
1589  UErrorCode status;
1590 
1591  if (strcmp(collcollate, collctype) != 0)
1592  ereport(ERROR,
1593  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1594  errmsg("collations with different collate and ctype values are not supported by ICU")));
1595 
1596  status = U_ZERO_ERROR;
1597  collator = ucol_open(collcollate, &status);
1598  if (U_FAILURE(status))
1599  ereport(ERROR,
1600  (errmsg("could not open collator for locale \"%s\": %s",
1601  collcollate, u_errorName(status))));
1602 
1603  if (U_ICU_VERSION_MAJOR_NUM < 54)
1604  icu_set_collation_attributes(collator, collcollate);
1605 
1606  /* We will leak this string if we get an error below :-( */
1607  result.info.icu.locale = MemoryContextStrdup(TopMemoryContext,
1608  collcollate);
1609  result.info.icu.ucol = collator;
1610 #else /* not USE_ICU */
1611  /* could get here if a collation was created by a build with ICU */
1612  ereport(ERROR,
1613  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1614  errmsg("ICU is not supported in this build"), \
1615  errhint("You need to rebuild PostgreSQL using --with-icu.")));
1616 #endif /* not USE_ICU */
1617  }
1618 
1619  collversion = SysCacheGetAttr(COLLOID, tp, Anum_pg_collation_collversion,
1620  &isnull);
1621  if (!isnull)
1622  {
1623  char *actual_versionstr;
1624  char *collversionstr;
1625 
1626  actual_versionstr = get_collation_actual_version(collform->collprovider, collcollate);
1627  if (!actual_versionstr)
1628  {
1629  /*
1630  * This could happen when specifying a version in CREATE
1631  * COLLATION for a libc locale, or manually creating a mess in
1632  * the catalogs.
1633  */
1634  ereport(ERROR,
1635  (errmsg("collation \"%s\" has no actual version, but a version was specified",
1636  NameStr(collform->collname))));
1637  }
1638  collversionstr = TextDatumGetCString(collversion);
1639 
1640  if (strcmp(actual_versionstr, collversionstr) != 0)
1641  ereport(WARNING,
1642  (errmsg("collation \"%s\" has version mismatch",
1643  NameStr(collform->collname)),
1644  errdetail("The collation in the database was created using version %s, "
1645  "but the operating system provides version %s.",
1646  collversionstr, actual_versionstr),
1647  errhint("Rebuild all objects affected by this collation and run "
1648  "ALTER COLLATION %s REFRESH VERSION, "
1649  "or build PostgreSQL with the right library version.",
1650  quote_qualified_identifier(get_namespace_name(collform->collnamespace),
1651  NameStr(collform->collname)))));
1652  }
1653 
1654  ReleaseSysCache(tp);
1655 
1656  /* We'll keep the pg_locale_t structures in TopMemoryContext */
1657  resultp = MemoryContextAlloc(TopMemoryContext, sizeof(*resultp));
1658  *resultp = result;
1659 
1660  cache_entry->locale = resultp;
1661  }
1662 
1663  return cache_entry->locale;
1664 }
int errhint(const char *fmt,...)
Definition: elog.c:1071
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
int errcode(int sqlerrcode)
Definition: elog.c:610
#define OidIsValid(objectId)
Definition: c.h:651
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3191
int errdetail(const char *fmt,...)
Definition: elog.c:957
#define locale_t
Definition: win32_port.h:363
MemoryContext TopMemoryContext
Definition: mcxt.c:44
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10811
#define WARNING
Definition: elog.h:40
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
pg_locale_t locale
Definition: pg_locale.c:128
#define TextDatumGetCString(d)
Definition: builtins.h:87
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 ereport(elevel,...)
Definition: elog.h:144
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:745
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:824
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:214
#define NameStr(name)
Definition: c.h:622
static collation_cache_entry * lookup_collation_cache(Oid collation, bool set_flags)
Definition: pg_locale.c:1282
Definition: pg_locale.c:122
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:225
char * get_collation_actual_version(char collprovider, const char *collcollate)
Definition: pg_locale.c:1671

◆ pg_perm_setlocale()

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

Definition at line 157 of file pg_locale.c.

References DEBUG3, 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().

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

◆ PGLC_localeconv()

struct lconv* PGLC_localeconv ( void  )

Definition at line 490 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().

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

◆ struct_lconv_is_valid()

static bool struct_lconv_is_valid ( struct lconv *  s)
static

Definition at line 429 of file pg_locale.c.

Referenced by PGLC_localeconv().

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

◆ wchar2char()

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

Definition at line 1981 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().

1982 {
1983  size_t result;
1984 
1985  Assert(!locale || locale->provider == COLLPROVIDER_LIBC);
1986 
1987  if (tolen == 0)
1988  return 0;
1989 
1990 #ifdef WIN32
1991 
1992  /*
1993  * On Windows, the "Unicode" locales assume UTF16 not UTF8 encoding, and
1994  * for some reason mbstowcs and wcstombs won't do this for us, so we use
1995  * MultiByteToWideChar().
1996  */
1997  if (GetDatabaseEncoding() == PG_UTF8)
1998  {
1999  result = WideCharToMultiByte(CP_UTF8, 0, from, -1, to, tolen,
2000  NULL, NULL);
2001  /* A zero return is failure */
2002  if (result <= 0)
2003  result = -1;
2004  else
2005  {
2006  Assert(result <= tolen);
2007  /* Microsoft counts the zero terminator in the result */
2008  result--;
2009  }
2010  }
2011  else
2012 #endif /* WIN32 */
2013  if (locale == (pg_locale_t) 0)
2014  {
2015  /* Use wcstombs directly for the default locale */
2016  result = wcstombs(to, from, tolen);
2017  }
2018  else
2019  {
2020 #ifdef HAVE_LOCALE_T
2021 #ifdef HAVE_WCSTOMBS_L
2022  /* Use wcstombs_l for nondefault locales */
2023  result = wcstombs_l(to, from, tolen, locale->info.lt);
2024 #else /* !HAVE_WCSTOMBS_L */
2025  /* We have to temporarily set the locale as current ... ugh */
2026  locale_t save_locale = uselocale(locale->info.lt);
2027 
2028  result = wcstombs(to, from, tolen);
2029 
2030  uselocale(save_locale);
2031 #endif /* HAVE_WCSTOMBS_L */
2032 #else /* !HAVE_LOCALE_T */
2033  /* Can't have locale != 0 without HAVE_LOCALE_T */
2034  elog(ERROR, "wcstombs_l is not available");
2035  result = 0; /* keep compiler quiet */
2036 #endif /* HAVE_LOCALE_T */
2037  }
2038 
2039  return result;
2040 }
#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:1151
#define Assert(condition)
Definition: c.h:745
#define elog(elevel,...)
Definition: elog.h:214
union pg_locale_struct::@142 info

Variable Documentation

◆ collation_cache

HTAB* collation_cache = NULL
static

Definition at line 131 of file pg_locale.c.

◆ CurrentLCTimeValid

bool CurrentLCTimeValid = false
static

Definition at line 104 of file pg_locale.c.

Referenced by assign_locale_time(), and cache_locale_time().

◆ CurrentLocaleConvValid

bool CurrentLocaleConvValid = false
static

Definition at line 103 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 110 of file pg_locale.c.

Referenced by pg_perm_setlocale().

◆ lc_ctype_envbuf

char lc_ctype_envbuf[LC_ENV_BUFSIZE]
static

Definition at line 111 of file pg_locale.c.

Referenced by pg_perm_setlocale().

◆ lc_monetary_envbuf

char lc_monetary_envbuf[LC_ENV_BUFSIZE]
static

Definition at line 116 of file pg_locale.c.

Referenced by pg_perm_setlocale().

◆ lc_numeric_envbuf

char lc_numeric_envbuf[LC_ENV_BUFSIZE]
static

Definition at line 117 of file pg_locale.c.

Referenced by pg_perm_setlocale().

◆ lc_time_envbuf

char lc_time_envbuf[LC_ENV_BUFSIZE]
static

Definition at line 118 of file pg_locale.c.

Referenced by pg_perm_setlocale().

◆ locale_messages

char* locale_messages

Definition at line 85 of file pg_locale.c.

◆ locale_monetary

char* locale_monetary

Definition at line 86 of file pg_locale.c.

Referenced by PGLC_localeconv().

◆ locale_numeric

char* locale_numeric

Definition at line 87 of file pg_locale.c.

Referenced by PGLC_localeconv().

◆ locale_time

char* locale_time

Definition at line 88 of file pg_locale.c.

Referenced by cache_locale_time().

◆ localized_abbrev_days

char* localized_abbrev_days[7+1]

Definition at line 97 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 99 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 98 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 100 of file pg_locale.c.

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