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 "catalog/pg_database.h"
#include "mb/pg_wchar.h"
#include "miscadmin.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
 

Functions

static char * get_collation_actual_version (char collprovider, const char *collcollate)
 
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_version_for_oid (Oid oid)
 
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 HTABcollation_cache = NULL
 

Macro Definition Documentation

◆ MAX_L10N_DATA

#define MAX_L10N_DATA   80

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

References pg_perm_setlocale().

364 {
365  /*
366  * LC_MESSAGES category does not exist everywhere, but accept it anyway.
367  * We ignore failure, as per comment above.
368  */
369 #ifdef LC_MESSAGES
370  (void) pg_perm_setlocale(LC_MESSAGES, newval);
371 #endif
372 }
char * pg_perm_setlocale(int category, const char *locale)
Definition: pg_locale.c:148
#define newval

◆ assign_locale_monetary()

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

Definition at line 300 of file pg_locale.c.

References CurrentLocaleConvValid.

301 {
302  CurrentLocaleConvValid = false;
303 }
static bool CurrentLocaleConvValid
Definition: pg_locale.c:105

◆ assign_locale_numeric()

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

Definition at line 312 of file pg_locale.c.

References CurrentLocaleConvValid.

313 {
314  CurrentLocaleConvValid = false;
315 }
static bool CurrentLocaleConvValid
Definition: pg_locale.c:105

◆ assign_locale_time()

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

Definition at line 324 of file pg_locale.c.

References CurrentLCTimeValid.

325 {
326  CurrentLCTimeValid = false;
327 }
static bool CurrentLCTimeValid
Definition: pg_locale.c:106

◆ cache_locale_time()

void cache_locale_time ( void  )

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

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

◆ cache_single_string()

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

Definition at line 729 of file pg_locale.c.

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

Referenced by cache_locale_time().

730 {
731  char *ptr;
732  char *olddst;
733 
734  /* Convert the string to the database encoding, or validate it's OK */
735  ptr = pg_any_to_server(src, strlen(src), encoding);
736 
737  /* Store the string in long-lived storage, replacing any previous value */
738  olddst = *dst;
740  if (olddst)
741  pfree(olddst);
742 
743  /* Might as well clean up any palloc'd conversion result, too */
744  if (ptr != src)
745  pfree(ptr);
746 }
void pfree(void *pointer)
Definition: mcxt.c:1057
MemoryContext TopMemoryContext
Definition: mcxt.c:44
int32 encoding
Definition: pg_database.h:41
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1174
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 2064 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().

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

◆ check_locale()

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

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

252 {
253  char *save;
254  char *res;
255 
256  if (canonname)
257  *canonname = NULL; /* in case of failure */
258 
259  save = setlocale(category, NULL);
260  if (!save)
261  return false; /* won't happen, we hope */
262 
263  /* save may be pointing at a modifiable scratch variable, see above. */
264  save = pstrdup(save);
265 
266  /* set the locale with setlocale, to see if it accepts it. */
267  res = setlocale(category, locale);
268 
269  /* save canonical name if requested. */
270  if (res && canonname)
271  *canonname = pstrdup(res);
272 
273  /* restore old value. */
274  if (!setlocale(category, save))
275  elog(WARNING, "failed to restore old locale \"%s\"", save);
276  pfree(save);
277 
278  return (res != NULL);
279 }
#define setlocale(a, b)
Definition: win32_port.h:436
char * pstrdup(const char *in)
Definition: mcxt.c:1187
void pfree(void *pointer)
Definition: mcxt.c:1057
#define WARNING
Definition: elog.h:40
#define elog(elevel,...)
Definition: elog.h:228
static char * locale
Definition: initdb.c:126

◆ check_locale_messages()

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

Definition at line 340 of file pg_locale.c.

References check_locale(), and PGC_S_DEFAULT.

341 {
342  if (**newval == '\0')
343  {
344  if (source == PGC_S_DEFAULT)
345  return true;
346  else
347  return false;
348  }
349 
350  /*
351  * LC_MESSAGES category does not exist everywhere, but accept it anyway
352  *
353  * On Windows, we can't even check the value, so accept blindly
354  */
355 #if defined(LC_MESSAGES) && !defined(WIN32)
356  return check_locale(LC_MESSAGES, *newval, NULL);
357 #else
358  return true;
359 #endif
360 }
bool check_locale(int category, const char *locale, char **canonname)
Definition: pg_locale.c:251
static rewind_source * source
Definition: pg_rewind.c:79
#define newval

