|
| 1 | +/* |
| 2 | + * |
| 3 | + * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 4 | + * |
| 5 | + * Licensed under the Apache License, Version 2.0 (the "License"). |
| 6 | + * You may not use this file except in compliance with the License. |
| 7 | + * A copy of the License is located at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * or in the "license" file accompanying this file. This file is distributed |
| 12 | + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either |
| 13 | + * express or implied. See the License for the specific language governing |
| 14 | + * permissions and limitations under the License. |
| 15 | + * |
| 16 | + */ |
| 17 | + |
| 18 | +package com.amazon.opendistroforelasticsearch.sql.data.model; |
| 19 | + |
| 20 | +import com.amazon.opendistroforelasticsearch.sql.data.type.ExprCoreType; |
| 21 | +import com.amazon.opendistroforelasticsearch.sql.exception.SemanticCheckException; |
| 22 | +import java.time.Instant; |
| 23 | +import java.time.LocalDateTime; |
| 24 | +import java.time.ZoneId; |
| 25 | +import java.time.format.DateTimeFormatter; |
| 26 | +import java.time.format.DateTimeParseException; |
| 27 | +import java.time.temporal.ChronoUnit; |
| 28 | +import lombok.EqualsAndHashCode; |
| 29 | +import lombok.RequiredArgsConstructor; |
| 30 | + |
| 31 | +/** |
| 32 | + * Timestamp Value. |
| 33 | + */ |
| 34 | +@EqualsAndHashCode |
| 35 | +@RequiredArgsConstructor |
| 36 | +public class ExprTimestampValue implements ExprValue { |
| 37 | + /** |
| 38 | + * todo. only support UTC now. |
| 39 | + */ |
| 40 | + private static final ZoneId ZONE = ZoneId.of("UTC"); |
| 41 | + /** |
| 42 | + * todo. only support timestamp in format yyyy-MM-dd HH:mm:ss. |
| 43 | + */ |
| 44 | + private static final DateTimeFormatter FORMATTER = DateTimeFormatter |
| 45 | + .ofPattern("yyyy-MM-dd HH:mm:ss"); |
| 46 | + private final Instant timestamp; |
| 47 | + |
| 48 | + /** |
| 49 | + * Constructor. |
| 50 | + */ |
| 51 | + public ExprTimestampValue(String timestamp) { |
| 52 | + try { |
| 53 | + this.timestamp = LocalDateTime.parse(timestamp, FORMATTER).atZone(ZONE).toInstant(); |
| 54 | + } catch (DateTimeParseException e) { |
| 55 | + throw new SemanticCheckException(String.format("timestamp:%s in unsupported format, please " |
| 56 | + + "use yyyy-MM-dd HH:mm:ss", timestamp)); |
| 57 | + } |
| 58 | + |
| 59 | + } |
| 60 | + |
| 61 | + @Override |
| 62 | + public String value() { |
| 63 | + return FORMATTER.withZone(ZONE).format(timestamp.truncatedTo(ChronoUnit.SECONDS)); |
| 64 | + } |
| 65 | + |
| 66 | + @Override |
| 67 | + public ExprCoreType type() { |
| 68 | + return ExprCoreType.TIMESTAMP; |
| 69 | + } |
| 70 | + |
| 71 | + @Override |
| 72 | + public String toString() { |
| 73 | + return String.format("TIMESTAMP '%s'", value()); |
| 74 | + } |
| 75 | +} |
0 commit comments