Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions be/src/util/jsonb_parser_simd.h
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,29 @@ struct JsonbParser {
simdjson::padded_string json_str {pch, len};
simdjson::ondemand::document doc = simdjson_parser.iterate(json_str);

auto is_json_whitespace = [](char c) {
return c == ' ' || c == '\t' || c == '\n' || c == '\r';
};
const char* json_begin = json_str.data();
const char* json_end = json_str.data() + len;
while (json_begin < json_end && is_json_whitespace(*json_begin)) {
++json_begin;
}
while (json_end > json_begin && is_json_whitespace(*(json_end - 1))) {
--json_end;
}

std::string_view raw_json;
simdjson::error_code raw_res = doc.raw_json().get(raw_json);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This raw_json() call consumes the entire document, then doc.rewind() makes the code parse and serialize the same JSON again. JsonbParser::parse is shared by json_valid, jsonb_parse, casts to JSONB, and other ingestion paths, so large object/array inputs now pay an extra full simdjson traversal just to detect trailing content. The later code already consumes the root value and checks doc.at_end(), while top-level scalar getters use simdjson's root APIs that disallow trailing content and the new is_null() check covers the not/partial-null case. Please avoid the whole-document raw_json() pre-pass and enforce the remaining scalar/null validation in the existing parse pass so JSONB parsing stays single-pass.

if (raw_res != simdjson::SUCCESS) {
return Status::InvalidArgument(fmt::format("simdjson raw_json failed: {}",
simdjson::error_message(raw_res)));
}
if (raw_json.data() != json_begin || raw_json.data() + raw_json.size() != json_end) {
return Status::InvalidArgument("simdjson parse exception: trailing content");
}
doc.rewind();

// simdjson process top level primitive types specially
// so some repeated code here
switch (doc.type()) {
Expand All @@ -102,6 +125,12 @@ struct JsonbParser {
break;
}
case simdjson::ondemand::json_type::null: {
bool is_null = false;
simdjson::error_code res = doc.is_null().get(is_null);
if (res != simdjson::SUCCESS || !is_null) {
return Status::InvalidArgument(fmt::format("simdjson get null failed: {}",
simdjson::error_message(res)));
}
if (writer.writeNull() == 0) {
return Status::InvalidArgument("writeNull failed");
}
Expand Down Expand Up @@ -130,6 +159,9 @@ struct JsonbParser {
break;
}
}
if (!doc.at_end()) {
return Status::InvalidArgument("simdjson parse exception: trailing content");
}
} catch (simdjson::simdjson_error& e) {
return Status::InvalidArgument(fmt::format("simdjson parse exception: {}", e.what()));
}
Expand Down
5 changes: 3 additions & 2 deletions be/test/core/value/jsonb_value_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ TEST(JsonBinaryValueTest, TestValidation) {
JsonBinaryValue json_val;

// Empty string and non-JSON text should fail to parse
std::vector<string> invalid_strs = {"", "abc"};
std::vector<string> invalid_strs = {"", "abc", "not",
"not json", "null junk", R"({"a":1} junk)"};
for (size_t i = 0; i < invalid_strs.size(); i++) {
auto status = json_val.from_json_string(invalid_strs[i].c_str(), invalid_strs[i].size());
EXPECT_FALSE(status.ok()) << "Should fail for: [" << invalid_strs[i] << "]";
Expand All @@ -55,4 +56,4 @@ TEST(JsonBinaryValueTest, TestValidation) {
EXPECT_TRUE(status.ok()) << "Should succeed for: [" << valid_strs[i] << "]";
}
}
} // namespace doris
} // namespace doris
18 changes: 18 additions & 0 deletions be/test/exprs/function/function_jsonb_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,24 @@ TEST(FunctionJsonbTEST, JsonbParseErrorToValueTest) {
ASSERT_EQ(st.code(), ErrorCode::INVALID_ARGUMENT) << st.to_string();
}