◆ check_locale_monetary()

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

Definition at line 294 of file pg_locale.c.

References check_locale().

295 {
296  return check_locale(LC_MONETARY, *newval, NULL);
297 }
bool check_locale(int category, const char *locale, char **canonname)
Definition: pg_locale.c:251
#define newval

◆ check_locale_numeric()

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

Definition at line 306 of file pg_locale.c.

References check_locale().

307 {
308  return check_locale(LC_NUMERIC, *newval, NULL);
309 }
bool check_locale(int category, const char *locale, char **canonname)
Definition: pg_locale.c:251
#define newval

◆ check_locale_time()

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

Definition at line 318 of file pg_locale.c.

References check_locale().

319 {
320  return check_locale(LC_TIME, *newval, NULL);
321 }
bool check_locale(int category, const char *locale, char **canonname)
Definition: pg_locale.c:251
#define newval

◆ check_strxfrm_bug()

void check_strxfrm_bug ( void  )

Definition at line 1192 of file pg_locale.c.

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

Referenced by CheckMyDatabase(), and main().

1193 {
1194  char buf[32];
1195  const int canary = 0x7F;
1196  bool ok = true;
1197 
1198  /*
1199  * Given a two-byte ASCII string and length limit 7, 8 or 9, Solaris 10
1200  * 05/08 returns 18 and modifies 10 bytes. It respects limits above or
1201  * below that range.
1202  *
1203  * The bug is present in Solaris 8 as well; it is absent in Solaris 10
1204  * 01/13 and Solaris 11.2. Affected locales include is_IS.ISO8859-1,
1205  * en_US.UTF-8, en_US.ISO8859-1, and ru_RU.KOI8-R. Unaffected locales
1206  * include de_DE.UTF-8, de_DE.ISO8859-1, zh_TW.UTF-8, and C.
1207  */
1208  buf[7] = canary;
1209  (void) strxfrm(buf, "ab", 7);
1210  if (buf[7] != canary)
1211  ok = false;
1212 
1213  /*
1214  * illumos bug #1594 was present in the source tree from 2010-10-11 to
1215  * 2012-02-01. Given an ASCII string of any length and length limit 1,
1216  * affected systems ignore the length limit and modify a number of bytes
1217  * one less than the return value. The problem inputs for this bug do not
1218  * overlap those for the Solaris bug, hence a distinct test.
1219  *
1220  * Affected systems include smartos-20110926T021612Z. Affected locales
1221  * include en_US.ISO8859-1 and en_US.UTF-8. Unaffected locales include C.
1222  */
1223  buf[1] = canary;
1224  (void) strxfrm(buf, "a", 1);
1225  if (buf[1] != canary)
1226  ok = false;
1227 
1228  if (!ok)
1229  ereport(ERROR,
1230  (errcode(ERRCODE_SYSTEM_ERROR),
1231  errmsg_internal("strxfrm(), in locale \"%s\", writes past the specified array length",
1232  setlocale(LC_COLLATE, NULL)),
1233  errhint("Apply system library package updates.")));
1234 }
int errhint(const char *fmt,...)
Definition: elog.c:1162
#define setlocale(a, b)
Definition: win32_port.h:436
int errcode(int sqlerrcode)
Definition: elog.c:704
#define ERROR
Definition: elog.h:45
static char * buf
Definition: pg_test_fsync.c:68
#define ereport(elevel,...)
Definition: elog.h:155
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1002

◆ db_encoding_convert()

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

Definition at line 440 of file pg_locale.c.

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

Referenced by PGLC_localeconv().

441 {
442  char *pstr;
443  char *mstr;
444 
445  /* convert the string to the database encoding */
446  pstr = pg_any_to_server(*str, strlen(*str), encoding);
447  if (pstr == *str)
448  return; /* no conversion happened */
449 
450  /* need it malloc'd not palloc'd */
451  mstr = strdup(pstr);
452  if (mstr == NULL)
453  ereport(ERROR,
454  (errcode(ERRCODE_OUT_OF_MEMORY),
455  errmsg("out of memory")));
456 
457  /* replace old string */
458  free(*str);
459  *str = mstr;
460 
461  pfree(pstr);
462 }
int errcode(int sqlerrcode)
Definition: elog.c:704
void pfree(void *pointer)
Definition: mcxt.c:1057
#define ERROR
Definition: elog.h:45
#define ereport(elevel,...)
Definition: elog.h:155
#define free(a)
Definition: header.h:65
int32 encoding
Definition: pg_database.h:41
int errmsg(const char *fmt,...)
Definition: elog.c:915
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 380 of file pg_locale.c.

