Debian Codegraph @

src/main/org/h2/value/Value.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: H2 Group
5 */
6 package org.h2.value;
7
8 import java.io.ByteArrayInputStream;
9 import java.io.ByteArrayOutputStream;
10 import java.io.InputStream;
11 import java.io.Reader;
12 import java.io.StringReader;
13 import java.lang.ref.SoftReference;
14 import java.math.BigDecimal;
15 import java.math.RoundingMode;
16 import java.nio.charset.StandardCharsets;
17 import java.util.Arrays;
18 import java.util.Iterator;
19 import java.util.Map;
20 import java.util.Set;
21
22 import org.h2.api.ErrorCode;
23 import org.h2.api.IntervalQualifier;
24 import org.h2.engine.CastDataProvider;
25 import org.h2.engine.Mode.CharPadding;
26 import org.h2.engine.SysProperties;
27 import org.h2.message.DbException;
28 import org.h2.store.DataHandler;
29 import org.h2.util.Bits;
30 import org.h2.util.DateTimeUtils;
31 import org.h2.util.HasSQL;
32 import org.h2.util.IntervalUtils;
33 import org.h2.util.JdbcUtils;
34 import org.h2.util.MathUtils;
35 import org.h2.util.StringUtils;
36 import org.h2.util.geometry.GeoJsonUtils;
37 import org.h2.util.json.JsonConstructorUtils;
38 import org.h2.value.lob.LobData;
39 import org.h2.value.lob.LobDataDatabase;
40 import org.h2.value.lob.LobDataInMemory;
41
42 /**
43 * This is the base class for all value classes.
44 * It provides conversion and comparison methods.
45 *
46 * @author Thomas Mueller
47 * @author Noel Grandin
48 * @author Nicolas Fortin, Atelier SIG, IRSTV FR CNRS 24888
49 */
50 public abstract class Value extends VersionedValue<Value> implements HasSQL, Typed {
51
52 /**
53 * The data type is unknown at this time.
54 */
55 public static final int UNKNOWN = -1;
56
57 /**
58 * The value type for NULL.
59 */
60 public static final int NULL = UNKNOWN + 1;
61
62 /**
63 * The value type for CHARACTER values.
64 */
65 public static final int CHAR = NULL + 1;
66
67 /**
68 * The value type for CHARACTER VARYING values.
69 */
70 public static final int VARCHAR = CHAR + 1;
71
72 /**
73 * The value type for CHARACTER LARGE OBJECT values.
74 */
75 public static final int CLOB = VARCHAR + 1;
76
77 /**
78 * The value type for VARCHAR_IGNORECASE values.
79 */
80 public static final int VARCHAR_IGNORECASE = CLOB + 1;
81
82 /**
83 * The value type for BINARY values.
84 */
85 public static final int BINARY = VARCHAR_IGNORECASE + 1;
86
87 /**
88 * The value type for BINARY VARYING values.
89 */
90 public static final int VARBINARY = BINARY + 1;
91
92 /**
93 * The value type for BINARY LARGE OBJECT values.
94 */
95 public static final int BLOB = VARBINARY + 1;
96
97 /**
98 * The value type for BOOLEAN values.
99 */
100 public static final int BOOLEAN = BLOB + 1;
101
102 /**
103 * The value type for TINYINT values.
104 */
105 public static final int TINYINT = BOOLEAN + 1;
106
107 /**
108 * The value type for SMALLINT values.
109 */
110 public static final int SMALLINT = TINYINT + 1;
111
112 /**
113 * The value type for INTEGER values.
114 */
115 public static final int INTEGER = SMALLINT + 1;
116
117 /**
118 * The value type for BIGINT values.
119 */
120 public static final int BIGINT = INTEGER + 1;
121
122 /**
123 * The value type for NUMERIC values.
124 */
125 public static final int NUMERIC = BIGINT + 1;
126
127 /**
128 * The value type for REAL values.
129 */
130 public static final int REAL = NUMERIC + 1;
131
132 /**
133 * The value type for DOUBLE PRECISION values.
134 */
135 public static final int DOUBLE = REAL + 1;
136
137 /**
138 * The value type for DECFLOAT values.
139 */
140 public static final int DECFLOAT = DOUBLE + 1;
141
142 /**
143 * The value type for DATE values.
144 */
145 public static final int DATE = DECFLOAT + 1;
146
147 /**
148 * The value type for TIME values.
149 */
150 public static final int TIME = DATE + 1;
151
152 /**
153 * The value type for TIME WITH TIME ZONE values.
154 */
155 public static final int TIME_TZ = TIME + 1;
156
157 /**
158 * The value type for TIMESTAMP values.
159 */
160 public static final int TIMESTAMP = TIME_TZ + 1;
161
162 /**
163 * The value type for TIMESTAMP WITH TIME ZONE values.
164 */
165 public static final int TIMESTAMP_TZ = TIMESTAMP + 1;
166
167 /**
168 * The value type for {@code INTERVAL YEAR} values.
169 */
170 public static final int INTERVAL_YEAR = TIMESTAMP_TZ + 1;
171
172 /**
173 * The value type for {@code INTERVAL MONTH} values.
174 */
175 public static final int INTERVAL_MONTH = INTERVAL_YEAR + 1;
176
177 /**
178 * The value type for {@code INTERVAL DAY} values.
179 */
180 public static final int INTERVAL_DAY = INTERVAL_MONTH + 1;
181
182 /**
183 * The value type for {@code INTERVAL HOUR} values.
184 */
185 public static final int INTERVAL_HOUR = INTERVAL_DAY + 1;
186
187 /**
188 * The value type for {@code INTERVAL MINUTE} values.
189 */
190 public static final int INTERVAL_MINUTE = INTERVAL_HOUR + 1;
191
192 /**
193 * The value type for {@code INTERVAL SECOND} values.
194 */
195 public static final int INTERVAL_SECOND = INTERVAL_MINUTE + 1;
196
197 /**
198 * The value type for {@code INTERVAL YEAR TO MONTH} values.
199 */
200 public static final int INTERVAL_YEAR_TO_MONTH = INTERVAL_SECOND + 1;
201
202 /**
203 * The value type for {@code INTERVAL DAY TO HOUR} values.
204 */
205 public static final int INTERVAL_DAY_TO_HOUR = INTERVAL_YEAR_TO_MONTH + 1;
206
207 /**
208 * The value type for {@code INTERVAL DAY TO MINUTE} values.
209 */
210 public static final int INTERVAL_DAY_TO_MINUTE = INTERVAL_DAY_TO_HOUR + 1;
211
212 /**
213 * The value type for {@code INTERVAL DAY TO SECOND} values.
214 */
215 public static final int INTERVAL_DAY_TO_SECOND = INTERVAL_DAY_TO_MINUTE + 1;
216
217 /**
218 * The value type for {@code INTERVAL HOUR TO MINUTE} values.
219 */
220 public static final int INTERVAL_HOUR_TO_MINUTE = INTERVAL_DAY_TO_SECOND + 1;
221
222 /**
223 * The value type for {@code INTERVAL HOUR TO SECOND} values.
224 */
225 public static final int INTERVAL_HOUR_TO_SECOND = INTERVAL_HOUR_TO_MINUTE + 1;
226
227 /**
228 * The value type for {@code INTERVAL MINUTE TO SECOND} values.
229 */
230 public static final int INTERVAL_MINUTE_TO_SECOND = INTERVAL_HOUR_TO_SECOND + 1;
231
232 /**
233 * The value type for JAVA_OBJECT values.
234 */
235 public static final int JAVA_OBJECT = INTERVAL_MINUTE_TO_SECOND + 1;
236
237 /**
238 * The value type for ENUM values.
239 */
240 public static final int ENUM = JAVA_OBJECT + 1;
241
242 /**
243 * The value type for string values with a fixed size.
244 */
245 public static final int GEOMETRY = ENUM + 1;
246
247 /**
248 * The value type for JSON values.
249 */
250 public static final int JSON = GEOMETRY + 1;
251
252 /**
253 * The value type for UUID values.
254 */
255 public static final int UUID = JSON + 1;
256
257 /**
258 * The value type for ARRAY values.
259 */
260 public static final int ARRAY = UUID + 1;
261
262 /**
263 * The value type for ROW values.
264 */
265 public static final int ROW = ARRAY + 1;
266
267 /**
268 * The number of value types.
269 */
270 public static final int TYPE_COUNT = ROW + 1;
271
272 /**
273 * Group for untyped NULL data type.
274 */
275 static final int GROUP_NULL = 0;
276
277 /**
278 * Group for character string data types.
279 */
280 static final int GROUP_CHARACTER_STRING = GROUP_NULL + 1;
281
282 /**
283 * Group for binary string data types.
284 */
285 static final int GROUP_BINARY_STRING = GROUP_CHARACTER_STRING + 1;
286
287 /**
288 * Group for BINARY data type.
289 */
290 static final int GROUP_BOOLEAN = GROUP_BINARY_STRING + 1;
291
292 /**
293 * Group for numeric data types.
294 */
295 static final int GROUP_NUMERIC = GROUP_BOOLEAN + 1;
296
297 /**
298 * Group for datetime data types.
299 */
300 static final int GROUP_DATETIME = GROUP_NUMERIC + 1;
301
302 /**
303 * Group for year-month interval data types.
304 */
305 static final int GROUP_INTERVAL_YM = GROUP_DATETIME + 1;
306
307 /**
308 * Group for day-time interval data types.
309 */
310 static final int GROUP_INTERVAL_DT = GROUP_INTERVAL_YM + 1;
311
312 /**
313 * Group for other data types (JAVA_OBJECT, UUID, GEOMETRY, ENUM, JSON).
314 */
315 static final int GROUP_OTHER = GROUP_INTERVAL_DT + 1;
316
317 /**
318 * Group for collection data types (ARRAY, ROW).
319 */
320 static final int GROUP_COLLECTION = GROUP_OTHER + 1;
321
322 static final byte GROUPS[] = {
323 // NULL
324 GROUP_NULL,
325 // CHAR, VARCHAR, CLOB, VARCHAR_IGNORECASE
326 GROUP_CHARACTER_STRING, GROUP_CHARACTER_STRING, GROUP_CHARACTER_STRING, GROUP_CHARACTER_STRING,
327 // BINARY, VARBINARY, BLOB
328 GROUP_BINARY_STRING, GROUP_BINARY_STRING, GROUP_BINARY_STRING,
329 // BOOLEAN
330 GROUP_BOOLEAN,
331 // TINYINT, SMALLINT, INTEGER, BIGINT, NUMERIC, REAL, DOUBLE, DECFLOAT
332 GROUP_NUMERIC, GROUP_NUMERIC, GROUP_NUMERIC, GROUP_NUMERIC, GROUP_NUMERIC, GROUP_NUMERIC, GROUP_NUMERIC,
333 GROUP_NUMERIC,
334 // DATE, TIME, TIME_TZ, TIMESTAMP, TIMESTAMP_TZ
335 GROUP_DATETIME, GROUP_DATETIME, GROUP_DATETIME, GROUP_DATETIME, GROUP_DATETIME,
336 // INTERVAL_YEAR, INTERVAL_MONTH
337 GROUP_INTERVAL_YM, GROUP_INTERVAL_YM,
338 // INTERVAL_DAY, INTERVAL_HOUR, INTERVAL_MINUTE, INTERVAL_SECOND
339 GROUP_INTERVAL_DT, GROUP_INTERVAL_DT, GROUP_INTERVAL_DT, GROUP_INTERVAL_DT,
340 // INTERVAL_YEAR_TO_MONTH
341 GROUP_INTERVAL_YM,
342 // INTERVAL_DAY_TO_HOUR, INTERVAL_DAY_TO_MINUTE,
343 // INTERVAL_DAY_TO_SECOND, INTERVAL_HOUR_TO_MINUTE,
344 // INTERVAL_HOUR_TO_SECOND, INTERVAL_MINUTE_TO_SECOND
345 GROUP_INTERVAL_DT, GROUP_INTERVAL_DT, GROUP_INTERVAL_DT, GROUP_INTERVAL_DT, GROUP_INTERVAL_DT,
346 GROUP_INTERVAL_DT,
347 // JAVA_OBJECT, ENUM, GEOMETRY, JSON, UUID
348 GROUP_OTHER, GROUP_OTHER, GROUP_OTHER, GROUP_OTHER, GROUP_OTHER,
349 // ARRAY, ROW
350 GROUP_COLLECTION, GROUP_COLLECTION,
351 //
352 };
353
354 private static final String NAMES[] = {
355 "UNKNOWN",
356 "NULL", //
357 "CHARACTER", "CHARACTER VARYING", "CHARACTER LARGE OBJECT", "VARCHAR_IGNORECASE", //
358 "BINARY", "BINARY VARYING", "BINARY LARGE OBJECT", //
359 "BOOLEAN", //
360 "TINYINT", "SMALLINT", "INTEGER", "BIGINT", //
361 "NUMERIC", "REAL", "DOUBLE PRECISION", "DECFLOAT", //
362 "DATE", "TIME", "TIME WITH TIME ZONE", "TIMESTAMP", "TIMESTAMP WITH TIME ZONE", //
363 "INTERVAL YEAR", "INTERVAL MONTH", //
364 "INTERVAL DAY", "INTERVAL HOUR", "INTERVAL MINUTE", "INTERVAL SECOND", //
365 "INTERVAL YEAR TO MONTH", //
366 "INTERVAL DAY TO HOUR", "INTERVAL DAY TO MINUTE", "INTERVAL DAY TO SECOND", //
367 "INTERVAL HOUR TO MINUTE", "INTERVAL HOUR TO SECOND", "INTERVAL MINUTE TO SECOND", //
368 "JAVA_OBJECT", "ENUM", "GEOMETRY", "JSON", "UUID", //
369 "ARRAY", "ROW", //
370 };
371
372 /**
373 * Empty array of values.
374 */
375 public static final Value[] EMPTY_VALUES = new Value[0];
376
377 private static SoftReference<Value[]> softCache;
378
379 static final BigDecimal MAX_LONG_DECIMAL = BigDecimal.valueOf(Long.MAX_VALUE);
380
381 /**
382 * The smallest Long value, as a BigDecimal.
383 */
384 public static final BigDecimal MIN_LONG_DECIMAL = BigDecimal.valueOf(Long.MIN_VALUE);
385
386 /**
387 * Convert a value to the specified type without taking scale and precision
388 * into account.
389 */
390 static final int CONVERT_TO = 0;
391
392 /**
393 * Cast a value to the specified type. The scale is set if applicable. The
394 * value is truncated to a required precision.
395 */
396 static final int CAST_TO = 1;
397
398 /**
399 * Cast a value to the specified type for assignment. The scale is set if
400 * applicable. If precision is too large an exception is thrown.
401 */
402 static final int ASSIGN_TO = 2;
403
404 /**
405 * Returns name of the specified data type.
406 *
407 * @param valueType
408 * the value type
409 * @return the name
410 */
411 public static String getTypeName(int valueType) {
412 return NAMES[valueType + 1];
413 }
414
415 /**
416 * Check the range of the parameters.
417 *
418 * @param zeroBasedOffset the offset (0 meaning no offset)
419 * @param length the length of the target
420 * @param dataSize the length of the source
421 */
422 static void rangeCheck(long zeroBasedOffset, long length, long dataSize) {
423 if ((zeroBasedOffset | length) < 0 || length > dataSize - zeroBasedOffset) {
424 if (zeroBasedOffset < 0 || zeroBasedOffset > dataSize) {
425 throw DbException.getInvalidValueException("offset", zeroBasedOffset + 1);
426 }
427 throw DbException.getInvalidValueException("length", length);
428 }
429 }
430
431 @Override
432 public abstract TypeInfo getType();
433
434 /**
435 * Get the value type.
436 *
437 * @return the value type
438 */
439 public abstract int getValueType();
440
441 /**
442 * Get the memory used by this object.
443 *
444 * @return the memory used in bytes
445 */
446 public int getMemory() {
447 /*
448 * Java 11 with -XX:-UseCompressedOops for all values up to ValueBigint
449 * and ValueDouble.
450 */
451 return 24;
452 }
453
454 @Override
455 public abstract int hashCode();
456
457 /**
458 * Check if the two values have the same hash code. No data conversion is
459 * made; this method returns false if the other object is not of the same
460 * class. For some values, compareTo may return 0 even if equals return
461 * false. Example: ValueDecimal 0.0 and 0.00.
462 *
463 * @param other the other value
464 * @return true if they are equal
465 */
466 @Override
467 public abstract boolean equals(Object other);
468
469 /**
470 * Get the higher value order type of two value types. If values need to be
471 * converted to match the other operands value type, the value with the
472 * lower order is converted to the value with the higher order.
473 *
474 * @param t1 the first value type
475 * @param t2 the second value type
476 * @return the higher value type of the two
477 */
478 public static int getHigherOrder(int t1, int t2) {
479 if (t1 == t2) {
480 if (t1 == UNKNOWN) {
481 throw DbException.get(ErrorCode.UNKNOWN_DATA_TYPE_1, "?, ?");
482 }
483 return t1;
484 }
485 if (t1 < t2) {
486 int t = t1;
487 t1 = t2;
488 t2 = t;
489 }
490 if (t1 == UNKNOWN) {
491 if (t2 == NULL) {
492 throw DbException.get(ErrorCode.UNKNOWN_DATA_TYPE_1, "?, NULL");
493 }
494 return t2;
495 } else if (t2 == UNKNOWN) {
496 if (t1 == NULL) {
497 throw DbException.get(ErrorCode.UNKNOWN_DATA_TYPE_1, "NULL, ?");
498 }
499 return t1;
500 }
501 if (t2 == NULL) {
502 return t1;
503 }
504 return getHigherOrderKnown(t1, t2);
505 }
506
507 private static int getHigherOrderNonNull(int t1, int t2) {
508 if (t1 == t2) {
509 return t1;
510 }
511 if (t1 < t2) {
512 int t = t1;
513 t1 = t2;
514 t2 = t;
515 }
516 return getHigherOrderKnown(t1, t2);
517 }
518
519 static int getHigherOrderKnown(int t1, int t2) {
520 int g1 = GROUPS[t1], g2 = GROUPS[t2];
521 switch (g1) {
522 case GROUP_BOOLEAN:
523 if (g2 == GROUP_BINARY_STRING) {
524 throw getDataTypeCombinationException(BOOLEAN, t2);
525 }
526 break;
527 case GROUP_NUMERIC:
528 return getHigherNumeric(t1, t2, g2);
529 case GROUP_DATETIME:
530 return getHigherDateTime(t1, t2, g2);
531 case GROUP_INTERVAL_YM:
532 return getHigherIntervalYearMonth(t1, t2, g2);
533 case GROUP_INTERVAL_DT:
534 return getHigherIntervalDayTime(t1, t2, g2);
535 case GROUP_OTHER:
536 return getHigherOther(t1, t2, g2);
537 }
538 return t1;
539 }
540
541 private static int getHigherNumeric(int t1, int t2, int g2) {
542 if (g2 == GROUP_NUMERIC) {
543 switch (t1) {
544 case REAL:
545 switch (t2) {
546 case INTEGER:
547 return DOUBLE;
548 case BIGINT:
549 case NUMERIC:
550 return DECFLOAT;
551 }
552 break;
553 case DOUBLE:
554 switch (t2) {
555 case BIGINT:
556 case NUMERIC:
557 return DECFLOAT;
558 }
559 break;
560 }
561 } else if (g2 == GROUP_BINARY_STRING) {
562 throw getDataTypeCombinationException(t1, t2);
563 }
564 return t1;
565 }
566
567 private static int getHigherDateTime(int t1, int t2, int g2) {
568 if (g2 == GROUP_CHARACTER_STRING) {
569 return t1;
570 }
571 if (g2 != GROUP_DATETIME) {
572 throw getDataTypeCombinationException(t1, t2);
573 }
574 switch (t1) {
575 case TIME:
576 if (t2 == DATE) {
577 return TIMESTAMP;
578 }
579 break;
580 case TIME_TZ:
581 if (t2 == DATE) {
582 return TIMESTAMP_TZ;
583 }
584 break;
585 case TIMESTAMP:
586 if (t2 == TIME_TZ) {
587 return TIMESTAMP_TZ;
588 }
589 }
590 return t1;
591 }
592
593 private static int getHigherIntervalYearMonth(int t1, int t2, int g2) {
594 switch (g2) {
595 case GROUP_INTERVAL_YM:
596 if (t1 == INTERVAL_MONTH && t2 == INTERVAL_YEAR) {
597 return INTERVAL_YEAR_TO_MONTH;
598 }
599 //$FALL-THROUGH$
600 case GROUP_CHARACTER_STRING:
601 case GROUP_NUMERIC:
602 return t1;
603 default:
604 throw getDataTypeCombinationException(t1, t2);
605 }
606 }
607
608 private static int getHigherIntervalDayTime(int t1, int t2, int g2) {
609 switch (g2) {
610 case GROUP_INTERVAL_DT:
611 break;
612 case GROUP_CHARACTER_STRING:
613 case GROUP_NUMERIC:
614 return t1;
615 default:
616 throw getDataTypeCombinationException(t1, t2);
617 }
618 switch (t1) {
619 case INTERVAL_HOUR:
620 return INTERVAL_DAY_TO_HOUR;
621 case INTERVAL_MINUTE:
622 if (t2 == INTERVAL_DAY) {
623 return INTERVAL_DAY_TO_MINUTE;
624 }
625 return INTERVAL_HOUR_TO_MINUTE;
626 case INTERVAL_SECOND:
627 if (t2 == INTERVAL_DAY) {
628 return INTERVAL_DAY_TO_SECOND;
629 }
630 if (t2 == INTERVAL_HOUR) {
631 return INTERVAL_HOUR_TO_SECOND;
632 }
633 return INTERVAL_MINUTE_TO_SECOND;
634 case INTERVAL_DAY_TO_HOUR:
635 if (t2 == INTERVAL_MINUTE) {
636 return INTERVAL_DAY_TO_MINUTE;
637 }
638 if (t2 == INTERVAL_SECOND) {
639 return INTERVAL_DAY_TO_SECOND;
640 }
641 break;
642 case INTERVAL_DAY_TO_MINUTE:
643 if (t2 == INTERVAL_SECOND) {
644 return INTERVAL_DAY_TO_SECOND;
645 }
646 break;
647 case INTERVAL_HOUR_TO_MINUTE:
648 switch (t2) {
649 case INTERVAL_DAY:
650 case INTERVAL_DAY_TO_HOUR:
651 case INTERVAL_DAY_TO_MINUTE:
652 return INTERVAL_DAY_TO_MINUTE;
653 case INTERVAL_SECOND:
654 return INTERVAL_HOUR_TO_SECOND;
655 case INTERVAL_DAY_TO_SECOND:
656 return INTERVAL_DAY_TO_SECOND;
657 }
658 break;
659 case INTERVAL_HOUR_TO_SECOND:
660 switch (t2) {
661 case INTERVAL_DAY:
662 case INTERVAL_DAY_TO_HOUR:
663 case INTERVAL_DAY_TO_MINUTE:
664 case INTERVAL_DAY_TO_SECOND:
665 return INTERVAL_DAY_TO_SECOND;
666 }
667 break;
668 case INTERVAL_MINUTE_TO_SECOND:
669 switch (t2) {
670 case INTERVAL_DAY:
671 case INTERVAL_DAY_TO_HOUR:
672 case INTERVAL_DAY_TO_MINUTE:
673 case INTERVAL_DAY_TO_SECOND:
674 return INTERVAL_DAY_TO_SECOND;
675 case INTERVAL_HOUR:
676 case INTERVAL_HOUR_TO_MINUTE:
677 case INTERVAL_HOUR_TO_SECOND:
678 return INTERVAL_HOUR_TO_SECOND;
679 }
680 }
681 return t1;
682 }
683
684 private static int getHigherOther(int t1, int t2, int g2) {
685 switch (t1) {
686 case JAVA_OBJECT:
687 if (g2 != GROUP_BINARY_STRING) {
688 throw getDataTypeCombinationException(t1, t2);
689 }
690 break;
691 case ENUM:
692 if (g2 != GROUP_CHARACTER_STRING && (g2 != GROUP_NUMERIC || t2 > INTEGER)) {
693 throw getDataTypeCombinationException(t1, t2);
694 }
695 break;
696 case GEOMETRY:
697 if (g2 != GROUP_CHARACTER_STRING && g2 != GROUP_BINARY_STRING) {
698 throw getDataTypeCombinationException(t1, t2);
699 }
700 break;
701 case JSON:
702 switch (g2) {
703 case GROUP_DATETIME:
704 case GROUP_INTERVAL_YM:
705 case GROUP_INTERVAL_DT:
706 case GROUP_OTHER:
707 throw getDataTypeCombinationException(t1, t2);
708 }
709 break;
710 case UUID:
711 switch (g2) {
712 case GROUP_CHARACTER_STRING:
713 case GROUP_BINARY_STRING:
714 break;
715 case GROUP_OTHER:
716 if (t2 == JAVA_OBJECT) {
717 break;
718 }
719 //$FALL-THROUGH$
720 default:
721 throw getDataTypeCombinationException(t1, t2);
722 }
723 }
724 return t1;
725 }
726
727 private static DbException getDataTypeCombinationException(int t1, int t2) {
728 return DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, getTypeName(t1) + ", " + getTypeName(t2));
729 }
730
731 /**
732 * Check if a value is in the cache that is equal to this value. If yes,
733 * this value should be used to save memory. If the value is not in the
734 * cache yet, it is added.
735 *
736 * @param v the value to look for
737 * @return the value in the cache or the value passed
738 */
739 static Value cache(Value v) {
740 if (SysProperties.OBJECT_CACHE) {
741 int hash = v.hashCode();
742 Value[] cache;
743 if (softCache == null || (cache = softCache.get()) == null) {
744 cache = new Value[SysProperties.OBJECT_CACHE_SIZE];
745 softCache = new SoftReference<>(cache);
746 }
747 int index = hash & (SysProperties.OBJECT_CACHE_SIZE - 1);
748 Value cached = cache[index];
749 if (cached != null) {
750 if (cached.getValueType() == v.getValueType() && v.equals(cached)) {
751 // cacheHit++;
752 return cached;
753 }
754 }
755 // cacheMiss++;
756 // cache[cacheCleaner] = null;
757 // cacheCleaner = (cacheCleaner + 1) &
758 // (Constants.OBJECT_CACHE_SIZE - 1);
759 cache[index] = v;
760 }
761 return v;
762 }
763
764 /**
765 * Clear the value cache. Used for testing.
766 */
767 public static void clearCache() {
768 softCache = null;
769 }
770
771 /**
772 * Get the value as a string.
773 *
774 * @return the string
775 */
776 public abstract String getString();
777
778 public Reader getReader() {
779 return new StringReader(getString());
780 }
781
782 /**
783 * Get the reader
784 *
785 * @param oneBasedOffset the offset (1 means no offset)
786 * @param length the requested length
787 * @return the new reader
788 */
789 public Reader getReader(long oneBasedOffset, long length) {
790 String string = getString();
791 long zeroBasedOffset = oneBasedOffset - 1;
792 rangeCheck(zeroBasedOffset, length, string.length());
793 int offset = (int) zeroBasedOffset;
794 return new StringReader(string.substring(offset, offset + (int) length));
795 }
796
797 public byte[] getBytes() {
798 throw getDataConversionError(VARBINARY);
799 }
800
801 public byte[] getBytesNoCopy() {
802 return getBytes();
803 }
804
805 public InputStream getInputStream() {
806 return new ByteArrayInputStream(getBytesNoCopy());
807 }
808
809 /**
810 * Get the input stream
811 *
812 * @param oneBasedOffset the offset (1 means no offset)
813 * @param length the requested length
814 * @return the new input stream
815 */
816 public InputStream getInputStream(long oneBasedOffset, long length) {
817 byte[] bytes = getBytesNoCopy();
818 long zeroBasedOffset = oneBasedOffset - 1;
819 rangeCheck(zeroBasedOffset, length, bytes.length);
820 return new ByteArrayInputStream(bytes, (int) zeroBasedOffset, (int) length);
821 }
822
823 /**
824 * Returns this value as a Java {@code boolean} value.
825 *
826 * @throws DbException
827 * if this value is {@code NULL} or cannot be casted to
828 * {@code BOOLEAN}
829 * @return value
830 * @see #isTrue()
831 * @see #isFalse()
832 */
833 public boolean getBoolean() {
834 return convertToBoolean().getBoolean();
835 }
836
837 /**
838 * Returns this value as a Java {@code byte} value.
839 *
840 * @throws DbException
841 * if this value is {@code NULL} or cannot be casted to
842 * {@code TINYINT}
843 * @return value
844 */
845 public byte getByte() {
846 return convertToTinyint(null).getByte();
847 }
848
849 /**
850 * Returns this value as a Java {@code short} value.
851 *
852 * @throws DbException
853 * if this value is {@code NULL} or cannot be casted to
854 * {@code SMALLINT}
855 * @return value
856 */
857 public short getShort() {
858 return convertToSmallint(null).getShort();
859 }
860
861 /**
862 * Returns this value as a Java {@code int} value.
863 *
864 * @throws DbException
865 * if this value is {@code NULL} or cannot be casted to
866 * {@code INTEGER}
867 * @return value
868 */
869 public int getInt() {
870 return convertToInt(null).getInt();
871 }
872
873 /**
874 * Returns this value as a Java {@code long} value.
875 *
876 * @throws DbException
877 * if this value is {@code NULL} or cannot be casted to
878 * {@code BIGINT}
879 * @return value
880 */
881 public long getLong() {
882 return convertToBigint(null).getLong();
883 }
884
885 public BigDecimal getBigDecimal() {
886 throw getDataConversionError(NUMERIC);
887 }
888
889 /**
890 * Returns this value as a Java {@code float} value.
891 *
892 * @throws DbException
893 * if this value is {@code NULL} or cannot be casted to
894 * {@code REAL}
895 * @return value
896 */
897 public float getFloat() {
898 throw getDataConversionError(REAL);
899 }
900
901 /**
902 * Returns this value as a Java {@code double} value.
903 *
904 * @throws DbException
905 * if this value is {@code NULL} or cannot be casted to
906 * {@code DOUBLE PRECISION}
907 * @return value
908 */
909 public double getDouble() {
910 throw getDataConversionError(DOUBLE);
911 }
912
913 /**
914 * Add a value and return the result.
915 *
916 * @param v the value to add
917 * @return the result
918 */
919 public Value add(@SuppressWarnings("unused") Value v) {
920 throw getUnsupportedExceptionForOperation("+");
921 }
922
923 public int getSignum() {
924 throw getUnsupportedExceptionForOperation("SIGNUM");
925 }
926
927 /**
928 * Return -value if this value support arithmetic operations.
929 *
930 * @return the negative
931 */
932 public Value negate() {
933 throw getUnsupportedExceptionForOperation("NEG");
934 }
935
936 /**
937 * Subtract a value and return the result.
938 *
939 * @param v the value to subtract
940 * @return the result
941 */
942 public Value subtract(@SuppressWarnings("unused") Value v) {
943 throw getUnsupportedExceptionForOperation("-");
944 }
945
946 /**
947 * Divide by a value and return the result.
948 *
949 * @param v the divisor
950 * @param quotientType the type of quotient (used only to read precision and scale
951 * when applicable)
952 * @return the result
953 */
954 public Value divide(@SuppressWarnings("unused") Value v, TypeInfo quotientType) {
955 throw getUnsupportedExceptionForOperation("/");
956 }
957
958 /**
959 * Multiply with a value and return the result.
960 *
961 * @param v the value to multiply with
962 * @return the result
963 */
964 public Value multiply(@SuppressWarnings("unused") Value v) {
965 throw getUnsupportedExceptionForOperation("*");
966 }
967
968 /**
969 * Take the modulus with a value and return the result.
970 *
971 * @param v the value to take the modulus with
972 * @return the result
973 */
974 public Value modulus(@SuppressWarnings("unused") Value v) {
975 throw getUnsupportedExceptionForOperation("%");
976 }
977
978 /**
979 * Convert a value to the specified type without taking scale and precision
980 * into account.
981 *
982 * @param targetType the type of the returned value
983 * @return the converted value
984 */
985 public final Value convertTo(int targetType) {
986 return convertTo(targetType, null);
987 }
988
989 /**
990 * Convert a value to the specified type without taking scale and precision
991 * into account.
992 *
993 * @param targetType the type of the returned value
994 * @return the converted value
995 */
996 public final Value convertTo(TypeInfo targetType) {
997 return convertTo(targetType, null, CONVERT_TO, null);
998 }
999
1000 /**
1001 * Convert a value to the specified type without taking scale and precision
1002 * into account.
1003 *
1004 * @param targetType the type of the returned value
1005 * @param provider the cast information provider
1006 * @return the converted value
1007 */
1008 public final Value convertTo(int targetType, CastDataProvider provider) {
1009 switch (targetType) {
1010 case ARRAY:
1011 return convertToAnyArray(provider);
1012 case ROW:
1013 return convertToAnyRow();
1014 default:
1015 return convertTo(TypeInfo.getTypeInfo(targetType), provider, CONVERT_TO, null);
1016 }
1017 }
1018
1019 /**
1020 * Convert a value to the specified type without taking scale and precision
1021 * into account.
1022 *
1023 * @param targetType
1024 * the type of the returned value
1025 * @param provider
1026 * the cast information provider
1027 * @return the converted value
1028 */
1029 public final Value convertTo(TypeInfo targetType, CastDataProvider provider) {
1030 return convertTo(targetType, provider, CONVERT_TO, null);
1031 }
1032
1033 /**
1034 * Convert a value to the specified type without taking scale and precision
1035 * into account.
1036 *
1037 * @param targetType
1038 * the type of the returned value
1039 * @param provider
1040 * the cast information provider
1041 * @param column
1042 * the column, used to improve the error message if conversion
1043 * fails
1044 * @return the converted value
1045 */
1046 public final Value convertTo(TypeInfo targetType, CastDataProvider provider, Object column) {
1047 return convertTo(targetType, provider, CONVERT_TO, column);
1048 }
1049
1050 /**
1051 * Convert this value to JSON data type.
1052 *
1053 * @return a JSON value
1054 */
1055 public final ValueJson convertToAnyJson() {
1056 return this != ValueNull.INSTANCE ? convertToJson(TypeInfo.TYPE_JSON, CONVERT_TO, null) : ValueJson.NULL;
1057 }
1058
1059 /**
1060 * Convert this value to any ARRAY data type.
1061 *
1062 * @param provider
1063 * the cast information provider
1064 * @return a row value
1065 */
1066 public final ValueArray convertToAnyArray(CastDataProvider provider) {
1067 if (getValueType() == Value.ARRAY) {
1068 return (ValueArray) this;
1069 }
1070 return ValueArray.get(this.getType(), new Value[] { this }, provider);
1071 }
1072
1073 /**
1074 * Convert this value to any ROW data type.
1075 *
1076 * @return a row value
1077 */
1078 public final ValueRow convertToAnyRow() {
1079 if (getValueType() == Value.ROW) {
1080 return (ValueRow) this;
1081 }
1082 return ValueRow.get(new Value[] { this });
1083 }
1084
1085 /**
1086 * Cast a value to the specified type. The scale is set if applicable. The
1087 * value is truncated to the required precision.
1088 *
1089 * @param targetType
1090 * the type of the returned value
1091 * @param provider
1092 * the cast information provider
1093 * @return the converted value
1094 */
1095 public final Value castTo(TypeInfo targetType, CastDataProvider provider) {
1096 return convertTo(targetType, provider, CAST_TO, null);
1097 }
1098
1099 /**
1100 * Cast a value to the specified type for assignment. The scale is set if
1101 * applicable. If precision is too large an exception is thrown.
1102 *
1103 * @param targetType
1104 * the type of the returned value
1105 * @param provider
1106 * the cast information provider
1107 * @param column
1108 * the column, used to improve the error message if conversion
1109 * fails
1110 * @return the converted value
1111 */
1112 public final Value convertForAssignTo(TypeInfo targetType, CastDataProvider provider, Object column) {
1113 return convertTo(targetType, provider, ASSIGN_TO, column);
1114 }
1115
1116 /**
1117 * Convert a value to the specified type.
1118 *
1119 * @param targetType the type of the returned value
1120 * @param provider the cast information provider
1121 * @param conversionMode conversion mode
1122 * @param column the column (if any), used to improve the error message if conversion fails
1123 * @return the converted value
1124 */
1125 private Value convertTo(TypeInfo targetType, CastDataProvider provider, int conversionMode, Object column) {
1126 int valueType = getValueType(), targetValueType;
1127 if (valueType == NULL
1128 || valueType == (targetValueType = targetType.getValueType()) && conversionMode == CONVERT_TO
1129 && targetType.getExtTypeInfo() == null && valueType != CHAR) {
1130 return this;
1131 }
1132 switch (targetValueType) {
1133 case NULL:
1134 return ValueNull.INSTANCE;
1135 case CHAR:
1136 return convertToChar(targetType, provider, conversionMode, column);
1137 case VARCHAR:
1138 return convertToVarchar(targetType, provider, conversionMode, column);
1139 case CLOB:
1140 return convertToClob(targetType, conversionMode, column);
1141 case VARCHAR_IGNORECASE:
1142 return convertToVarcharIgnoreCase(targetType, conversionMode, column);
1143 case BINARY:
1144 return convertToBinary(targetType, conversionMode, column);
1145 case VARBINARY:
1146 return convertToVarbinary(targetType, conversionMode, column);
1147 case BLOB:
1148 return convertToBlob(targetType, conversionMode, column);
1149 case BOOLEAN:
1150 return convertToBoolean();
1151 case TINYINT:
1152 return convertToTinyint(column);
1153 case SMALLINT:
1154 return convertToSmallint(column);
1155 case INTEGER:
1156 return convertToInt(column);
1157 case BIGINT:
1158 return convertToBigint(column);
1159 case NUMERIC:
1160 return convertToNumeric(targetType, provider, conversionMode, column);
1161 case REAL:
1162 return convertToReal();
1163 case DOUBLE:
1164 return convertToDouble();
1165 case DECFLOAT:
1166 return convertToDecfloat(targetType, conversionMode);
1167 case DATE:
1168 return convertToDate(provider);
1169 case TIME:
1170 return convertToTime(targetType, provider, conversionMode);
1171 case TIME_TZ:
1172 return convertToTimeTimeZone(targetType, provider, conversionMode);
1173 case TIMESTAMP:
1174 return convertToTimestamp(targetType, provider, conversionMode);
1175 case TIMESTAMP_TZ:
1176 return convertToTimestampTimeZone(targetType, provider, conversionMode);
1177 case INTERVAL_YEAR:
1178 case INTERVAL_MONTH:
1179 case INTERVAL_YEAR_TO_MONTH:
1180 return convertToIntervalYearMonth(targetType, conversionMode, column);
1181 case INTERVAL_DAY:
1182 case INTERVAL_HOUR:
1183 case INTERVAL_MINUTE:
1184 case INTERVAL_SECOND:
1185 case INTERVAL_DAY_TO_HOUR:
1186 case INTERVAL_DAY_TO_MINUTE:
1187 case INTERVAL_DAY_TO_SECOND:
1188 case INTERVAL_HOUR_TO_MINUTE:
1189 case INTERVAL_HOUR_TO_SECOND:
1190 case INTERVAL_MINUTE_TO_SECOND:
1191 return convertToIntervalDayTime(targetType, conversionMode, column);
1192 case JAVA_OBJECT:
1193 return convertToJavaObject(targetType, conversionMode, column);
1194 case ENUM:
1195 return convertToEnum((ExtTypeInfoEnum) targetType.getExtTypeInfo(), provider);
1196 case GEOMETRY:
1197 return convertToGeometry((ExtTypeInfoGeometry) targetType.getExtTypeInfo());
1198 case JSON:
1199 return convertToJson(targetType, conversionMode, column);
1200 case UUID:
1201 return convertToUuid();
1202 case ARRAY:
1203 return convertToArray(targetType, provider, conversionMode, column);
1204 case ROW:
1205 return convertToRow(targetType, provider, conversionMode, column);
1206 default:
1207 throw getDataConversionError(targetValueType);
1208 }
1209 }
1210
1211 /**
1212 * Converts this value to a CHAR value. May not be called on a NULL value.
1213 *
1214 * @return a CHAR value.
1215 */
1216 public ValueChar convertToChar() {
1217 return convertToChar(TypeInfo.getTypeInfo(CHAR), null, CONVERT_TO, null);
1218 }
1219
1220 private ValueChar convertToChar(TypeInfo targetType, CastDataProvider provider, int conversionMode, //
1221 Object column) {
1222 int valueType = getValueType();
1223 switch (valueType) {
1224 case BLOB:
1225 case JAVA_OBJECT:
1226 throw getDataConversionError(targetType.getValueType());
1227 }
1228 String s = getString();
1229 int length = s.length(), newLength = length;
1230 if (conversionMode == CONVERT_TO) {
1231 while (newLength > 0 && s.charAt(newLength - 1) == ' ') {
1232 newLength--;
1233 }
1234 } else {
1235 int p = MathUtils.convertLongToInt(targetType.getPrecision());
1236 if (provider == null || provider.getMode().charPadding == CharPadding.ALWAYS) {
1237 if (newLength != p) {
1238 if (newLength < p) {
1239 return ValueChar.get(StringUtils.pad(s, p, null, true));
1240 } else if (conversionMode == CAST_TO) {
1241 newLength = p;
1242 } else {
1243 do {
1244 if (s.charAt(--newLength) != ' ') {
1245 throw getValueTooLongException(targetType, column);
1246 }
1247 } while (newLength > p);
1248 }
1249 }
1250 } else {
1251 if (conversionMode == CAST_TO && newLength > p) {
1252 newLength = p;
1253 }
1254 while (newLength > 0 && s.charAt(newLength - 1) == ' ') {
1255 newLength--;
1256 }
1257 if (conversionMode == ASSIGN_TO && newLength > p) {
1258 throw getValueTooLongException(targetType, column);
1259 }
1260 }
1261 }
1262 if (length != newLength) {
1263 s = s.substring(0, newLength);
1264 } else if (valueType == CHAR) {
1265 return (ValueChar) this;
1266 }
1267 return ValueChar.get(s);
1268 }
1269
1270 private Value convertToVarchar(TypeInfo targetType, CastDataProvider provider, int conversionMode, Object column) {
1271 int valueType = getValueType();
1272 switch (valueType) {
1273 case BLOB:
1274 case JAVA_OBJECT:
1275 throw getDataConversionError(targetType.getValueType());
1276 }
1277 if (conversionMode != CONVERT_TO) {
1278 String s = getString();
1279 int p = MathUtils.convertLongToInt(targetType.getPrecision());
1280 if (s.length() > p) {
1281 if (conversionMode != CAST_TO) {
1282 throw getValueTooLongException(targetType, column);
1283 }
1284 return ValueVarchar.get(s.substring(0, p), provider);
1285 }
1286 }
1287 return valueType == Value.VARCHAR ? this : ValueVarchar.get(getString(), provider);
1288 }
1289
1290 private ValueClob convertToClob(TypeInfo targetType, int conversionMode, Object column) {
1291 ValueClob v;
1292 switch (getValueType()) {
1293 case CLOB:
1294 v = (ValueClob) this;
1295 break;
1296 case JAVA_OBJECT:
1297 throw getDataConversionError(targetType.getValueType());
1298 case BLOB: {
1299 LobData data = ((ValueBlob) this).lobData;
1300 // Try to reuse the array, if possible
1301 if (data instanceof LobDataInMemory) {
1302 byte[] small = ((LobDataInMemory) data).getSmall();
1303 byte[] bytes = new String(small, StandardCharsets.UTF_8).getBytes(StandardCharsets.UTF_8);
1304 if (Arrays.equals(bytes, small)) {
1305 bytes = small;
1306 }
1307 v = ValueClob.createSmall(bytes);
1308 break;
1309 } else if (data instanceof LobDataDatabase) {
1310 v = data.getDataHandler().getLobStorage().createClob(getReader(), -1);
1311 break;
1312 }
1313 }
1314 //$FALL-THROUGH$
1315 default:
1316 v = ValueClob.createSmall(getString());
1317 }
1318 if (conversionMode != CONVERT_TO) {
1319 if (conversionMode == CAST_TO) {
1320 v = v.convertPrecision(targetType.getPrecision());
1321 } else if (v.charLength() > targetType.getPrecision()) {
1322 throw v.getValueTooLongException(targetType, column);
1323 }
1324 }
1325 return v;
1326 }
1327
1328 private Value convertToVarcharIgnoreCase(TypeInfo targetType, int conversionMode, Object column) {
1329 int valueType = getValueType();
1330 switch (valueType) {
1331 case BLOB:
1332 case JAVA_OBJECT:
1333 throw getDataConversionError(targetType.getValueType());
1334 }
1335 if (conversionMode != CONVERT_TO) {
1336 String s = getString();
1337 int p = MathUtils.convertLongToInt(targetType.getPrecision());
1338 if (s.length() > p) {
1339 if (conversionMode != CAST_TO) {
1340 throw getValueTooLongException(targetType, column);
1341 }
1342 return ValueVarcharIgnoreCase.get(s.substring(0, p));
1343 }
1344 }
1345 return valueType == Value.VARCHAR_IGNORECASE ? this : ValueVarcharIgnoreCase.get(getString());
1346 }
1347
1348 private ValueBinary convertToBinary(TypeInfo targetType, int conversionMode, Object column) {
1349 ValueBinary v;
1350 if (getValueType() == BINARY) {
1351 v = (ValueBinary) this;
1352 } else {
1353 try {
1354 v = ValueBinary.getNoCopy(getBytesNoCopy());
1355 } catch (DbException e) {
1356 if (e.getErrorCode() == ErrorCode.DATA_CONVERSION_ERROR_1) {
1357 throw getDataConversionError(BINARY);
1358 }
1359 throw e;
1360 }
1361 }
1362 if (conversionMode != CONVERT_TO) {
1363 byte[] value = v.getBytesNoCopy();
1364 int length = value.length;
1365 int p = MathUtils.convertLongToInt(targetType.getPrecision());
1366 if (length != p) {
1367 if (conversionMode == ASSIGN_TO && length > p) {
1368 throw v.getValueTooLongException(targetType, column);
1369 }
1370 v = ValueBinary.getNoCopy(Arrays.copyOf(value, p));
1371 }
1372 }
1373 return v;
1374 }
1375
1376 private ValueVarbinary convertToVarbinary(TypeInfo targetType, int conversionMode, Object column) {
1377 ValueVarbinary v;
1378 if (getValueType() == VARBINARY) {
1379 v = (ValueVarbinary) this;
1380 } else {
1381 v = ValueVarbinary.getNoCopy(getBytesNoCopy());
1382 }
1383 if (conversionMode != CONVERT_TO) {
1384 byte[] value = v.getBytesNoCopy();
1385 int length = value.length;
1386 int p = MathUtils.convertLongToInt(targetType.getPrecision());
1387 if (conversionMode == CAST_TO) {
1388 if (length > p) {
1389 v = ValueVarbinary.getNoCopy(Arrays.copyOf(value, p));
1390 }
1391 } else if (length > p) {
1392 throw v.getValueTooLongException(targetType, column);
1393 }
1394 }
1395 return v;
1396 }
1397
1398 private ValueBlob convertToBlob(TypeInfo targetType, int conversionMode, Object column) {
1399 ValueBlob v;
1400 switch (getValueType()) {
1401 case BLOB:
1402 v = (ValueBlob) this;
1403 break;
1404 case CLOB:
1405 DataHandler handler = ((ValueLob) this).lobData.getDataHandler();
1406 if (handler != null) {
1407 v = handler.getLobStorage().createBlob(getInputStream(), -1);
1408 break;
1409 }
1410 //$FALL-THROUGH$
1411 default:
1412 try {
1413 v = ValueBlob.createSmall(getBytesNoCopy());
1414 } catch (DbException e) {
1415 if (e.getErrorCode() == ErrorCode.DATA_CONVERSION_ERROR_1) {
1416 throw getDataConversionError(BLOB);
1417 }
1418 throw e;
1419 }
1420 break;
1421 }
1422 if (conversionMode != CONVERT_TO) {
1423 if (conversionMode == CAST_TO) {
1424 v = v.convertPrecision(targetType.getPrecision());
1425 } else if (v.octetLength() > targetType.getPrecision()) {
1426 throw v.getValueTooLongException(targetType, column);
1427 }
1428 }
1429 return v;
1430 }
1431
1432 /**
1433 * Converts this value to a BOOLEAN value. May not be called on a NULL
1434 * value.
1435 *
1436 * @return the BOOLEAN value
1437 */
1438 public final ValueBoolean convertToBoolean() {
1439 switch (getValueType()) {
1440 case BOOLEAN:
1441 return (ValueBoolean) this;
1442 case CHAR:
1443 case VARCHAR:
1444 case VARCHAR_IGNORECASE:
1445 return ValueBoolean.get(getBoolean());
1446 case TINYINT:
1447 case SMALLINT:
1448 case INTEGER:
1449 case BIGINT:
1450 case NUMERIC:
1451 case DOUBLE:
1452 case REAL:
1453 case DECFLOAT:
1454 return ValueBoolean.get(getSignum() != 0);
1455 default:
1456 throw getDataConversionError(BOOLEAN);
1457 case NULL:
1458 throw DbException.getInternalError();
1459 }
1460 }
1461
1462 /**
1463 * Converts this value to a TINYINT value. May not be called on a NULL
1464 * value.
1465 *
1466 * @param column
1467 * the column, used for to improve the error message if
1468 * conversion fails
1469 * @return the TINYINT value
1470 */
1471 public final ValueTinyint convertToTinyint(Object column) {
1472 switch (getValueType()) {
1473 case TINYINT:
1474 return (ValueTinyint) this;
1475 case CHAR:
1476 case VARCHAR:
1477 case VARCHAR_IGNORECASE:
1478 case BOOLEAN:
1479 return ValueTinyint.get(getByte());
1480 case SMALLINT:
1481 case ENUM:
1482 case INTEGER:
1483 return ValueTinyint.get(convertToByte(getInt(), column));
1484 case BIGINT:
1485 case INTERVAL_YEAR:
1486 case INTERVAL_MONTH:
1487 case INTERVAL_DAY:
1488 case INTERVAL_HOUR:
1489 case INTERVAL_MINUTE:
1490 case INTERVAL_SECOND:
1491 case INTERVAL_YEAR_TO_MONTH:
1492 case INTERVAL_DAY_TO_HOUR:
1493 case INTERVAL_DAY_TO_MINUTE:
1494 case INTERVAL_DAY_TO_SECOND:
1495 case INTERVAL_HOUR_TO_MINUTE:
1496 case INTERVAL_HOUR_TO_SECOND:
1497 case INTERVAL_MINUTE_TO_SECOND:
1498 return ValueTinyint.get(convertToByte(getLong(), column));
1499 case NUMERIC:
1500 case DECFLOAT:
1501 return ValueTinyint.get(convertToByte(convertToLong(getBigDecimal(), column), column));
1502 case REAL:
1503 case DOUBLE:
1504 return ValueTinyint.get(convertToByte(convertToLong(getDouble(), column), column));
1505 case BINARY:
1506 case VARBINARY: {
1507 byte[] bytes = getBytesNoCopy();
1508 if (bytes.length == 1) {
1509 return ValueTinyint.get(bytes[0]);
1510 }
1511 }
1512 //$FALL-THROUGH$
1513 default:
1514 throw getDataConversionError(TINYINT);
1515 case NULL:
1516 throw DbException.getInternalError();
1517 }
1518 }
1519
1520 /**
1521 * Converts this value to a SMALLINT value. May not be called on a NULL value.
1522 *
1523 * @param column
1524 * the column, used for to improve the error message if
1525 * conversion fails
1526 * @return the SMALLINT value
1527 */
1528 public final ValueSmallint convertToSmallint(Object column) {
1529 switch (getValueType()) {
1530 case SMALLINT:
1531 return (ValueSmallint) this;
1532 case CHAR:
1533 case VARCHAR:
1534 case VARCHAR_IGNORECASE:
1535 case BOOLEAN:
1536 case TINYINT:
1537 return ValueSmallint.get(getShort());
1538 case ENUM:
1539 case INTEGER:
1540 return ValueSmallint.get(convertToShort(getInt(), column));
1541 case BIGINT:
1542 case INTERVAL_YEAR:
1543 case INTERVAL_MONTH:
1544 case INTERVAL_DAY:
1545 case INTERVAL_HOUR:
1546 case INTERVAL_MINUTE:
1547 case INTERVAL_SECOND:
1548 case INTERVAL_YEAR_TO_MONTH:
1549 case INTERVAL_DAY_TO_HOUR:
1550 case INTERVAL_DAY_TO_MINUTE:
1551 case INTERVAL_DAY_TO_SECOND:
1552 case INTERVAL_HOUR_TO_MINUTE:
1553 case INTERVAL_HOUR_TO_SECOND:
1554 case INTERVAL_MINUTE_TO_SECOND:
1555 return ValueSmallint.get(convertToShort(getLong(), column));
1556 case NUMERIC:
1557 case DECFLOAT:
1558 return ValueSmallint.get(convertToShort(convertToLong(getBigDecimal(), column), column));
1559 case REAL:
1560 case DOUBLE:
1561 return ValueSmallint.get(convertToShort(convertToLong(getDouble(), column), column));
1562 case BINARY:
1563 case VARBINARY: {
1564 byte[] bytes = getBytesNoCopy();
1565 if (bytes.length == 2) {
1566 return ValueSmallint.get((short) ((bytes[0] << 8) + (bytes[1] & 0xff)));
1567 }
1568 }
1569 //$FALL-THROUGH$
1570 default:
1571 throw getDataConversionError(SMALLINT);
1572 case NULL:
1573 throw DbException.getInternalError();
1574 }
1575 }
1576
1577 /**
1578 * Converts this value to a INT value. May not be called on a NULL value.
1579 *
1580 * @param column
1581 * the column, used for to improve the error message if
1582 * conversion fails
1583 * @return the INT value
1584 */
1585 public final ValueInteger convertToInt(Object column) {
1586 switch (getValueType()) {
1587 case INTEGER:
1588 return (ValueInteger) this;
1589 case CHAR:
1590 case VARCHAR:
1591 case VARCHAR_IGNORECASE:
1592 case BOOLEAN:
1593 case TINYINT:
1594 case ENUM:
1595 case SMALLINT:
1596 return ValueInteger.get(getInt());
1597 case BIGINT:
1598 case INTERVAL_YEAR:
1599 case INTERVAL_MONTH:
1600 case INTERVAL_DAY:
1601 case INTERVAL_HOUR:
1602 case INTERVAL_MINUTE:
1603 case INTERVAL_SECOND:
1604 case INTERVAL_YEAR_TO_MONTH:
1605 case INTERVAL_DAY_TO_HOUR:
1606 case INTERVAL_DAY_TO_MINUTE:
1607 case INTERVAL_DAY_TO_SECOND:
1608 case INTERVAL_HOUR_TO_MINUTE:
1609 case INTERVAL_HOUR_TO_SECOND:
1610 case INTERVAL_MINUTE_TO_SECOND:
1611 return ValueInteger.get(convertToInt(getLong(), column));
1612 case NUMERIC:
1613 case DECFLOAT:
1614 return ValueInteger.get(convertToInt(convertToLong(getBigDecimal(), column), column));
1615 case REAL:
1616 case DOUBLE:
1617 return ValueInteger.get(convertToInt(convertToLong(getDouble(), column), column));
1618 case BINARY:
1619 case VARBINARY: {
1620 byte[] bytes = getBytesNoCopy();
1621 if (bytes.length == 4) {
1622 return ValueInteger.get(Bits.readInt(bytes, 0));
1623 }
1624 }
1625 //$FALL-THROUGH$
1626 default:
1627 throw getDataConversionError(INTEGER);
1628 case NULL:
1629 throw DbException.getInternalError();
1630 }
1631 }
1632
1633 /**
1634 * Converts this value to a BIGINT value. May not be called on a NULL value.
1635 *
1636 * @param column
1637 * the column, used for to improve the error message if
1638 * conversion fails
1639 * @return the BIGINT value
1640 */
1641 public final ValueBigint convertToBigint(Object column) {
1642 switch (getValueType()) {
1643 case BIGINT:
1644 return (ValueBigint) this;
1645 case CHAR:
1646 case VARCHAR:
1647 case VARCHAR_IGNORECASE:
1648 case BOOLEAN:
1649 case TINYINT:
1650 case SMALLINT:
1651 case INTEGER:
1652 case INTERVAL_YEAR:
1653 case INTERVAL_MONTH:
1654 case INTERVAL_DAY:
1655 case INTERVAL_HOUR:
1656 case INTERVAL_MINUTE:
1657 case INTERVAL_SECOND:
1658 case INTERVAL_YEAR_TO_MONTH:
1659 case INTERVAL_DAY_TO_HOUR:
1660 case INTERVAL_DAY_TO_MINUTE:
1661 case INTERVAL_DAY_TO_SECOND:
1662 case INTERVAL_HOUR_TO_MINUTE:
1663 case INTERVAL_HOUR_TO_SECOND:
1664 case INTERVAL_MINUTE_TO_SECOND:
1665 case ENUM:
1666 return ValueBigint.get(getLong());
1667 case NUMERIC:
1668 case DECFLOAT:
1669 return ValueBigint.get(convertToLong(getBigDecimal(), column));
1670 case REAL:
1671 case DOUBLE:
1672 return ValueBigint.get(convertToLong(getDouble(), column));
1673 case BINARY:
1674 case VARBINARY: {
1675 byte[] bytes = getBytesNoCopy();
1676 if (bytes.length == 8) {
1677 return ValueBigint.get(Bits.readLong(bytes, 0));
1678 }
1679 }
1680 //$FALL-THROUGH$
1681 default:
1682 throw getDataConversionError(BIGINT);
1683 case NULL:
1684 throw DbException.getInternalError();
1685 }
1686 }
1687
1688 private ValueNumeric convertToNumeric(TypeInfo targetType, CastDataProvider provider, int conversionMode,
1689 Object column) {
1690 ValueNumeric v;
1691 switch (getValueType()) {
1692 case NUMERIC:
1693 v = (ValueNumeric) this;
1694 break;
1695 case BOOLEAN:
1696 v = getBoolean() ? ValueNumeric.ONE : ValueNumeric.ZERO;
1697 break;
1698 default: {
1699 BigDecimal value = getBigDecimal();
1700 int targetScale = targetType.getScale();
1701 int scale = value.scale();
1702 if (scale < 0 || scale > ValueNumeric.MAXIMUM_SCALE || conversionMode != CONVERT_TO && scale != targetScale
1703 && (scale >= targetScale || !provider.getMode().convertOnlyToSmallerScale)) {
1704 value = ValueNumeric.setScale(value, targetScale);
1705 }
1706 if (conversionMode != CONVERT_TO
1707 && value.precision() > targetType.getPrecision() - targetScale + value.scale()) {
1708 throw getValueTooLongException(targetType, column);
1709 }
1710 return ValueNumeric.get(value);
1711 }
1712 case NULL:
1713 throw DbException.getInternalError();
1714 }
1715 if (conversionMode != CONVERT_TO) {
1716 int targetScale = targetType.getScale();
1717 BigDecimal value = v.getBigDecimal();
1718 int scale = value.scale();
1719 if (scale != targetScale && (scale >= targetScale || !provider.getMode().convertOnlyToSmallerScale)) {
1720 v = ValueNumeric.get(ValueNumeric.setScale(value, targetScale));
1721 }
1722 BigDecimal bd = v.getBigDecimal();
1723 if (bd.precision() > targetType.getPrecision() - targetScale + bd.scale()) {
1724 throw v.getValueTooLongException(targetType, column);
1725 }
1726 }
1727 return v;
1728 }
1729
1730 /**
1731 * Converts this value to a REAL value. May not be called on a NULL value.
1732 *
1733 * @return the REAL value
1734 */
1735 public final ValueReal convertToReal() {
1736 switch (getValueType()) {
1737 case REAL:
1738 return (ValueReal) this;
1739 case BOOLEAN:
1740 return getBoolean() ? ValueReal.ONE : ValueReal.ZERO;
1741 default:
1742 return ValueReal.get(getFloat());
1743 case NULL:
1744 throw DbException.getInternalError();
1745 }
1746 }
1747
1748 /**
1749 * Converts this value to a DOUBLE value. May not be called on a NULL value.
1750 *
1751 * @return the DOUBLE value
1752 */
1753 public final ValueDouble convertToDouble() {
1754 switch (getValueType()) {
1755 case DOUBLE:
1756 return (ValueDouble) this;
1757 case BOOLEAN:
1758 return getBoolean() ? ValueDouble.ONE : ValueDouble.ZERO;
1759 default:
1760 return ValueDouble.get(getDouble());
1761 case NULL:
1762 throw DbException.getInternalError();
1763 }
1764 }
1765
1766 private ValueDecfloat convertToDecfloat(TypeInfo targetType, int conversionMode) {
1767 ValueDecfloat v;
1768 switch (getValueType()) {
1769 case DECFLOAT:
1770 v = (ValueDecfloat) this;
1771 if (v.value == null) {
1772 return v;
1773 }
1774 break;
1775 case CHAR:
1776 case VARCHAR:
1777 case VARCHAR_IGNORECASE: {
1778 String s = getString().trim();
1779 try {
1780 v = ValueDecfloat.get(new BigDecimal(s));
1781 } catch (NumberFormatException e) {
1782 switch (s) {
1783 case "-Infinity":
1784 return ValueDecfloat.NEGATIVE_INFINITY;
1785 case "Infinity":
1786 case "+Infinity":
1787 return ValueDecfloat.POSITIVE_INFINITY;
1788 case "NaN":
1789 case "-NaN":
1790 case "+NaN":
1791 return ValueDecfloat.NAN;
1792 default:
1793 throw getDataConversionError(DECFLOAT);
1794 }
1795 }
1796 break;
1797 }
1798 case BOOLEAN:
1799 v = getBoolean() ? ValueDecfloat.ONE : ValueDecfloat.ZERO;
1800 break;
1801 case REAL: {
1802 float value = getFloat();
1803 if (Float.isFinite(value)) {
1804 v = ValueDecfloat.get(new BigDecimal(Float.toString(value)));
1805 } else if (value == Float.POSITIVE_INFINITY) {
1806 return ValueDecfloat.POSITIVE_INFINITY;
1807 } else if (value == Float.NEGATIVE_INFINITY) {
1808 return ValueDecfloat.NEGATIVE_INFINITY;
1809 } else {
1810 return ValueDecfloat.NAN;
1811 }
1812 break;
1813 }
1814 case DOUBLE: {
1815 double value = getDouble();
1816 if (Double.isFinite(value)) {
1817 v = ValueDecfloat.get(new BigDecimal(Double.toString(value)));
1818 } else if (value == Double.POSITIVE_INFINITY) {
1819 return ValueDecfloat.POSITIVE_INFINITY;
1820 } else if (value == Double.NEGATIVE_INFINITY) {
1821 return ValueDecfloat.NEGATIVE_INFINITY;
1822 } else {
1823 return ValueDecfloat.NAN;
1824 }
1825 break;
1826 }
1827 default:
1828 try {
1829 v = ValueDecfloat.get(getBigDecimal());
1830 } catch (DbException e) {
1831 if (e.getErrorCode() == ErrorCode.DATA_CONVERSION_ERROR_1) {
1832 throw getDataConversionError(DECFLOAT);
1833 }
1834 throw e;
1835 }
1836 break;
1837 case NULL:
1838 throw DbException.getInternalError();
1839 }
1840 if (conversionMode != CONVERT_TO) {
1841 BigDecimal bd = v.value;
1842 int precision = bd.precision(), targetPrecision = (int) targetType.getPrecision();
1843 if (precision > targetPrecision) {
1844 v = ValueDecfloat.get(bd.setScale(bd.scale() - precision + targetPrecision, RoundingMode.HALF_UP));
1845 }
1846 }
1847 return v;
1848 }
1849
1850 /**
1851 * Converts this value to a DATE value. May not be called on a NULL value.
1852 *
1853 * @param provider
1854 * the cast information provider
1855 * @return the DATE value
1856 */
1857 public final ValueDate convertToDate(CastDataProvider provider) {
1858 switch (getValueType()) {
1859 case DATE:
1860 return (ValueDate) this;
1861 case TIMESTAMP:
1862 return ValueDate.fromDateValue(((ValueTimestamp) this).getDateValue());
1863 case TIMESTAMP_TZ: {
1864 ValueTimestampTimeZone ts = (ValueTimestampTimeZone) this;
1865 long timeNanos = ts.getTimeNanos();
1866 long epochSeconds = DateTimeUtils.getEpochSeconds(ts.getDateValue(), timeNanos,
1867 ts.getTimeZoneOffsetSeconds());
1868 return ValueDate.fromDateValue(DateTimeUtils
1869 .dateValueFromLocalSeconds(epochSeconds
1870 + provider.currentTimeZone().getTimeZoneOffsetUTC(epochSeconds)));
1871 }
1872 case VARCHAR:
1873 case VARCHAR_IGNORECASE:
1874 case CHAR:
1875 return ValueDate.parse(getString().trim());
1876 default:
1877 throw getDataConversionError(DATE);
1878 case NULL:
1879 throw DbException.getInternalError();
1880 }
1881 }
1882
1883 private ValueTime convertToTime(TypeInfo targetType, CastDataProvider provider, int conversionMode) {
1884 ValueTime v;
1885 switch (getValueType()) {
1886 case TIME:
1887 v = (ValueTime) this;
1888 break;
1889 case TIME_TZ:
1890 v = ValueTime.fromNanos(getLocalTimeNanos(provider));
1891 break;
1892 case TIMESTAMP:
1893 v = ValueTime.fromNanos(((ValueTimestamp) this).getTimeNanos());
1894 break;
1895 case TIMESTAMP_TZ: {
1896 ValueTimestampTimeZone ts = (ValueTimestampTimeZone) this;
1897 long timeNanos = ts.getTimeNanos();
1898 long epochSeconds = DateTimeUtils.getEpochSeconds(ts.getDateValue(), timeNanos,
1899 ts.getTimeZoneOffsetSeconds());
1900 v = ValueTime.fromNanos(
1901 DateTimeUtils.nanosFromLocalSeconds(epochSeconds
1902 + provider.currentTimeZone().getTimeZoneOffsetUTC(epochSeconds))
1903 + timeNanos % DateTimeUtils.NANOS_PER_SECOND);
1904 break;
1905 }
1906 case VARCHAR:
1907 case VARCHAR_IGNORECASE:
1908 case CHAR:
1909 v = ValueTime.parse(getString().trim(), provider);
1910 break;
1911 default:
1912 throw getDataConversionError(TIME);
1913 }
1914 if (conversionMode != CONVERT_TO) {
1915 int targetScale = targetType.getScale();
1916 if (targetScale < ValueTime.MAXIMUM_SCALE) {
1917 long n = v.getNanos();
1918 long n2 = DateTimeUtils.convertScale(n, targetScale, DateTimeUtils.NANOS_PER_DAY);
1919 if (n2 != n) {
1920 v = ValueTime.fromNanos(n2);
1921 }
1922 }
1923 }
1924 return v;
1925 }
1926
1927 private ValueTimeTimeZone convertToTimeTimeZone(TypeInfo targetType, CastDataProvider provider,
1928 int conversionMode) {
1929 ValueTimeTimeZone v;
1930 switch (getValueType()) {
1931 case TIME_TZ:
1932 v = (ValueTimeTimeZone) this;
1933 break;
1934 case TIME:
1935 v = ValueTimeTimeZone.fromNanos(((ValueTime) this).getNanos(),
1936 provider.currentTimestamp().getTimeZoneOffsetSeconds());
1937 break;
1938 case TIMESTAMP: {
1939 ValueTimestamp ts = (ValueTimestamp) this;
1940 long timeNanos = ts.getTimeNanos();
1941 v = ValueTimeTimeZone.fromNanos(timeNanos,
1942 provider.currentTimeZone().getTimeZoneOffsetLocal(ts.getDateValue(), timeNanos));
1943 break;
1944 }
1945 case TIMESTAMP_TZ: {
1946 ValueTimestampTimeZone ts = (ValueTimestampTimeZone) this;
1947 v = ValueTimeTimeZone.fromNanos(ts.getTimeNanos(), ts.getTimeZoneOffsetSeconds());
1948 break;
1949 }
1950 case VARCHAR:
1951 case VARCHAR_IGNORECASE:
1952 case CHAR:
1953 v = ValueTimeTimeZone.parse(getString().trim(), provider);
1954 break;
1955 default:
1956 throw getDataConversionError(TIME_TZ);
1957 }
1958 if (conversionMode != CONVERT_TO) {
1959 int targetScale = targetType.getScale();
1960 if (targetScale < ValueTime.MAXIMUM_SCALE) {
1961 long n = v.getNanos();
1962 long n2 = DateTimeUtils.convertScale(n, targetScale, DateTimeUtils.NANOS_PER_DAY);
1963 if (n2 != n) {
1964 v = ValueTimeTimeZone.fromNanos(n2, v.getTimeZoneOffsetSeconds());
1965 }
1966 }
1967 }
1968 return v;
1969 }
1970
1971 private ValueTimestamp convertToTimestamp(TypeInfo targetType, CastDataProvider provider, int conversionMode) {
1972 ValueTimestamp v;
1973 switch (getValueType()) {
1974 case TIMESTAMP:
1975 v = (ValueTimestamp) this;
1976 break;
1977 case TIME:
1978 v = ValueTimestamp.fromDateValueAndNanos(provider.currentTimestamp().getDateValue(),
1979 ((ValueTime) this).getNanos());
1980 break;
1981 case TIME_TZ:
1982 v = ValueTimestamp.fromDateValueAndNanos(provider.currentTimestamp().getDateValue(),
1983 getLocalTimeNanos(provider));
1984 break;
1985 case DATE:
1986 // Scale is always 0
1987 return ValueTimestamp.fromDateValueAndNanos(((ValueDate) this).getDateValue(), 0);
1988 case TIMESTAMP_TZ: {
1989 ValueTimestampTimeZone ts = (ValueTimestampTimeZone) this;
1990 long timeNanos = ts.getTimeNanos();
1991 long epochSeconds = DateTimeUtils.getEpochSeconds(ts.getDateValue(), timeNanos,
1992 ts.getTimeZoneOffsetSeconds());
1993 epochSeconds += provider.currentTimeZone().getTimeZoneOffsetUTC(epochSeconds);
1994 v = ValueTimestamp.fromDateValueAndNanos(DateTimeUtils.dateValueFromLocalSeconds(epochSeconds),
1995 DateTimeUtils.nanosFromLocalSeconds(epochSeconds) + timeNanos % DateTimeUtils.NANOS_PER_SECOND);
1996 break;
1997 }
1998 case VARCHAR:
1999 case VARCHAR_IGNORECASE:
2000 case CHAR:
2001 v = ValueTimestamp.parse(getString().trim(), provider);
2002 break;
2003 default:
2004 throw getDataConversionError(TIMESTAMP);
2005 }
2006 if (conversionMode != CONVERT_TO) {
2007 int targetScale = targetType.getScale();
2008 if (targetScale < ValueTimestamp.MAXIMUM_SCALE) {
2009 long dv = v.getDateValue(), n = v.getTimeNanos();
2010 long n2 = DateTimeUtils.convertScale(n, targetScale,
2011 dv == DateTimeUtils.MAX_DATE_VALUE ? DateTimeUtils.NANOS_PER_DAY : Long.MAX_VALUE);
2012 if (n2 != n) {
2013 if (n2 >= DateTimeUtils.NANOS_PER_DAY) {
2014 n2 -= DateTimeUtils.NANOS_PER_DAY;
2015 dv = DateTimeUtils.incrementDateValue(dv);
2016 }
2017 v = ValueTimestamp.fromDateValueAndNanos(dv, n2);
2018 }
2019 }
2020 }
2021 return v;
2022 }
2023
2024 private long getLocalTimeNanos(CastDataProvider provider) {
2025 ValueTimeTimeZone ts = (ValueTimeTimeZone) this;
2026 int localOffset = provider.currentTimestamp().getTimeZoneOffsetSeconds();
2027 return DateTimeUtils.normalizeNanosOfDay(ts.getNanos() +
2028 (localOffset - ts.getTimeZoneOffsetSeconds()) * DateTimeUtils.NANOS_PER_SECOND);
2029 }
2030
2031 private ValueTimestampTimeZone convertToTimestampTimeZone(TypeInfo targetType, CastDataProvider provider,
2032 int conversionMode) {
2033 ValueTimestampTimeZone v;
2034 switch (getValueType()) {
2035 case TIMESTAMP_TZ:
2036 v = (ValueTimestampTimeZone) this;
2037 break;
2038 case TIME: {
2039 long dateValue = provider.currentTimestamp().getDateValue();
2040 long timeNanos = ((ValueTime) this).getNanos();
2041 v = ValueTimestampTimeZone.fromDateValueAndNanos(dateValue, timeNanos,
2042 provider.currentTimeZone().getTimeZoneOffsetLocal(dateValue, timeNanos));
2043 break;
2044 }
2045 case TIME_TZ: {
2046 ValueTimeTimeZone t = (ValueTimeTimeZone) this;
2047 v = ValueTimestampTimeZone.fromDateValueAndNanos(provider.currentTimestamp().getDateValue(),
2048 t.getNanos(), t.getTimeZoneOffsetSeconds());
2049 break;
2050 }
2051 case DATE: {
2052 long dateValue = ((ValueDate) this).getDateValue();
2053 // Scale is always 0
2054 return ValueTimestampTimeZone.fromDateValueAndNanos(dateValue, 0L,
2055 provider.currentTimeZone().getTimeZoneOffsetLocal(dateValue, 0L));
2056 }
2057 case TIMESTAMP: {
2058 ValueTimestamp ts = (ValueTimestamp) this;
2059 long dateValue = ts.getDateValue();
2060 long timeNanos = ts.getTimeNanos();
2061 v = ValueTimestampTimeZone.fromDateValueAndNanos(dateValue, timeNanos,
2062 provider.currentTimeZone().getTimeZoneOffsetLocal(dateValue, timeNanos));
2063 break;
2064 }
2065 case VARCHAR:
2066 case VARCHAR_IGNORECASE:
2067 case CHAR:
2068 v = ValueTimestampTimeZone.parse(getString().trim(), provider);
2069 break;
2070 default:
2071 throw getDataConversionError(TIMESTAMP_TZ);
2072 }
2073 if (conversionMode != CONVERT_TO) {
2074 int targetScale = targetType.getScale();
2075 if (targetScale < ValueTimestamp.MAXIMUM_SCALE) {
2076 long dv = v.getDateValue();
2077 long n = v.getTimeNanos();
2078 long n2 = DateTimeUtils.convertScale(n, targetScale,
2079 dv == DateTimeUtils.MAX_DATE_VALUE ? DateTimeUtils.NANOS_PER_DAY : Long.MAX_VALUE);
2080 if (n2 != n) {
2081 if (n2 >= DateTimeUtils.NANOS_PER_DAY) {
2082 n2 -= DateTimeUtils.NANOS_PER_DAY;
2083 dv = DateTimeUtils.incrementDateValue(dv);
2084 }
2085 v = ValueTimestampTimeZone.fromDateValueAndNanos(dv, n2, v.getTimeZoneOffsetSeconds());
2086 }
2087 }
2088 }
2089 return v;
2090 }
2091
2092 private ValueInterval convertToIntervalYearMonth(TypeInfo targetType, int conversionMode, Object column) {
2093 ValueInterval v = convertToIntervalYearMonth(targetType.getValueType(), column);
2094 if (conversionMode != CONVERT_TO) {
2095 if (!v.checkPrecision(targetType.getPrecision())) {
2096 throw v.getValueTooLongException(targetType, column);
2097 }
2098 }
2099 return v;
2100 }
2101
2102 private ValueInterval convertToIntervalYearMonth(int targetType, Object column) {
2103 long leading;
2104 switch (getValueType()) {
2105 case TINYINT:
2106 case SMALLINT:
2107 case INTEGER:
2108 leading = getInt();
2109 break;
2110 case BIGINT:
2111 leading = getLong();
2112 break;
2113 case REAL:
2114 case DOUBLE:
2115 if (targetType == INTERVAL_YEAR_TO_MONTH) {
2116 return IntervalUtils.intervalFromAbsolute(IntervalQualifier.YEAR_TO_MONTH, getBigDecimal()
2117 .multiply(BigDecimal.valueOf(12)).setScale(0, RoundingMode.HALF_UP).toBigInteger());
2118 }
2119 leading = convertToLong(getDouble(), column);
2120 break;
2121 case NUMERIC:
2122 case DECFLOAT:
2123 if (targetType == INTERVAL_YEAR_TO_MONTH) {
2124 return IntervalUtils.intervalFromAbsolute(IntervalQualifier.YEAR_TO_MONTH, getBigDecimal()
2125 .multiply(BigDecimal.valueOf(12)).setScale(0, RoundingMode.HALF_UP).toBigInteger());
2126 }
2127 leading = convertToLong(getBigDecimal(), column);
2128 break;
2129 case VARCHAR:
2130 case VARCHAR_IGNORECASE:
2131 case CHAR: {
2132 String s = getString();
2133 try {
2134 return (ValueInterval) IntervalUtils
2135 .parseFormattedInterval(IntervalQualifier.valueOf(targetType - INTERVAL_YEAR), s)
2136 .convertTo(targetType);
2137 } catch (Exception e) {
2138 throw DbException.get(ErrorCode.INVALID_DATETIME_CONSTANT_2, e, "INTERVAL", s);
2139 }
2140 }
2141 case INTERVAL_YEAR:
2142 case INTERVAL_MONTH:
2143 case INTERVAL_YEAR_TO_MONTH:
2144 return IntervalUtils.intervalFromAbsolute(IntervalQualifier.valueOf(targetType - INTERVAL_YEAR),
2145 IntervalUtils.intervalToAbsolute((ValueInterval) this));
2146 default:
2147 throw getDataConversionError(targetType);
2148 }
2149 boolean negative = false;
2150 if (leading < 0) {
2151 negative = true;
2152 leading = -leading;
2153 }
2154 return ValueInterval.from(IntervalQualifier.valueOf(targetType - INTERVAL_YEAR), negative, leading,
2155 0L);
2156 }
2157
2158 private ValueInterval convertToIntervalDayTime(TypeInfo targetType, int conversionMode, Object column) {
2159 ValueInterval v = convertToIntervalDayTime(targetType.getValueType(), column);
2160 if (conversionMode != CONVERT_TO) {
2161 v = v.setPrecisionAndScale(targetType, column);
2162 }
2163 return v;
2164 }
2165
2166 private ValueInterval convertToIntervalDayTime(int targetType, Object column) {
2167 long leading;
2168 switch (getValueType()) {
2169 case TINYINT:
2170 case SMALLINT:
2171 case INTEGER:
2172 leading = getInt();
2173 break;
2174 case BIGINT:
2175 leading = getLong();
2176 break;
2177 case REAL:
2178 case DOUBLE:
2179 if (targetType > INTERVAL_MINUTE) {
2180 return convertToIntervalDayTime(getBigDecimal(), targetType);
2181 }
2182 leading = convertToLong(getDouble(), column);
2183 break;
2184 case NUMERIC:
2185 case DECFLOAT:
2186 if (targetType > INTERVAL_MINUTE) {
2187 return convertToIntervalDayTime(getBigDecimal(), targetType);
2188 }
2189 leading = convertToLong(getBigDecimal(), column);
2190 break;
2191 case VARCHAR:
2192 case VARCHAR_IGNORECASE:
2193 case CHAR: {
2194 String s = getString();
2195 try {
2196 return (ValueInterval) IntervalUtils
2197 .parseFormattedInterval(IntervalQualifier.valueOf(targetType - INTERVAL_YEAR), s)
2198 .convertTo(targetType);
2199 } catch (Exception e) {
2200 throw DbException.get(ErrorCode.INVALID_DATETIME_CONSTANT_2, e, "INTERVAL", s);
2201 }
2202 }
2203 case INTERVAL_DAY:
2204 case INTERVAL_HOUR:
2205 case INTERVAL_MINUTE:
2206 case INTERVAL_SECOND:
2207 case INTERVAL_DAY_TO_HOUR:
2208 case INTERVAL_DAY_TO_MINUTE:
2209 case INTERVAL_DAY_TO_SECOND:
2210 case INTERVAL_HOUR_TO_MINUTE:
2211 case INTERVAL_HOUR_TO_SECOND:
2212 case INTERVAL_MINUTE_TO_SECOND:
2213 return IntervalUtils.intervalFromAbsolute(IntervalQualifier.valueOf(targetType - INTERVAL_YEAR),
2214 IntervalUtils.intervalToAbsolute((ValueInterval) this));
2215 default:
2216 throw getDataConversionError(targetType);
2217 }
2218 boolean negative = false;
2219 if (leading < 0) {
2220 negative = true;
2221 leading = -leading;
2222 }
2223 return ValueInterval.from(IntervalQualifier.valueOf(targetType - INTERVAL_YEAR), negative, leading,
2224 0L);
2225 }
2226
2227 private ValueInterval convertToIntervalDayTime(BigDecimal bigDecimal, int targetType) {
2228 long multiplier;
2229 switch (targetType) {
2230 case INTERVAL_SECOND:
2231 multiplier = DateTimeUtils.NANOS_PER_SECOND;
2232 break;
2233 case INTERVAL_DAY_TO_HOUR:
2234 case INTERVAL_DAY_TO_MINUTE:
2235 case INTERVAL_DAY_TO_SECOND:
2236 multiplier = DateTimeUtils.NANOS_PER_DAY;
2237 break;
2238 case INTERVAL_HOUR_TO_MINUTE:
2239 case INTERVAL_HOUR_TO_SECOND:
2240 multiplier = DateTimeUtils.NANOS_PER_HOUR;
2241 break;
2242 case INTERVAL_MINUTE_TO_SECOND:
2243 multiplier = DateTimeUtils.NANOS_PER_MINUTE;
2244 break;
2245 default:
2246 throw getDataConversionError(targetType);
2247 }
2248 return IntervalUtils.intervalFromAbsolute(IntervalQualifier.valueOf(targetType - INTERVAL_YEAR),
2249 bigDecimal.multiply(BigDecimal.valueOf(multiplier)).setScale(0, RoundingMode.HALF_UP).toBigInteger());
2250 }
2251
2252 /**
2253 * Converts this value to a JAVA_OBJECT value. May not be called on a NULL
2254 * value.
2255 *
2256 * @param targetType
2257 * the type of the returned value
2258 * @param conversionMode
2259 * conversion mode
2260 * @param column
2261 * the column (if any), used to improve the error message if
2262 * conversion fails
2263 * @return the JAVA_OBJECT value
2264 */
2265 public final ValueJavaObject convertToJavaObject(TypeInfo targetType, int conversionMode, Object column) {
2266 ValueJavaObject v;
2267 switch (getValueType()) {
2268 case JAVA_OBJECT:
2269 v = (ValueJavaObject) this;
2270 break;
2271 case BINARY:
2272 case VARBINARY:
2273 case BLOB:
2274 v = ValueJavaObject.getNoCopy(getBytesNoCopy());
2275 break;
2276 default:
2277 throw getDataConversionError(JAVA_OBJECT);
2278 case NULL:
2279 throw DbException.getInternalError();
2280 }
2281 if (conversionMode != CONVERT_TO && v.getBytesNoCopy().length > targetType.getPrecision()) {
2282 throw v.getValueTooLongException(targetType, column);
2283 }
2284 return v;
2285 }
2286
2287 /**
2288 * Converts this value to an ENUM value. May not be called on a NULL value.
2289 *
2290 * @param extTypeInfo
2291 * the extended data type information
2292 * @param provider
2293 * the cast information provider
2294 * @return the ENUM value
2295 */
2296 public final ValueEnum convertToEnum(ExtTypeInfoEnum extTypeInfo, CastDataProvider provider) {
2297 switch (getValueType()) {
2298 case ENUM: {
2299 ValueEnum v = (ValueEnum) this;
2300 if (extTypeInfo.equals(v.getEnumerators())) {
2301 return v;
2302 }
2303 return extTypeInfo.getValue(v.getString(), provider);
2304 }
2305 case TINYINT:
2306 case SMALLINT:
2307 case INTEGER:
2308 case BIGINT:
2309 case NUMERIC:
2310 case DECFLOAT:
2311 return extTypeInfo.getValue(getInt(), provider);
2312 case VARCHAR:
2313 case VARCHAR_IGNORECASE:
2314 case CHAR:
2315 return extTypeInfo.getValue(getString(), provider);
2316 default:
2317 throw getDataConversionError(ENUM);
2318 case NULL:
2319 throw DbException.getInternalError();
2320 }
2321 }
2322
2323 /**
2324 * Converts this value to a GEOMETRY value. May not be called on a NULL
2325 * value.
2326 *
2327 * @param extTypeInfo
2328 * the extended data type information, or null
2329 * @return the GEOMETRY value
2330 */
2331 public final ValueGeometry convertToGeometry(ExtTypeInfoGeometry extTypeInfo) {
2332 ValueGeometry result;
2333 switch (getValueType()) {
2334 case GEOMETRY:
2335 result = (ValueGeometry) this;
2336 break;
2337 case BINARY:
2338 case VARBINARY:
2339 case BLOB:
2340 result = ValueGeometry.getFromEWKB(getBytesNoCopy());
2341 break;
2342 case JSON: {
2343 int srid = 0;
2344 if (extTypeInfo != null) {
2345 Integer s = extTypeInfo.getSrid();
2346 if (s != null) {
2347 srid = s;
2348 }
2349 }
2350 try {
2351 result = ValueGeometry.get(GeoJsonUtils.geoJsonToEwkb(getBytesNoCopy(), srid));
2352 } catch (RuntimeException ex) {
2353 throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, getTraceSQL());
2354 }
2355 break;
2356 }
2357 case CHAR:
2358 case VARCHAR:
2359 case CLOB:
2360 case VARCHAR_IGNORECASE:
2361 result = ValueGeometry.get(getString());
2362 break;
2363 default:
2364 throw getDataConversionError(GEOMETRY);
2365 case NULL:
2366 throw DbException.getInternalError();
2367 }
2368 if (extTypeInfo != null) {
2369 int type = extTypeInfo.getType();
2370 Integer srid = extTypeInfo.getSrid();
2371 if (type != 0 && result.getTypeAndDimensionSystem() != type || srid != null && result.getSRID() != srid) {
2372 StringBuilder builder = ExtTypeInfoGeometry
2373 .toSQL(new StringBuilder(), result.getTypeAndDimensionSystem(), result.getSRID())
2374 .append(" -> ");
2375 extTypeInfo.getSQL(builder, TRACE_SQL_FLAGS);
2376 throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, builder.toString());
2377 }
2378 }
2379 return result;
2380 }
2381
2382 private ValueJson convertToJson(TypeInfo targetType, int conversionMode, Object column) {
2383 ValueJson v;
2384 switch (getValueType()) {
2385 case JSON:
2386 v = (ValueJson) this;
2387 break;
2388 case BOOLEAN:
2389 v = ValueJson.get(getBoolean());
2390 break;
2391 case TINYINT:
2392 case SMALLINT:
2393 case INTEGER:
2394 v = ValueJson.get(getInt());
2395 break;
2396 case BIGINT:
2397 v = ValueJson.get(getLong());
2398 break;
2399 case REAL:
2400 case DOUBLE:
2401 case NUMERIC:
2402 case DECFLOAT:
2403 v = ValueJson.get(getBigDecimal());
2404 break;
2405 case BINARY:
2406 case VARBINARY:
2407 case BLOB:
2408 v = ValueJson.fromJson(getBytesNoCopy());
2409 break;
2410 case CHAR:
2411 case VARCHAR:
2412 case CLOB:
2413 case VARCHAR_IGNORECASE:
2414 case DATE:
2415 case TIME:
2416 case TIME_TZ:
2417 case ENUM:
2418 case UUID:
2419 v = ValueJson.get(getString());
2420 break;
2421 case TIMESTAMP:
2422 v = ValueJson.get(((ValueTimestamp) this).getISOString());
2423 break;
2424 case TIMESTAMP_TZ:
2425 v = ValueJson.get(((ValueTimestampTimeZone) this).getISOString());
2426 break;
2427 case GEOMETRY: {
2428 ValueGeometry vg = (ValueGeometry) this;
2429 v = ValueJson.getInternal(GeoJsonUtils.ewkbToGeoJson(vg.getBytesNoCopy(), vg.getDimensionSystem()));
2430 break;
2431 }
2432 case ARRAY: {
2433 ByteArrayOutputStream baos = new ByteArrayOutputStream();
2434 baos.write('[');
2435 for (Value e : ((ValueArray) this).getList()) {
2436 JsonConstructorUtils.jsonArrayAppend(baos, e, 0);
2437 }
2438 baos.write(']');
2439 v = ValueJson.getInternal(baos.toByteArray());
2440 break;
2441 }
2442 default:
2443 throw getDataConversionError(JSON);
2444 }
2445 if (conversionMode != CONVERT_TO && v.getBytesNoCopy().length > targetType.getPrecision()) {
2446 throw v.getValueTooLongException(targetType, column);
2447 }
2448 return v;
2449 }
2450
2451 /**
2452 * Converts this value to a UUID value. May not be called on a NULL value.
2453 *
2454 * @return the UUID value
2455 */
2456 public final ValueUuid convertToUuid() {
2457 switch (getValueType()) {
2458 case UUID:
2459 return (ValueUuid) this;
2460 case BINARY:
2461 case VARBINARY:
2462 return ValueUuid.get(getBytesNoCopy());
2463 case JAVA_OBJECT:
2464 return JdbcUtils.deserializeUuid(getBytesNoCopy());
2465 case CHAR:
2466 case VARCHAR:
2467 case VARCHAR_IGNORECASE:
2468 return ValueUuid.get(getString());
2469 default:
2470 throw getDataConversionError(UUID);
2471 case NULL:
2472 throw DbException.getInternalError();
2473 }
2474 }
2475
2476 private ValueArray convertToArray(TypeInfo targetType, CastDataProvider provider, int conversionMode,
2477 Object column) {
2478 TypeInfo componentType = (TypeInfo) targetType.getExtTypeInfo();
2479 int valueType = getValueType();
2480 ValueArray v;
2481 if (valueType == ARRAY) {
2482 v = (ValueArray) this;
2483 } else {
2484 Value[] a;
2485 switch (valueType) {
2486 case BLOB:
2487 a = new Value[] { ValueVarbinary.get(getBytesNoCopy()) };
2488 break;
2489 case CLOB:
2490 a = new Value[] { ValueVarchar.get(getString()) };
2491 break;
2492 default:
2493 a = new Value[] { this };
2494 }
2495 v = ValueArray.get(a, provider);
2496 }
2497 if (componentType != null) {
2498 Value[] values = v.getList();
2499 int length = values.length;
2500 loop: for (int i = 0; i < length; i++) {
2501 Value v1 = values[i];
2502 Value v2 = v1.convertTo(componentType, provider, conversionMode, column);
2503 if (v1 != v2) {
2504 Value[] newValues = new Value[length];
2505 System.arraycopy(values, 0, newValues, 0, i);
2506 newValues[i] = v2;
2507 while (++i < length) {
2508 newValues[i] = values[i].convertTo(componentType, provider, conversionMode, column);
2509 }
2510 v = ValueArray.get(componentType, newValues, provider);
2511 break loop;
2512 }
2513 }
2514 }
2515 if (conversionMode != CONVERT_TO) {
2516 Value[] values = v.getList();
2517 int cardinality = values.length;
2518 if (conversionMode == CAST_TO) {
2519 int p = MathUtils.convertLongToInt(targetType.getPrecision());
2520 if (cardinality > p) {
2521 v = ValueArray.get(v.getComponentType(), Arrays.copyOf(values, p), provider);
2522 }
2523 } else if (cardinality > targetType.getPrecision()) {
2524 throw v.getValueTooLongException(targetType, column);
2525 }
2526 }
2527 return v;
2528 }
2529
2530 private Value convertToRow(TypeInfo targetType, CastDataProvider provider, int conversionMode,
2531 Object column) {
2532 ValueRow v;
2533 if (getValueType() == ROW) {
2534 v = (ValueRow) this;
2535 } else {
2536 v = ValueRow.get(new Value[] { this });
2537 }
2538 ExtTypeInfoRow ext = (ExtTypeInfoRow) targetType.getExtTypeInfo();
2539 if (ext != null) {
2540 Value[] values = v.getList();
2541 int length = values.length;
2542 Set<Map.Entry<String, TypeInfo>> fields = ext.getFields();
2543 if (length != fields.size()) {
2544 throw getDataConversionError(targetType);
2545 }
2546 Iterator<Map.Entry<String, TypeInfo>> iter = fields.iterator();
2547 loop: for (int i = 0; i < length; i++) {
2548 Value v1 = values[i];
2549 TypeInfo componentType = iter.next().getValue();
2550 Value v2 = v1.convertTo(componentType, provider, conversionMode, column);
2551 if (v1 != v2) {
2552 Value[] newValues = new Value[length];
2553 System.arraycopy(values, 0, newValues, 0, i);
2554 newValues[i] = v2;
2555 while (++i < length) {
2556 newValues[i] = values[i].convertTo(componentType, provider, conversionMode, column);
2557 }
2558 v = ValueRow.get(targetType, newValues);
2559 break loop;
2560 }
2561 }
2562 }
2563 return v;
2564 }
2565
2566 /**
2567 * Creates new instance of the DbException for data conversion error.
2568 *
2569 * @param targetType Target data type.
2570 * @return instance of the DbException.
2571 */
2572 final DbException getDataConversionError(int targetType) {
2573 throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, getTypeName(getValueType()) + " to "
2574 + getTypeName(targetType));
2575 }
2576
2577 /**
2578 * Creates new instance of the DbException for data conversion error.
2579 *
2580 * @param targetType target data type.
2581 * @return instance of the DbException.
2582 */
2583 final DbException getDataConversionError(TypeInfo targetType) {
2584 throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, getTypeName(getValueType()) + " to "
2585 + targetType.getTraceSQL());
2586 }
2587
2588 final DbException getValueTooLongException(TypeInfo targetType, Object column) {
2589 StringBuilder builder = new StringBuilder();
2590 if (column != null) {
2591 builder.append(column).append(' ');
2592 }
2593 targetType.getSQL(builder, TRACE_SQL_FLAGS);
2594 return DbException.getValueTooLongException(builder.toString(), getTraceSQL(), getType().getPrecision());
2595 }
2596
2597 /**
2598 * Compare this value against another value given that the values are of the
2599 * same data type.
2600 *
2601 * @param v the other value
2602 * @param mode the compare mode
2603 * @param provider the cast information provider
2604 * @return 0 if both values are equal, -1 if the other value is smaller, and
2605 * 1 otherwise
2606 */
2607 public abstract int compareTypeSafe(Value v, CompareMode mode, CastDataProvider provider);
2608
2609 /**
2610 * Compare this value against another value using the specified compare
2611 * mode.
2612 *
2613 * @param v the other value
2614 * @param provider the cast information provider
2615 * @param compareMode the compare mode
2616 * @return 0 if both values are equal, -1 if this value is smaller, and
2617 * 1 otherwise
2618 */
2619 public final int compareTo(Value v, CastDataProvider provider, CompareMode compareMode) {
2620 if (this == v) {
2621 return 0;
2622 }
2623 if (this == ValueNull.INSTANCE) {
2624 return -1;
2625 } else if (v == ValueNull.INSTANCE) {
2626 return 1;
2627 }
2628 return compareToNotNullable(this, v, provider, compareMode);
2629 }
2630
2631 private static int compareToNotNullable(Value l, Value r, CastDataProvider provider, CompareMode compareMode) {
2632 int leftType = l.getValueType();
2633 int rightType = r.getValueType();
2634 if (leftType != rightType || leftType == ENUM) {
2635 int dataType = getHigherOrderNonNull(leftType, rightType);
2636 if (DataType.isNumericType(dataType)) {
2637 return compareNumeric(l, r, leftType, rightType, dataType);
2638 }
2639 if (dataType == ENUM) {
2640 ExtTypeInfoEnum enumerators = ExtTypeInfoEnum.getEnumeratorsForBinaryOperation(l, r);
2641 return Integer.compare(l.convertToEnum(enumerators, provider).getInt(),
2642 r.convertToEnum(enumerators, provider).getInt());
2643 } else {
2644 if (dataType <= BLOB) {
2645 if (dataType <= CLOB) {
2646 if (leftType == CHAR || rightType == CHAR) {
2647 dataType = CHAR;
2648 }
2649 } else if (dataType >= BINARY && (leftType == BINARY || rightType == BINARY)) {
2650 dataType = BINARY;
2651 }
2652 }
2653 l = l.convertTo(dataType, provider);
2654 r = r.convertTo(dataType, provider);
2655 }
2656 }
2657 return l.compareTypeSafe(r, compareMode, provider);
2658 }
2659
2660 private static int compareNumeric(Value l, Value r, int leftType, int rightType, int dataType) {
2661 if (DataType.isNumericType(leftType) && DataType.isNumericType(rightType)) {
2662 switch (dataType) {
2663 case TINYINT:
2664 case SMALLINT:
2665 case INTEGER:
2666 return Integer.compare(l.getInt(), r.getInt());
2667 case BIGINT:
2668 return Long.compare(l.getLong(), r.getLong());
2669 case NUMERIC:
2670 return l.getBigDecimal().compareTo(r.getBigDecimal());
2671 case REAL:
2672 return Float.compare(l.getFloat(), r.getFloat());
2673 case DOUBLE:
2674 return Double.compare(l.getDouble(), r.getDouble());
2675 }
2676 }
2677 return l.convertToDecfloat(null, CONVERT_TO).compareTypeSafe( //
2678 r.convertToDecfloat(null, CONVERT_TO), null, null);
2679 }
2680
2681 /**
2682 * Compare this value against another value using the specified compare
2683 * mode.
2684 *
2685 * @param v the other value
2686 * @param forEquality perform only check for equality
2687 * @param provider the cast information provider
2688 * @param compareMode the compare mode
2689 * @return 0 if both values are equal, -1 if this value is smaller, 1
2690 * if other value is larger, {@link Integer#MIN_VALUE} if order is
2691 * not defined due to NULL comparison
2692 */
2693 public int compareWithNull(Value v, boolean forEquality, CastDataProvider provider,
2694 CompareMode compareMode) {
2695 if (this == ValueNull.INSTANCE || v == ValueNull.INSTANCE) {
2696 return Integer.MIN_VALUE;
2697 }
2698 return compareToNotNullable(this, v, provider, compareMode);
2699 }
2700
2701 /**
2702 * Returns true if this value is NULL or contains NULL value.
2703 *
2704 * @return true if this value is NULL or contains NULL value
2705 */
2706 public boolean containsNull() {
2707 return false;
2708 }
2709
2710 private static byte convertToByte(long x, Object column) {
2711 if (x > Byte.MAX_VALUE || x < Byte.MIN_VALUE) {
2712 throw DbException.get(
2713 ErrorCode.NUMERIC_VALUE_OUT_OF_RANGE_2, Long.toString(x), getColumnName(column));
2714 }
2715 return (byte) x;
2716 }
2717
2718 private static short convertToShort(long x, Object column) {
2719 if (x > Short.MAX_VALUE || x < Short.MIN_VALUE) {
2720 throw DbException.get(
2721 ErrorCode.NUMERIC_VALUE_OUT_OF_RANGE_2, Long.toString(x), getColumnName(column));
2722 }
2723 return (short) x;
2724 }
2725
2726 /**
2727 * Convert to integer, throwing exception if out of range.
2728 *
2729 * @param x integer value.
2730 * @param column Column info.
2731 * @return x
2732 */
2733 public static int convertToInt(long x, Object column) {
2734 if (x > Integer.MAX_VALUE || x < Integer.MIN_VALUE) {
2735 throw DbException.get(
2736 ErrorCode.NUMERIC_VALUE_OUT_OF_RANGE_2, Long.toString(x), getColumnName(column));
2737 }
2738 return (int) x;
2739 }
2740
2741 private static long convertToLong(double x, Object column) {
2742 if (x > Long.MAX_VALUE || x < Long.MIN_VALUE) {
2743 // TODO document that +Infinity, -Infinity throw an exception and
2744 // NaN returns 0
2745 throw DbException.get(
2746 ErrorCode.NUMERIC_VALUE_OUT_OF_RANGE_2, Double.toString(x), getColumnName(column));
2747 }
2748 return Math.round(x);
2749 }
2750
2751 private static long convertToLong(BigDecimal x, Object column) {
2752 if (x.compareTo(MAX_LONG_DECIMAL) > 0 ||
2753 x.compareTo(MIN_LONG_DECIMAL) < 0) {
2754 throw DbException.get(
2755 ErrorCode.NUMERIC_VALUE_OUT_OF_RANGE_2, x.toString(), getColumnName(column));
2756 }
2757 return x.setScale(0, RoundingMode.HALF_UP).longValue();
2758 }
2759
2760 private static String getColumnName(Object column) {
2761 return column == null ? "" : column.toString();
2762 }
2763
2764 @Override
2765 public String toString() {
2766 return getTraceSQL();
2767 }
2768
2769 /**
2770 * Create an exception meaning the specified operation is not supported for
2771 * this data type.
2772 *
2773 * @param op the operation
2774 * @return the exception
2775 */
2776 protected final DbException getUnsupportedExceptionForOperation(String op) {
2777 return DbException.getUnsupportedException(getTypeName(getValueType()) + ' ' + op);
2778 }
2779
2780 /**
2781 * Returns length of this value in characters.
2782 *
2783 * @return length of this value in characters
2784 * @throws NullPointerException if this value is {@code NULL}
2785 */
2786 public long charLength() {
2787 return getString().length();
2788 }
2789
2790 /**
2791 * Returns length of this value in bytes.
2792 *
2793 * @return length of this value in bytes
2794 * @throws NullPointerException if this value is {@code NULL}
2795 */
2796 public long octetLength() {
2797 return getBytesNoCopy().length;
2798 }
2799
2800 /**
2801 * Returns whether this value {@code IS TRUE}.
2802 *
2803 * @return {@code true} if it is. For {@code BOOLEAN} values returns
2804 * {@code true} for {@code TRUE} and {@code false} for {@code FALSE}
2805 * and {@code UNKNOWN} ({@code NULL}).
2806 * @see #getBoolean()
2807 * @see #isFalse()
2808 */
2809 public final boolean isTrue() {
2810 return this != ValueNull.INSTANCE ? getBoolean() : false;
2811 }
2812
2813 /**
2814 * Returns whether this value {@code IS FALSE}.
2815 *
2816 * @return {@code true} if it is. For {@code BOOLEAN} values returns
2817 * {@code true} for {@code FALSE} and {@code false} for {@code TRUE}
2818 * and {@code UNKNOWN} ({@code NULL}).
2819 * @see #getBoolean()
2820 * @see #isTrue()
2821 */
2822 public final boolean isFalse() {
2823 return this != ValueNull.INSTANCE && !getBoolean();
2824 }
2825
2826 }