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 117 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 392 of file pg_locale.c.

References pg_perm_setlocale().

393 {
394  /*
395  * LC_MESSAGES category does not exist everywhere, but accept it anyway.
396  * We ignore failure, as per comment above.
397  */
398 #ifdef LC_MESSAGES
399  (void) pg_perm_setlocale(LC_MESSAGES, newval);
400 #endif
401 }
char * pg_perm_setlocale(int category, const char *locale)
Definition: pg_locale.c:166
#define newval

◆ assign_locale_monetary()

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

Definition at line 329 of file pg_locale.c.

References CurrentLocaleConvValid.

330 {
331  CurrentLocaleConvValid = false;
332 }
static bool CurrentLocaleConvValid
Definition: pg_locale.c:112

◆ assign_locale_numeric()

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

Definition at line 341 of file pg_locale.c.

References CurrentLocaleConvValid.

342 {
343  CurrentLocaleConvValid = false;
344 }
static bool CurrentLocaleConvValid
Definition: pg_locale.c:112

◆ assign_locale_time()

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

Definition at line 353 of file pg_locale.c.

References CurrentLCTimeValid.

354 {
355  CurrentLCTimeValid = false;
356 }
static bool CurrentLCTimeValid
Definition: pg_locale.c:113

◆ cache_locale_time()

void cache_locale_time ( void  )

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

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

◆ cache_single_string()

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

Definition at line 758 of file pg_locale.c.

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

Referenced by cache_locale_time().

759 {
760  char *ptr;
761  char *olddst;
762 
763  /* Convert the string to the database encoding, or validate it's OK */
764  ptr = pg_any_to_server(src, strlen(src), encoding);
765 
766  /* Store the string in long-lived storage, replacing any previous value */
767  olddst = *dst;
769  if (olddst)
770  pfree(olddst);
771 
772  /* Might as well clean up any palloc'd conversion result, too */
773  if (ptr != src)
774  pfree(ptr);
775 }
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 2061 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().

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

281 {
282  char *save;
283  char *res;
284 
285  if (canonname)
286  *canonname = NULL; /* in case of failure */
287 
288  save = setlocale(category, NULL);
289  if (!save)
290  return false; /* won't happen, we hope */
291 
292  /* save may be pointing at a modifiable scratch variable, see above. */
293  save = pstrdup(save);
294 
295  /* set the locale with setlocale, to see if it accepts it. */
296  res = setlocale(category, locale);
297 
298  /* save canonical name if requested. */
299  if (res && canonname)
300  *canonname = pstrdup(res);
301 
302  /* restore old value. */
303  if (!setlocale(category, save))
304  elog(WARNING, "failed to restore old locale \"%s\"", save);
305  pfree(save);
306 
307  return (res != NULL);
308 }
#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 369 of file pg_locale.c.

References check_locale(), and PGC_S_DEFAULT.

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

◆ check_locale_monetary()

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

Definition at line 323 of file pg_locale.c.

References check_locale().

324 {
325  return check_locale(LC_MONETARY, *newval, NULL);
326 }
bool check_locale(int category, const char *locale, char **canonname)
Definition: pg_locale.c:280
#define newval

◆ check_locale_numeric()

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

Definition at line 335 of file pg_locale.c.

References check_locale().

336 {
337  return check_locale(LC_NUMERIC, *newval, NULL);
338 }
bool check_locale(int category, const char *locale, char **canonname)
Definition: pg_locale.c:280
#define newval

◆ check_locale_time()

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

Definition at line 347 of file pg_locale.c.

References check_locale().

348 {
349  return check_locale(LC_TIME, *newval, NULL);
350 }
bool check_locale(int category, const char *locale, char **canonname)
Definition: pg_locale.c:280
#define newval

◆ check_strxfrm_bug()

void check_strxfrm_bug ( void  )

Definition at line 1221 of file pg_locale.c.

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

Referenced by CheckMyDatabase(), and main().

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

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

Referenced by PGLC_localeconv().

470 {
471  char *pstr;
472  char *mstr;
473 
474  /* convert the string to the database encoding */
475  pstr = pg_any_to_server(*str, strlen(*str), encoding);
476  if (pstr == *str)
477  return; /* no conversion happened */
478 
479  /* need it malloc'd not palloc'd */
480  mstr = strdup(pstr);
481  if (mstr == NULL)
482  ereport(ERROR,
483  (errcode(ERRCODE_OUT_OF_MEMORY),
484  errmsg("out of memory")));
485 
486  /* replace old string */
487  free(*str);
488  *str = mstr;
489 
490  pfree(pstr);
491 }
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 409 of file pg_locale.c.

References free.

Referenced by PGLC_localeconv().

410 {
411  if (s->decimal_point)
412  free(s->decimal_point);
413  if (s->thousands_sep)
414  free(s->thousands_sep);
415  if (s->grouping)
416  free(s->grouping);
417  if (s->int_curr_symbol)
418  free(s->int_curr_symbol);
419  if (s->currency_symbol)
420  free(s->currency_symbol);
421  if (s->mon_decimal_point)
422  free(s->mon_decimal_point);
423  if (s->mon_thousands_sep)
424  free(s->mon_thousands_sep);
425  if (s->mon_grouping)
426  free(s->mon_grouping);
427  if (s->positive_sign)
428  free(s->positive_sign);
429  if (s->negative_sign)
430  free(s->negative_sign);
431 }
#define free(a)
Definition: header.h:65