References free.

Referenced by PGLC_localeconv().

381 {
382  if (s->decimal_point)
383  free(s->decimal_point);
384  if (s->thousands_sep)
385  free(s->thousands_sep);
386  if (s->grouping)
387  free(s->grouping);
388  if (s->int_curr_symbol)
389  free(s->int_curr_symbol);
390  if (s->currency_symbol)
391  free(s->currency_symbol);
392  if (s->mon_decimal_point)
393  free(s->mon_decimal_point);
394  if (s->mon_thousands_sep)
395  free(s->mon_thousands_sep);
396  if (s->mon_grouping)
397  free(s->mon_grouping);
398  if (s->positive_sign)
399  free(s->positive_sign);
400  if (s->negative_sign)
401  free(s->negative_sign);
402 }
#define free(a)
Definition: header.h:65

◆ get_collation_actual_version()

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

Definition at line 1613 of file pg_locale.c.

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

Referenced by get_collation_version_for_oid().

1614 {
1615  char *collversion = NULL;
1616 
1617 #ifdef USE_ICU
1618  if (collprovider == COLLPROVIDER_ICU)
1619  {
1620  UCollator *collator;
1621  UErrorCode status;
1622  UVersionInfo versioninfo;
1623  char buf[U_MAX_VERSION_STRING_LENGTH];
1624 
1625  status = U_ZERO_ERROR;
1626  collator = ucol_open(collcollate, &status);
1627  if (U_FAILURE(status))
1628  ereport(ERROR,
1629  (errmsg("could not open collator for locale \"%s\": %s",
1630  collcollate, u_errorName(status))));
1631  ucol_getVersion(collator, versioninfo);
1632  ucol_close(collator);
1633 
1634  u_versionToString(versioninfo, buf);
1635  collversion = pstrdup(buf);
1636  }
1637  else
1638 #endif
1639  if (collprovider == COLLPROVIDER_LIBC)
1640  {
1641 #if defined(__GLIBC__)
1642  char *copy = pstrdup(collcollate);
1643  char *copy_suffix = strstr(copy, ".");
1644  bool need_version = true;
1645 
1646  /*
1647  * Check for names like C.UTF-8 by chopping off the encoding suffix on
1648  * our temporary copy, so we can skip the version.
1649  */
1650  if (copy_suffix)
1651  *copy_suffix = '\0';
1652  if (pg_strcasecmp("c", copy) == 0 ||
1653  pg_strcasecmp("posix", copy) == 0)
1654  need_version = false;
1655  pfree(copy);
1656  if (!need_version)
1657  return NULL;
1658 
1659  /* Use the glibc version because we don't have anything better. */
1660  collversion = pstrdup(gnu_get_libc_version());
1661 #elif defined(LC_VERSION_MASK)
1662  locale_t loc;
1663 
1664  /* C[.encoding] and POSIX never change. */
1665  if (strcmp("C", collcollate) == 0 ||
1666  strncmp("C.", collcollate, 2) == 0 ||
1667  strcmp("POSIX", collcollate) == 0)
1668  return NULL;
1669 
1670  /* Look up FreeBSD collation version. */
1671  loc = newlocale(LC_COLLATE, collcollate, NULL);
1672  if (loc)
1673  {
1674  collversion =
1675  pstrdup(querylocale(LC_COLLATE_MASK | LC_VERSION_MASK, loc));
1676  freelocale(loc);
1677  }
1678  else
1679  ereport(ERROR,
1680  (errmsg("could not load locale \"%s\"", collcollate)));
1681 #elif defined(WIN32) && _WIN32_WINNT >= 0x0600
1682  /*
1683  * If we are targeting Windows Vista and above, we can ask for a name
1684  * given a collation name (earlier versions required a location code
1685  * that we don't have).
1686  */
1687  NLSVERSIONINFOEX version = {sizeof(NLSVERSIONINFOEX)};
1688  WCHAR wide_collcollate[LOCALE_NAME_MAX_LENGTH];
1689 
1690  /* These would be invalid arguments, but have no version. */
1691  if (pg_strcasecmp("c", collcollate) == 0 ||
1692  pg_strcasecmp("posix", collcollate) == 0)
1693  return NULL;
1694 
1695  /* For all other names, ask the OS. */
1696  MultiByteToWideChar(CP_ACP, 0, collcollate, -1, wide_collcollate,
1697  LOCALE_NAME_MAX_LENGTH);
1698  if (!GetNLSVersionEx(COMPARE_STRING, wide_collcollate, &version))
1699  {
1700  /*
1701  * GetNLSVersionEx() wants a language tag such as "en-US", not a
1702  * locale name like "English_United States.1252". Until those
1703  * values can be prevented from entering the system, or 100%
1704  * reliably converted to the more useful tag format, tolerate the
1705  * resulting error and report that we have no version data.
1706  */
1707  if (GetLastError() == ERROR_INVALID_PARAMETER)
1708  return NULL;
1709 
1710  ereport(ERROR,
1711  (errmsg("could not get collation version for locale \"%s\": error code %lu",
1712  collcollate,
1713  GetLastError())));
1714  }
1715  collversion = psprintf("%d.%d,%d.%d",
1716  (version.dwNLSVersion >> 8) & 0xFFFF,
1717  version.dwNLSVersion & 0xFF,
1718  (version.dwDefinedVersion >> 8) & 0xFFFF,
1719  version.dwDefinedVersion & 0xFF);
1720 #endif
1721  }
1722 
1723  return collversion;
1724 }
char * pstrdup(const char *in)
Definition: mcxt.c:1187
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:1057
#define ERROR
Definition: elog.h:45
static char * buf
Definition: pg_test_fsync.c:68
#define locale_t
Definition: win32_port.h:391
#define ereport(elevel,...)
Definition: elog.h:155
int errmsg(const char *fmt,...)
Definition: elog.c:915
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227

