Debian Codegraph @

src/main/org/h2/expression/function/ToCharFunction.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: Daniel Gredler
5 */
6 package org.h2.expression.function;
7
8 import java.math.BigDecimal;
9 import java.math.RoundingMode;
10 import java.text.DateFormatSymbols;
11 import java.text.DecimalFormat;
12 import java.text.DecimalFormatSymbols;
13 import java.text.SimpleDateFormat;
14 import java.util.Arrays;
15 import java.util.Currency;
16 import java.util.Locale;
17
18 import org.h2.api.ErrorCode;
19 import org.h2.engine.SessionLocal;
20 import org.h2.expression.Expression;
21 import org.h2.expression.TypedValueExpression;
22 import org.h2.message.DbException;
23 import org.h2.util.DateTimeUtils;
24 import org.h2.util.StringUtils;
25 import org.h2.util.TimeZoneProvider;
26 import org.h2.value.TypeInfo;
27 import org.h2.value.Value;
28 import org.h2.value.ValueTimeTimeZone;
29 import org.h2.value.ValueTimestamp;
30 import org.h2.value.ValueTimestampTimeZone;
31 import org.h2.value.ValueVarchar;
32
33 /**
34 * Emulates Oracle's TO_CHAR function.
35 */
36 public final class ToCharFunction extends FunctionN {
37
38 /**
39 * The beginning of the Julian calendar.
40 */
41 public static final int JULIAN_EPOCH = -2_440_588;
42
43 private static final int[] ROMAN_VALUES = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9,
44 5, 4, 1 };
45
46 private static final String[] ROMAN_NUMERALS = { "M", "CM", "D", "CD", "C", "XC",
47 "L", "XL", "X", "IX", "V", "IV", "I" };
48
49 /**
50 * The month field.
51 */
52 public static final int MONTHS = 0;
53
54 /**
55 * The month field (short form).
56 */
57 public static final int SHORT_MONTHS = 1;
58
59 /**
60 * The weekday field.
61 */
62 public static final int WEEKDAYS = 2;
63
64 /**
65 * The weekday field (short form).
66 */
67 public static final int SHORT_WEEKDAYS = 3;
68
69 /**
70 * The AM / PM field.
71 */
72 static final int AM_PM = 4;
73
74 private static volatile String[][] NAMES;
75
76 /**
77 * Emulates Oracle's TO_CHAR(number) function.
78 *
79 * <table border="1">
80 * <caption>TO_CHAR(number) function</caption>
81 * <tr><th>Input</th>
82 * <th>Output</th>
83 * <th>Closest {@link DecimalFormat} Equivalent</th></tr>
84 * <tr><td>,</td>
85 * <td>Grouping separator.</td>
86 * <td>,</td></tr>
87 * <tr><td>.</td>
88 * <td>Decimal separator.</td>
89 * <td>.</td></tr>
90 * <tr><td>$</td>
91 * <td>Leading dollar sign.</td>
92 * <td>$</td></tr>
93 * <tr><td>0</td>
94 * <td>Leading or trailing zeroes.</td>
95 * <td>0</td></tr>
96 * <tr><td>9</td>
97 * <td>Digit.</td>
98 * <td>#</td></tr>
99 * <tr><td>B</td>
100 * <td>Blanks integer part of a fixed point number less than 1.</td>
101 * <td>#</td></tr>
102 * <tr><td>C</td>
103 * <td>ISO currency symbol.</td>
104 * <td>\u00A4</td></tr>
105 * <tr><td>D</td>
106 * <td>Local decimal separator.</td>
107 * <td>.</td></tr>
108 * <tr><td>EEEE</td>
109 * <td>Returns a value in scientific notation.</td>
110 * <td>E</td></tr>
111 * <tr><td>FM</td>
112 * <td>Returns values with no leading or trailing spaces.</td>
113 * <td>None.</td></tr>
114 * <tr><td>G</td>
115 * <td>Local grouping separator.</td>
116 * <td>,</td></tr>
117 * <tr><td>L</td>
118 * <td>Local currency symbol.</td>
119 * <td>\u00A4</td></tr>
120 * <tr><td>MI</td>
121 * <td>Negative values get trailing minus sign,
122 * positive get trailing space.</td>
123 * <td>-</td></tr>
124 * <tr><td>PR</td>
125 * <td>Negative values get enclosing angle brackets,
126 * positive get spaces.</td>
127 * <td>None.</td></tr>
128 * <tr><td>RN</td>
129 * <td>Returns values in Roman numerals.</td>
130 * <td>None.</td></tr>
131 * <tr><td>S</td>
132 * <td>Returns values with leading/trailing +/- signs.</td>
133 * <td>None.</td></tr>
134 * <tr><td>TM</td>
135 * <td>Returns smallest number of characters possible.</td>
136 * <td>None.</td></tr>
137 * <tr><td>U</td>
138 * <td>Returns the dual currency symbol.</td>
139 * <td>None.</td></tr>
140 * <tr><td>V</td>
141 * <td>Returns a value multiplied by 10^n.</td>
142 * <td>None.</td></tr>
143 * <tr><td>X</td>
144 * <td>Hex value.</td>
145 * <td>None.</td></tr>
146 * </table>
147 * See also TO_CHAR(number) and number format models
148 * in the Oracle documentation.
149 *
150 * @param number the number to format
151 * @param format the format pattern to use (if any)
152 * @param nlsParam the NLS parameter (if any)
153 * @return the formatted number
154 */
155 public static String toChar(BigDecimal number, String format,
156 @SuppressWarnings("unused") String nlsParam) {
157
158 // short-circuit logic for formats that don't follow common logic below
159 String formatUp = format != null ? StringUtils.toUpperEnglish(format) : null;
160 if (formatUp == null || formatUp.equals("TM") || formatUp.equals("TM9")) {
161 String s = number.toPlainString();
162 return s.startsWith("0.") ? s.substring(1) : s;
163 } else if (formatUp.equals("TME")) {
164 int pow = number.precision() - number.scale() - 1;
165 number = number.movePointLeft(pow);
166 return number.toPlainString() + "E" +
167 (pow < 0 ? '-' : '+') + (Math.abs(pow) < 10 ? "0" : "") + Math.abs(pow);
168 } else if (formatUp.equals("RN")) {
169 boolean lowercase = format.startsWith("r");
170 String rn = StringUtils.pad(toRomanNumeral(number.intValue()), 15, " ", false);
171 return lowercase ? rn.toLowerCase() : rn;
172 } else if (formatUp.equals("FMRN")) {
173 boolean lowercase = format.charAt(2) == 'r';
174 String rn = toRomanNumeral(number.intValue());
175 return lowercase ? rn.toLowerCase() : rn;
176 } else if (formatUp.endsWith("X")) {
177 return toHex(number, format);
178 }
179
180 String originalFormat = format;
181 DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance();
182 char localGrouping = symbols.getGroupingSeparator();
183 char localDecimal = symbols.getDecimalSeparator();
184
185 boolean leadingSign = formatUp.startsWith("S");
186 if (leadingSign) {
187 format = format.substring(1);
188 }
189
190 boolean trailingSign = formatUp.endsWith("S");
191 if (trailingSign) {
192 format = format.substring(0, format.length() - 1);
193 }
194
195 boolean trailingMinus = formatUp.endsWith("MI");
196 if (trailingMinus) {
197 format = format.substring(0, format.length() - 2);
198 }
199
200 boolean angleBrackets = formatUp.endsWith("PR");
201 if (angleBrackets) {
202 format = format.substring(0, format.length() - 2);
203 }
204
205 int v = formatUp.indexOf('V');
206 if (v >= 0) {
207 int digits = 0;
208 for (int i = v + 1; i < format.length(); i++) {
209 char c = format.charAt(i);
210 if (c == '0' || c == '9') {
211 digits++;
212 }
213 }
214 number = number.movePointRight(digits);
215 format = format.substring(0, v) + format.substring(v + 1);
216 }
217
218 Integer power;
219 if (format.endsWith("EEEE")) {
220 power = number.precision() - number.scale() - 1;
221 number = number.movePointLeft(power);
222 format = format.substring(0, format.length() - 4);
223 } else {
224 power = null;
225 }
226
227 int maxLength = 1;
228 boolean fillMode = !formatUp.startsWith("FM");
229 if (!fillMode) {
230 format = format.substring(2);
231 }
232
233 // blanks flag doesn't seem to actually do anything
234 format = format.replaceAll("[Bb]", "");
235
236 // if we need to round the number to fit into the format specified,
237 // go ahead and do that first
238 int separator = findDecimalSeparator(format);
239 int formatScale = calculateScale(format, separator);
240 int numberScale = number.scale();
241 if (formatScale < numberScale) {
242 number = number.setScale(formatScale, RoundingMode.HALF_UP);
243 } else if (numberScale < 0) {
244 number = number.setScale(0);
245 }
246
247 // any 9s to the left of the decimal separator but to the right of a
248 // 0 behave the same as a 0, e.g. "09999.99" -> "00000.99"
249 for (int i = format.indexOf('0'); i >= 0 && i < separator; i++) {
250 if (format.charAt(i) == '9') {
251 format = format.substring(0, i) + "0" + format.substring(i + 1);
252 }
253 }
254
255 StringBuilder output = new StringBuilder();
256 String unscaled = (number.abs().compareTo(BigDecimal.ONE) < 0 ?
257 zeroesAfterDecimalSeparator(number) : "") +
258 number.unscaledValue().abs().toString();
259
260 // start at the decimal point and fill in the numbers to the left,
261 // working our way from right to left
262 int i = separator - 1;
263 int j = unscaled.length() - number.scale() - 1;
264 for (; i >= 0; i--) {
265 char c = format.charAt(i);
266 maxLength++;
267 if (c == '9' || c == '0') {
268 if (j >= 0) {
269 char digit = unscaled.charAt(j);
270 output.insert(0, digit);
271 j--;
272 } else if (c == '0' && power == null) {
273 output.insert(0, '0');
274 }
275 } else if (c == ',') {
276 // only add the grouping separator if we have more numbers
277 if (j >= 0 || (i > 0 && format.charAt(i - 1) == '0')) {
278 output.insert(0, c);
279 }
280 } else if (c == 'G' || c == 'g') {
281 // only add the grouping separator if we have more numbers
282 if (j >= 0 || (i > 0 && format.charAt(i - 1) == '0')) {
283 output.insert(0, localGrouping);
284 }
285 } else if (c == 'C' || c == 'c') {
286 Currency currency = getCurrency();
287 output.insert(0, currency.getCurrencyCode());
288 maxLength += 6;
289 } else if (c == 'L' || c == 'l' || c == 'U' || c == 'u') {
290 Currency currency = getCurrency();
291 output.insert(0, currency.getSymbol());
292 maxLength += 9;
293 } else if (c == '$') {
294 Currency currency = getCurrency();
295 String cs = currency.getSymbol();
296 output.insert(0, cs);
297 } else {
298 throw DbException.get(
299 ErrorCode.INVALID_TO_CHAR_FORMAT, originalFormat);
300 }
301 }
302
303 // if the format (to the left of the decimal point) was too small
304 // to hold the number, return a big "######" string
305 if (j >= 0) {
306 return StringUtils.pad("", format.length() + 1, "#", true);
307 }
308
309 if (separator < format.length()) {
310
311 // add the decimal point
312 maxLength++;
313 char pt = format.charAt(separator);
314 if (pt == 'd' || pt == 'D') {
315 output.append(localDecimal);
316 } else {
317 output.append(pt);
318 }
319
320 // start at the decimal point and fill in the numbers to the right,
321 // working our way from left to right
322 i = separator + 1;
323 j = unscaled.length() - number.scale();
324 for (; i < format.length(); i++) {
325 char c = format.charAt(i);
326 maxLength++;
327 if (c == '9' || c == '0') {
328 if (j < unscaled.length()) {
329 char digit = unscaled.charAt(j);
330 output.append(digit);
331 j++;
332 } else {
333 if (c == '0' || fillMode) {
334 output.append('0');
335 }
336 }
337 } else {
338 throw DbException.get(
339 ErrorCode.INVALID_TO_CHAR_FORMAT, originalFormat);
340 }
341 }
342 }
343
344 addSign(output, number.signum(), leadingSign, trailingSign,
345 trailingMinus, angleBrackets, fillMode);
346
347 if (power != null) {
348 output.append('E');
349 output.append(power < 0 ? '-' : '+');
350 output.append(Math.abs(power) < 10 ? "0" : "");
351 output.append(Math.abs(power));
352 }
353
354 if (fillMode) {
355 if (power != null) {
356 output.insert(0, ' ');
357 } else {
358 while (output.length() < maxLength) {
359 output.insert(0, ' ');
360 }
361 }
362 }
363
364 return output.toString();
365 }
366
367 private static Currency getCurrency() {
368 Locale locale = Locale.getDefault();
369 return Currency.getInstance(locale.getCountry().length() == 2 ? locale : Locale.US);
370 }
371
372 private static String zeroesAfterDecimalSeparator(BigDecimal number) {
373 final String numberStr = number.toPlainString();
374 final int idx = numberStr.indexOf('.');
375 if (idx < 0) {
376 return "";
377 }
378 int i = idx + 1;
379 boolean allZeroes = true;
380 int length = numberStr.length();
381 for (; i < length; i++) {
382 if (numberStr.charAt(i) != '0') {
383 allZeroes = false;
384 break;
385 }
386 }
387 final char[] zeroes = new char[allZeroes ? length - idx - 1: i - 1 - idx];
388 Arrays.fill(zeroes, '0');
389 return String.valueOf(zeroes);
390 }
391
392 private static void addSign(StringBuilder output, int signum,
393 boolean leadingSign, boolean trailingSign, boolean trailingMinus,
394 boolean angleBrackets, boolean fillMode) {
395 if (angleBrackets) {
396 if (signum < 0) {
397 output.insert(0, '<');
398 output.append('>');
399 } else if (fillMode) {
400 output.insert(0, ' ');
401 output.append(' ');
402 }
403 } else {
404 String sign;
405 if (signum == 0) {
406 sign = "";
407 } else if (signum < 0) {
408 sign = "-";
409 } else {
410 if (leadingSign || trailingSign) {
411 sign = "+";
412 } else if (fillMode) {
413 sign = " ";
414 } else {
415 sign = "";
416 }
417 }
418 if (trailingMinus || trailingSign) {
419 output.append(sign);
420 } else {
421 output.insert(0, sign);
422 }
423 }
424 }
425
426 private static int findDecimalSeparator(String format) {
427 int index = format.indexOf('.');
428 if (index == -1) {
429 index = format.indexOf('D');
430 if (index == -1) {
431 index = format.indexOf('d');
432 if (index == -1) {
433 index = format.length();
434 }
435 }
436 }
437 return index;
438 }
439
440 private static int calculateScale(String format, int separator) {
441 int scale = 0;
442 for (int i = separator; i < format.length(); i++) {
443 char c = format.charAt(i);
444 if (c == '0' || c == '9') {
445 scale++;
446 }
447 }
448 return scale;
449 }
450
451 private static String toRomanNumeral(int number) {
452 StringBuilder result = new StringBuilder();
453 for (int i = 0; i < ROMAN_VALUES.length; i++) {
454 int value = ROMAN_VALUES[i];
455 String numeral = ROMAN_NUMERALS[i];
456 while (number >= value) {
457 result.append(numeral);
458 number -= value;
459 }
460 }
461 return result.toString();
462 }
463
464 private static String toHex(BigDecimal number, String format) {
465
466 boolean fillMode = !StringUtils.toUpperEnglish(format).startsWith("FM");
467 boolean uppercase = !format.contains("x");
468 boolean zeroPadded = format.startsWith("0");
469 int digits = 0;
470 for (int i = 0; i < format.length(); i++) {
471 char c = format.charAt(i);
472 if (c == '0' || c == 'X' || c == 'x') {
473 digits++;
474 }
475 }
476
477 int i = number.setScale(0, RoundingMode.HALF_UP).intValue();
478 String hex = Integer.toHexString(i);
479 if (digits < hex.length()) {
480 hex = StringUtils.pad("", digits + 1, "#", true);
481 } else {
482 if (uppercase) {
483 hex = StringUtils.toUpperEnglish(hex);
484 }
485 if (zeroPadded) {
486 hex = StringUtils.pad(hex, digits, "0", false);
487 }
488 if (fillMode) {
489 hex = StringUtils.pad(hex, format.length() + 1, " ", false);
490 }
491 }
492
493 return hex;
494 }
495
496 /**
497 * Get the date (month / weekday / ...) names.
498 *
499 * @param names the field
500 * @return the names
501 */
502 public static String[] getDateNames(int names) {
503 String[][] result = NAMES;
504 if (result == null) {
505 result = new String[5][];
506 DateFormatSymbols dfs = DateFormatSymbols.getInstance();
507 result[MONTHS] = dfs.getMonths();
508 String[] months = dfs.getShortMonths();
509 for (int i = 0; i < 12; i++) {
510 String month = months[i];
511 if (month.endsWith(".")) {
512 months[i] = month.substring(0, month.length() - 1);
513 }
514 }
515 result[SHORT_MONTHS] = months;
516 result[WEEKDAYS] = dfs.getWeekdays();
517 result[SHORT_WEEKDAYS] = dfs.getShortWeekdays();
518 result[AM_PM] = dfs.getAmPmStrings();
519 NAMES = result;
520 }
521 return result[names];
522 }
523
524 /**
525 * Used for testing.
526 */
527 public static void clearNames() {
528 NAMES = null;
529 }
530
531 /**
532 * Returns time zone display name or ID for the specified date-time value.
533 *
534 * @param session
535 * the session
536 * @param value
537 * value
538 * @param tzd
539 * if {@code true} return TZD (time zone region with Daylight Saving
540 * Time information included), if {@code false} return TZR (time zone
541 * region)
542 * @return time zone display name or ID
543 */
544 private static String getTimeZone(SessionLocal session, Value value, boolean tzd) {
545 if (value instanceof ValueTimestampTimeZone) {
546 return DateTimeUtils.timeZoneNameFromOffsetSeconds(((ValueTimestampTimeZone) value)
547 .getTimeZoneOffsetSeconds());
548 } else if (value instanceof ValueTimeTimeZone) {
549 return DateTimeUtils.timeZoneNameFromOffsetSeconds(((ValueTimeTimeZone) value)
550 .getTimeZoneOffsetSeconds());
551 } else {
552 TimeZoneProvider tz = session.currentTimeZone();
553 if (tzd) {
554 ValueTimestamp v = (ValueTimestamp) value.convertTo(TypeInfo.TYPE_TIMESTAMP, session);
555 return tz.getShortId(tz.getEpochSecondsFromLocal(v.getDateValue(), v.getTimeNanos()));
556 }
557 return tz.getId();
558 }
559 }
560
561 /**
562 * Emulates Oracle's TO_CHAR(datetime) function.
563 *
564 * <table border="1">
565 * <caption>TO_CHAR(datetime) function</caption>
566 * <tr><th>Input</th>
567 * <th>Output</th>
568 * <th>Closest {@link SimpleDateFormat} Equivalent</th></tr>
569 * <tr><td>- / , . ; : "text"</td>
570 * <td>Reproduced verbatim.</td>
571 * <td>'text'</td></tr>
572 * <tr><td>A.D. AD B.C. BC</td>
573 * <td>Era designator, with or without periods.</td>
574 * <td>G</td></tr>
575 * <tr><td>A.M. AM P.M. PM</td>
576 * <td>AM/PM marker.</td>
577 * <td>a</td></tr>
578 * <tr><td>CC SCC</td>
579 * <td>Century.</td>
580 * <td>None.</td></tr>
581 * <tr><td>D</td>
582 * <td>Day of week.</td>
583 * <td>u</td></tr>
584 * <tr><td>DAY</td>
585 * <td>Name of day.</td>
586 * <td>EEEE</td></tr>
587 * <tr><td>DY</td>
588 * <td>Abbreviated day name.</td>
589 * <td>EEE</td></tr>
590 * <tr><td>DD</td>
591 * <td>Day of month.</td>
592 * <td>d</td></tr>
593 * <tr><td>DDD</td>
594 * <td>Day of year.</td>
595 * <td>D</td></tr>
596 * <tr><td>DL</td>
597 * <td>Long date format.</td>
598 * <td>EEEE, MMMM d, yyyy</td></tr>
599 * <tr><td>DS</td>
600 * <td>Short date format.</td>
601 * <td>MM/dd/yyyy</td></tr>
602 * <tr><td>E</td>
603 * <td>Abbreviated era name (Japanese, Chinese, Thai)</td>
604 * <td>None.</td></tr>
605 * <tr><td>EE</td>
606 * <td>Full era name (Japanese, Chinese, Thai)</td>
607 * <td>None.</td></tr>
608 * <tr><td>FF[1-9]</td>
609 * <td>Fractional seconds.</td>
610 * <td>S</td></tr>
611 * <tr><td>FM</td>
612 * <td>Returns values with no leading or trailing spaces.</td>
613 * <td>None.</td></tr>
614 * <tr><td>FX</td>
615 * <td>Requires exact matches between character data and format model.</td>
616 * <td>None.</td></tr>
617 * <tr><td>HH HH12</td>
618 * <td>Hour in AM/PM (1-12).</td>
619 * <td>hh</td></tr>
620 * <tr><td>HH24</td>
621 * <td>Hour in day (0-23).</td>
622 * <td>HH</td></tr>
623 * <tr><td>IW</td>
624 * <td>Week in year.</td>
625 * <td>w</td></tr>
626 * <tr><td>WW</td>
627 * <td>Week in year.</td>
628 * <td>w</td></tr>
629 * <tr><td>W</td>
630 * <td>Week in month.</td>
631 * <td>W</td></tr>
632 * <tr><td>IYYY IYY IY I</td>
633 * <td>Last 4/3/2/1 digit(s) of ISO year.</td>
634 * <td>yyyy yyy yy y</td></tr>
635 * <tr><td>RRRR RR</td>
636 * <td>Last 4/2 digits of year.</td>
637 * <td>yyyy yy</td></tr>
638 * <tr><td>Y,YYY</td>
639 * <td>Year with comma.</td>
640 * <td>None.</td></tr>
641 * <tr><td>YEAR SYEAR</td>
642 * <td>Year spelled out (S prefixes BC years with minus sign).</td>
643 * <td>None.</td></tr>
644 * <tr><td>YYYY SYYYY</td>
645 * <td>4-digit year (S prefixes BC years with minus sign).</td>
646 * <td>yyyy</td></tr>
647 * <tr><td>YYY YY Y</td>
648 * <td>Last 3/2/1 digit(s) of year.</td>
649 * <td>yyy yy y</td></tr>
650 * <tr><td>J</td>
651 * <td>Julian day (number of days since January 1, 4712 BC).</td>
652 * <td>None.</td></tr>
653 * <tr><td>MI</td>
654 * <td>Minute in hour.</td>
655 * <td>mm</td></tr>
656 * <tr><td>MM</td>
657 * <td>Month in year.</td>
658 * <td>MM</td></tr>
659 * <tr><td>MON</td>
660 * <td>Abbreviated name of month.</td>
661 * <td>MMM</td></tr>
662 * <tr><td>MONTH</td>
663 * <td>Name of month, padded with spaces.</td>
664 * <td>MMMM</td></tr>
665 * <tr><td>RM</td>
666 * <td>Roman numeral month.</td>
667 * <td>None.</td></tr>
668 * <tr><td>Q</td>
669 * <td>Quarter of year.</td>
670 * <td>None.</td></tr>
671 * <tr><td>SS</td>
672 * <td>Seconds in minute.</td>
673 * <td>ss</td></tr>
674 * <tr><td>SSSSS</td>
675 * <td>Seconds in day.</td>
676 * <td>None.</td></tr>
677 * <tr><td>TS</td>
678 * <td>Short time format.</td>
679 * <td>h:mm:ss aa</td></tr>
680 * <tr><td>TZD</td>
681 * <td>Daylight savings time zone abbreviation.</td>
682 * <td>z</td></tr>
683 * <tr><td>TZR</td>
684 * <td>Time zone region information.</td>
685 * <td>zzzz</td></tr>
686 * <tr><td>X</td>
687 * <td>Local radix character.</td>
688 * <td>None.</td></tr>
689 * </table>
690 * <p>
691 * See also TO_CHAR(datetime) and datetime format models
692 * in the Oracle documentation.
693 *
694 * @param session the session
695 * @param value the date-time value to format
696 * @param format the format pattern to use (if any)
697 * @param nlsParam the NLS parameter (if any)
698 *
699 * @return the formatted timestamp
700 */
701 public static String toCharDateTime(SessionLocal session, Value value, String format,
702 @SuppressWarnings("unused") String nlsParam) {
703 long[] a = DateTimeUtils.dateAndTimeFromValue(value, session);
704 long dateValue = a[0];
705 long timeNanos = a[1];
706 int year = DateTimeUtils.yearFromDateValue(dateValue);
707 int monthOfYear = DateTimeUtils.monthFromDateValue(dateValue);
708 int dayOfMonth = DateTimeUtils.dayFromDateValue(dateValue);
709 int posYear = Math.abs(year);
710 int second = (int) (timeNanos / 1_000_000_000);
711 int nanos = (int) (timeNanos - second * 1_000_000_000);
712 int minute = second / 60;
713 second -= minute * 60;
714 int hour = minute / 60;
715 minute -= hour * 60;
716 int h12 = (hour + 11) % 12 + 1;
717 boolean isAM = hour < 12;
718 if (format == null) {
719 format = "DD-MON-YY HH.MI.SS.FF PM";
720 }
721
722 StringBuilder output = new StringBuilder();
723 boolean fillMode = true;
724
725 for (int i = 0, length = format.length(); i < length;) {
726
727 Capitalization cap;
728
729 // AD / BC
730
731 if ((cap = containsAt(format, i, "A.D.", "B.C.")) != null) {
732 String era = year > 0 ? "A.D." : "B.C.";
733 output.append(cap.apply(era));
734 i += 4;
735 } else if ((cap = containsAt(format, i, "AD", "BC")) != null) {
736 String era = year > 0 ? "AD" : "BC";
737 output.append(cap.apply(era));
738 i += 2;
739
740 // AM / PM
741
742 } else if ((cap = containsAt(format, i, "A.M.", "P.M.")) != null) {
743 String am = isAM ? "A.M." : "P.M.";
744 output.append(cap.apply(am));
745 i += 4;
746 } else if ((cap = containsAt(format, i, "AM", "PM")) != null) {
747 String am = isAM ? "AM" : "PM";
748 output.append(cap.apply(am));
749 i += 2;
750
751 // Long/short date/time format
752
753 } else if (containsAt(format, i, "DL") != null) {
754 String day = getDateNames(WEEKDAYS)[DateTimeUtils.getSundayDayOfWeek(dateValue)];
755 String month = getDateNames(MONTHS)[monthOfYear - 1];
756 output.append(day).append(", ").append(month).append(' ').append(dayOfMonth).append(", ");
757 StringUtils.appendZeroPadded(output, 4, posYear);
758 i += 2;
759 } else if (containsAt(format, i, "DS") != null) {
760 StringUtils.appendTwoDigits(output, monthOfYear).append('/');
761 StringUtils.appendTwoDigits(output, dayOfMonth).append('/');
762 StringUtils.appendZeroPadded(output, 4, posYear);
763 i += 2;
764 } else if (containsAt(format, i, "TS") != null) {
765 output.append(h12).append(':');
766 StringUtils.appendTwoDigits(output, minute).append(':');
767 StringUtils.appendTwoDigits(output, second).append(' ').append(getDateNames(AM_PM)[isAM ? 0 : 1]);
768 i += 2;
769
770 // Day
771
772 } else if (containsAt(format, i, "DDD") != null) {
773 output.append(DateTimeUtils.getDayOfYear(dateValue));
774 i += 3;
775 } else if (containsAt(format, i, "DD") != null) {
776 StringUtils.appendTwoDigits(output, dayOfMonth);
777 i += 2;
778 } else if ((cap = containsAt(format, i, "DY")) != null) {
779 String day = getDateNames(SHORT_WEEKDAYS)[DateTimeUtils.getSundayDayOfWeek(dateValue)];
780 output.append(cap.apply(day));
781 i += 2;
782 } else if ((cap = containsAt(format, i, "DAY")) != null) {
783 String day = getDateNames(WEEKDAYS)[DateTimeUtils.getSundayDayOfWeek(dateValue)];
784 if (fillMode) {
785 day = StringUtils.pad(day, "Wednesday".length(), " ", true);
786 }
787 output.append(cap.apply(day));
788 i += 3;
789 } else if (containsAt(format, i, "D") != null) {
790 output.append(DateTimeUtils.getSundayDayOfWeek(dateValue));
791 i += 1;
792 } else if (containsAt(format, i, "J") != null) {
793 output.append(DateTimeUtils.absoluteDayFromDateValue(dateValue) - JULIAN_EPOCH);
794 i += 1;
795
796 // Hours
797
798 } else if (containsAt(format, i, "HH24") != null) {
799 StringUtils.appendTwoDigits(output, hour);
800 i += 4;
801 } else if (containsAt(format, i, "HH12") != null) {
802 StringUtils.appendTwoDigits(output, h12);
803 i += 4;
804 } else if (containsAt(format, i, "HH") != null) {
805 StringUtils.appendTwoDigits(output, h12);
806 i += 2;
807
808 // Minutes
809
810 } else if (containsAt(format, i, "MI") != null) {
811 StringUtils.appendTwoDigits(output, minute);
812 i += 2;
813
814 // Seconds
815
816 } else if (containsAt(format, i, "SSSSS") != null) {
817 int seconds = (int) (timeNanos / 1_000_000_000);
818 output.append(seconds);
819 i += 5;
820 } else if (containsAt(format, i, "SS") != null) {
821 StringUtils.appendTwoDigits(output, second);
822 i += 2;
823
824 // Fractional seconds
825
826 } else if (containsAt(format, i, "FF1", "FF2",
827 "FF3", "FF4", "FF5", "FF6", "FF7", "FF8", "FF9") != null) {
828 int x = format.charAt(i + 2) - '0';
829 int ff = (int) (nanos * Math.pow(10, x - 9));
830 StringUtils.appendZeroPadded(output, x, ff);
831 i += 3;
832 } else if (containsAt(format, i, "FF") != null) {
833 StringUtils.appendZeroPadded(output, 9, nanos);
834 i += 2;
835
836 // Time zone
837
838 } else if (containsAt(format, i, "TZR") != null) {
839 output.append(getTimeZone(session, value, false));
840 i += 3;
841 } else if (containsAt(format, i, "TZD") != null) {
842 output.append(getTimeZone(session, value, true));
843 i += 3;
844 } else if (containsAt(format, i, "TZH") != null) {
845 int hours = DateTimeFunction.extractDateTime(session, value, DateTimeFunction.TIMEZONE_HOUR);
846 output.append( hours < 0 ? '-' : '+');
847 StringUtils.appendTwoDigits(output, Math.abs(hours));
848 i += 3;
849
850 } else if (containsAt(format, i, "TZM") != null) {
851 StringUtils.appendTwoDigits(output,
852 Math.abs(DateTimeFunction.extractDateTime(session, value, DateTimeFunction.TIMEZONE_MINUTE)));
853 i += 3;
854
855 // Week
856 } else if (containsAt(format, i, "WW") != null) {
857 StringUtils.appendTwoDigits(output, (DateTimeUtils.getDayOfYear(dateValue) - 1) / 7 + 1);
858 i += 2;
859 } else if (containsAt(format, i, "IW") != null) {
860 StringUtils.appendTwoDigits(output, DateTimeUtils.getIsoWeekOfYear(dateValue));
861 i += 2;
862 } else if (containsAt(format, i, "W") != null) {
863 output.append((dayOfMonth - 1) / 7 + 1);
864 i += 1;
865
866 // Year
867
868 } else if (containsAt(format, i, "Y,YYY") != null) {
869 output.append(new DecimalFormat("#,###").format(posYear));
870 i += 5;
871 } else if (containsAt(format, i, "SYYYY") != null) {
872 // Should be <= 0, but Oracle prints negative years with off-by-one difference
873 if (year < 0) {
874 output.append('-');
875 }
876 StringUtils.appendZeroPadded(output, 4, posYear);
877 i += 5;
878 } else if (containsAt(format, i, "YYYY", "RRRR") != null) {
879 StringUtils.appendZeroPadded(output, 4, posYear);
880 i += 4;
881 } else if (containsAt(format, i, "IYYY") != null) {
882 StringUtils.appendZeroPadded(output, 4, Math.abs(DateTimeUtils.getIsoWeekYear(dateValue)));
883 i += 4;
884 } else if (containsAt(format, i, "YYY") != null) {
885 StringUtils.appendZeroPadded(output, 3, posYear % 1000);
886 i += 3;
887 } else if (containsAt(format, i, "IYY") != null) {
888 StringUtils.appendZeroPadded(output, 3, Math.abs(DateTimeUtils.getIsoWeekYear(dateValue)) % 1000);
889 i += 3;
890 } else if (containsAt(format, i, "YY", "RR") != null) {
891 StringUtils.appendTwoDigits(output, posYear % 100);
892 i += 2;
893 } else if (containsAt(format, i, "IY") != null) {
894 StringUtils.appendTwoDigits(output, Math.abs(DateTimeUtils.getIsoWeekYear(dateValue)) % 100);
895 i += 2;
896 } else if (containsAt(format, i, "Y") != null) {
897 output.append(posYear % 10);
898 i += 1;
899 } else if (containsAt(format, i, "I") != null) {
900 output.append(Math.abs(DateTimeUtils.getIsoWeekYear(dateValue)) % 10);
901 i += 1;
902
903 // Month / quarter
904
905 } else if ((cap = containsAt(format, i, "MONTH")) != null) {
906 String month = getDateNames(MONTHS)[monthOfYear - 1];
907 if (fillMode) {
908 month = StringUtils.pad(month, "September".length(), " ", true);
909 }
910 output.append(cap.apply(month));
911 i += 5;
912 } else if ((cap = containsAt(format, i, "MON")) != null) {
913 String month = getDateNames(SHORT_MONTHS)[monthOfYear - 1];
914 output.append(cap.apply(month));
915 i += 3;
916 } else if (containsAt(format, i, "MM") != null) {
917 StringUtils.appendTwoDigits(output, monthOfYear);
918 i += 2;
919 } else if ((cap = containsAt(format, i, "RM")) != null) {
920 output.append(cap.apply(toRomanNumeral(monthOfYear)));
921 i += 2;
922 } else if (containsAt(format, i, "Q") != null) {
923 int q = 1 + ((monthOfYear - 1) / 3);
924 output.append(q);
925 i += 1;
926
927 // Local radix character
928
929 } else if (containsAt(format, i, "X") != null) {
930 char c = DecimalFormatSymbols.getInstance().getDecimalSeparator();
931 output.append(c);
932 i += 1;
933
934 // Format modifiers
935
936 } else if (containsAt(format, i, "FM") != null) {
937 fillMode = !fillMode;
938 i += 2;
939 } else if (containsAt(format, i, "FX") != null) {
940 i += 2;
941
942 // Literal text
943
944 } else if (containsAt(format, i, "\"") != null) {
945 for (i = i + 1; i < format.length(); i++) {
946 char c = format.charAt(i);
947 if (c != '"') {
948 output.append(c);
949 } else {
950 i++;
951 break;
952 }
953 }
954 } else if (format.charAt(i) == '-'
955 || format.charAt(i) == '/'
956 || format.charAt(i) == ','
957 || format.charAt(i) == '.'
958 || format.charAt(i) == ';'
959 || format.charAt(i) == ':'
960 || format.charAt(i) == ' ') {
961 output.append(format.charAt(i));
962 i += 1;
963
964 // Anything else
965
966 } else {
967 throw DbException.get(ErrorCode.INVALID_TO_CHAR_FORMAT, format);
968 }
969 }
970
971 return output.toString();
972 }
973
974 /**
975 * Returns a capitalization strategy if the specified string contains any of
976 * the specified substrings at the specified index. The capitalization
977 * strategy indicates the casing of the substring that was found. If none of
978 * the specified substrings are found, this method returns <code>null</code>
979 * .
980 *
981 * @param s the string to check
982 * @param index the index to check at
983 * @param substrings the substrings to check for within the string
984 * @return a capitalization strategy if the specified string contains any of
985 * the specified substrings at the specified index,
986 * <code>null</code> otherwise
987 */
988 private static Capitalization containsAt(String s, int index,
989 String... substrings) {
990 for (String substring : substrings) {
991 if (index + substring.length() <= s.length()) {
992 boolean found = true;
993 Boolean up1 = null;
994 Boolean up2 = null;
995 for (int i = 0; i < substring.length(); i++) {
996 char c1 = s.charAt(index + i);
997 char c2 = substring.charAt(i);
998 if (c1 != c2 && Character.toUpperCase(c1) != Character.toUpperCase(c2)) {
999 found = false;
1000 break;
1001 } else if (Character.isLetter(c1)) {
1002 if (up1 == null) {
1003 up1 = Character.isUpperCase(c1);
1004 } else if (up2 == null) {
1005 up2 = Character.isUpperCase(c1);
1006 }
1007 }
1008 }
1009 if (found) {
1010 return Capitalization.toCapitalization(up1, up2);
1011 }
1012 }
1013 }
1014 return null;
1015 }
1016
1017 /** Represents a capitalization / casing strategy. */
1018 public enum Capitalization {
1019
1020 /**
1021 * All letters are uppercased.
1022 */
1023 UPPERCASE,
1024
1025 /**
1026 * All letters are lowercased.
1027 */
1028 LOWERCASE,
1029
1030 /**
1031 * The string is capitalized (first letter uppercased, subsequent
1032 * letters lowercased).
1033 */
1034 CAPITALIZE;
1035
1036 /**
1037 * Returns the capitalization / casing strategy which should be used
1038 * when the first and second letters have the specified casing.
1039 *
1040 * @param up1 whether or not the first letter is uppercased
1041 * @param up2 whether or not the second letter is uppercased
1042 * @return the capitalization / casing strategy which should be used
1043 * when the first and second letters have the specified casing
1044 */
1045 static Capitalization toCapitalization(Boolean up1, Boolean up2) {
1046 if (up1 == null) {
1047 return Capitalization.CAPITALIZE;
1048 } else if (up2 == null) {
1049 return up1 ? Capitalization.UPPERCASE : Capitalization.LOWERCASE;
1050 } else if (up1) {
1051 return up2 ? Capitalization.UPPERCASE : Capitalization.CAPITALIZE;
1052 } else {
1053 return Capitalization.LOWERCASE;
1054 }
1055 }
1056
1057 /**
1058 * Applies this capitalization strategy to the specified string.
1059 *
1060 * @param s the string to apply this strategy to
1061 * @return the resultant string
1062 */
1063 public String apply(String s) {
1064 if (s == null || s.isEmpty()) {
1065 return s;
1066 }
1067 switch (this) {
1068 case UPPERCASE:
1069 return StringUtils.toUpperEnglish(s);
1070 case LOWERCASE:
1071 return StringUtils.toLowerEnglish(s);
1072 case CAPITALIZE:
1073 return Character.toUpperCase(s.charAt(0)) +
1074 (s.length() > 1 ? StringUtils.toLowerEnglish(s).substring(1) : "");
1075 default:
1076 throw new IllegalArgumentException(
1077 "Unknown capitalization strategy: " + this);
1078 }
1079 }
1080 }
1081
1082 public ToCharFunction(Expression arg1, Expression arg2, Expression arg3) {
1083 super(arg2 == null ? new Expression[] { arg1 }
1084 : arg3 == null ? new Expression[] { arg1, arg2 } : new Expression[] { arg1, arg2, arg3 });
1085 }
1086
1087 @Override
1088 public Value getValue(SessionLocal session, Value v1, Value v2, Value v3) {
1089 switch (v1.getValueType()) {
1090 case Value.DATE:
1091 case Value.TIME:
1092 case Value.TIME_TZ:
1093 case Value.TIMESTAMP:
1094 case Value.TIMESTAMP_TZ:
1095 v1 = ValueVarchar.get(toCharDateTime(session, v1, v2 == null ? null : v2.getString(),
1096 v3 == null ? null : v3.getString()), session);
1097 break;
1098 case Value.TINYINT:
1099 case Value.SMALLINT:
1100 case Value.INTEGER:
1101 case Value.BIGINT:
1102 case Value.NUMERIC:
1103 case Value.REAL:
1104 case Value.DOUBLE:
1105 case Value.DECFLOAT:
1106 v1 = ValueVarchar.get(toChar(v1.getBigDecimal(), v2 == null ? null : v2.getString(),
1107 v3 == null ? null : v3.getString()), session);
1108 break;
1109 default:
1110 v1 = ValueVarchar.get(v1.getString(), session);
1111 }
1112 return v1;
1113 }
1114
1115 @Override
1116 public Expression optimize(SessionLocal session) {
1117 boolean allConst = optimizeArguments(session, true);
1118 type = TypeInfo.TYPE_VARCHAR;
1119 if (allConst) {
1120 return TypedValueExpression.getTypedIfNull(getValue(session), type);
1121 }
1122 return this;
1123 }
1124
1125 @Override
1126 public String getName() {
1127 return "TO_CHAR";
1128 }
1129
1130 }