◆ get_collation_actual_version()

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

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

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

1357 {
1358  /*
1359  * If we're asked about "collation 0", return false, so that the code will
1360  * go into the non-C path and report that the collation is bogus.
1361  */
1362  if (!OidIsValid(collation))
1363  return false;
1364 
1365  /*
1366  * If we're asked about the default collation, we have to inquire of the C
1367  * library. Cache the result so we only have to compute it once.
1368  */
1369  if (collation == DEFAULT_COLLATION_OID)
1370  {
1371  static int result = -1;
1372  char *localeptr;
1373 
1374  if (result >= 0)
1375  return (bool) result;
1376  localeptr = setlocale(LC_COLLATE, NULL);
1377  if (!localeptr)
1378  elog(ERROR, "invalid LC_COLLATE setting");
1379 
1380  if (strcmp(localeptr, "C") == 0)
1381  result = true;
1382  else if (strcmp(localeptr, "POSIX") == 0)
1383  result = true;
1384  else
1385  result = false;
1386  return (bool) result;
1387  }
1388 
1389  /*
1390  * If we're asked about the built-in C/POSIX collations, we know that.
1391  */
1392  if (collation == C_COLLATION_OID ||
1393  collation == POSIX_COLLATION_OID)
1394  return true;
1395 
1396  /*
1397  * Otherwise, we have to consult pg_collation, but we cache that.
1398  */
1399  return (lookup_collation_cache(collation, true))->collate_is_c;
1400 }
#define setlocale(a, b)
Definition: win32_port.h:408
#define OidIsValid(objectId)
Definition: c.h:644
#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:1291

◆ lc_ctype_is_c()

bool lc_ctype_is_c ( Oid  collation)

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

1407 {
1408  /*
1409  * If we're asked about "collation 0", return false, so that the code will
1410  * go into the non-C path and report that the collation is bogus.
1411  */
1412  if (!OidIsValid(collation))
1413  return false;
1414 
1415  /*
1416  * If we're asked about the default collation, we have to inquire of the C
1417  * library. Cache the result so we only have to compute it once.
1418  */
1419  if (collation == DEFAULT_COLLATION_OID)
1420  {
1421  static int result = -1;
1422  char *localeptr;
1423 
1424  if (result >= 0)
1425  return (bool) result;
1426  localeptr = setlocale(LC_CTYPE, NULL);
1427  if (!localeptr)
1428  elog(ERROR, "invalid LC_CTYPE setting");
1429 
1430  if (strcmp(localeptr, "C") == 0)
1431  result = true;
1432  else if (strcmp(localeptr, "POSIX") == 0)
1433  result = true;
1434  else
1435  result = false;
1436  return (bool) result;
1437  }
1438 
1439  /*
1440  * If we're asked about the built-in C/POSIX collations, we know that.
1441  */
1442  if (collation == C_COLLATION_OID ||
1443  collation == POSIX_COLLATION_OID)
1444  return true;
1445 
1446  /*
1447  * Otherwise, we have to consult pg_collation, but we cache that.
1448  */
1449  return (lookup_collation_cache(collation, true))->ctype_is_c;
1450 }
#define setlocale(a, b)
Definition: win32_port.h:408
#define OidIsValid(objectId)
Definition: c.h:644
#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:1291

◆ lookup_collation_cache()

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

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

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

◆ pg_newlocale_from_collation()

pg_locale_t pg_newlocale_from_collation ( Oid  collid)

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

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

◆ pg_perm_setlocale()

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

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

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

◆ PGLC_localeconv()

struct lconv* PGLC_localeconv ( void  )

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

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

Referenced by PGLC_localeconv().

439 {
440  if (s->decimal_point == NULL)
441  return false;
442  if (s->thousands_sep == NULL)
443  return false;
444  if (s->grouping == NULL)
445  return false;
446  if (s->int_curr_symbol == NULL)
447  return false;
448  if (s->currency_symbol == NULL)
449  return false;
450  if (s->mon_decimal_point == NULL)
451  return false;
452  if (s->mon_thousands_sep == NULL)
453  return false;
454  if (s->mon_grouping == NULL)
455  return false;
456  if (s->positive_sign == NULL)
457  return false;
458  if (s->negative_sign == NULL)
459  return false;
460  return true;
461 }

◆ wchar2char()

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

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

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

◆ CurrentLCTimeValid

bool CurrentLCTimeValid = false
static

Definition at line 113 of file pg_locale.c.

Referenced by assign_locale_time(), and cache_locale_time().

◆ CurrentLocaleConvValid

bool CurrentLocaleConvValid = false
static

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

Referenced by pg_perm_setlocale().

◆ lc_ctype_envbuf

char lc_ctype_envbuf[LC_ENV_BUFSIZE]
static

Definition at line 120 of file pg_locale.c.

Referenced by pg_perm_setlocale().

◆ lc_monetary_envbuf

char lc_monetary_envbuf[LC_ENV_BUFSIZE]
static

Definition at line 125 of file pg_locale.c.

Referenced by pg_perm_setlocale().

◆ lc_numeric_envbuf

char lc_numeric_envbuf[LC_ENV_BUFSIZE]
static

Definition at line 126 of file pg_locale.c.

Referenced by pg_perm_setlocale().

◆ lc_time_envbuf

char lc_time_envbuf[LC_ENV_BUFSIZE]
static

Definition at line 127 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+1]

Definition at line 106 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 108 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 107 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 109 of file pg_locale.c.

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