◆ get_collation_version_for_oid()

char* get_collation_version_for_oid ( Oid  oid)

Definition at line 1732 of file pg_locale.c.

References asc_tolower(), COLLOID, DATABASEOID, elog, ereport, errcode(), errmsg(), ERROR, get_collation_actual_version(), get_encoding_name_for_icu(), GetDatabaseEncoding(), GETSTRUCT, HeapTupleIsValid, MyDatabaseId, name, NameStr, ObjectIdGetDatum, palloc(), pg_attribute_unused(), pg_encoding_to_char(), ReleaseSysCache(), SearchSysCache1(), status(), generate_unaccent_rules::str, and value.

Referenced by do_collation_version_check(), do_collation_version_update(), pg_collation_actual_version(), and recordMultipleDependencies().

1733 {
1734  HeapTuple tp;
1735  char *version;
1736 
1737  if (oid == DEFAULT_COLLATION_OID)
1738  {
1739  Form_pg_database dbform;
1740 
1742  if (!HeapTupleIsValid(tp))
1743  elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
1744  dbform = (Form_pg_database) GETSTRUCT(tp);
1745  version = get_collation_actual_version(COLLPROVIDER_LIBC,
1746  NameStr(dbform->datcollate));
1747  }
1748  else
1749  {
1750  Form_pg_collation collform;
1751 
1753  if (!HeapTupleIsValid(tp))
1754  elog(ERROR, "cache lookup failed for collation %u", oid);
1755  collform = (Form_pg_collation) GETSTRUCT(tp);
1756  version = get_collation_actual_version(collform->collprovider,
1757  NameStr(collform->collcollate));
1758  }
1759 
1760  ReleaseSysCache(tp);
1761 
1762  return version;
1763 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
FormData_pg_database * Form_pg_database
Definition: pg_database.h:81
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:45
static char * get_collation_actual_version(char collprovider, const char *collcollate)
Definition: pg_locale.c:1613
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
Oid MyDatabaseId
Definition: globals.c:86
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:47
#define elog(elevel,...)
Definition: elog.h:228
#define NameStr(name)
Definition: c.h:669

◆ lc_collate_is_c()

bool lc_collate_is_c ( Oid  collation)

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

1327 {
1328  /*
1329  * If we're asked about "collation 0", return false, so that the code will
1330  * go into the non-C path and report that the collation is bogus.
1331  */
1332  if (!OidIsValid(collation))
1333  return false;
1334 
1335  /*
1336  * If we're asked about the default collation, we have to inquire of the C
1337  * library. Cache the result so we only have to compute it once.
1338  */
1339  if (collation == DEFAULT_COLLATION_OID)
1340  {
1341  static int result = -1;
1342  char *localeptr;
1343 
1344  if (result >= 0)
1345  return (bool) result;
1346  localeptr = setlocale(LC_COLLATE, NULL);
1347  if (!localeptr)
1348  elog(ERROR, "invalid LC_COLLATE setting");
1349 
1350  if (strcmp(localeptr, "C") == 0)
1351  result = true;
1352  else if (strcmp(localeptr, "POSIX") == 0)
1353  result = true;
1354  else
1355  result = false;
1356  return (bool) result;
1357  }
1358 
1359  /*
1360  * If we're asked about the built-in C/POSIX collations, we know that.
1361  */
1362  if (collation == C_COLLATION_OID ||
1363  collation == POSIX_COLLATION_OID)
1364  return true;
1365 
1366  /*
1367  * Otherwise, we have to consult pg_collation, but we cache that.
1368  */
1369  return (lookup_collation_cache(collation, true))->collate_is_c;
1370 }
#define setlocale(a, b)
Definition: win32_port.h:436
#define OidIsValid(objectId)
Definition: c.h:698
#define ERROR
Definition: elog.h:45
#define elog(elevel,...)
Definition: elog.h:228
static collation_cache_entry * lookup_collation_cache(Oid collation, bool set_flags)
Definition: pg_locale.c:1262

◆ lc_ctype_is_c()

bool lc_ctype_is_c ( Oid  collation)

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

1377 {
1378  /*
1379  * If we're asked about "collation 0", return false, so that the code will
1380  * go into the non-C path and report that the collation is bogus.
1381  */
1382  if (!OidIsValid(collation))
1383  return false;
1384 
1385  /*
1386  * If we're asked about the default collation, we have to inquire of the C
1387  * library. Cache the result so we only have to compute it once.
1388  */
1389  if (collation == DEFAULT_COLLATION_OID)
1390  {
1391  static int result = -1;
1392  char *localeptr;
1393 
1394  if (result >= 0)
1395  return (bool) result;
1396  localeptr = setlocale(LC_CTYPE, NULL);
1397  if (!localeptr)
1398  elog(ERROR, "invalid LC_CTYPE setting");
1399 
1400  if (strcmp(localeptr, "C") == 0)
1401  result = true;
1402  else if (strcmp(localeptr, "POSIX") == 0)
1403  result = true;
1404  else
1405  result = false;
1406  return (bool) result;
1407  }
1408 
1409  /*
1410  * If we're asked about the built-in C/POSIX collations, we know that.
1411  */
1412  if (collation == C_COLLATION_OID ||
1413  collation == POSIX_COLLATION_OID)
1414  return true;
1415 
1416  /*
1417  * Otherwise, we have to consult pg_collation, but we cache that.
1418  */
1419  return (lookup_collation_cache(collation, true))->ctype_is_c;
1420 }
#define setlocale(a, b)
Definition: win32_port.h:436
#define OidIsValid(objectId)
Definition: c.h:698
#define ERROR
Definition: elog.h:45
#define elog(elevel,...)
Definition: elog.h:228
static collation_cache_entry * lookup_collation_cache(Oid collation, bool set_flags)
Definition: pg_locale.c:1262

◆ lookup_collation_cache()

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

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

1263 {
1264  collation_cache_entry *cache_entry;
1265  bool found;
1266 
1267  Assert(OidIsValid(collation));
1268  Assert(collation != DEFAULT_COLLATION_OID);
1269 
1270  if (collation_cache == NULL)
1271  {
1272  /* First time through, initialize the hash table */
1273  HASHCTL ctl;
1274 
1275  ctl.keysize = sizeof(Oid);
1276  ctl.entrysize = sizeof(collation_cache_entry);
1277  collation_cache = hash_create("Collation cache", 100, &ctl,
1278  HASH_ELEM | HASH_BLOBS);
1279  }
1280 
1281  cache_entry = hash_search(collation_cache, &collation, HASH_ENTER, &found);
1282  if (!found)
1283  {
1284  /*
1285  * Make sure cache entry is marked invalid, in case we fail before
1286  * setting things.
1287  */
1288  cache_entry->flags_valid = false;
1289  cache_entry->locale = 0;
1290  }
1291 
1292  if (set_flags && !cache_entry->flags_valid)
1293  {
1294  /* Attempt to set the flags */
1295  HeapTuple tp;
1296  Form_pg_collation collform;
1297  const char *collcollate;
1298  const char *collctype;
1299 
1300  tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collation));
1301  if (!HeapTupleIsValid(tp))
1302  elog(ERROR, "cache lookup failed for collation %u", collation);
1303  collform = (Form_pg_collation) GETSTRUCT(tp);
1304 
1305  collcollate = NameStr(collform->collcollate);
1306  collctype = NameStr(collform->collctype);
1307 
1308  cache_entry->collate_is_c = ((strcmp(collcollate, "C") == 0) ||
1309  (strcmp(collcollate, "POSIX") == 0));
1310  cache_entry->ctype_is_c = ((strcmp(collctype, "C") == 0) ||
1311  (strcmp(collctype, "POSIX") == 0));
1312 
1313  cache_entry->flags_valid = true;
1314 
1315  ReleaseSysCache(tp);
1316  }
1317 
1318  return cache_entry;
1319 }
bool flags_valid
Definition: pg_locale.c:115
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define HASH_ELEM
Definition: hsearch.h:95
bool ctype_is_c
Definition: pg_locale.c:114
Size entrysize
Definition: hsearch.h:76
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:698
bool collate_is_c
Definition: pg_locale.c:113
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:45
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:349
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
pg_locale_t locale
Definition: pg_locale.c:116
#define HASH_BLOBS
Definition: hsearch.h:97
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
Size keysize
Definition: hsearch.h:75
static HTAB * collation_cache
Definition: pg_locale.c:119
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:792
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:47
#define elog(elevel,...)
Definition: elog.h:228
#define NameStr(name)
Definition: c.h:669
Definition: pg_locale.c:110

