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