| 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.expression.function; |
| 7 |
|
| 8 |
import java.time.DateTimeException; |
| 9 |
import java.time.Instant; |
| 10 |
import java.time.LocalDate; |
| 11 |
import java.time.LocalDateTime; |
| 12 |
import java.time.LocalTime; |
| 13 |
import java.time.OffsetDateTime; |
| 14 |
import java.time.OffsetTime; |
| 15 |
import java.time.ZoneId; |
| 16 |
import java.time.ZoneOffset; |
| 17 |
import java.time.format.DateTimeFormatter; |
| 18 |
import java.time.format.DateTimeFormatterBuilder; |
| 19 |
import java.time.temporal.ChronoField; |
| 20 |
import java.time.temporal.TemporalAccessor; |
| 21 |
import java.time.temporal.TemporalQueries; |
| 22 |
import java.time.zone.ZoneRules; |
| 23 |
import java.util.Locale; |
| 24 |
import java.util.Objects; |
| 25 |
|
| 26 |
import org.h2.api.ErrorCode; |
| 27 |
import org.h2.engine.SessionLocal; |
| 28 |
import org.h2.expression.Expression; |
| 29 |
import org.h2.expression.TypedValueExpression; |
| 30 |
import org.h2.message.DbException; |
| 31 |
import org.h2.util.JSR310Utils; |
| 32 |
import org.h2.util.SmallLRUCache; |
| 33 |
import org.h2.value.TypeInfo; |
| 34 |
import org.h2.value.Value; |
| 35 |
import org.h2.value.ValueTime; |
| 36 |
import org.h2.value.ValueTimestampTimeZone; |
| 37 |
import org.h2.value.ValueVarchar; |
| 38 |
|
| 39 |
/** |
| 40 |
* A date-time format function. |
| 41 |
*/ |
| 42 |
public final class DateTimeFormatFunction extends FunctionN { |
| 43 |
|
| 44 |
private static final class CacheKey { |
| 45 |
|
| 46 |
private final String format; |
| 47 |
|
| 48 |
private final String locale; |
| 49 |
|
| 50 |
private final String timeZone; |
| 51 |
|
| 52 |
CacheKey(String format, String locale, String timeZone) { |
| 53 |
this.format = format; |
| 54 |
this.locale = locale; |
| 55 |
this.timeZone = timeZone; |
| 56 |
} |
| 57 |
|
| 58 |
@Override |
| 59 |
public int hashCode() { |
| 60 |
final int prime = 31; |
| 61 |
int result = 1; |
| 62 |
result = prime * result + format.hashCode(); |
| 63 |
result = prime * result + ((locale == null) ? 0 : locale.hashCode()); |
| 64 |
result = prime * result + ((timeZone == null) ? 0 : timeZone.hashCode()); |
| 65 |
return result; |
| 66 |
} |
| 67 |
|
| 68 |
@Override |
| 69 |
public boolean equals(Object obj) { |
| 70 |
if (this == obj) |
| 71 |
return true; |
| 72 |
if (!(obj instanceof CacheKey)) { |
| 73 |
return false; |
| 74 |
} |
| 75 |
CacheKey other = (CacheKey) obj; |
| 76 |
return format.equals(other.format) && Objects.equals(locale, other.locale) |
| 77 |
&& Objects.equals(timeZone, other.timeZone); |
| 78 |
} |
| 79 |
|
| 80 |
} |
| 81 |
|
| 82 |
private static final class CacheValue { |
| 83 |
|
| 84 |
final DateTimeFormatter formatter; |
| 85 |
|
| 86 |
final ZoneId zoneId; |
| 87 |
|
| 88 |
CacheValue(DateTimeFormatter formatter, ZoneId zoneId) { |
| 89 |
this.formatter = formatter; |
| 90 |
this.zoneId = zoneId; |
| 91 |
} |
| 92 |
|
| 93 |
} |
| 94 |
|
| 95 |
/** |
| 96 |
* FORMATDATETIME() (non-standard). |
| 97 |
*/ |
| 98 |
public static final int FORMATDATETIME = 0; |
| 99 |
|
| 100 |
/** |
| 101 |
* PARSEDATETIME() (non-standard). |
| 102 |
*/ |
| 103 |
public static final int PARSEDATETIME = FORMATDATETIME + 1; |
| 104 |
|
| 105 |
private static final String[] NAMES = { // |
| 106 |
"FORMATDATETIME", "PARSEDATETIME" // |
| 107 |
}; |
| 108 |
|
| 109 |
private static final SmallLRUCache<CacheKey, CacheValue> CACHE = SmallLRUCache.newInstance(100); |
| 110 |
|
| 111 |
private final int function; |
| 112 |
|
| 113 |
public DateTimeFormatFunction(int function) { |
| 114 |
super(new Expression[4]); |
| 115 |
this.function = function; |
| 116 |
} |
| 117 |
|
| 118 |
@Override |
| 119 |
public Value getValue(SessionLocal session, Value v1, Value v2, Value v3) { |
| 120 |
String format = v2.getString(), locale, tz; |
| 121 |
if (v3 != null) { |
| 122 |
locale = v3.getString(); |
| 123 |
tz = args.length > 3 ? args[3].getValue(session).getString() : null; |
| 124 |
} else { |
| 125 |
tz = locale = null; |
| 126 |
} |
| 127 |
switch (function) { |
| 128 |
case FORMATDATETIME: |
| 129 |
v1 = ValueVarchar.get(formatDateTime(session, v1, format, locale, tz)); |
| 130 |
break; |
| 131 |
case PARSEDATETIME: |
| 132 |
v1 = parseDateTime(session, v1.getString(), format, locale, tz); |
| 133 |
break; |
| 134 |
default: |
| 135 |
throw DbException.getInternalError("function=" + function); |
| 136 |
} |
| 137 |
return v1; |
| 138 |
} |
| 139 |
|
| 140 |
/** |
| 141 |
* Formats a date using a format string. |
| 142 |
* |
| 143 |
* @param session |
| 144 |
* the session |
| 145 |
* @param date |
| 146 |
* the date to format |
| 147 |
* @param format |
| 148 |
* the format string |
| 149 |
* @param locale |
| 150 |
* the locale |
| 151 |
* @param timeZone |
| 152 |
* the time zone |
| 153 |
* @return the formatted date |
| 154 |
*/ |
| 155 |
public static String formatDateTime(SessionLocal session, Value date, String format, String locale, |
| 156 |
String timeZone) { |
| 157 |
CacheValue formatAndZone = getDateFormat(format, locale, timeZone); |
| 158 |
ZoneId zoneId = formatAndZone.zoneId; |
| 159 |
TemporalAccessor value; |
| 160 |
switch (date.getValueType()) { |
| 161 |
case Value.DATE: |
| 162 |
case Value.TIMESTAMP: |
| 163 |
value = JSR310Utils.valueToLocalDateTime(date, session) |
| 164 |
.atZone(zoneId != null ? zoneId : ZoneId.of(session.currentTimeZone().getId())); |
| 165 |
break; |
| 166 |
case Value.TIME: { |
| 167 |
LocalTime time = JSR310Utils.valueToLocalTime(date, session); |
| 168 |
value = zoneId != null ? time.atOffset(getTimeOffset(zoneId, timeZone)) : time; |
| 169 |
break; |
| 170 |
} |
| 171 |
case Value.TIME_TZ: { |
| 172 |
OffsetTime time = JSR310Utils.valueToOffsetTime(date, session); |
| 173 |
value = zoneId != null ? time.withOffsetSameInstant(getTimeOffset(zoneId, timeZone)) : time; |
| 174 |
break; |
| 175 |
} |
| 176 |
case Value.TIMESTAMP_TZ: { |
| 177 |
OffsetDateTime dateTime = JSR310Utils.valueToOffsetDateTime(date, session); |
| 178 |
ZoneId zoneToSet; |
| 179 |
if (zoneId != null) { |
| 180 |
zoneToSet = zoneId; |
| 181 |
} else { |
| 182 |
ZoneOffset offset = dateTime.getOffset(); |
| 183 |
zoneToSet = ZoneId.ofOffset(offset.getTotalSeconds() == 0 ? "UTC" : "GMT", offset); |
| 184 |
} |
| 185 |
value = dateTime.atZoneSameInstant(zoneToSet); |
| 186 |
break; |
| 187 |
} |
| 188 |
default: |
| 189 |
throw DbException.getInvalidValueException("dateTime", date.getTraceSQL()); |
| 190 |
} |
| 191 |
try { |
| 192 |
return formatAndZone.formatter.format(value); |
| 193 |
} catch (DateTimeException e) { |
| 194 |
throw DbException.getInvalidValueException(e, "format", format); |
| 195 |
} |
| 196 |
} |
| 197 |
|
| 198 |
private static ZoneOffset getTimeOffset(ZoneId zoneId, String timeZone) { |
| 199 |
if (zoneId instanceof ZoneOffset) { |
| 200 |
return (ZoneOffset) zoneId; |
| 201 |
} |
| 202 |
ZoneRules zoneRules = zoneId.getRules(); |
| 203 |
if (!zoneRules.isFixedOffset()) { |
| 204 |
throw DbException.getInvalidValueException("timeZone", timeZone); |
| 205 |
} |
| 206 |
return zoneRules.getOffset(Instant.EPOCH); |
| 207 |
} |
| 208 |
|
| 209 |
/** |
| 210 |
* Parses a date using a format string. |
| 211 |
* |
| 212 |
* @param session |
| 213 |
* the session |
| 214 |
* @param date |
| 215 |
* the date to parse |
| 216 |
* @param format |
| 217 |
* the parsing format |
| 218 |
* @param locale |
| 219 |
* the locale |
| 220 |
* @param timeZone |
| 221 |
* the time zone |
| 222 |
* @return the parsed date |
| 223 |
*/ |
| 224 |
public static ValueTimestampTimeZone parseDateTime(SessionLocal session, String date, String format, String locale, |
| 225 |
String timeZone) { |
| 226 |
CacheValue formatAndZone = getDateFormat(format, locale, timeZone); |
| 227 |
try { |
| 228 |
ValueTimestampTimeZone result; |
| 229 |
TemporalAccessor parsed = formatAndZone.formatter.parse(date); |
| 230 |
ZoneId parsedZoneId = parsed.query(TemporalQueries.zoneId()); |
| 231 |
if (parsed.isSupported(ChronoField.OFFSET_SECONDS)) { |
| 232 |
result = JSR310Utils.offsetDateTimeToValue(OffsetDateTime.from(parsed)); |
| 233 |
} else { |
| 234 |
if (parsed.isSupported(ChronoField.INSTANT_SECONDS)) { |
| 235 |
Instant instant = Instant.from(parsed); |
| 236 |
if (parsedZoneId == null) { |
| 237 |
parsedZoneId = formatAndZone.zoneId; |
| 238 |
} |
| 239 |
if (parsedZoneId != null) { |
| 240 |
result = JSR310Utils.zonedDateTimeToValue(instant.atZone(parsedZoneId)); |
| 241 |
} else { |
| 242 |
result = JSR310Utils.offsetDateTimeToValue(instant.atOffset(ZoneOffset.ofTotalSeconds( // |
| 243 |
session.currentTimeZone().getTimeZoneOffsetUTC(instant.getEpochSecond())))); |
| 244 |
} |
| 245 |
} else { |
| 246 |
LocalDate localDate = parsed.query(TemporalQueries.localDate()); |
| 247 |
LocalTime localTime = parsed.query(TemporalQueries.localTime()); |
| 248 |
if (parsedZoneId == null) { |
| 249 |
parsedZoneId = formatAndZone.zoneId; |
| 250 |
} |
| 251 |
if (localDate != null) { |
| 252 |
LocalDateTime localDateTime = localTime != null ? LocalDateTime.of(localDate, localTime) |
| 253 |
: localDate.atStartOfDay(); |
| 254 |
result = parsedZoneId != null |
| 255 |
? JSR310Utils.zonedDateTimeToValue(localDateTime.atZone(parsedZoneId)) |
| 256 |
: (ValueTimestampTimeZone) JSR310Utils.localDateTimeToValue(localDateTime) |
| 257 |
.convertTo(Value.TIMESTAMP_TZ, session); |
| 258 |
} else { |
| 259 |
result = parsedZoneId != null |
| 260 |
? JSR310Utils.zonedDateTimeToValue( |
| 261 |
JSR310Utils.valueToInstant(session.currentTimestamp(), session) |
| 262 |
.atZone(parsedZoneId).with(localTime)) |
| 263 |
: (ValueTimestampTimeZone) ValueTime.fromNanos(localTime.toNanoOfDay()) |
| 264 |
.convertTo(Value.TIMESTAMP_TZ, session); |
| 265 |
} |
| 266 |
} |
| 267 |
} |
| 268 |
return result; |
| 269 |
} catch (RuntimeException e) { |
| 270 |
throw DbException.get(ErrorCode.PARSE_ERROR_1, e, date); |
| 271 |
} |
| 272 |
} |
| 273 |
|
| 274 |
private static CacheValue getDateFormat(String format, String locale, String timeZone) { |
| 275 |
Exception ex = null; |
| 276 |
if (format.length() <= 100) { |
| 277 |
try { |
| 278 |
CacheValue value; |
| 279 |
CacheKey key = new CacheKey(format, locale, timeZone); |
| 280 |
synchronized (CACHE) { |
| 281 |
value = CACHE.get(key); |
| 282 |
if (value == null) { |
| 283 |
DateTimeFormatter df = new DateTimeFormatterBuilder().parseCaseInsensitive() |
| 284 |
.appendPattern(format) |
| 285 |
.toFormatter(locale == null ? Locale.getDefault(Locale.Category.FORMAT) |
| 286 |
: new Locale(locale)); |
| 287 |
ZoneId zoneId; |
| 288 |
if (timeZone != null) { |
| 289 |
zoneId = getZoneId(timeZone); |
| 290 |
df = df.withZone(zoneId); |
| 291 |
} else { |
| 292 |
zoneId = null; |
| 293 |
} |
| 294 |
value = new CacheValue(df, zoneId); |
| 295 |
CACHE.put(key, value); |
| 296 |
} |
| 297 |
} |
| 298 |
return value; |
| 299 |
} catch (Exception e) { |
| 300 |
ex = e; |
| 301 |
} |
| 302 |
} |
| 303 |
throw DbException.get(ErrorCode.PARSE_ERROR_1, ex, format + '/' + locale); |
| 304 |
} |
| 305 |
|
| 306 |
private static ZoneId getZoneId(String timeZone) { |
| 307 |
try { |
| 308 |
return ZoneId.of(timeZone, ZoneId.SHORT_IDS); |
| 309 |
} catch (RuntimeException e) { |
| 310 |
throw DbException.getInvalidValueException("TIME ZONE", timeZone); |
| 311 |
} |
| 312 |
} |
| 313 |
|
| 314 |
@Override |
| 315 |
public Expression optimize(SessionLocal session) { |
| 316 |
boolean allConst = optimizeArguments(session, true); |
| 317 |
switch (function) { |
| 318 |
case FORMATDATETIME: |
| 319 |
type = TypeInfo.TYPE_VARCHAR; |
| 320 |
break; |
| 321 |
case PARSEDATETIME: |
| 322 |
type = TypeInfo.TYPE_TIMESTAMP_TZ; |
| 323 |
break; |
| 324 |
default: |
| 325 |
throw DbException.getInternalError("function=" + function); |
| 326 |
} |
| 327 |
if (allConst) { |
| 328 |
return TypedValueExpression.getTypedIfNull(getValue(session), type); |
| 329 |
} |
| 330 |
return this; |
| 331 |
} |
| 332 |
|
| 333 |
@Override |
| 334 |
public String getName() { |
| 335 |
return NAMES[function]; |
| 336 |
} |
| 337 |
|
| 338 |
} |