◆ pg_newlocale_from_collation()

pg_locale_t pg_newlocale_from_collation ( Oid  collid)

Definition at line 1473 of file pg_locale.c.

References Assert, COLLOID, pg_locale_struct::deterministic, elog, ereport, errcode(), errhint(), errmsg(), ERROR, 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, ReleaseSysCache(), SearchSysCache1(), status(), and TopMemoryContext.

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().

1474 {
1475  collation_cache_entry *cache_entry;
1476 
1477  /* Callers must pass a valid OID */
1478  Assert(OidIsValid(collid));
1479 
1480  /* Return 0 for "default" collation, just in case caller forgets */
1481  if (collid == DEFAULT_COLLATION_OID)
1482  return (pg_locale_t) 0;
1483 
1484  cache_entry = lookup_collation_cache(collid, false);
1485 
1486  if (cache_entry->locale == 0)
1487  {
1488  /* We haven't computed this yet in this session, so do it */
1489  HeapTuple tp;
1490  Form_pg_collation collform;
1491  const char *collcollate pg_attribute_unused();
1492  const char *collctype pg_attribute_unused();
1493  struct pg_locale_struct result;
1494  pg_locale_t resultp;
1495 
1496  tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(collid));
1497  if (!HeapTupleIsValid(tp))
1498  elog(ERROR, "cache lookup failed for collation %u", collid);
1499  collform = (Form_pg_collation) GETSTRUCT(tp);
1500 
1501  collcollate = NameStr(collform->collcollate);
1502  collctype = NameStr(collform->collctype);
1503 
1504  /* We'll fill in the result struct locally before allocating memory */
1505  memset(&result, 0, sizeof(result));
1506  result.provider = collform->collprovider;
1507  result.deterministic = collform->collisdeterministic;
1508 
1509  if (collform->collprovider == COLLPROVIDER_LIBC)
1510  {
1511 #ifdef HAVE_LOCALE_T
1512  locale_t loc;
1513 
1514  if (strcmp(collcollate, collctype) == 0)
1515  {
1516  /* Normal case where they're the same */
1517  errno = 0;
1518 #ifndef WIN32
1519  loc = newlocale(LC_COLLATE_MASK | LC_CTYPE_MASK, collcollate,
1520  NULL);
1521 #else
1522  loc = _create_locale(LC_ALL, collcollate);
1523 #endif
1524  if (!loc)
1525  report_newlocale_failure(collcollate);
1526  }
1527  else
1528  {
1529 #ifndef WIN32
1530  /* We need two newlocale() steps */
1531  locale_t loc1;
1532 
1533  errno = 0;
1534  loc1 = newlocale(LC_COLLATE_MASK, collcollate, NULL);
1535  if (!loc1)
1536  report_newlocale_failure(collcollate);
1537  errno = 0;
1538  loc = newlocale(LC_CTYPE_MASK, collctype, loc1);
1539  if (!loc)
1540  report_newlocale_failure(collctype);
1541 #else
1542 
1543  /*
1544  * XXX The _create_locale() API doesn't appear to support
1545  * this. Could perhaps be worked around by changing
1546  * pg_locale_t to contain two separate fields.
1547  */
1548  ereport(ERROR,
1549  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1550  errmsg("collations with different collate and ctype values are not supported on this platform")));
1551 #endif
1552  }
1553 
1554  result.info.lt = loc;
1555 #else /* not HAVE_LOCALE_T */
1556  /* platform that doesn't support locale_t */
1557  ereport(ERROR,
1558  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1559  errmsg("collation provider LIBC is not supported on this platform")));
1560 #endif /* not HAVE_LOCALE_T */
1561  }
1562  else if (collform->collprovider == COLLPROVIDER_ICU)
1563  {
1564 #ifdef USE_ICU
1565  UCollator *collator;
1566  UErrorCode status;
1567 
1568  if (strcmp(collcollate, collctype) != 0)
1569  ereport(ERROR,
1570  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1571  errmsg("collations with different collate and ctype values are not supported by ICU")));
1572 
1573  status = U_ZERO_ERROR;
1574  collator = ucol_open(collcollate, &status);
1575  if (U_FAILURE(status))
1576  ereport(ERROR,
1577  (errmsg("could not open collator for locale \"%s\": %s",
1578  collcollate, u_errorName(status))));
1579 
1580  if (U_ICU_VERSION_MAJOR_NUM < 54)
1581  icu_set_collation_attributes(collator, collcollate);
1582 
1583  /* We will leak this string if we get an error below :-( */
1584  result.info.icu.locale = MemoryContextStrdup(TopMemoryContext,
1585  collcollate);
1586  result.info.icu.ucol = collator;
1587 #else /* not USE_ICU */
1588  /* could get here if a collation was created by a build with ICU */
1589  ereport(ERROR,
1590  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1591  errmsg("ICU is not supported in this build"), \
1592  errhint("You need to rebuild PostgreSQL using --with-icu.")));
1593 #endif /* not USE_ICU */
1594  }
1595 
1596  ReleaseSysCache(tp);
1597 
1598  /* We'll keep the pg_locale_t structures in TopMemoryContext */
1599  resultp = MemoryContextAlloc(TopMemoryContext, sizeof(*resultp));
1600  *resultp = result;
1601 
1602  cache_entry->locale = resultp;
1603  }
1604 
1605  return cache_entry->locale;
1606 }
int errhint(const char *fmt,...)
Definition: elog.c:1162
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
int errcode(int sqlerrcode)
Definition: elog.c:704
#define OidIsValid(objectId)
Definition: c.h:698
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:45
#define locale_t
Definition: win32_port.h:391
MemoryContext TopMemoryContext
Definition: mcxt.c:44
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
pg_locale_t locale
Definition: pg_locale.c:116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
#define ereport(elevel,...)
Definition: elog.h:155
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:792
pg_attribute_unused()
Definition: isn.c:63
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:47
int errmsg(const char *fmt,...)
Definition: elog.c:915
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1174
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:797
#define elog(elevel,...)
Definition: elog.h:228
#define NameStr(name)
Definition: c.h:669
static collation_cache_entry * lookup_collation_cache(Oid collation, bool set_flags)
Definition: pg_locale.c:1262
Definition: pg_locale.c:110
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227

