PostgreSQL Source Code git master
Loading...
Searching...
No Matches
pg_locale.c
Go to the documentation of this file.
1/*-----------------------------------------------------------------------
2 *
3 * PostgreSQL locale utilities
4 *
5 * Portions Copyright (c) 2002-2026, PostgreSQL Global Development Group
6 *
7 * src/backend/utils/adt/pg_locale.c
8 *
9 *-----------------------------------------------------------------------
10 */
11
12/*----------
13 * Here is how the locale stuff is handled: LC_COLLATE and LC_CTYPE
14 * are fixed at CREATE DATABASE time, stored in pg_database, and cannot
15 * be changed. Thus, the effects of strcoll(), strxfrm(), isupper(),
16 * toupper(), etc. are always in the same fixed locale.
17 *
18 * LC_MESSAGES is settable at run time and will take effect
19 * immediately.
20 *
21 * The other categories, LC_MONETARY, LC_NUMERIC, and LC_TIME are
22 * permanently set to "C", and then we use temporary locale_t
23 * objects when we need to look up locale data based on the GUCs
24 * of the same name. Information is cached when the GUCs change.
25 * The cached information is only used by the formatting functions
26 * (to_char, etc.) and the money type. For the user, this should all be
27 * transparent.
28 *----------
29 */
30
31
32#include "postgres.h"
33
34#include <time.h>
35#ifdef USE_ICU
36#include <unicode/ucol.h>
37#endif
38
39#include "access/htup_details.h"
41#include "catalog/pg_database.h"
42#include "common/hashfn.h"
43#include "common/string.h"
44#include "mb/pg_wchar.h"
45#include "miscadmin.h"
46#include "utils/builtins.h"
47#include "utils/guc_hooks.h"
48#include "utils/lsyscache.h"
49#include "utils/memutils.h"
50#include "utils/pg_locale.h"
51#include "utils/pg_locale_c.h"
52#include "utils/relcache.h"
53#include "utils/syscache.h"
54
55#ifdef WIN32
56#include <shlwapi.h>
57#endif
58
59/* Error triggered for locale-sensitive subroutines */
60#define PGLOCALE_SUPPORT_ERROR(provider) \
61 elog(ERROR, "unsupported collprovider for %s: %c", __func__, provider)
62
63/*
64 * This should be large enough that most strings will fit, but small enough
65 * that we feel comfortable putting it on the stack
66 */
67#define TEXTBUFLEN 1024
68
69#define MAX_L10N_DATA 80
70
71/* pg_locale_builtin.c */
74
75/* pg_locale_icu.c */
76#ifdef USE_ICU
77extern UCollator *pg_ucol_open(const char *loc_str);
78extern char *get_collation_actual_version_icu(const char *collcollate);
79#endif
81
82/* pg_locale_libc.c */
84extern char *get_collation_actual_version_libc(const char *collcollate);
85
86/* GUC settings */
91
93
94/*
95 * lc_time localization cache.
96 *
97 * We use only the first 7 or 12 entries of these arrays. The last array
98 * element is left as NULL for the convenience of outside code that wants
99 * to sequentially scan these arrays.
100 */
105
107
108/* indicates whether locale information cache is valid */
109static bool CurrentLocaleConvValid = false;
110static bool CurrentLCTimeValid = false;
111
112static struct pg_locale_struct c_locale = {
113 .deterministic = true,
114 .collate_is_c = true,
115 .ctype_is_c = true,
116};
117
118/* Cache for collation-related knowledge */
119
120typedef struct
121{
122 Oid collid; /* hash key: pg_collation OID */
123 pg_locale_t locale; /* locale_t struct, or 0 if not valid */
124
125 /* needed for simplehash */
127 char status;
129
130#define SH_PREFIX collation_cache
131#define SH_ELEMENT_TYPE collation_cache_entry
132#define SH_KEY_TYPE Oid
133#define SH_KEY collid
134#define SH_HASH_KEY(tb, key) murmurhash32((uint32) key)
135#define SH_EQUAL(tb, a, b) (a == b)
136#define SH_GET_HASH(tb, a) a->hash
137#define SH_SCOPE static inline
138#define SH_STORE_HASH
139#define SH_DECLARE
140#define SH_DEFINE
141#include "lib/simplehash.h"
142
145
146/*
147 * The collation cache is often accessed repeatedly for the same collation, so
148 * remember the last one used.
149 */
152
153#if defined(WIN32) && defined(LC_MESSAGES)
154static char *IsoLocaleName(const char *);
155#endif
156
157/*
158 * pg_perm_setlocale
159 *
160 * This wraps the libc function setlocale(), with two additions. First, when
161 * changing LC_CTYPE, update gettext's encoding for the current message
162 * domain. GNU gettext automatically tracks LC_CTYPE on most platforms, but
163 * not on Windows. Second, if the operation is successful, the corresponding
164 * LC_XXX environment variable is set to match. By setting the environment
165 * variable, we ensure that any subsequent use of setlocale(..., "") will
166 * preserve the settings made through this routine. Of course, LC_ALL must
167 * also be unset to fully ensure that, but that has to be done elsewhere after
168 * all the individual LC_XXX variables have been set correctly. (Thank you
169 * Perl for making this kluge necessary.)
170 */
171char *
172pg_perm_setlocale(int category, const char *locale)
173{
174 char *result;
175 const char *envvar;
176
177#ifndef WIN32
178 result = setlocale(category, locale);
179#else
180
181 /*
182 * On Windows, setlocale(LC_MESSAGES) does not work, so just assume that
183 * the given value is good and set it in the environment variables. We
184 * must ignore attempts to set to "", which means "keep using the old
185 * environment value".
186 */
187#ifdef LC_MESSAGES
188 if (category == LC_MESSAGES)
189 {
190 result = (char *) locale;
191 if (locale == NULL || locale[0] == '\0')
192 return result;
193 }
194 else
195#endif
196 result = setlocale(category, locale);
197#endif /* WIN32 */
198
199 if (result == NULL)
200 return result; /* fall out immediately on failure */
201
202 /*
203 * Use the right encoding in translated messages. Under ENABLE_NLS, let
204 * pg_bind_textdomain_codeset() figure it out. Under !ENABLE_NLS, message
205 * format strings are ASCII, but database-encoding strings may enter the
206 * message via %s. This makes the overall message encoding equal to the
207 * database encoding.
208 */
209 if (category == LC_CTYPE)
210 {
212
213 /* copy setlocale() return value before callee invokes it again */
216
217#ifdef ENABLE_NLS
219#else
221#endif
222 }
223
224 switch (category)
225 {
226 case LC_COLLATE:
227 envvar = "LC_COLLATE";
228 break;
229 case LC_CTYPE:
230 envvar = "LC_CTYPE";
231 break;
232#ifdef LC_MESSAGES
233 case LC_MESSAGES:
234 envvar = "LC_MESSAGES";
235#ifdef WIN32
237 if (result == NULL)
238 result = (char *) locale;
239 elog(DEBUG3, "IsoLocaleName() executed; locale: \"%s\"", result);
240#endif /* WIN32 */
241 break;
242#endif /* LC_MESSAGES */
243 case LC_MONETARY:
244 envvar = "LC_MONETARY";
245 break;
246 case LC_NUMERIC:
247 envvar = "LC_NUMERIC";
248 break;
249 case LC_TIME:
250 envvar = "LC_TIME";
251 break;
252 default:
253 elog(FATAL, "unrecognized LC category: %d", category);
254 return NULL; /* keep compiler quiet */
255 }
256
257 if (setenv(envvar, result, 1) != 0)
258 return NULL;
259
260 return result;
261}
262
263
264/*
265 * Is the locale name valid for the locale category?
266 *
267 * If successful, and canonname isn't NULL, a palloc'd copy of the locale's
268 * canonical name is stored there. This is especially useful for figuring out
269 * what locale name "" means (ie, the server environment value). (Actually,
270 * it seems that on most implementations that's the only thing it's good for;
271 * we could wish that setlocale gave back a canonically spelled version of
272 * the locale name, but typically it doesn't.)
273 */
274bool
275check_locale(int category, const char *locale, char **canonname)
276{
277 char *save;
278 char *res;
279
280 /* Don't let Windows' non-ASCII locale names in. */
281 if (!pg_is_ascii(locale))
282 {
285 errmsg("locale name \"%s\" contains non-ASCII characters",
286 locale)));
287 return false;
288 }
289
290 if (canonname)
291 *canonname = NULL; /* in case of failure */
292
293 save = setlocale(category, NULL);
294 if (!save)
295 return false; /* won't happen, we hope */
296
297 /* save may be pointing at a modifiable scratch variable, see above. */
298 save = pstrdup(save);
299
300 /* set the locale with setlocale, to see if it accepts it. */
301 res = setlocale(category, locale);
302
303 /* save canonical name if requested. */
304 if (res && canonname)
305 *canonname = pstrdup(res);
306
307 /* restore old value. */
308 if (!setlocale(category, save))
309 elog(WARNING, "failed to restore old locale \"%s\"", save);
310 pfree(save);
311
312 /* Don't let Windows' non-ASCII locale names out. */
314 {
317 errmsg("locale name \"%s\" contains non-ASCII characters",
318 *canonname)));
320 *canonname = NULL;
321 return false;
322 }
323
324 return (res != NULL);
325}
326
327
328/*
329 * GUC check/assign hooks
330 *
331 * For most locale categories, the assign hook doesn't actually set the locale
332 * permanently, just reset flags so that the next use will cache the
333 * appropriate values. (See explanation at the top of this file.)
334 *
335 * Note: we accept value = "" as selecting the postmaster's environment
336 * value, whatever it was (so long as the environment setting is legal).
337 * This will have been locked down by an earlier call to pg_perm_setlocale.
338 */
339bool
341{
343}
344
345void
346assign_locale_monetary(const char *newval, void *extra)
347{
349}
350
351bool
353{
355}
356
357void
358assign_locale_numeric(const char *newval, void *extra)
359{
361}
362
363bool
365{
366 return check_locale(LC_TIME, *newval, NULL);
367}
368
369void
370assign_locale_time(const char *newval, void *extra)
371{
372 CurrentLCTimeValid = false;
373}
374
375/*
376 * We allow LC_MESSAGES to actually be set globally.
377 *
378 * Note: we normally disallow value = "" because it wouldn't have consistent
379 * semantics (it'd effectively just use the previous value). However, this
380 * is the value passed for PGC_S_DEFAULT, so don't complain in that case,
381 * not even if the attempted setting fails due to invalid environment value.
382 * The idea there is just to accept the environment setting *if possible*
383 * during startup, until we can read the proper value from postgresql.conf.
384 */
385bool
387{
388 if (**newval == '\0')
389 {
390 if (source == PGC_S_DEFAULT)
391 return true;
392 else
393 return false;
394 }
395
396 /*
397 * LC_MESSAGES category does not exist everywhere, but accept it anyway
398 *
399 * On Windows, we can't even check the value, so accept blindly
400 */
401#if defined(LC_MESSAGES) && !defined(WIN32)
403#else
404 return true;
405#endif
406}
407
408void
409assign_locale_messages(const char *newval, void *extra)
410{
411 /*
412 * LC_MESSAGES category does not exist everywhere, but accept it anyway.
413 * We ignore failure, as per comment above.
414 */
415#ifdef LC_MESSAGES
417#endif
418}
419
420
421/*
422 * Frees the malloced content of a struct lconv. (But not the struct
423 * itself.) It's important that this not throw elog(ERROR).
424 */
425static void
427{
428 free(s->decimal_point);
429 free(s->thousands_sep);
430 free(s->grouping);
431 free(s->int_curr_symbol);
432 free(s->currency_symbol);
433 free(s->mon_decimal_point);
434 free(s->mon_thousands_sep);
435 free(s->mon_grouping);
436 free(s->positive_sign);
437 free(s->negative_sign);
438}
439
440/*
441 * Check that all fields of a struct lconv (or at least, the ones we care
442 * about) are non-NULL. The field list must match free_struct_lconv().
443 */
444static bool
446{
447 if (s->decimal_point == NULL)
448 return false;
449 if (s->thousands_sep == NULL)
450 return false;
451 if (s->grouping == NULL)
452 return false;
453 if (s->int_curr_symbol == NULL)
454 return false;
455 if (s->currency_symbol == NULL)
456 return false;
457 if (s->mon_decimal_point == NULL)
458 return false;
459 if (s->mon_thousands_sep == NULL)
460 return false;
461 if (s->mon_grouping == NULL)
462 return false;
463 if (s->positive_sign == NULL)
464 return false;
465 if (s->negative_sign == NULL)
466 return false;
467 return true;
468}
469
470
471/*
472 * Convert the strdup'd string at *str from the specified encoding to the
473 * database encoding.
474 */
475static void
477{
478 char *pstr;
479 char *mstr;
480
481 /* convert the string to the database encoding */
483 if (pstr == *str)
484 return; /* no conversion happened */
485
486 /* need it malloc'd not palloc'd */
487 mstr = strdup(pstr);
488 if (mstr == NULL)
491 errmsg("out of memory")));
492
493 /* replace old string */
494 free(*str);
495 *str = mstr;
496
497 pfree(pstr);
498}
499
500
501/*
502 * Return the POSIX lconv struct (contains number/money formatting
503 * information) with locale information for all categories.
504 */
505struct lconv *
507{
508 static struct lconv CurrentLocaleConv;
509 static bool CurrentLocaleConvAllocated = false;
510 struct lconv *extlconv;
511 struct lconv tmp;
512 struct lconv worklconv = {0};
513
514 /* Did we do it already? */
516 return &CurrentLocaleConv;
517
518 /* Free any already-allocated storage */
520 {
523 }
524
525 /*
526 * Use thread-safe method of obtaining a copy of lconv from the operating
527 * system.
528 */
531 &tmp) != 0)
532 elog(ERROR,
533 "could not get lconv for LC_MONETARY = \"%s\", LC_NUMERIC = \"%s\": %m",
535
536 /* Must copy data now so we can re-encode it. */
537 extlconv = &tmp;
538 worklconv.decimal_point = strdup(extlconv->decimal_point);
539 worklconv.thousands_sep = strdup(extlconv->thousands_sep);
540 worklconv.grouping = strdup(extlconv->grouping);
541 worklconv.int_curr_symbol = strdup(extlconv->int_curr_symbol);
542 worklconv.currency_symbol = strdup(extlconv->currency_symbol);
543 worklconv.mon_decimal_point = strdup(extlconv->mon_decimal_point);
544 worklconv.mon_thousands_sep = strdup(extlconv->mon_thousands_sep);
545 worklconv.mon_grouping = strdup(extlconv->mon_grouping);
546 worklconv.positive_sign = strdup(extlconv->positive_sign);
547 worklconv.negative_sign = strdup(extlconv->negative_sign);
548 /* Copy scalar fields as well */
549 worklconv.int_frac_digits = extlconv->int_frac_digits;
550 worklconv.frac_digits = extlconv->frac_digits;
551 worklconv.p_cs_precedes = extlconv->p_cs_precedes;
552 worklconv.p_sep_by_space = extlconv->p_sep_by_space;
553 worklconv.n_cs_precedes = extlconv->n_cs_precedes;
554 worklconv.n_sep_by_space = extlconv->n_sep_by_space;
555 worklconv.p_sign_posn = extlconv->p_sign_posn;
556 worklconv.n_sign_posn = extlconv->n_sign_posn;
557
558 /* Free the contents of the object populated by pg_localeconv_r(). */
559 pg_localeconv_free(&tmp);
560
561 /* If any of the preceding strdup calls failed, complain now. */
565 errmsg("out of memory")));
566
567 PG_TRY();
568 {
569 int encoding;
570
571 /*
572 * Now we must perform encoding conversion from whatever's associated
573 * with the locales into the database encoding. If we can't identify
574 * the encoding implied by LC_NUMERIC or LC_MONETARY (ie we get -1),
575 * use PG_SQL_ASCII, which will result in just validating that the
576 * strings are OK in the database encoding.
577 */
579 if (encoding < 0)
581
582 db_encoding_convert(encoding, &worklconv.decimal_point);
583 db_encoding_convert(encoding, &worklconv.thousands_sep);
584 /* grouping is not text and does not require conversion */
585
587 if (encoding < 0)
589
590 db_encoding_convert(encoding, &worklconv.int_curr_symbol);
591 db_encoding_convert(encoding, &worklconv.currency_symbol);
592 db_encoding_convert(encoding, &worklconv.mon_decimal_point);
593 db_encoding_convert(encoding, &worklconv.mon_thousands_sep);
594 /* mon_grouping is not text and does not require conversion */
595 db_encoding_convert(encoding, &worklconv.positive_sign);
596 db_encoding_convert(encoding, &worklconv.negative_sign);
597 }
598 PG_CATCH();
599 {
601 PG_RE_THROW();
602 }
603 PG_END_TRY();
604
605 /*
606 * Everything is good, so save the results.
607 */
611 return &CurrentLocaleConv;
612}
613
614#ifdef WIN32
615/*
616 * On Windows, strftime() returns its output in encoding CP_ACP (the default
617 * operating system codepage for the computer), which is likely different
618 * from SERVER_ENCODING. This is especially important in Japanese versions
619 * of Windows which will use SJIS encoding, which we don't support as a
620 * server encoding.
621 *
622 * So, instead of using strftime(), use wcsftime() to return the value in
623 * wide characters (internally UTF16) and then convert to UTF8, which we
624 * know how to handle directly.
625 *
626 * Note that this only affects the calls to strftime() in this file, which are
627 * used to get the locale-aware strings. Other parts of the backend use
628 * pg_strftime(), which isn't locale-aware and does not need to be replaced.
629 */
630static size_t
631strftime_l_win32(char *dst, size_t dstlen,
632 const char *format, const struct tm *tm, locale_t locale)
633{
634 size_t len;
635 wchar_t wformat[8]; /* formats used below need 3 chars */
636 wchar_t wbuf[MAX_L10N_DATA];
637
638 /*
639 * Get a wchar_t version of the format string. We only actually use
640 * plain-ASCII formats in this file, so we can say that they're UTF8.
641 */
644 if (len == 0)
645 elog(ERROR, "could not convert format string from UTF-8: error code %lu",
646 GetLastError());
647
649 if (len == 0)
650 {
651 /*
652 * wcsftime failed, possibly because the result would not fit in
653 * MAX_L10N_DATA. Return 0 with the contents of dst unspecified.
654 */
655 return 0;
656 }
657
659 NULL, NULL);
660 if (len == 0)
661 elog(ERROR, "could not convert string to UTF-8: error code %lu",
662 GetLastError());
663
664 dst[len] = '\0';
665
666 return len;
667}
668
669/* redefine strftime_l() */
670#define strftime_l(a,b,c,d,e) strftime_l_win32(a,b,c,d,e)
671#endif /* WIN32 */
672
673/*
674 * Subroutine for cache_locale_time().
675 * Convert the given string from encoding "encoding" to the database
676 * encoding, and store the result at *dst, replacing any previous value.
677 */
678static void
679cache_single_string(char **dst, const char *src, int encoding)
680{
681 char *ptr;
682 char *olddst;
683
684 /* Convert the string to the database encoding, or validate it's OK */
685 ptr = pg_any_to_server(src, strlen(src), encoding);
686
687 /* Store the string in long-lived storage, replacing any previous value */
688 olddst = *dst;
690 if (olddst)
691 pfree(olddst);
692
693 /* Might as well clean up any palloc'd conversion result, too */
694 if (ptr != src)
695 pfree(ptr);
696}
697
698/*
699 * Update the lc_time localization cache variables if needed.
700 */
701void
703{
704 char buf[(2 * 7 + 2 * 12) * MAX_L10N_DATA];
705 char *bufptr;
707 struct tm *timeinfo;
708 struct tm timeinfobuf;
709 bool strftimefail = false;
710 int encoding;
711 int i;
712 locale_t locale;
713
714 /* did we do this already? */
716 return;
717
718 elog(DEBUG3, "cache_locale_time() executed; locale: \"%s\"", locale_time);
719
720 errno = ENOENT;
721#ifdef WIN32
723 if (locale == (locale_t) 0)
725#else
727#endif
728 if (!locale)
730
731 /* We use times close to current time as data for strftime(). */
732 timenow = time(NULL);
734
735 /* Store the strftime results in MAX_L10N_DATA-sized portions of buf[] */
736 bufptr = buf;
737
738 /*
739 * MAX_L10N_DATA is sufficient buffer space for every known locale, and
740 * POSIX defines no strftime() errors. (Buffer space exhaustion is not an
741 * error.) An implementation might report errors (e.g. ENOMEM) by
742 * returning 0 (or, less plausibly, a negative value) and setting errno.
743 * Report errno just in case the implementation did that, but clear it in
744 * advance of the calls so we don't emit a stale, unrelated errno.
745 */
746 errno = 0;
747
748 /* localized days */
749 for (i = 0; i < 7; i++)
750 {
751 timeinfo->tm_wday = i;
752 if (strftime_l(bufptr, MAX_L10N_DATA, "%a", timeinfo, locale) <= 0)
753 strftimefail = true;
754 bufptr += MAX_L10N_DATA;
755 if (strftime_l(bufptr, MAX_L10N_DATA, "%A", timeinfo, locale) <= 0)
756 strftimefail = true;
757 bufptr += MAX_L10N_DATA;
758 }
759
760 /* localized months */
761 for (i = 0; i < 12; i++)
762 {
763 timeinfo->tm_mon = i;
764 timeinfo->tm_mday = 1; /* make sure we don't have invalid date */
765 if (strftime_l(bufptr, MAX_L10N_DATA, "%b", timeinfo, locale) <= 0)
766 strftimefail = true;
767 bufptr += MAX_L10N_DATA;
768 if (strftime_l(bufptr, MAX_L10N_DATA, "%B", timeinfo, locale) <= 0)
769 strftimefail = true;
770 bufptr += MAX_L10N_DATA;
771 }
772
773#ifdef WIN32
774 _free_locale(locale);
775#else
776 freelocale(locale);
777#endif
778
779 /*
780 * At this point we've done our best to clean up, and can throw errors, or
781 * call functions that might throw errors, with a clean conscience.
782 */
783 if (strftimefail)
784 elog(ERROR, "strftime_l() failed");
785
786#ifndef WIN32
787
788 /*
789 * As in PGLC_localeconv(), we must convert strftime()'s output from the
790 * encoding implied by LC_TIME to the database encoding. If we can't
791 * identify the LC_TIME encoding, just perform encoding validation.
792 */
794 if (encoding < 0)
796
797#else
798
799 /*
800 * On Windows, strftime_win32() always returns UTF8 data, so convert from
801 * that if necessary.
802 */
804
805#endif /* WIN32 */
806
807 bufptr = buf;
808
809 /* localized days */
810 for (i = 0; i < 7; i++)
811 {
813 bufptr += MAX_L10N_DATA;
815 bufptr += MAX_L10N_DATA;
816 }
819
820 /* localized months */
821 for (i = 0; i < 12; i++)
822 {
824 bufptr += MAX_L10N_DATA;
826 bufptr += MAX_L10N_DATA;
827 }
830
831 CurrentLCTimeValid = true;
832}
833
834
835#if defined(WIN32) && defined(LC_MESSAGES)
836/*
837 * Convert a Windows setlocale() argument to a Unix-style one.
838 *
839 * Regardless of platform, we install message catalogs under a Unix-style
840 * LL[_CC][.ENCODING][@VARIANT] naming convention. Only LC_MESSAGES settings
841 * following that style will elicit localized interface strings.
842 *
843 * Before Visual Studio 2012 (msvcr110.dll), Windows setlocale() accepted "C"
844 * (but not "c") and strings of the form <Language>[_<Country>][.<CodePage>],
845 * case-insensitive. setlocale() returns the fully-qualified form; for
846 * example, setlocale("thaI") returns "Thai_Thailand.874". Internally,
847 * setlocale() and _create_locale() select a "locale identifier"[1] and store
848 * it in an undocumented _locale_t field. From that LCID, we can retrieve the
849 * ISO 639 language and the ISO 3166 country. Character encoding does not
850 * matter, because the server and client encodings govern that.
851 *
852 * Windows Vista introduced the "locale name" concept[2], closely following
853 * RFC 4646. Locale identifiers are now deprecated. Starting with Visual
854 * Studio 2012, setlocale() accepts locale names in addition to the strings it
855 * accepted historically. It does not standardize them; setlocale("Th-tH")
856 * returns "Th-tH". setlocale(category, "") still returns a traditional
857 * string. Furthermore, msvcr110.dll changed the undocumented _locale_t
858 * content to carry locale names instead of locale identifiers.
859 *
860 * Visual Studio 2015 should still be able to do the same as Visual Studio
861 * 2012, but the declaration of locale_name is missing in _locale_t, causing
862 * this code compilation to fail, hence this falls back instead on to
863 * enumerating all system locales by using EnumSystemLocalesEx to find the
864 * required locale name. If the input argument is in Unix-style then we can
865 * get ISO Locale name directly by using GetLocaleInfoEx() with LCType as
866 * LOCALE_SNAME.
867 *
868 * This function returns a pointer to a static buffer bearing the converted
869 * name or NULL if conversion fails.
870 *
871 * [1] https://docs.microsoft.com/en-us/windows/win32/intl/locale-identifiers
872 * [2] https://docs.microsoft.com/en-us/windows/win32/intl/locale-names
873 */
874
875/*
876 * Callback function for EnumSystemLocalesEx() in get_iso_localename().
877 *
878 * This function enumerates all system locales, searching for one that matches
879 * an input with the format: <Language>[_<Country>], e.g.
880 * English[_United States]
881 *
882 * The input is a three wchar_t array as an LPARAM. The first element is the
883 * locale_name we want to match, the second element is an allocated buffer
884 * where the Unix-style locale is copied if a match is found, and the third
885 * element is the search status, 1 if a match was found, 0 otherwise.
886 */
887static BOOL CALLBACK
889{
891 wchar_t **argv;
892
893 (void) (dwFlags);
894
895 argv = (wchar_t **) lparam;
896 *argv[2] = (wchar_t) 0;
897
898 memset(test_locale, 0, sizeof(test_locale));
899
900 /* Get the name of the <Language> in English */
903 {
904 /*
905 * If the enumerated locale does not have a hyphen ("en") OR the
906 * locale_name input does not have an underscore ("English"), we only
907 * need to compare the <Language> tags.
908 */
909 if (wcsrchr(pStr, '-') == NULL || wcsrchr(argv[0], '_') == NULL)
910 {
911 if (_wcsicmp(argv[0], test_locale) == 0)
912 {
913 wcscpy(argv[1], pStr);
914 *argv[2] = (wchar_t) 1;
915 return FALSE;
916 }
917 }
918
919 /*
920 * We have to compare a full <Language>_<Country> tag, so we append
921 * the underscore and name of the country/region in English, e.g.
922 * "English_United States".
923 */
924 else
925 {
926 size_t len;
927
928 wcscat(test_locale, L"_");
933 {
934 if (_wcsicmp(argv[0], test_locale) == 0)
935 {
936 wcscpy(argv[1], pStr);
937 *argv[2] = (wchar_t) 1;
938 return FALSE;
939 }
940 }
941 }
942 }
943
944 return TRUE;
945}
946
947/*
948 * This function converts a Windows locale name to an ISO formatted version
949 * for Visual Studio 2015 or greater.
950 *
951 * Returns NULL, if no valid conversion was found.
952 */
953static char *
955{
957 wchar_t buffer[LOCALE_NAME_MAX_LENGTH];
959 const char *period;
960 int len;
961 int ret_val;
962
963 /*
964 * Valid locales have the following syntax:
965 * <Language>[_<Country>[.<CodePage>]]
966 *
967 * GetLocaleInfoEx can only take locale name without code-page and for the
968 * purpose of this API the code-page doesn't matter.
969 */
970 period = strchr(winlocname, '.');
971 if (period != NULL)
973 else
975
977 memset(buffer, 0, sizeof(buffer));
980
981 /*
982 * If the lc_messages is already a Unix-style string, we have a direct
983 * match with LOCALE_SNAME, e.g. en-US, en_US.
984 */
987 if (!ret_val)
988 {
989 /*
990 * Search for a locale in the system that matches language and country
991 * name.
992 */
993 wchar_t *argv[3];
994
995 argv[0] = wc_locale_name;
996 argv[1] = buffer;
997 argv[2] = (wchar_t *) &ret_val;
999 NULL);
1000 }
1001
1002 if (ret_val)
1003 {
1004 size_t rc;
1005 char *hyphen;
1006
1007 /* Locale names use only ASCII, any conversion locale suffices. */
1008 rc = wchar2char(iso_lc_messages, buffer, sizeof(iso_lc_messages), NULL);
1009 if (rc == -1 || rc == sizeof(iso_lc_messages))
1010 return NULL;
1011
1012 /*
1013 * Since the message catalogs sit on a case-insensitive filesystem, we
1014 * need not standardize letter case here. So long as we do not ship
1015 * message catalogs for which it would matter, we also need not
1016 * translate the script/variant portion, e.g. uz-Cyrl-UZ to
1017 * uz_UZ@cyrillic. Simply replace the hyphen with an underscore.
1018 */
1020 if (hyphen)
1021 *hyphen = '_';
1022 return iso_lc_messages;
1023 }
1024
1025 return NULL;
1026}
1027
1028static char *
1029IsoLocaleName(const char *winlocname)
1030{
1032
1033 if (pg_strcasecmp("c", winlocname) == 0 ||
1034 pg_strcasecmp("posix", winlocname) == 0)
1035 {
1036 strcpy(iso_lc_messages, "C");
1037 return iso_lc_messages;
1038 }
1039 else
1041}
1042
1043#endif /* WIN32 && LC_MESSAGES */
1044
1045/*
1046 * Create a new pg_locale_t struct for the given collation oid.
1047 */
1048static pg_locale_t
1050{
1051 HeapTuple tp;
1054 Datum datum;
1055 bool isnull;
1056
1058 if (!HeapTupleIsValid(tp))
1059 elog(ERROR, "cache lookup failed for collation %u", collid);
1061
1062 if (collform->collprovider == COLLPROVIDER_BUILTIN)
1064 else if (collform->collprovider == COLLPROVIDER_ICU)
1066 else if (collform->collprovider == COLLPROVIDER_LIBC)
1068 else
1069 /* shouldn't happen */
1070 PGLOCALE_SUPPORT_ERROR(collform->collprovider);
1071
1072 result->is_default = false;
1073
1074 Assert((result->collate_is_c && result->collate == NULL) ||
1075 (!result->collate_is_c && result->collate != NULL));
1076
1077 Assert((result->ctype_is_c && result->ctype == NULL) ||
1078 (!result->ctype_is_c && result->ctype != NULL));
1079
1081 &isnull);
1082 if (!isnull)
1083 {
1084 char *actual_versionstr;
1085 char *collversionstr;
1086
1088
1089 if (collform->collprovider == COLLPROVIDER_LIBC)
1091 else
1093
1095 TextDatumGetCString(datum));
1096 if (!actual_versionstr)
1097 {
1098 /*
1099 * This could happen when specifying a version in CREATE COLLATION
1100 * but the provider does not support versioning, or manually
1101 * creating a mess in the catalogs.
1102 */
1103 ereport(ERROR,
1104 (errmsg("collation \"%s\" has no actual version, but a version was recorded",
1105 NameStr(collform->collname))));
1106 }
1107
1110 (errmsg("collation \"%s\" has version mismatch",
1111 NameStr(collform->collname)),
1112 errdetail("The collation in the database was created using version %s, "
1113 "but the operating system provides version %s.",
1115 errhint("Rebuild all objects affected by this collation and run "
1116 "ALTER COLLATION %s REFRESH VERSION, "
1117 "or build PostgreSQL with the right library version.",
1119 NameStr(collform->collname)))));
1120 }
1121
1122 ReleaseSysCache(tp);
1123
1124 return result;
1125}
1126
1127/*
1128 * Initialize default_locale with database locale settings.
1129 */
1130void
1132{
1133 HeapTuple tup;
1136
1138
1139 /* Fetch our pg_database row normally, via syscache */
1141 if (!HeapTupleIsValid(tup))
1142 elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
1144
1145 if (dbform->datlocprovider == COLLPROVIDER_BUILTIN)
1148 else if (dbform->datlocprovider == COLLPROVIDER_ICU)
1151 else if (dbform->datlocprovider == COLLPROVIDER_LIBC)
1154 else
1155 /* shouldn't happen */
1156 PGLOCALE_SUPPORT_ERROR(dbform->datlocprovider);
1157
1158 result->is_default = true;
1159
1160 Assert((result->collate_is_c && result->collate == NULL) ||
1161 (!result->collate_is_c && result->collate != NULL));
1162
1163 Assert((result->ctype_is_c && result->ctype == NULL) ||
1164 (!result->ctype_is_c && result->ctype != NULL));
1165
1167
1169}
1170
1171/*
1172 * Get database default locale.
1173 */
1179
1180/*
1181 * Create a pg_locale_t from a collation OID. Results are cached for the
1182 * lifetime of the backend. Thus, do not free the result with freelocale().
1183 *
1184 * For simplicity, we always generate COLLATE + CTYPE even though we
1185 * might only need one of them. Since this is called only once per session,
1186 * it shouldn't cost much.
1187 */
1190{
1192 bool found;
1193
1195 return default_locale;
1196
1197 /*
1198 * Some callers expect C_COLLATION_OID to succeed even without catalog
1199 * access.
1200 */
1201 if (collid == C_COLLATION_OID)
1202 return &c_locale;
1203
1204 if (!OidIsValid(collid))
1205 elog(ERROR, "cache lookup failed for collation %u", collid);
1206
1208
1211
1212 if (CollationCache == NULL)
1213 {
1215 "collation cache",
1218 16, NULL);
1219 }
1220
1222 if (!found)
1223 {
1224 /*
1225 * Make sure cache entry is marked invalid, in case we fail before
1226 * setting things.
1227 */
1228 cache_entry->locale = NULL;
1229 }
1230
1231 if (cache_entry->locale == NULL)
1232 {
1234 }
1235
1238
1239 return cache_entry->locale;
1240}
1241
1242/*
1243 * Get provider-specific collation version string for the given collation from
1244 * the operating system/library.
1245 */
1246char *
1262
1263/* lowercasing/casefolding in C locale */
1264static size_t
1265strlower_c(char *dst, size_t dstsize, const char *src, size_t srclen)
1266{
1267 int i;
1268
1269 for (i = 0; i < srclen && i < dstsize; i++)
1270 dst[i] = pg_ascii_tolower(src[i]);
1271 if (i < dstsize)
1272 dst[i] = '\0';
1273 return srclen;
1274}
1275
1276/* titlecasing in C locale */
1277static size_t
1278strtitle_c(char *dst, size_t dstsize, const char *src, size_t srclen)
1279{
1280 bool wasalnum = false;
1281 int i;
1282
1283 for (i = 0; i < srclen && i < dstsize; i++)
1284 {
1285 char c = src[i];
1286
1287 if (wasalnum)
1288 dst[i] = pg_ascii_tolower(c);
1289 else
1290 dst[i] = pg_ascii_toupper(c);
1291
1292 wasalnum = ((c >= '0' && c <= '9') ||
1293 (c >= 'A' && c <= 'Z') ||
1294 (c >= 'a' && c <= 'z'));
1295 }
1296 if (i < dstsize)
1297 dst[i] = '\0';
1298 return srclen;
1299}
1300
1301/* uppercasing in C locale */
1302static size_t
1303strupper_c(char *dst, size_t dstsize, const char *src, size_t srclen)
1304{
1305 int i;
1306
1307 for (i = 0; i < srclen && i < dstsize; i++)
1308 dst[i] = pg_ascii_toupper(src[i]);
1309 if (i < dstsize)
1310 dst[i] = '\0';
1311 return srclen;
1312}
1313
1314size_t
1315pg_strlower(char *dst, size_t dstsize, const char *src, size_t srclen,
1316 pg_locale_t locale)
1317{
1318 if (locale->ctype == NULL)
1319 return strlower_c(dst, dstsize, src, srclen);
1320 else
1321 return locale->ctype->strlower(dst, dstsize, src, srclen, locale);
1322}
1323
1324size_t
1325pg_strtitle(char *dst, size_t dstsize, const char *src, size_t srclen,
1326 pg_locale_t locale)
1327{
1328 if (locale->ctype == NULL)
1329 return strtitle_c(dst, dstsize, src, srclen);
1330 else
1331 return locale->ctype->strtitle(dst, dstsize, src, srclen, locale);
1332}
1333
1334size_t
1335pg_strupper(char *dst, size_t dstsize, const char *src, size_t srclen,
1336 pg_locale_t locale)
1337{
1338 if (locale->ctype == NULL)
1339 return strupper_c(dst, dstsize, src, srclen);
1340 else
1341 return locale->ctype->strupper(dst, dstsize, src, srclen, locale);
1342}
1343
1344size_t
1345pg_strfold(char *dst, size_t dstsize, const char *src, size_t srclen,
1346 pg_locale_t locale)
1347{
1348 /* in the C locale, casefolding is the same as lowercasing */
1349 if (locale->ctype == NULL)
1350 return strlower_c(dst, dstsize, src, srclen);
1351 else
1352 return locale->ctype->strfold(dst, dstsize, src, srclen, locale);
1353}
1354
1355/*
1356 * Lowercase an identifier using the database default locale.
1357 *
1358 * For historical reasons, does not use ordinary locale behavior. Should only
1359 * be used for identifiers. XXX: can we make this equivalent to
1360 * pg_strfold(..., default_locale)?
1361 */
1362size_t
1363pg_downcase_ident(char *dst, size_t dstsize, const char *src, size_t srclen)
1364{
1365 pg_locale_t locale = default_locale;
1366
1367 if (locale == NULL || locale->ctype == NULL ||
1368 locale->ctype->downcase_ident == NULL)
1369 return strlower_c(dst, dstsize, src, srclen);
1370 else
1371 return locale->ctype->downcase_ident(dst, dstsize, src, srclen,
1372 locale);
1373}
1374
1375/*
1376 * pg_strcoll
1377 *
1378 * Like pg_strncoll for NUL-terminated input strings.
1379 */
1380int
1381pg_strcoll(const char *arg1, const char *arg2, pg_locale_t locale)
1382{
1383 return locale->collate->strcoll(arg1, arg2, locale);
1384}
1385
1386/*
1387 * pg_strncoll
1388 *
1389 * Call ucol_strcollUTF8(), ucol_strcoll(), strcoll_l() or wcscoll_l() as
1390 * appropriate for the given locale, platform, and database encoding. If the
1391 * locale is not specified, use the database collation.
1392 *
1393 * The input strings must be encoded in the database encoding.
1394 *
1395 * The caller is responsible for breaking ties if the collation is
1396 * deterministic; this maintains consistency with pg_strnxfrm(), which cannot
1397 * easily account for deterministic collations.
1398 */
1399int
1400pg_strncoll(const char *arg1, size_t len1, const char *arg2, size_t len2,
1401 pg_locale_t locale)
1402{
1403 return locale->collate->strncoll(arg1, len1, arg2, len2, locale);
1404}
1405
1406/*
1407 * Return true if the collation provider supports pg_strxfrm() and
1408 * pg_strnxfrm(); otherwise false.
1409 *
1410 *
1411 * No similar problem is known for the ICU provider.
1412 */
1413bool
1415{
1416 /*
1417 * locale->collate->strnxfrm is still a required method, even if it may
1418 * have the wrong behavior, because the planner uses it for estimates in
1419 * some cases.
1420 */
1421 return locale->collate->strxfrm_is_safe;
1422}
1423
1424/*
1425 * pg_strxfrm
1426 *
1427 * Like pg_strnxfrm for a NUL-terminated input string.
1428 */
1429size_t
1430pg_strxfrm(char *dest, const char *src, size_t destsize, pg_locale_t locale)
1431{
1432 return locale->collate->strxfrm(dest, destsize, src, locale);
1433}
1434
1435/*
1436 * pg_strnxfrm
1437 *
1438 * Transforms 'src' to a nul-terminated string stored in 'dest' such that
1439 * ordinary strcmp() on transformed strings is equivalent to pg_strcoll() on
1440 * untransformed strings.
1441 *
1442 * The input string must be encoded in the database encoding. If 'destsize' is
1443 * zero, 'dest' may be NULL.
1444 *
1445 * Not all providers support pg_strnxfrm() safely. The caller should check
1446 * pg_strxfrm_enabled() first, otherwise this function may return wrong
1447 * results or an error.
1448 *
1449 * Returns the number of bytes needed (or more) to store the transformed
1450 * string, excluding the terminating nul byte. If the value returned is
1451 * 'destsize' or greater, the resulting contents of 'dest' are undefined.
1452 */
1453size_t
1454pg_strnxfrm(char *dest, size_t destsize, const char *src, size_t srclen,
1455 pg_locale_t locale)
1456{
1457 return locale->collate->strnxfrm(dest, destsize, src, srclen, locale);
1458}
1459
1460/*
1461 * Return true if the collation provider supports pg_strxfrm_prefix() and
1462 * pg_strnxfrm_prefix(); otherwise false.
1463 */
1464bool
1466{
1467 return (locale->collate->strnxfrm_prefix != NULL);
1468}
1469
1470/*
1471 * pg_strxfrm_prefix
1472 *
1473 * Like pg_strnxfrm_prefix for a NUL-terminated input string.
1474 */
1475size_t
1476pg_strxfrm_prefix(char *dest, const char *src, size_t destsize,
1477 pg_locale_t locale)
1478{
1479 return locale->collate->strxfrm_prefix(dest, destsize, src, locale);
1480}
1481
1482/*
1483 * pg_strnxfrm_prefix
1484 *
1485 * Transforms 'src' to a byte sequence stored in 'dest' such that ordinary
1486 * memcmp() on the byte sequence is equivalent to pg_strncoll() on
1487 * untransformed strings. The result is not nul-terminated.
1488 *
1489 * The input string must be encoded in the database encoding.
1490 *
1491 * Not all providers support pg_strnxfrm_prefix() safely. The caller should
1492 * check pg_strxfrm_prefix_enabled() first, otherwise this function may return
1493 * wrong results or an error.
1494 *
1495 * If destsize is not large enough to hold the resulting byte sequence, stores
1496 * only the first destsize bytes in 'dest'. Returns the number of bytes
1497 * actually copied to 'dest'.
1498 */
1499size_t
1500pg_strnxfrm_prefix(char *dest, size_t destsize, const char *src,
1501 size_t srclen, pg_locale_t locale)
1502{
1503 return locale->collate->strnxfrm_prefix(dest, destsize, src, srclen, locale);
1504}
1505
1506bool
1508{
1509 if (locale->ctype == NULL)
1510 return (wc <= (pg_wchar) 127 &&
1512 else
1513 return locale->ctype->wc_isdigit(wc, locale);
1514}
1515
1516bool
1518{
1519 if (locale->ctype == NULL)
1520 return (wc <= (pg_wchar) 127 &&
1522 else
1523 return locale->ctype->wc_isalpha(wc, locale);
1524}
1525
1526bool
1528{
1529 if (locale->ctype == NULL)
1530 return (wc <= (pg_wchar) 127 &&
1532 else
1533 return locale->ctype->wc_isalnum(wc, locale);
1534}
1535
1536bool
1538{
1539 if (locale->ctype == NULL)
1540 return (wc <= (pg_wchar) 127 &&
1542 else
1543 return locale->ctype->wc_isupper(wc, locale);
1544}
1545
1546bool
1548{
1549 if (locale->ctype == NULL)
1550 return (wc <= (pg_wchar) 127 &&
1552 else
1553 return locale->ctype->wc_islower(wc, locale);
1554}
1555
1556bool
1558{
1559 if (locale->ctype == NULL)
1560 return (wc <= (pg_wchar) 127 &&
1562 else
1563 return locale->ctype->wc_isgraph(wc, locale);
1564}
1565
1566bool
1568{
1569 if (locale->ctype == NULL)
1570 return (wc <= (pg_wchar) 127 &&
1572 else
1573 return locale->ctype->wc_isprint(wc, locale);
1574}
1575
1576bool
1578{
1579 if (locale->ctype == NULL)
1580 return (wc <= (pg_wchar) 127 &&
1582 else
1583 return locale->ctype->wc_ispunct(wc, locale);
1584}
1585
1586bool
1588{
1589 if (locale->ctype == NULL)
1590 return (wc <= (pg_wchar) 127 &&
1592 else
1593 return locale->ctype->wc_isspace(wc, locale);
1594}
1595
1596bool
1598{
1599 if (locale->ctype == NULL)
1600 return (wc <= (pg_wchar) 127 &&
1601 ((pg_char_properties[wc] & PG_ISDIGIT) ||
1602 ((wc >= 'A' && wc <= 'F') ||
1603 (wc >= 'a' && wc <= 'f'))));
1604 else
1605 return locale->ctype->wc_isxdigit(wc, locale);
1606}
1607
1608bool
1610{
1611 /* for the C locale, Cased and Alpha are equivalent */
1612 if (locale->ctype == NULL)
1613 return (wc <= (pg_wchar) 127 &&
1615 else
1616 return locale->ctype->wc_iscased(wc, locale);
1617}
1618
1621{
1622 if (locale->ctype == NULL)
1623 {
1624 if (wc <= (pg_wchar) 127)
1625 return pg_ascii_toupper((unsigned char) wc);
1626 return wc;
1627 }
1628 else
1629 return locale->ctype->wc_toupper(wc, locale);
1630}
1631
1634{
1635 if (locale->ctype == NULL)
1636 {
1637 if (wc <= (pg_wchar) 127)
1638 return pg_ascii_tolower((unsigned char) wc);
1639 return wc;
1640 }
1641 else
1642 return locale->ctype->wc_tolower(wc, locale);
1643}
1644
1645/* version of Unicode used by ICU */
1646const char *
1648{
1649#ifdef USE_ICU
1650 return U_UNICODE_VERSION;
1651#else
1652 return NULL;
1653#endif
1654}
1655
1656/*
1657 * Return required encoding ID for the given locale, or -1 if any encoding is
1658 * valid for the locale.
1659 */
1660int
1661builtin_locale_encoding(const char *locale)
1662{
1663 if (strcmp(locale, "C") == 0)
1664 return -1;
1665 else if (strcmp(locale, "C.UTF-8") == 0)
1666 return PG_UTF8;
1667 else if (strcmp(locale, "PG_UNICODE_FAST") == 0)
1668 return PG_UTF8;
1669
1670
1671 ereport(ERROR,
1673 errmsg("invalid locale name \"%s\" for builtin provider",
1674 locale)));
1675
1676 return 0; /* keep compiler quiet */
1677}
1678
1679
1680/*
1681 * Validate the locale and encoding combination, and return the canonical form
1682 * of the locale name.
1683 */
1684const char *
1685builtin_validate_locale(int encoding, const char *locale)
1686{
1687 const char *canonical_name = NULL;
1689
1690 if (strcmp(locale, "C") == 0)
1691 canonical_name = "C";
1692 else if (strcmp(locale, "C.UTF-8") == 0 || strcmp(locale, "C.UTF8") == 0)
1693 canonical_name = "C.UTF-8";
1694 else if (strcmp(locale, "PG_UNICODE_FAST") == 0)
1695 canonical_name = "PG_UNICODE_FAST";
1696
1697 if (!canonical_name)
1698 ereport(ERROR,
1700 errmsg("invalid locale name \"%s\" for builtin provider",
1701 locale)));
1702
1705 ereport(ERROR,
1707 errmsg("encoding \"%s\" does not match locale \"%s\"",
1708 pg_encoding_to_char(encoding), locale)));
1709
1710 return canonical_name;
1711}
1712
1713
1714
1715/*
1716 * Return the BCP47 language tag representation of the requested locale.
1717 *
1718 * This function should be called before passing the string to ucol_open(),
1719 * because conversion to a language tag also performs "level 2
1720 * canonicalization". In addition to producing a consistent format, level 2
1721 * canonicalization is able to more accurately interpret different input
1722 * locale string formats, such as POSIX and .NET IDs.
1723 */
1724char *
1725icu_language_tag(const char *loc_str, int elevel)
1726{
1727#ifdef USE_ICU
1728 UErrorCode status;
1729 char *langtag;
1730 size_t buflen = 32; /* arbitrary starting buffer size */
1731 const bool strict = true;
1732
1733 /*
1734 * A BCP47 language tag doesn't have a clearly-defined upper limit (cf.
1735 * RFC5646 section 4.4). Additionally, in older ICU versions,
1736 * uloc_toLanguageTag() doesn't always return the ultimate length on the
1737 * first call, necessitating a loop.
1738 */
1739 langtag = palloc(buflen);
1740 while (true)
1741 {
1742 status = U_ZERO_ERROR;
1743 uloc_toLanguageTag(loc_str, langtag, buflen, strict, &status);
1744
1745 /* try again if the buffer is not large enough */
1746 if ((status == U_BUFFER_OVERFLOW_ERROR ||
1748 buflen < MaxAllocSize)
1749 {
1750 buflen = Min(buflen * 2, MaxAllocSize);
1751 langtag = repalloc(langtag, buflen);
1752 continue;
1753 }
1754
1755 break;
1756 }
1757
1758 if (U_FAILURE(status))
1759 {
1760 pfree(langtag);
1761
1762 if (elevel > 0)
1763 ereport(elevel,
1765 errmsg("could not convert locale name \"%s\" to language tag: %s",
1766 loc_str, u_errorName(status))));
1767 return NULL;
1768 }
1769
1770 return langtag;
1771#else /* not USE_ICU */
1772 ereport(ERROR,
1774 errmsg("ICU is not supported in this build")));
1775 return NULL; /* keep compiler quiet */
1776#endif /* not USE_ICU */
1777}
1778
1779/*
1780 * Perform best-effort check that the locale is a valid one.
1781 */
1782void
1784{
1785#ifdef USE_ICU
1787 UErrorCode status;
1788 char lang[ULOC_LANG_CAPACITY];
1789 bool found = false;
1790 int elevel = icu_validation_level;
1791
1792 /* no validation */
1793 if (elevel < 0)
1794 return;
1795
1796 /* downgrade to WARNING during pg_upgrade */
1797 if (IsBinaryUpgrade && elevel > WARNING)
1798 elevel = WARNING;
1799
1800 /* validate that we can extract the language */
1801 status = U_ZERO_ERROR;
1803 if (U_FAILURE(status) || status == U_STRING_NOT_TERMINATED_WARNING)
1804 {
1805 ereport(elevel,
1807 errmsg("could not get language from ICU locale \"%s\": %s",
1808 loc_str, u_errorName(status)),
1809 errhint("To disable ICU locale validation, set the parameter \"%s\" to \"%s\".",
1810 "icu_validation_level", "disabled")));
1811 return;
1812 }
1813
1814 /* check for special language name */
1815 if (strcmp(lang, "") == 0 ||
1816 strcmp(lang, "root") == 0 || strcmp(lang, "und") == 0)
1817 found = true;
1818
1819 /* search for matching language within ICU */
1820 for (int32_t i = 0; !found && i < uloc_countAvailable(); i++)
1821 {
1822 const char *otherloc = uloc_getAvailable(i);
1824
1825 status = U_ZERO_ERROR;
1827 if (U_FAILURE(status) || status == U_STRING_NOT_TERMINATED_WARNING)
1828 continue;
1829
1830 if (strcmp(lang, otherlang) == 0)
1831 found = true;
1832 }
1833
1834 if (!found)
1835 ereport(elevel,
1837 errmsg("ICU locale \"%s\" has unknown language \"%s\"",
1838 loc_str, lang),
1839 errhint("To disable ICU locale validation, set the parameter \"%s\" to \"%s\".",
1840 "icu_validation_level", "disabled")));
1841
1842 /* check that it can be opened */
1845#else /* not USE_ICU */
1846 /* could get here if a collation was created by a build with ICU */
1847 ereport(ERROR,
1849 errmsg("ICU is not supported in this build")));
1850#endif /* not USE_ICU */
1851}
#define TextDatumGetCString(d)
Definition builtins.h:99
#define NameStr(name)
Definition c.h:835
#define Min(x, y)
Definition c.h:1091
#define Assert(condition)
Definition c.h:943
uint32_t uint32
Definition c.h:624
#define lengthof(array)
Definition c.h:873
#define OidIsValid(objectId)
Definition c.h:858
uint32 result
Oid collid
int errcode(int sqlerrcode)
Definition elog.c:875
#define PG_RE_THROW()
Definition elog.h:407
int errhint(const char *fmt,...) pg_attribute_printf(1
#define DEBUG3
Definition elog.h:29
int errdetail(const char *fmt,...) pg_attribute_printf(1
#define FATAL
Definition elog.h:42
#define PG_TRY(...)
Definition elog.h:374
#define WARNING
Definition elog.h:37
#define PG_END_TRY(...)
Definition elog.h:399
#define ERROR
Definition elog.h:40
#define PG_CATCH(...)
Definition elog.h:384
#define elog(elevel,...)
Definition elog.h:228
#define ereport(elevel,...)
Definition elog.h:152
#define MaxAllocSize
Definition fe_memutils.h:22
bool IsBinaryUpgrade
Definition globals.c:123
Oid MyDatabaseId
Definition globals.c:96
#define newval
GucSource
Definition guc.h:112
@ PGC_S_DEFAULT
Definition guc.h:113
const char * str
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
#define period
static char * encoding
Definition initdb.c:139
int i
Definition isn.c:77
static struct pg_tm tm
Definition localtime.c:104
char * get_namespace_name(Oid nspid)
Definition lsyscache.c:3599
#define PG_UTF8
Definition mbprint.c:43
unsigned int pg_wchar
Definition mbprint.c:31
int GetDatabaseEncoding(void)
Definition mbutils.c:1389
char * pg_any_to_server(const char *s, int len, int encoding)
Definition mbutils.c:687
int pg_mbstrlen(const char *mbstr)
Definition mbutils.c:1165
void SetMessageEncoding(int encoding)
Definition mbutils.c:1300
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition mcxt.c:1897
char * pstrdup(const char *in)
Definition mcxt.c:1910
void * repalloc(void *pointer, Size size)
Definition mcxt.c:1635
void pfree(void *pointer)
Definition mcxt.c:1619
MemoryContext TopMemoryContext
Definition mcxt.c:167
void * palloc(Size size)
Definition mcxt.c:1390
#define AllocSetContextCreate
Definition memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition memutils.h:160
static char * errmsg
static char format
END_CATALOG_STRUCT typedef FormData_pg_collation * Form_pg_collation
const void size_t len
END_CATALOG_STRUCT typedef FormData_pg_database * Form_pg_database
size_t pg_strfold(char *dst, size_t dstsize, const char *src, size_t srclen, pg_locale_t locale)
Definition pg_locale.c:1345
size_t pg_strnxfrm(char *dest, size_t destsize, const char *src, size_t srclen, pg_locale_t locale)
Definition pg_locale.c:1454
const char * pg_icu_unicode_version(void)
Definition pg_locale.c:1647
int icu_validation_level
Definition pg_locale.c:92
static pg_locale_t last_collation_cache_locale
Definition pg_locale.c:151
void cache_locale_time(void)
Definition pg_locale.c:702
bool pg_strxfrm_enabled(pg_locale_t locale)
Definition pg_locale.c:1414
char * localized_full_months[12+1]
Definition pg_locale.c:104
int pg_strncoll(const char *arg1, size_t len1, const char *arg2, size_t len2, pg_locale_t locale)
Definition pg_locale.c:1400
pg_wchar pg_towlower(pg_wchar wc, pg_locale_t locale)
Definition pg_locale.c:1633
bool pg_iswalnum(pg_wchar wc, pg_locale_t locale)
Definition pg_locale.c:1527
void icu_validate_locale(const char *loc_str)
Definition pg_locale.c:1783
bool pg_iswcased(pg_wchar wc, pg_locale_t locale)
Definition pg_locale.c:1609
pg_locale_t create_pg_locale_libc(Oid collid, MemoryContext context)
static bool CurrentLCTimeValid
Definition pg_locale.c:110
void assign_locale_time(const char *newval, void *extra)
Definition pg_locale.c:370
char * get_collation_actual_version(char collprovider, const char *collcollate)
Definition pg_locale.c:1247
pg_locale_t create_pg_locale_builtin(Oid collid, MemoryContext context)
bool check_locale_time(char **newval, void **extra, GucSource source)
Definition pg_locale.c:364
char * locale_messages
Definition pg_locale.c:87
size_t pg_strlower(char *dst, size_t dstsize, const char *src, size_t srclen, pg_locale_t locale)
Definition pg_locale.c:1315
bool pg_iswgraph(pg_wchar wc, pg_locale_t locale)
Definition pg_locale.c:1557
bool pg_iswprint(pg_wchar wc, pg_locale_t locale)
Definition pg_locale.c:1567
char * locale_numeric
Definition pg_locale.c:89
pg_locale_t pg_newlocale_from_collation(Oid collid)
Definition pg_locale.c:1189
size_t pg_strtitle(char *dst, size_t dstsize, const char *src, size_t srclen, pg_locale_t locale)
Definition pg_locale.c:1325
bool pg_iswdigit(pg_wchar wc, pg_locale_t locale)
Definition pg_locale.c:1507
bool pg_iswupper(pg_wchar wc, pg_locale_t locale)
Definition pg_locale.c:1537
int builtin_locale_encoding(const char *locale)
Definition pg_locale.c:1661
static struct pg_locale_struct c_locale
Definition pg_locale.c:112
bool pg_iswxdigit(pg_wchar wc, pg_locale_t locale)
Definition pg_locale.c:1597
char * pg_perm_setlocale(int category, const char *locale)
Definition pg_locale.c:172
#define PGLOCALE_SUPPORT_ERROR(provider)
Definition pg_locale.c:60
static pg_locale_t create_pg_locale(Oid collid, MemoryContext context)
Definition pg_locale.c:1049
char * locale_time
Definition pg_locale.c:90
size_t pg_downcase_ident(char *dst, size_t dstsize, const char *src, size_t srclen)
Definition pg_locale.c:1363
static void cache_single_string(char **dst, const char *src, int encoding)
Definition pg_locale.c:679
static size_t strupper_c(char *dst, size_t dstsize, const char *src, size_t srclen)
Definition pg_locale.c:1303
char * get_collation_actual_version_libc(const char *collcollate)
pg_wchar pg_towupper(pg_wchar wc, pg_locale_t locale)
Definition pg_locale.c:1620
bool check_locale_numeric(char **newval, void **extra, GucSource source)
Definition pg_locale.c:352
pg_locale_t pg_database_locale(void)
Definition pg_locale.c:1175
bool pg_iswspace(pg_wchar wc, pg_locale_t locale)
Definition pg_locale.c:1587
static void db_encoding_convert(int encoding, char **str)
Definition pg_locale.c:476
void assign_locale_numeric(const char *newval, void *extra)
Definition pg_locale.c:358
bool check_locale_messages(char **newval, void **extra, GucSource source)
Definition pg_locale.c:386
#define MAX_L10N_DATA
Definition pg_locale.c:69
size_t pg_strupper(char *dst, size_t dstsize, const char *src, size_t srclen, pg_locale_t locale)
Definition pg_locale.c:1335
char * get_collation_actual_version_builtin(const char *collcollate)
static void free_struct_lconv(struct lconv *s)
Definition pg_locale.c:426
static MemoryContext CollationCacheContext
Definition pg_locale.c:143
void assign_locale_messages(const char *newval, void *extra)
Definition pg_locale.c:409
static bool CurrentLocaleConvValid
Definition pg_locale.c:109
static size_t strtitle_c(char *dst, size_t dstsize, const char *src, size_t srclen)
Definition pg_locale.c:1278
static size_t strlower_c(char *dst, size_t dstsize, const char *src, size_t srclen)
Definition pg_locale.c:1265
struct lconv * PGLC_localeconv(void)
Definition pg_locale.c:506
pg_locale_t create_pg_locale_icu(Oid collid, MemoryContext context)
int pg_strcoll(const char *arg1, const char *arg2, pg_locale_t locale)
Definition pg_locale.c:1381
bool pg_iswpunct(pg_wchar wc, pg_locale_t locale)
Definition pg_locale.c:1577
bool pg_strxfrm_prefix_enabled(pg_locale_t locale)
Definition pg_locale.c:1465
char * icu_language_tag(const char *loc_str, int elevel)
Definition pg_locale.c:1725
char * localized_abbrev_months[12+1]
Definition pg_locale.c:103
static pg_locale_t default_locale
Definition pg_locale.c:106
static collation_cache_hash * CollationCache
Definition pg_locale.c:144
size_t pg_strnxfrm_prefix(char *dest, size_t destsize, const char *src, size_t srclen, pg_locale_t locale)
Definition pg_locale.c:1500
bool pg_iswlower(pg_wchar wc, pg_locale_t locale)
Definition pg_locale.c:1547
static bool struct_lconv_is_valid(struct lconv *s)
Definition pg_locale.c:445
void init_database_collation(void)
Definition pg_locale.c:1131
char * localized_full_days[7+1]
Definition pg_locale.c:102
size_t pg_strxfrm(char *dest, const char *src, size_t destsize, pg_locale_t locale)
Definition pg_locale.c:1430
const char * builtin_validate_locale(int encoding, const char *locale)
Definition pg_locale.c:1685
bool pg_iswalpha(pg_wchar wc, pg_locale_t locale)
Definition pg_locale.c:1517
void assign_locale_monetary(const char *newval, void *extra)
Definition pg_locale.c:346
bool check_locale(int category, const char *locale, char **canonname)
Definition pg_locale.c:275
char * localized_abbrev_days[7+1]
Definition pg_locale.c:101
size_t pg_strxfrm_prefix(char *dest, const char *src, size_t destsize, pg_locale_t locale)
Definition pg_locale.c:1476
char * locale_monetary
Definition pg_locale.c:88
bool check_locale_monetary(char **newval, void **extra, GucSource source)
Definition pg_locale.c:340
static Oid last_collation_cache_oid
Definition pg_locale.c:150
#define LOCALE_NAME_BUFLEN
Definition pg_locale.h:18
#define PG_ISLOWER
Definition pg_locale_c.h:23
#define PG_ISPRINT
Definition pg_locale_c.h:25
#define PG_ISALPHA
Definition pg_locale_c.h:20
#define PG_ISGRAPH
Definition pg_locale_c.h:24
#define PG_ISPUNCT
Definition pg_locale_c.h:26
#define PG_ISDIGIT
Definition pg_locale_c.h:19
#define PG_ISUPPER
Definition pg_locale_c.h:22
#define PG_ISALNUM
Definition pg_locale_c.h:21
#define PG_ISSPACE
Definition pg_locale_c.h:27
static const unsigned char pg_char_properties[128]
Definition pg_locale_c.h:29
size_t wchar2char(char *to, const wchar_t *from, size_t tolen, locale_t loc)
void report_newlocale_failure(const char *localename)
static rewind_source * source
Definition pg_rewind.c:89
static char buf[DEFAULT_XLOG_SEG_SIZE]
@ PG_SQL_ASCII
Definition pg_wchar.h:76
#define pg_encoding_to_char
Definition pg_wchar.h:483
int pg_strcasecmp(const char *s1, const char *s2)
int pg_localeconv_r(const char *lc_monetary, const char *lc_numeric, struct lconv *output)
static unsigned char pg_ascii_tolower(unsigned char ch)
Definition port.h:189
static unsigned char pg_ascii_toupper(unsigned char ch)
Definition port.h:178
int pg_get_encoding_from_locale(const char *ctype, bool write_message)
Definition chklocale.c:301
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition strlcpy.c:45
void pg_localeconv_free(struct lconv *lconv)
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:252
uint64_t Datum
Definition postgres.h:70
#define InvalidOid
unsigned int Oid
char * c
static int fb(int x)
static void AssertCouldGetRelation(void)
Definition relcache.h:44
char * quote_qualified_identifier(const char *qualifier, const char *ident)
#define free(a)
bool pg_is_ascii(const char *str)
Definition string.c:132
size_t(* strnxfrm)(char *dest, size_t destsize, const char *src, size_t srclen, pg_locale_t locale)
Definition pg_locale.h:74
size_t(* strxfrm)(char *dest, size_t destsize, const char *src, pg_locale_t locale)
Definition pg_locale.h:78
size_t(* strxfrm_prefix)(char *dest, size_t destsize, const char *src, pg_locale_t locale)
Definition pg_locale.h:86
size_t(* strnxfrm_prefix)(char *dest, size_t destsize, const char *src, size_t srclen, pg_locale_t locale)
Definition pg_locale.h:82
int(* strncoll)(const char *arg1, size_t len1, const char *arg2, size_t len2, pg_locale_t locale)
Definition pg_locale.h:66
int(* strcoll)(const char *arg1, const char *arg2, pg_locale_t locale)
Definition pg_locale.h:70
bool strxfrm_is_safe
Definition pg_locale.h:95
Definition pg_locale.c:121
char status
Definition pg_locale.c:127
Oid collid
Definition pg_locale.c:122
pg_locale_t locale
Definition pg_locale.c:123
uint32 hash
Definition pg_locale.c:126
size_t(* strfold)(char *dest, size_t destsize, const char *src, size_t srclen, pg_locale_t locale)
Definition pg_locale.h:110
size_t(* downcase_ident)(char *dest, size_t destsize, const char *src, size_t srclen, pg_locale_t locale)
Definition pg_locale.h:113
pg_wchar(* wc_toupper)(pg_wchar wc, pg_locale_t locale)
Definition pg_locale.h:129
bool(* wc_isxdigit)(pg_wchar wc, pg_locale_t locale)
Definition pg_locale.h:127
bool(* wc_ispunct)(pg_wchar wc, pg_locale_t locale)
Definition pg_locale.h:125
bool(* wc_isprint)(pg_wchar wc, pg_locale_t locale)
Definition pg_locale.h:124
size_t(* strlower)(char *dest, size_t destsize, const char *src, size_t srclen, pg_locale_t locale)
Definition pg_locale.h:101
bool(* wc_isalpha)(pg_wchar wc, pg_locale_t locale)
Definition pg_locale.h:119
pg_wchar(* wc_tolower)(pg_wchar wc, pg_locale_t locale)
Definition pg_locale.h:130
size_t(* strtitle)(char *dest, size_t destsize, const char *src, size_t srclen, pg_locale_t locale)
Definition pg_locale.h:104
bool(* wc_isupper)(pg_wchar wc, pg_locale_t locale)
Definition pg_locale.h:121
bool(* wc_isspace)(pg_wchar wc, pg_locale_t locale)
Definition pg_locale.h:126
bool(* wc_isgraph)(pg_wchar wc, pg_locale_t locale)
Definition pg_locale.h:123
bool(* wc_islower)(pg_wchar wc, pg_locale_t locale)
Definition pg_locale.h:122
size_t(* strupper)(char *dest, size_t destsize, const char *src, size_t srclen, pg_locale_t locale)
Definition pg_locale.h:107
bool(* wc_isalnum)(pg_wchar wc, pg_locale_t locale)
Definition pg_locale.h:120
bool(* wc_isdigit)(pg_wchar wc, pg_locale_t locale)
Definition pg_locale.h:118
bool(* wc_iscased)(pg_wchar wc, pg_locale_t locale)
Definition pg_locale.h:128
const struct ctype_methods * ctype
Definition pg_locale.h:155
const struct collate_methods * collate
Definition pg_locale.h:154
const char * locale
Definition pg_locale.h:161
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:265
Datum SysCacheGetAttrNotNull(SysCacheIdentifier cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition syscache.c:626
HeapTuple SearchSysCache1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:221
Datum SysCacheGetAttr(SysCacheIdentifier cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition syscache.c:596
#define locale_t
Definition win32_port.h:429
void _dosmaperr(unsigned long)
Definition win32error.c:177
#define setenv(x, y, z)
Definition win32_port.h:542
#define setlocale(a, b)
Definition win32_port.h:472