TEST(FunctionJsonbTEST, JsonValidStrictTest) {
std::string func_name = "json_valid";
InputTypeSet input_types = {Nullable {PrimitiveType::TYPE_VARCHAR}};

DataSet data_set = {
{{Null()}, Null()},
{{STRING("not")}, INT(0)},
{{STRING("not json")}, INT(0)},
{{STRING("null junk")}, INT(0)},
{{STRING(R"({"a":1} junk)")}, INT(0)},
{{STRING("null")}, INT(1)},
{{STRING("true")}, INT(1)},
{{STRING(R"({"a":1})")}, INT(1)},
};

static_cast<void>(check_function<DataTypeInt32, true>(func_name, input_types, data_set));
}

TEST(FunctionJsonbTEST, JsonbExtractTest) {
std::string func_name = "jsonb_extract";
InputTypeSet input_types = {PrimitiveType::TYPE_JSONB, PrimitiveType::TYPE_VARCHAR};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ public <R, C> R accept(ExpressionVisitor<R, C> visitor, C context) {
@Override
public Expression rewriteWhenAnalyze() {
JsonbExtract jsonExtract = new JsonbExtract(children.get(0), children.get(1));
// Keep the historical JSON typed-extract behavior: extract JSONB first and then use the
// normal cast rules, so convertible mismatched JSON values are allowed by design.
return new Cast(jsonExtract, BigIntType.INSTANCE, false);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ public <R, C> R accept(ExpressionVisitor<R, C> visitor, C context) {
@Override
public Expression rewriteWhenAnalyze() {
JsonbExtract jsonExtract = new JsonbExtract(children.get(0), children.get(1));
// Keep the historical JSON typed-extract behavior: extract JSONB first and then use the
// normal cast rules, so convertible mismatched JSON values are allowed by design.
return new Cast(jsonExtract, BooleanType.INSTANCE, false);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ public <R, C> R accept(ExpressionVisitor<R, C> visitor, C context) {
@Override
public Expression rewriteWhenAnalyze() {
JsonbExtract jsonExtract = new JsonbExtract(children.get(0), children.get(1));
// Keep the historical JSON typed-extract behavior: extract JSONB first and then use the
// normal cast rules, so convertible mismatched JSON values are allowed by design.
return new Cast(jsonExtract, DoubleType.INSTANCE, false);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ public <R, C> R accept(ExpressionVisitor<R, C> visitor, C context) {
@Override
public Expression rewriteWhenAnalyze() {
JsonbExtract jsonExtract = new JsonbExtract(children.get(0), children.get(1));
// Keep the historical JSON typed-extract behavior: extract JSONB first and then use the
// normal cast rules, so convertible mismatched JSON values are allowed by design.
return new Cast(jsonExtract, IntegerType.INSTANCE, false);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ public <R, C> R accept(ExpressionVisitor<R, C> visitor, C context) {
@Override
public Expression rewriteWhenAnalyze() {
JsonbExtract jsonExtract = new JsonbExtract(children.get(0), children.get(1));
// Keep the historical JSON typed-extract behavior: extract JSONB first and then use the
// normal cast rules, so convertible mismatched JSON values are allowed by design.
return new Cast(jsonExtract, LargeIntType.INSTANCE, false);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@ public <R, C> R accept(ExpressionVisitor<R, C> visitor, C context) {
@Override
public Expression rewriteWhenAnalyze() {
JsonbExtract jsonExtract = new JsonbExtract(children.get(0), children.get(1));
// Keep the historical JSON typed-extract behavior: extract JSONB first and then use the
// normal cast rules, so convertible mismatched JSON values are allowed by design.
return new Cast(jsonExtract, StringType.INSTANCE, false);
}
}
34 changes: 34 additions & 0 deletions regression-test/suites/jsonb_p0/test_json_valid_strict.groovy
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// 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.

suite("test_json_valid_strict") {
def jsonValid = sql """
select
json_valid('not json'),
json_valid('not'),
json_valid('null junk'),
json_valid('{"a":1} junk'),
json_valid('{"a":1}')
from (select 1) t
order by 1
"""
assertEquals(0, jsonValid[0][0])
assertEquals(0, jsonValid[0][1])
assertEquals(0, jsonValid[0][2])
assertEquals(0, jsonValid[0][3])
assertEquals(1, jsonValid[0][4])
}
Loading