◆ pg_perm_setlocale()

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

Definition at line 148 of file pg_locale.c.

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

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

149 {
150  char *result;
151  const char *envvar;
152 
153 #ifndef WIN32
154  result = setlocale(category, locale);
155 #else
156 
157  /*
158  * On Windows, setlocale(LC_MESSAGES) does not work, so just assume that
159  * the given value is good and set it in the environment variables. We
160  * must ignore attempts to set to "", which means "keep using the old
161  * environment value".
162  */
163 #ifdef LC_MESSAGES
164  if (category == LC_MESSAGES)
165  {
166  result = (char *) locale;
167  if (locale == NULL || locale[0] == '\0')
168  return result;
169  }
170  else
171 #endif
172  result = setlocale(category, locale);
173 #endif /* WIN32 */
174 
175  if (result == NULL)
176  return result; /* fall out immediately on failure */
177 
178  /*
179  * Use the right encoding in translated messages. Under ENABLE_NLS, let
180  * pg_bind_textdomain_codeset() figure it out. Under !ENABLE_NLS, message
181  * format strings are ASCII, but database-encoding strings may enter the
182  * message via %s. This makes the overall message encoding equal to the
183  * database encoding.
184  */
185  if (category == LC_CTYPE)
186  {
187  static char save_lc_ctype[NAMEDATALEN + 20];
188 
189  /* copy setlocale() return value before callee invokes it again */
190  strlcpy(save_lc_ctype, result, sizeof(save_lc_ctype));
191  result = save_lc_ctype;
192 
193 #ifdef ENABLE_NLS
194  SetMessageEncoding(pg_bind_textdomain_codeset(textdomain(NULL)));
195 #else
197 #endif
198  }
199 
200  switch (category)
201  {
202  case LC_COLLATE:
203  envvar = "LC_COLLATE";
204  break;
205  case LC_CTYPE:
206  envvar = "LC_CTYPE";
207  break;
208 #ifdef LC_MESSAGES
209  case LC_MESSAGES:
210  envvar = "LC_MESSAGES";
211 #ifdef WIN32
212  result = IsoLocaleName(locale);
213  if (result == NULL)
214  result = (char *) locale;
215  elog(DEBUG3, "IsoLocaleName() executed; locale: \"%s\"", result);
216 #endif /* WIN32 */
217  break;
218 #endif /* LC_MESSAGES */
219  case LC_MONETARY:
220  envvar = "LC_MONETARY";
221  break;
222  case LC_NUMERIC:
223  envvar = "LC_NUMERIC";
224  break;
225  case LC_TIME:
226  envvar = "LC_TIME";
227  break;
228  default:
229  elog(FATAL, "unrecognized LC category: %d", category);
230  return NULL; /* keep compiler quiet */
231  }
232 
233  if (setenv(envvar, result, 1) != 0)
234  return NULL;
235 
236  return result;
237 }
void SetMessageEncoding(int encoding)
Definition: mbutils.c:1055
#define setlocale(a, b)
Definition: win32_port.h:436
#define DEBUG3
Definition: elog.h:23
#define NAMEDATALEN
#define setenv(x, y, z)
Definition: win32_port.h:497
#define FATAL
Definition: elog.h:54
int GetDatabaseEncoding(void)
Definition: mbutils.c:1151
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define elog(elevel,...)
Definition: elog.h:228
static char * locale
Definition: initdb.c:126

