jacktengg commented on code in PR #66761:
URL: https://github.com/apache/doris/pull/66761#discussion_r3826928570


##########
be/src/core/data_type_serde/data_type_timestamp_ns_serde.cpp:
##########
@@ -0,0 +1,270 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include "core/data_type_serde/data_type_timestamp_ns_serde.h"
+
+#include <cctz/time_zone.h>
+
+#include <algorithm>
+#include <cctype>
+#include <limits>
+#include <string>
+
+#include "common/exception.h"
+#include "core/assert_cast.h"
+#include "core/column/column_nullable.h"
+#include "core/column/column_string.h"
+#include "core/value/vdatetime_value.h"
+#include "exprs/function/cast/cast_to_datetimev2_impl.hpp"
+#include "util/mysql_row_buffer.h"
+#include "util/unaligned.h"
+
+namespace doris {
+Status parse_timestamp_ns(StringRef str, int64_t* epoch_nanos,
+                          const cctz::time_zone* local_time_zone) {
+    std::string input(str.data, str.size);
+    const size_t dot = input.rfind('.');
+    size_t fraction_begin = std::string::npos;
+    size_t fraction_end = std::string::npos;
+    if (dot != std::string::npos && dot + 1 < input.size() &&
+        std::isdigit(static_cast<unsigned char>(input[dot + 1]))) {
+        fraction_begin = dot + 1;
+        fraction_end = fraction_begin;
+        while (fraction_end < input.size() &&
+               std::isdigit(static_cast<unsigned char>(input[fraction_end]))) {
+            ++fraction_end;
+        }
+    }
+
+    uint32_t nanos = 0;
+    size_t fraction_length = 0;
+    if (fraction_begin != std::string::npos) {
+        fraction_length = fraction_end - fraction_begin;
+        const size_t copied_digits =
+                std::min<size_t>(fraction_length, 
TimeStampNsValue::FRACTIONAL_DIGITS);
+        for (size_t i = 0; i < copied_digits; ++i) {
+            nanos = nanos * 10 + static_cast<uint32_t>(input[fraction_begin + 
i] - '0');
+        }
+        for (size_t i = copied_digits; i < 
TimeStampNsValue::FRACTIONAL_DIGITS; ++i) {
+            nanos *= 10;
+        }
+    }
+
+    if (fraction_length > TimeStampNsValue::FRACTIONAL_DIGITS &&
+        input[fraction_begin + TimeStampNsValue::FRACTIONAL_DIGITS] >= '5') {
+        ++nanos;
+    }
+
+    // Keep the fractional token in place so that the legacy parser validates 
its position and all
+    // trailing syntax. Zeroing the digits prevents its scale-0 rounding from 
changing the second;
+    // the nanosecond rounding above remains the only source of fractional 
rounding.
+    if (fraction_begin != std::string::npos) {
+        std::fill(input.begin() + fraction_begin, input.begin() + 
fraction_end, '0');
+    }
+    const StringRef input_ref(input.data(), input.size());
+    DateV2Value<DateTimeV2ValueType> datetime;
+    CastParameters params {.status = Status::OK(), .is_strict = true};
+    CastToDatetimeV2::from_string_strict_mode<DatelikeParseMode::STRICT>(
+            input_ref, datetime, local_time_zone, 0, params);
+    if (!params.status.ok()) {
+        if (dot != std::string::npos) {
+            return Status::InvalidArgument("Invalid TIMESTAMP_NS value '{}'",
+                                           std::string(str.data, str.size));
+        }
+        return params.status;
+    }
+
+    if (nanos == TimeStampNsValue::NANOS_PER_SECOND) {
+        if (!datetime.date_add_interval<TimeUnit::SECOND>(
+                    TimeInterval {TimeUnit::SECOND, 1, false})) {
+            return Status::InvalidArgument("TIMESTAMP_NS value overflows while 
rounding '{}'",
+                                           std::string(str.data, str.size));
+        }
+        nanos = 0;
+    }
+    datetime.set_microsecond(nanos / TimeStampNsValue::NANOS_PER_MICROSECOND);
+    TimeStampNsValue value;
+    if (!value.from_datetime(
+                datetime, static_cast<uint16_t>(nanos % 
TimeStampNsValue::NANOS_PER_MICROSECOND))) {
+        return Status::InvalidArgument(
+                "TIMESTAMP_NS value '{}' is outside [{}, {}]", 
std::string(str.data, str.size),
+                
TimeStampNsValue(std::numeric_limits<int64_t>::min()).to_string(),
+                
TimeStampNsValue(std::numeric_limits<int64_t>::max()).to_string());
+    }
+    *epoch_nanos = value.epoch_nanos();
+    return Status::OK();
+}
+
+Status DataTypeTimeStampNsSerDe::from_string_batch(const ColumnString& strings,
+                                                   ColumnNullable& result,
+                                                   const FormatOptions& 
options) const {
+    auto& data = 
assert_cast<ColumnTimeStampNs&>(result.get_nested_column()).get_data();
+    auto& null_map = result.get_null_map_column().get_data();
+    result.resize(strings.size());
+    for (size_t i = 0; i < strings.size(); ++i) {
+        int64_t value = 0;
+        const auto status = parse_timestamp_ns(strings.get_data_at(i), &value, 
options.timezone);
+        null_map[i] = !status.ok();
+        data[i] = TimeStampNsValue(value);
+    }
+    return Status::OK();
+}
+
+Status DataTypeTimeStampNsSerDe::from_string_strict_mode_batch(
+        const ColumnString& strings, IColumn& result, const FormatOptions& 
options,
+        const NullMap::value_type* null_map) const {
+    auto& data = assert_cast<ColumnTimeStampNs&>(result).get_data();
+    result.resize(strings.size());
+    for (size_t i = 0; i < strings.size(); ++i) {
+        if (null_map != nullptr && null_map[i]) {
+            continue;
+        }
+        int64_t value = 0;
+        RETURN_IF_ERROR(parse_timestamp_ns(strings.get_data_at(i), &value, 
options.timezone));
+        data[i] = TimeStampNsValue(value);
+    }
+    return Status::OK();
+}
+
+Status DataTypeTimeStampNsSerDe::from_string(StringRef& str, IColumn& column,
+                                             const FormatOptions& options) 
const {
+    int64_t value = 0;
+    RETURN_IF_ERROR(parse_timestamp_ns(str, &value, options.timezone));
+    
assert_cast<ColumnTimeStampNs&>(column).insert_value(TimeStampNsValue(value));
+    return Status::OK();
+}
+
+Status DataTypeTimeStampNsSerDe::from_string_strict_mode(StringRef& str, 
IColumn& column,
+                                                         const FormatOptions& 
options) const {
+    return from_string(str, column, options);
+}
+
+Status DataTypeTimeStampNsSerDe::serialize_column_to_json(const IColumn& 
column, int64_t start_idx,
+                                                          int64_t end_idx, 
BufferWritable& bw,
+                                                          FormatOptions& 
options) const {
+    SERIALIZE_COLUMN_TO_JSON();
+}
+
+Status DataTypeTimeStampNsSerDe::serialize_one_cell_to_json(const IColumn& 
column, int64_t row_num,
+                                                            BufferWritable& bw,
+                                                            FormatOptions& 
options) const {
+    auto [column_ptr, index] = check_column_const_set_readability(column, 
row_num);
+    if (_nesting_level > 1) {
+        bw.write('"');
+    }
+    const auto value =
+            assert_cast<const ColumnTimeStampNs&, 
TypeCheckOnRelease::DISABLE>(*column_ptr)
+                    .get_element(index);
+    const std::string result = value.to_string();
+    bw.write(result.data(), result.size());
+    if (_nesting_level > 1) {
+        bw.write('"');
+    }
+    return Status::OK();
+}
+
+Status DataTypeTimeStampNsSerDe::deserialize_column_from_json_vector(
+        IColumn& column, std::vector<Slice>& slices, uint64_t* 
num_deserialized,
+        const FormatOptions& options) const {
+    DESERIALIZE_COLUMN_FROM_JSON_VECTOR();
+    return Status::OK();
+}
+
+Status DataTypeTimeStampNsSerDe::deserialize_one_cell_from_json(
+        IColumn& column, Slice& slice, const FormatOptions& options) const {
+    if (_nesting_level > 1) {
+        slice.trim_quote();
+    }
+    StringRef str(slice.data, slice.size);
+    return from_string(str, column, options);
+}
+
+Status DataTypeTimeStampNsSerDe::deserialize_column_from_jsonb(IColumn& column,
+                                                               const 
JsonbValue* jsonb_value,
+                                                               CastParameters& 
cast_params) const {
+    DORIS_CHECK(jsonb_value->isString());
+    return parse_column_from_jsonb_string(column, jsonb_value, cast_params);
+}
+
+Status DataTypeTimeStampNsSerDe::deserialize_column_from_jsonb_vector(
+        ColumnNullable& column_to, const ColumnString& column_from,
+        CastParameters& cast_params) const {
+    return DataTypeSerDe::deserialize_column_from_jsonb_vector(column_to, 
column_from, cast_params);
+}
+
+Status DataTypeTimeStampNsSerDe::write_column_to_arrow(const IColumn& column,
+                                                       const NullMap* null_map,
+                                                       arrow::ArrayBuilder* 
array_builder,
+                                                       int64_t start, int64_t 
end,
+                                                       const cctz::time_zone& 
ctz) const {
+    return 
Status::NotSupported("DataTypeTimeStampNsSerDe::write_column_to_arrow");

Review Comment:
   external table will be supported later.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to