◆ PGLC_localeconv()

struct lconv* PGLC_localeconv ( void  )

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

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

◆ struct_lconv_is_valid()

static bool struct_lconv_is_valid ( struct lconv *  s)
static

Definition at line 409 of file pg_locale.c.

Referenced by PGLC_localeconv().

410 {
411  if (s->decimal_point == NULL)
412  return false;
413  if (s->thousands_sep == NULL)
414  return false;
415  if (s->grouping == NULL)
416  return false;
417  if (s->int_curr_symbol == NULL)
418  return false;
419  if (s->currency_symbol == NULL)
420  return false;
421  if (s->mon_decimal_point == NULL)
422  return false;
423  if (s->mon_thousands_sep == NULL)
424  return false;
425  if (s->mon_grouping == NULL)
426  return false;
427  if (s->positive_sign == NULL)
428  return false;
429  if (s->negative_sign == NULL)
430  return false;
431  return true;
432 }

◆ wchar2char()

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

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

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

Variable Documentation

◆ collation_cache

HTAB* collation_cache = NULL
static

Definition at line 119 of file pg_locale.c.

◆ CurrentLCTimeValid

bool CurrentLCTimeValid = false
static

Definition at line 106 of file pg_locale.c.

Referenced by assign_locale_time(), and cache_locale_time().

◆ CurrentLocaleConvValid

bool CurrentLocaleConvValid = false
static

Definition at line 105 of file pg_locale.c.

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

◆ locale_messages

char* locale_messages

Definition at line 87 of file pg_locale.c.

◆ locale_monetary

char* locale_monetary

Definition at line 88 of file pg_locale.c.

Referenced by PGLC_localeconv().

◆ locale_numeric

char* locale_numeric

Definition at line 89 of file pg_locale.c.

Referenced by PGLC_localeconv().

◆ locale_time

char* locale_time

Definition at line 90 of file pg_locale.c.

Referenced by cache_locale_time().

◆ localized_abbrev_days

char* localized_abbrev_days[7+1]

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

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