This is an automated email from the ASF dual-hosted git repository.
jacktengg pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git
The following commit(s) were added to refs/heads/master by this push:
new 8e5aa4a8420 [fix](arrow-flight) Preserve nullable MAP keys with an
optional list schema (#71157)
8e5aa4a8420 is described below
commit 8e5aa4a8420c2d7ba6d4aeabbb7175b18087123b
Author: TengJianPing <[email protected]>
AuthorDate: Thu Dec 3 18:10:54 2026 +0800
[fix](arrow-flight) Preserve nullable MAP keys with an optional list schema
(#71157)
### Background
Doris MAP permits NULL keys; Arrow MAP requires non-null keys. Flight
publishes schemas through query and metadata APIs before streaming
record batches, so the chosen representation must agree across these
paths and across every batch.
### What problem does this PR solve?
Issue Number: close #67372
Related PR: #21955 (introduced explicit NULL-key rejection in Arrow MAP
serialization)
PR Type: Bugfix
Problem Summary:
Flight queries fail when a Doris MAP contains a NULL key. Add the
default-off session option arrow_flight_sql_map_as_list: when enabled,
every MAP in the result recursively becomes a LIST of key/value STRUCT
entries with nullable keys. This preserves entries without changing the
schema based on batch contents; existing clients retain Arrow MAP unless
they opt in.
### Details
- **Change map:** 19 files, +576/-15: production code +133/-15, tests
+413/-0, generated output +30/-0, docs/build files 0. FE carries the
session policy into schema APIs and both result-sink planning paths. BE
constructs the matching schema, validates nested bindings and writes
nullable list entries. Tests cover schema consistency, stale prepared
handles, constants, nesting, slices and IPC.
- **Frequency:** Any streamed MAP with a NULL key fails under the
existing Arrow MAP representation, including a later batch after earlier
valid keys.
- **Root cause:** Arrow's key-nullability constraint cannot represent
Doris's full MAP domain. The existing SerDe correctly rejects such keys
but Flight offered no lossless alternative.
- **Why existing tests missed it:** DataTypeMapNullKeySerDeTest uses the
string "NULL", not a null key. Prior Flight schema tests did not
exercise a query-wide nullable-key representation.
- **Fix:** Carry an immutable query policy through optional TResultSink
field 5; recursively align GetSchema, prepare, GetTables and BE schemas.
The new writer preserves NULL keys/values, empty maps and outer SQL
NULL. Existing strict MAP serialization remains the default.
- **Other paths and branches:** Both result sink planners and
local/remote DoGet use the policy. Generic table/export Arrow converters
retain their existing schema. Flight disables typed FE-side query
results and SQL-cache replay; existing prepared-schema checks invalidate
handles after a policy change. Cached release refs 3.1 through 4.2
retain the rejection; no backport is included.
- **Behavior change:** Run SET arrow_flight_sql_map_as_list = true on
the Flight session to opt in. The default is false; the option affects
all nested MAPs. Enable it only after FE and serving BEs are upgraded.
Field 5 is optional, unused on all audited release branches, and
allocated on master first; storage formats are unchanged.
### Testing
Local run-fe-ut.sh: 53 tests passed across DorisFlightSqlSchemaTest,
FlightSqlMetadataOrderTest and ResultSinkMetadataTest. Local ASAN
run-be-ut.sh: 61 tests passed across the new map tests and adjacent
schema, metadata, Variant, timestamp and generic converter suites.
clang-format 16, header hygiene, clang-tidy and FE Checkstyle passed.
The full ASAN FE/BE build passed. On an isolated single-BE cluster, the
new Flight JDBC suite reproduced the error with the option off, then
passed with it on for constants, nesting, empty results, prepared
queries and serial/parallel sinks. Runner-generated output was inspected
and a separate comparison run passed. Remote-reader propagation was
checked statically; no multi-BE or mixed-version cluster was run.
### Release note
Arrow Flight SQL can return MAP values containing NULL keys when
arrow_flight_sql_map_as_list is enabled. The result uses a list of
key/value structs; the default Arrow MAP schema is unchanged.
### Check List (For Author)
- Behavior changed: Yes (see Details)
- Does this need documentation: Yes; add the session option, output
schema example and upgrade prerequisite to apache/doris-website before
release.
- Pre-submission status: Ready
### AI Disclosure
- Tool: Codex (GPT-6)
- Generated: Code, unit/regression tests and this description; subagents
collected read-only evidence.
- Human review: Pending.
<!-- Recommended: develop the change with the develop-with-evidence
skill and write this description with the doris-pr-description skill,
both from https://github.com/apache/doris-skills (the doris-skills
submodule of this repository). -->
### Background
<!-- How the feature or module this PR touches works today, in two to
four plain sentences, for a reviewer who doesn't know it. Link the user
doc if there is one. Leave the problem and the fix to Problem Summary.
-->
### What problem does this PR solve?
<!-- Issue Number: "close #N" if this PR resolves the issue, "#N" if it
only relates to it, "None" if there is none. A Feature needs an issue.
-->
<!-- Related PR: "#N (relation)" for each PR a reviewer should know
about, such as "#123 (introduced the bug)", separated by commas. Write
"None" if no related PR is known. -->
<!-- PR Type: Bugfix, Performance, Feature, Enhancement, Refactor, Test,
Build/CI/Chore, Revert, Release/Dependency, or Other. -->
Issue Number:
Related PR:
PR Type:
Problem Summary:
<!-- Two to five sentences: the problem or need and who is affected; the
approach in one sentence; when the diff is larger than that suggests,
what else it had to handle, or that most of it is tests; and what
existing users see after an upgrade. -->
### Details
<!--
For a diff of more than about 300 changed lines, start with "- **Change
map:**": how many lines are production code, tests, generated files, and
docs, then the code in parts, each with the problem it handles and its
size.
Then answer each field of your PR type on its own line, as "- **Field:**
answer", in this order:
Bugfix: Frequency, Root cause, Why existing tests missed it, Fix, Other
paths and branches
Performance: Why it was slow, Optimization, Results, Applicability and
cost
Feature: Scope, Design, Usage, Default behavior, Compatibility
Enhancement: Before and after, Configs and defaults, Impact on existing
users
Refactor: Moves vs. logic changes, Behavior change, Compatibility,
Performance impact, Rollback
Test, adding tests: Scenarios, What existing tests miss, Fails when
broken
Test, fixing a test: Failure, Cause, Stability evidence
Build/CI/Chore: Affected, Developer and release impact, License and
third-party, Rollback
Revert: Why not fix forward, Original author notified, Follow-up
Release/Dependency: Versions, Upstream changes, Compatibility, Rollback
Other: Why Other
"None" is a valid answer when it is true. Don't restate the diff.
-->
### Testing
<!-- The tests, suites, or commands that ran, what each shows, and where
it ran (locally or in CI). For a fix, the test that fails before it and
passes after. -->
### Notes for Reviewers
<!-- Optional; delete this section if there is nothing to say. Why each
non-obvious edit was made, what you are unsure about, and where to start
reading if Details has no Change map. -->
### Release note
<!-- One paragraph on what users will notice, or None. -->
### Check List (For Author)
<!-- Behavior changed: "No", or "Yes (see Details)" with a Behavior
change field in Details. -->
<!-- Does this need documentation: "No", or "Yes" with the
apache/doris-website PR or the plan. -->
<!-- Pre-submission status: "Ready"; "Partially verified: " and what is
not verified; or "Not ready: " and why, for a Draft PR. -->
- Behavior changed:
- Does this need documentation:
- Pre-submission status:
### AI Disclosure
<!-- Tool: the agent and model, or None. Generated: the parts it wrote
(code, tests, this description), or None. Human review: what you
reviewed of the generated parts, or "Not applicable" without AI tools.
You may add "- Prompts:" to summarize how you directed the agent. -->
- Tool:
- Generated:
- Human review:
---
.../core/data_type_serde/data_type_map_serde.cpp | 26 ++-
be/src/exec/operator/result_sink_operator.cpp | 10 +-
be/src/exec/operator/result_sink_operator.h | 1 +
be/src/format/arrow/arrow_block_convertor.cpp | 28 +++
be/src/format/arrow/arrow_row_batch.cpp | 15 ++
be/src/format/arrow/arrow_row_batch.h | 11 +-
be/test/format/arrow/arrow_flight_map_test.cpp | 240 +++++++++++++++++++++
.../doris/arrowflight/FlightSqlQuerySchema.java | 6 +-
.../doris/arrowflight/FlightSqlSchemaHelper.java | 21 +-
.../glue/translator/PhysicalPlanTranslator.java | 3 +-
.../org/apache/doris/planner/PlanFragment.java | 4 +-
.../java/org/apache/doris/planner/ResultSink.java | 7 +
.../java/org/apache/doris/qe/SessionVariable.java | 14 ++
.../arrowflight/DorisFlightSqlSchemaTest.java | 54 +++++
.../arrowflight/FlightSqlMetadataOrderTest.java | 46 ++++
.../FlightSqlSchemaHelperCatalogTest.java | 2 +
.../doris/planner/ResultSinkMetadataTest.java | 15 ++
gensrc/thrift/DataSinks.thrift | 2 +
.../test_flight_map_nullable_keys.out | 30 +++
.../test_flight_map_nullable_keys.groovy | 58 +++++
20 files changed, 578 insertions(+), 15 deletions(-)
diff --git a/be/src/core/data_type_serde/data_type_map_serde.cpp
b/be/src/core/data_type_serde/data_type_map_serde.cpp
index 545b1bb9e68..9e08088896f 100644
--- a/be/src/core/data_type_serde/data_type_map_serde.cpp
+++ b/be/src/core/data_type_serde/data_type_map_serde.cpp
@@ -397,16 +397,38 @@ void DataTypeMapSerDe::write_one_cell_to_jsonb(const
IColumn& column, JsonbWrite
Status DataTypeMapSerDe::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 {
- auto& builder = assert_cast<arrow::MapBuilder&>(*array_builder);
const auto& map_column = assert_cast<const ColumnMap&>(column);
const IColumn& nested_keys_column = map_column.get_keys();
const IColumn& nested_values_column = map_column.get_values();
// now we default set key value in map is nullable
DCHECK(nested_keys_column.is_nullable());
DCHECK(nested_values_column.is_nullable());
+ const auto& offsets = map_column.get_offsets();
+ // The opted-in Flight LIST schema can retain MAP(NULL, 100), which Arrow
MAP rejects.
+ if (array_builder->type()->id() == arrow::Type::LIST) {
+ auto& list = assert_cast<arrow::ListBuilder&>(*array_builder);
+ auto& entries =
assert_cast<arrow::StructBuilder&>(*list.value_builder());
+ for (int64_t row = start; row < end; ++row) {
+ if (null_map && (*null_map)[row]) {
+ RETURN_IF_ERROR(checkArrowStatus(list.AppendNull(), column,
*array_builder));
+ continue;
+ }
+ RETURN_IF_ERROR(checkArrowStatus(list.Append(), column,
*array_builder));
+ RETURN_IF_ERROR(
+ checkArrowStatus(entries.AppendValues(offsets[row] -
offsets[row - 1], nullptr),
+ column, *array_builder));
+
RETURN_IF_ERROR(key_serde->write_column_to_arrow(nested_keys_column, nullptr,
+
entries.field_builder(0),
+ offsets[row - 1],
offsets[row], ctz));
+ RETURN_IF_ERROR(value_serde->write_column_to_arrow(
+ nested_values_column, nullptr, entries.field_builder(1),
offsets[row - 1],
+ offsets[row], ctz));
+ }
+ return Status::OK();
+ }
+ auto& builder = assert_cast<arrow::MapBuilder&>(*array_builder);
const auto* keys_nullmap_data =
assert_cast<const
ColumnNullable&>(nested_keys_column).get_null_map_data().data();
- const auto& offsets = map_column.get_offsets();
auto* key_builder = builder.key_builder();
auto* value_builder = builder.item_builder();
diff --git a/be/src/exec/operator/result_sink_operator.cpp
b/be/src/exec/operator/result_sink_operator.cpp
index cf705be1257..dd24fb21d6d 100644
--- a/be/src/exec/operator/result_sink_operator.cpp
+++ b/be/src/exec/operator/result_sink_operator.cpp
@@ -101,6 +101,8 @@ ResultSinkOperatorX::ResultSinkOperatorX(int operator_id,
int node_id,
: sink.type),
_enable_arrow_type_metadata(sink.__isset.enable_arrow_type_metadata
&&
sink.enable_arrow_type_metadata),
+
_arrow_flight_sql_map_as_list(sink.__isset.arrow_flight_sql_map_as_list &&
+ sink.arrow_flight_sql_map_as_list),
_result_sink_buffer_size_rows(_sink_type ==
TResultSinkType::ARROW_FLIGHT_PROTOCOL
?
config::arrow_flight_result_sink_buffer_size_rows
: RESULT_SINK_BUFFER_SIZE),
@@ -120,11 +122,11 @@ Status ResultSinkOperatorX::prepare(RuntimeState* state) {
if (_sink_type == TResultSinkType::ARROW_FLIGHT_PROTOCOL) {
// Capability negotiation selects one immutable policy for schema
fetches and batches.
if (_enable_arrow_type_metadata) {
- _arrow_schema_convertor =
-
std::make_shared<ArrowFlightSchemaConvertor>(state->timezone());
+ _arrow_schema_convertor =
std::make_shared<ArrowFlightSchemaConvertor>(
+ state->timezone(), _arrow_flight_sql_map_as_list);
} else {
- _arrow_schema_convertor =
-
std::make_shared<LegacyArrowFlightSchemaConvertor>(state->timezone());
+ _arrow_schema_convertor =
std::make_shared<LegacyArrowFlightSchemaConvertor>(
+ state->timezone(), _arrow_flight_sql_map_as_list);
}
}
diff --git a/be/src/exec/operator/result_sink_operator.h
b/be/src/exec/operator/result_sink_operator.h
index 45bf7f54aac..a5b2cfbd5a4 100644
--- a/be/src/exec/operator/result_sink_operator.h
+++ b/be/src/exec/operator/result_sink_operator.h
@@ -154,6 +154,7 @@ private:
const TResultSinkType::type _sink_type;
const bool _enable_arrow_type_metadata;
+ const bool _arrow_flight_sql_map_as_list;
std::shared_ptr<const DorisArrowSchemaConvertor> _arrow_schema_convertor;
const int _result_sink_buffer_size_rows;
diff --git a/be/src/format/arrow/arrow_block_convertor.cpp
b/be/src/format/arrow/arrow_block_convertor.cpp
index b4d38f939f2..42b1cbb9ef8 100644
--- a/be/src/format/arrow/arrow_block_convertor.cpp
+++ b/be/src/format/arrow/arrow_block_convertor.cpp
@@ -323,6 +323,27 @@ bool is_declared_plain_arrow_binding(const DataTypePtr&
type,
is_declared_plain_arrow_binding(array.get_nested_type(),
plain_list.value_type(),
target_list.value_type());
}
+ if (primitive == TYPE_MAP && plain_arrow_type->id() == arrow::Type::LIST &&
+ target_type->id() == arrow::Type::LIST) {
+ const auto& map = assert_cast<const
DataTypeMap&>(*remove_nullable(type));
+ const auto& plain_entries = plain_arrow_type->field(0);
+ const auto& target_entries = target_type->field(0);
+ if
(!plain_entries->WithType(target_entries->type())->Equals(target_entries) ||
+ target_entries->type()->id() != arrow::Type::STRUCT ||
+ target_entries->type()->num_fields() != 2) {
+ return false;
+ }
+ for (int i = 0; i < 2; ++i) {
+ const auto& plain_field = plain_entries->type()->field(i);
+ const auto& target_field = target_entries->type()->field(i);
+ if
(!plain_field->WithType(target_field->type())->Equals(target_field) ||
+ !is_declared_plain_arrow_binding(i == 0 ? map.get_key_type() :
map.get_value_type(),
+ plain_field->type(),
target_field->type())) {
+ return false;
+ }
+ }
+ return true;
+ }
if (primitive == TYPE_MAP && plain_arrow_type->id() == arrow::Type::MAP &&
target_type->id() == arrow::Type::MAP) {
const auto& map = assert_cast<const
DataTypeMap&>(*remove_nullable(type));
@@ -473,6 +494,13 @@ Status ArrowFlightArrowBlockConvertor::write_column(const
std::shared_ptr<const
if (is_declared_plain_arrow_binding(type, native_type, field->type())) {
return serde.write_column_to_arrow(column, null_map, array_builder,
start, end, ctz);
}
+ // MAP-as-LIST is a schema policy, including nested MAPs. Validate the
whole shape
+ // before using the nullable-key writer; arbitrary LIST/STRUCT bindings
remain invalid.
+ RETURN_IF_ERROR(
+ ArrowFlightSchemaConvertor(ctz.name(),
true).convert_to_arrow_type(type, &native_type));
+ if (is_declared_plain_arrow_binding(type, native_type, field->type())) {
+ return serde.write_column_to_arrow(column, null_map, array_builder,
start, end, ctz);
+ }
return DorisArrowBlockConvertor::write_column(type, serde, column,
null_map, field,
array_builder, start, end,
ctz);
}
diff --git a/be/src/format/arrow/arrow_row_batch.cpp
b/be/src/format/arrow/arrow_row_batch.cpp
index 28b6163c322..77cd6702e7b 100644
--- a/be/src/format/arrow/arrow_row_batch.cpp
+++ b/be/src/format/arrow/arrow_row_batch.cpp
@@ -273,6 +273,21 @@ std::string
PythonArrowSchemaConvertor::timestamp_timezone(PrimitiveType type) c
Status ArrowFlightSchemaConvertor::convert_to_arrow_type(
const DataTypePtr& type, std::shared_ptr<arrow::DataType>* result)
const {
+ // MAP(NULL, 100) cannot use Arrow MAP: its key field must be non-nullable.
+ // The explicit LIST policy preserves that entry with a nullable key.
+ if (_map_as_list && type->get_primitive_type() == TYPE_MAP) {
+ const auto& map = assert_cast<const
DataTypeMap&>(*remove_nullable(type));
+ std::shared_ptr<arrow::DataType> key_type;
+ std::shared_ptr<arrow::DataType> value_type;
+ RETURN_IF_ERROR(convert_to_arrow_type(map.get_key_type(), &key_type));
+ RETURN_IF_ERROR(convert_to_arrow_type(map.get_value_type(),
&value_type));
+ auto entries = arrow::struct_(
+ {make_child_field("key", key_type, true,
map.get_key_type()->get_primitive_type()),
+ make_child_field("value", value_type, true,
+
map.get_value_type()->get_primitive_type())});
+ *result = arrow::list(arrow::field("entries", entries, false));
+ return Status::OK();
+ }
// Flight always uses native Variant, including recursively converted
children.
if (type->get_primitive_type() == TYPE_VARIANT) {
// Reject by type before reading rows, including empty results and
nested legacy leaves.
diff --git a/be/src/format/arrow/arrow_row_batch.h
b/be/src/format/arrow/arrow_row_batch.h
index e7c78edc97a..703a59c787c 100644
--- a/be/src/format/arrow/arrow_row_batch.h
+++ b/be/src/format/arrow/arrow_row_batch.h
@@ -97,16 +97,19 @@ private:
class ArrowFlightSchemaConvertor : public DorisArrowSchemaConvertor {
public:
- explicit ArrowFlightSchemaConvertor(std::string timezone)
- : DorisArrowSchemaConvertor(std::move(timezone)) {}
- ArrowFlightSchemaConvertor(const Block& header, std::string timezone)
- : DorisArrowSchemaConvertor(header, std::move(timezone)) {}
+ explicit ArrowFlightSchemaConvertor(std::string timezone, bool map_as_list
= false)
+ : DorisArrowSchemaConvertor(std::move(timezone)),
_map_as_list(map_as_list) {}
+ ArrowFlightSchemaConvertor(const Block& header, std::string timezone, bool
map_as_list = false)
+ : DorisArrowSchemaConvertor(header, std::move(timezone)),
_map_as_list(map_as_list) {}
Status convert_to_arrow_type(const DataTypePtr& type,
std::shared_ptr<arrow::DataType>* result)
const override;
protected:
std::string timestamp_timezone(PrimitiveType type) const override;
+
+private:
+ const bool _map_as_list;
};
// Old FEs require the pre-capability metadata layout, including metadata-free
nested fields.
diff --git a/be/test/format/arrow/arrow_flight_map_test.cpp
b/be/test/format/arrow/arrow_flight_map_test.cpp
new file mode 100644
index 00000000000..d11ae6635cf
--- /dev/null
+++ b/be/test/format/arrow/arrow_flight_map_test.cpp
@@ -0,0 +1,240 @@
+// 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 <arrow/api.h>
+#include <arrow/io/api.h>
+#include <arrow/ipc/api.h>
+#include <gtest/gtest.h>
+
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "core/assert_cast.h"
+#include "core/column/column_const.h"
+#include "core/column/column_nullable.h"
+#include "core/data_type/data_type_array.h"
+#include "core/data_type/data_type_map.h"
+#include "core/data_type/data_type_nullable.h"
+#include "core/data_type/data_type_number.h"
+#include "core/data_type/data_type_string.h"
+#include "core/data_type/data_type_struct.h"
+#include "core/data_type/data_type_timestamptz.h"
+#include "format/arrow/arrow_block_convertor.h"
+#include "format/arrow/arrow_row_batch.h"
+#include "testutil/datetime_ut_util.h"
+#include "util/timezone_utils.h"
+
+namespace doris {
+namespace {
+
+DataTypePtr map_type() {
+ return
std::make_shared<DataTypeMap>(make_nullable(std::make_shared<DataTypeString>()),
+
make_nullable(std::make_shared<DataTypeInt32>()));
+}
+
+Field map_value(bool null_key) {
+ return Field::create_field<TYPE_MAP>(Map {
+ Field::create_field<TYPE_ARRAY>(
+ Array {null_key ? Field() :
Field::create_field<TYPE_STRING>("a"),
+ Field::create_field<TYPE_STRING>("b")}),
+ Field::create_field<TYPE_ARRAY>(Array
{Field::create_field<TYPE_INT>(100), Field()})});
+}
+
+std::shared_ptr<arrow::Schema> list_schema(const Block& block) {
+ std::shared_ptr<arrow::Schema> schema;
+ EXPECT_TRUE(ArrowFlightSchemaConvertor(block, "UTC",
true).get_arrow_schema(&schema).ok());
+ return schema;
+}
+
+void check_null_entry(const arrow::Array& array, int row) {
+ const auto& list = assert_cast<const arrow::ListArray&>(array);
+ ASSERT_FALSE(list.IsNull(row));
+ ASSERT_EQ(list.value_length(row), 2);
+ const auto& entries = assert_cast<const
arrow::StructArray&>(*list.values());
+ int64_t start = list.value_offset(row);
+ EXPECT_FALSE(entries.IsNull(start));
+ EXPECT_TRUE(entries.field(0)->IsNull(start));
+ EXPECT_EQ(assert_cast<const
arrow::Int32Array&>(*entries.field(1)).Value(start), 100);
+ EXPECT_EQ(assert_cast<const
arrow::StringArray&>(*entries.field(0)).GetString(start + 1), "b");
+ EXPECT_TRUE(entries.field(1)->IsNull(start + 1));
+}
+
+TEST(ArrowFlightMapTest, NullableKeysSurviveBatchesSlicesAndIpc) {
+ auto type = map_type();
+ auto column = type->create_column();
+ column->insert(map_value(false));
+ column->insert(map_value(true));
+ column->insert_default(); // Empty MAP, distinct from a NULL MAP.
+ column->insert(map_value(true)); // Hidden children under SQL NULL must
not leak.
+ auto nulls = ColumnUInt8::create();
+ nulls->get_data().assign({0, 0, 0, 1});
+ Block block {{ColumnNullable::create(std::move(column), std::move(nulls)),
make_nullable(type),
+ "m"}};
+ auto schema = list_schema(block);
+ ASSERT_EQ(schema->field(0)->type()->id(), arrow::Type::LIST);
+ auto entries_field = schema->field(0)->type()->field(0);
+ EXPECT_EQ(entries_field->name(), "entries");
+ EXPECT_FALSE(entries_field->nullable());
+ EXPECT_TRUE(entries_field->type()->field(0)->nullable());
+ ArrowFlightArrowBlockConvertor converter(schema, cctz::utc_time_zone());
+ std::shared_ptr<arrow::RecordBatch> batch;
+ auto status = converter.convert_to_arrow(block,
arrow::default_memory_pool(), &batch);
+ ASSERT_TRUE(status.ok()) << status;
+ ASSERT_TRUE(batch->ValidateFull().ok());
+ check_null_entry(*batch->column(0), 1);
+ const auto& list = assert_cast<const arrow::ListArray&>(*batch->column(0));
+ EXPECT_EQ(list.value_length(2), 0);
+ EXPECT_FALSE(list.IsNull(2));
+ EXPECT_TRUE(list.IsNull(3));
+ EXPECT_EQ(list.values()->length(), 4);
+
+ auto output = arrow::io::BufferOutputStream::Create().ValueOrDie();
+ auto writer = arrow::ipc::MakeStreamWriter(output, schema).ValueOrDie();
+ ASSERT_TRUE(writer->WriteRecordBatch(*batch).ok());
+ ASSERT_TRUE(writer->Close().ok());
+ auto input =
std::make_shared<arrow::io::BufferReader>(output->Finish().ValueOrDie());
+ auto reader =
arrow::ipc::RecordBatchStreamReader::Open(input).ValueOrDie();
+ auto restored = reader->Next().ValueOrDie();
+ EXPECT_TRUE(batch->Equals(*restored));
+ check_null_entry(*restored->column(0), 1);
+
+ // The first batch has no NULL keys; the second must retain exactly the
same schema.
+ ASSERT_TRUE(converter.convert_to_arrow(block,
arrow::default_memory_pool(), &batch, 0, 1).ok());
+ EXPECT_TRUE(batch->schema()->Equals(schema));
+ ASSERT_TRUE(converter.convert_to_arrow(block,
arrow::default_memory_pool(), &batch, 1, 4).ok());
+ ASSERT_TRUE(batch->ValidateFull().ok());
+ EXPECT_TRUE(batch->schema()->Equals(schema));
+ check_null_entry(*batch->column(0), 0);
+ EXPECT_TRUE(batch->column(0)->IsNull(2));
+}
+
+TEST(ArrowFlightMapTest, ConstantsAndNestedMapsUseTheSamePolicy) {
+ auto map = map_type();
+ auto scalar = make_nullable(map)->create_column();
+ scalar->insert(map_value(true));
+ Block constant {{ColumnConst::create(std::move(scalar), 3),
make_nullable(map), "m"}};
+ ArrowFlightArrowBlockConvertor constant_converter(list_schema(constant),
cctz::utc_time_zone());
+ std::shared_ptr<arrow::RecordBatch> batch;
+ ASSERT_TRUE(constant_converter.convert_to_arrow(constant,
arrow::default_memory_pool(), &batch)
+ .ok());
+ ASSERT_TRUE(batch->ValidateFull().ok());
+ for (int row = 0; row < 3; ++row) {
+ check_null_entry(*batch->column(0), row);
+ }
+
+ auto null_scalar = make_nullable(map)->create_column();
+ null_scalar->insert_default();
+ Block null_constant {{ColumnConst::create(std::move(null_scalar), 3),
make_nullable(map), "m"}};
+ ASSERT_TRUE(
+ constant_converter.convert_to_arrow(null_constant,
arrow::default_memory_pool(), &batch)
+ .ok());
+ ASSERT_TRUE(batch->ValidateFull().ok());
+ EXPECT_EQ(batch->column(0)->null_count(), 3);
+
+ auto array = std::make_shared<DataTypeArray>(make_nullable(map));
+ auto structure =
+ std::make_shared<DataTypeStruct>(DataTypes {make_nullable(map)},
Strings {"m"});
+ auto nested_map = std::make_shared<DataTypeMap>(
+ make_nullable(std::make_shared<DataTypeString>()),
make_nullable(map));
+ auto array_column = array->create_column();
+ array_column->insert(Field::create_field<TYPE_ARRAY>(Array
{map_value(true), Field()}));
+ auto struct_column = structure->create_column();
+ struct_column->insert(Field::create_field<TYPE_STRUCT>(Struct
{map_value(true)}));
+ auto map_column = nested_map->create_column();
+ map_column->insert(Field::create_field<TYPE_MAP>(
+ Map {Field::create_field<TYPE_ARRAY>(Array {Field()}),
+ Field::create_field<TYPE_ARRAY>(Array {map_value(true)})}));
+ Block nested {{std::move(array_column), array, "a"},
+ {std::move(struct_column), structure, "s"},
+ {std::move(map_column), nested_map, "m"}};
+ ArrowFlightArrowBlockConvertor nested_converter(list_schema(nested),
cctz::utc_time_zone());
+ auto status = nested_converter.convert_to_arrow(nested,
arrow::default_memory_pool(), &batch);
+ ASSERT_TRUE(status.ok()) << status;
+ ASSERT_TRUE(batch->ValidateFull().ok());
+ const auto& outer_array = assert_cast<const
arrow::ListArray&>(*batch->column(0));
+ check_null_entry(*outer_array.values(), 0);
+ EXPECT_TRUE(outer_array.values()->IsNull(1));
+ check_null_entry(*assert_cast<const
arrow::StructArray&>(*batch->column(1)).field(0), 0);
+ const auto& outer_map = assert_cast<const
arrow::ListArray&>(*batch->column(2));
+ const auto& entries = assert_cast<const
arrow::StructArray&>(*outer_map.values());
+ EXPECT_TRUE(entries.field(0)->IsNull(0));
+ check_null_entry(*entries.field(1), 0);
+}
+
+TEST(ArrowFlightMapTest,
NullableTimestampKeysKeepTimezoneAliasesAndLogicalMetadata) {
+ TimezoneUtils::load_timezones_to_cache();
+ cctz::time_zone timezone;
+ ASSERT_TRUE(TimezoneUtils::find_cctz_time_zone("+05:45", timezone));
+ auto type =
+
std::make_shared<DataTypeMap>(make_nullable(std::make_shared<DataTypeTimeStampTz>(6)),
+
make_nullable(std::make_shared<DataTypeInt128>()));
+ auto column = type->create_column();
+ column->insert(Field::create_field<TYPE_MAP>(
+ Map {Field::create_field<TYPE_ARRAY>(
+ Array {Field(), Field::create_field<TYPE_TIMESTAMPTZ>(
+ make_timestamptz(1970, 1, 1,
0, 0, 0, 0))}),
+ Field::create_field<TYPE_ARRAY>(
+ Array {Field::create_field<TYPE_LARGEINT>(Int128(1)
<< 100), Field()})}));
+ Block block {{std::move(column), type, "m"}};
+ std::shared_ptr<arrow::Schema> schema;
+ ASSERT_TRUE(ArrowFlightSchemaConvertor(block, "+05:45",
true).get_arrow_schema(&schema).ok());
+ auto entries_type = schema->field(0)->type()->field(0)->type();
+
EXPECT_EQ(entries_type->field(1)->metadata()->Get("doris_type").ValueOrDie(),
"LARGEINT");
+ ArrowFlightArrowBlockConvertor converter(schema, timezone);
+ std::shared_ptr<arrow::RecordBatch> batch;
+ auto status = converter.convert_to_arrow(block,
arrow::default_memory_pool(), &batch);
+ ASSERT_TRUE(status.ok()) << status;
+ ASSERT_TRUE(batch->ValidateFull().ok());
+ const auto& entries = assert_cast<const arrow::StructArray&>(
+ *assert_cast<const arrow::ListArray&>(*batch->column(0)).values());
+ EXPECT_TRUE(entries.field(0)->IsNull(0));
+ EXPECT_EQ(assert_cast<const
arrow::TimestampArray&>(*entries.field(0)).Value(1), 0);
+ EXPECT_EQ(assert_cast<const
arrow::StringArray&>(*entries.field(1)).GetString(0),
+ "1267650600228229401496703205376");
+ EXPECT_TRUE(entries.field(1)->IsNull(1));
+}
+
+TEST(ArrowFlightMapTest, DefaultAndInvalidBindingsRemainStrict) {
+ auto type = map_type();
+ auto column = type->create_column();
+ column->insert(map_value(true));
+ Block block {{std::move(column), type, "m"}};
+ std::shared_ptr<arrow::Schema> schema;
+ ASSERT_TRUE(ArrowFlightSchemaConvertor(block,
"UTC").get_arrow_schema(&schema).ok());
+ EXPECT_EQ(schema->field(0)->type()->id(), arrow::Type::MAP);
+ ArrowFlightArrowBlockConvertor strict(schema, cctz::utc_time_zone());
+ std::shared_ptr<arrow::RecordBatch> batch;
+ auto status = strict.convert_to_arrow(block, arrow::default_memory_pool(),
&batch);
+ EXPECT_FALSE(status.ok());
+ EXPECT_NE(status.to_string().find("null value of map key"),
std::string::npos);
+
+ auto malformed =
+ arrow::list(arrow::field("entries",
+ arrow::struct_({arrow::field("key",
arrow::utf8(), false),
+ arrow::field("value",
arrow::int32(), true)}),
+ false));
+ ArrowFlightArrowBlockConvertor invalid(arrow::schema({arrow::field("m",
malformed, false)}),
+ cctz::utc_time_zone());
+ EXPECT_FALSE(invalid.convert_to_arrow(block, arrow::default_memory_pool(),
&batch).ok());
+ std::shared_ptr<arrow::DataType> plain;
+ ASSERT_TRUE(DorisArrowSchemaConvertor("UTC").convert_to_arrow_type(type,
&plain).ok());
+ EXPECT_EQ(plain->id(), arrow::Type::MAP);
+}
+
+} // namespace
+} // namespace doris
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/arrowflight/FlightSqlQuerySchema.java
b/fe/fe-core/src/main/java/org/apache/doris/arrowflight/FlightSqlQuerySchema.java
index 3976ffa2edf..6f441e43598 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/arrowflight/FlightSqlQuerySchema.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/arrowflight/FlightSqlQuerySchema.java
@@ -215,8 +215,10 @@ final class FlightSqlQuerySchema {
// The zone BE stamps on TIMESTAMPTZ: the one it is sent, see
CoordinatorContext.
String timezone =
TimeUtils.getCanonicalTimeZone(context.getSessionVariable().getTimeZone());
for (Slot slot : analyzed.getOutput()) {
- fields.add(field(slot.getName(),
slot.getDataType().toCatalogDataType(), slot.nullable(),
- timezone));
+ Field field = field(slot.getName(),
slot.getDataType().toCatalogDataType(), slot.nullable(),
+ timezone);
+
fields.add(context.getSessionVariable().isArrowFlightSqlMapAsList()
+ ? FlightSqlSchemaHelper.withMapAsList(field) :
field);
}
}
return new Schema(fields);
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/arrowflight/FlightSqlSchemaHelper.java
b/fe/fe-core/src/main/java/org/apache/doris/arrowflight/FlightSqlSchemaHelper.java
index d167436ea26..70921670312 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/arrowflight/FlightSqlSchemaHelper.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/arrowflight/FlightSqlSchemaHelper.java
@@ -96,6 +96,24 @@ public class FlightSqlSchemaHelper {
private static final byte[] EMPTY_SERIALIZED_SCHEMA =
getSerializedSchema(Collections.emptyList());
+ // Choose the representation from the session, never from the rows in a
particular batch.
+ static Field withMapAsList(Field field) {
+ List<Field> children = field.getChildren().stream()
+
.map(FlightSqlSchemaHelper::withMapAsList).collect(Collectors.toList());
+ FieldType fieldType = field.getFieldType();
+ if (field.getType() instanceof ArrowType.Map) {
+ Field entries = children.get(0);
+ List<Field> pair = new ArrayList<>(entries.getChildren());
+ Field key = pair.get(0);
+ pair.set(0, new Field(key.getName(),
+ new FieldType(true, key.getType(), key.getDictionary(),
key.getMetadata()), key.getChildren()));
+ children.set(0, new Field(entries.getName(),
entries.getFieldType(), pair));
+ fieldType = new FieldType(field.isNullable(), new ArrowType.List(),
+ field.getDictionary(), field.getMetadata());
+ }
+ return new Field(field.getName(), fieldType, children);
+ }
+
static Field withDorisTypeMetadata(Field field, Type type) {
if (type.isVariantType()) {
if (field.getMetadata() == null
@@ -274,7 +292,8 @@ public class FlightSqlSchemaHelper {
Integer tableOffset =
describeTablesResult.getTablesOffset().get(tableIndex);
for (; columnIndex < tableOffset; columnIndex++) {
TColumnDef columnDef =
describeTablesResult.getColumns().get(columnIndex);
- fields.add(buildField(dbName, tableName,
columnDef.getColumnDesc()));
+ Field field = buildField(dbName, tableName,
columnDef.getColumnDesc());
+
fields.add(ctx.getSessionVariable().isArrowFlightSqlMapAsList() ?
withMapAsList(field) : field);
}
tableToFields.put(tableName, fields);
}
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/nereids/glue/translator/PhysicalPlanTranslator.java
b/fe/fe-core/src/main/java/org/apache/doris/nereids/glue/translator/PhysicalPlanTranslator.java
index 4910df358a8..ba2b392f055 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/nereids/glue/translator/PhysicalPlanTranslator.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/nereids/glue/translator/PhysicalPlanTranslator.java
@@ -492,7 +492,8 @@ public class PhysicalPlanTranslator extends
DefaultPlanVisitor<PlanFragment, Pla
PlanFragment planFragment = physicalResultSink.child().accept(this,
context);
TResultSinkType resultSinkType = context.getConnectContext() != null
? context.getConnectContext().getResultSinkType() : null;
- planFragment.setSink(new
ResultSink(planFragment.getPlanRoot().getId(), resultSinkType));
+ planFragment.setSink(new
ResultSink(planFragment.getPlanRoot().getId(), resultSinkType,
+ context.getConnectContext() != null &&
context.getSessionVariable().isArrowFlightSqlMapAsList()));
return planFragment;
}
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/planner/PlanFragment.java
b/fe/fe-core/src/main/java/org/apache/doris/planner/PlanFragment.java
index 98621ccc4f6..8d89f6ba84d 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/planner/PlanFragment.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/planner/PlanFragment.java
@@ -299,7 +299,9 @@ public class PlanFragment extends TreeNode<PlanFragment> {
return;
}
Preconditions.checkState(sink == null);
- sink = new ResultSink(planRoot.getId(), resultSinkType);
+ ConnectContext context = ConnectContext.get();
+ sink = new ResultSink(planRoot.getId(), resultSinkType,
+ context != null &&
context.getSessionVariable().isArrowFlightSqlMapAsList());
}
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/planner/ResultSink.java
b/fe/fe-core/src/main/java/org/apache/doris/planner/ResultSink.java
index 1d0ed9f5f9a..2904e0494b5 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/planner/ResultSink.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/planner/ResultSink.java
@@ -30,6 +30,7 @@ import org.apache.doris.thrift.TResultSinkType;
*/
public class ResultSink extends DataSink {
private final PlanNodeId exchNodeId;
+ private final boolean arrowFlightSqlMapAsList;
private TResultSinkType resultSinkType = TResultSinkType.MYSQL_PROTOCOL;
public ResultSink(PlanNodeId exchNodeId) {
@@ -37,8 +38,13 @@ public class ResultSink extends DataSink {
}
public ResultSink(PlanNodeId exchNodeId, TResultSinkType resultSinkType) {
+ this(exchNodeId, resultSinkType, false);
+ }
+
+ public ResultSink(PlanNodeId exchNodeId, TResultSinkType resultSinkType,
boolean arrowFlightSqlMapAsList) {
this.exchNodeId = exchNodeId;
this.resultSinkType = resultSinkType;
+ this.arrowFlightSqlMapAsList = arrowFlightSqlMapAsList;
}
@Override
@@ -58,6 +64,7 @@ public class ResultSink extends DataSink {
tResultSink.setType(resultSinkType);
if (resultSinkType == TResultSinkType.ARROW_FLIGHT_PROTOCOL) {
tResultSink.setEnableArrowTypeMetadata(true);
+ tResultSink.setArrowFlightSqlMapAsList(arrowFlightSqlMapAsList);
}
result.setResultSink(tResultSink);
return result;
diff --git a/fe/fe-core/src/main/java/org/apache/doris/qe/SessionVariable.java
b/fe/fe-core/src/main/java/org/apache/doris/qe/SessionVariable.java
index 3dc55b6dc92..885ef535872 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/qe/SessionVariable.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/qe/SessionVariable.java
@@ -281,6 +281,7 @@ public class SessionVariable implements Serializable,
Writable {
public static final String RUNTIME_FILTER_TREE_PUBLISH_MAX_SEND_BYTES =
"runtime_filter_tree_publish_max_send_bytes";
+ public static final String ARROW_FLIGHT_SQL_MAP_AS_LIST =
"arrow_flight_sql_map_as_list";
public static final String ENABLE_PARALLEL_RESULT_SINK =
"enable_parallel_result_sink";
public static final String HIVE_TEXT_COMPRESSION = "hive_text_compression";
@@ -1918,6 +1919,19 @@ public class SessionVariable implements Serializable,
Writable {
@VarAttrDef.VarAttr(name = "runtime_filter_max_build_row_count",
needForward = true, fuzzy = false)
public long runtimeFilterMaxBuildRowCount = 64L * 1024L * 1024L;
+ @VarAttrDef.VarAttr(name = ARROW_FLIGHT_SQL_MAP_AS_LIST, needForward =
true,
+ affectQueryResultInPlan = true,
+ description = "Return Arrow Flight MAP values as LIST<STRUCT<key,
value>> with nullable keys.")
+ private boolean arrowFlightSqlMapAsList = false;
+
+ public boolean isArrowFlightSqlMapAsList() {
+ return arrowFlightSqlMapAsList;
+ }
+
+ public void setArrowFlightSqlMapAsList(boolean value) {
+ arrowFlightSqlMapAsList = value;
+ }
+
@VarAttrDef.VarAttr(name = ENABLE_PARALLEL_RESULT_SINK, needForward =
true, fuzzy = true)
private boolean enableParallelResultSink = true;
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/arrowflight/DorisFlightSqlSchemaTest.java
b/fe/fe-core/src/test/java/org/apache/doris/arrowflight/DorisFlightSqlSchemaTest.java
index 9f9c9cc6d3c..5e26426eebf 100644
---
a/fe/fe-core/src/test/java/org/apache/doris/arrowflight/DorisFlightSqlSchemaTest.java
+++
b/fe/fe-core/src/test/java/org/apache/doris/arrowflight/DorisFlightSqlSchemaTest.java
@@ -682,6 +682,60 @@ public class DorisFlightSqlSchemaTest extends
TestWithFeService {
}
}
+ @Test
+ void mapPolicyIsRecursiveAndSharedByGetSchemaAndPrepare() throws Exception
{
+ String map = "CAST(MAP(NULL, 100, 'key', NULL) AS MAP<STRING, INT>)";
+ String query = "SELECT " + map + " AS m, ARRAY(" + map + ") AS a, "
+ + "NAMED_STRUCT('m', " + map + ") AS s";
+ boolean original =
flightContext.getSessionVariable().isArrowFlightSqlMapAsList();
+ try {
+ for (boolean asList : Arrays.asList(false, true)) {
+
flightContext.getSessionVariable().setArrowFlightSqlMapAsList(asList);
+ Schema schema = schema(query);
+ Assertions.assertEquals(schema, preparedSchema(query));
+ List<Field> maps = Arrays.asList(schema.getFields().get(0),
+ schema.getFields().get(1).getChildren().get(0),
+ schema.getFields().get(2).getChildren().get(0));
+ for (Field field : maps) {
+ Assertions.assertEquals(asList ? new ArrowType.List() :
new ArrowType.Map(false),
+ field.getType());
+ Field entries = field.getChildren().get(0);
+ Assertions.assertFalse(entries.isNullable());
+ Assertions.assertEquals(asList,
entries.getChildren().get(0).isNullable());
+
Assertions.assertTrue(entries.getChildren().get(1).isNullable());
+ }
+ }
+ } finally {
+
flightContext.getSessionVariable().setArrowFlightSqlMapAsList(original);
+ }
+ }
+
+ @Test
+ void preparedMapSchemaCannotDriftWithSessionPolicy() throws Exception {
+ boolean original =
flightContext.getSessionVariable().isArrowFlightSqlMapAsList();
+ try {
+ for (boolean fetchSchema : Arrays.asList(true, false)) {
+
flightContext.getSessionVariable().setArrowFlightSqlMapAsList(false);
+ ActionCreatePreparedStatementResult result = prepare("SELECT
MAP('key', 1) AS m");
+ CommandPreparedStatementQuery command = command(result);
+
flightContext.getSessionVariable().setArrowFlightSqlMapAsList(true);
+ FlightRuntimeException error =
Assertions.assertThrows(FlightRuntimeException.class, () -> {
+ if (fetchSchema) {
+ producer.getSchemaPreparedStatement(command,
callContext,
+ FlightDescriptor.command(new byte[0]));
+ } else {
+ producer.getFlightInfoPreparedStatement(command,
callContext,
+ FlightDescriptor.command(new byte[0]));
+ }
+ });
+ Assertions.assertEquals(FlightStatusCode.NOT_FOUND,
error.status().code());
+
Assertions.assertNull(flightContext.getPreparedQuery(preparedId(result)));
+ }
+ } finally {
+
flightContext.getSessionVariable().setArrowFlightSqlMapAsList(original);
+ }
+ }
+
@Test
void preparedSchemaCannotDriftWithSqlMode() throws Exception {
long mode = flightContext.getSessionVariable().getSqlMode();
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/arrowflight/FlightSqlMetadataOrderTest.java
b/fe/fe-core/src/test/java/org/apache/doris/arrowflight/FlightSqlMetadataOrderTest.java
index 7bac1e8cbd3..54cf63f6ead 100644
---
a/fe/fe-core/src/test/java/org/apache/doris/arrowflight/FlightSqlMetadataOrderTest.java
+++
b/fe/fe-core/src/test/java/org/apache/doris/arrowflight/FlightSqlMetadataOrderTest.java
@@ -47,6 +47,8 @@ import org.apache.arrow.vector.VarBinaryVector;
import org.apache.arrow.vector.VectorSchemaRoot;
import org.apache.arrow.vector.ipc.ReadChannel;
import org.apache.arrow.vector.ipc.message.MessageSerializer;
+import org.apache.arrow.vector.types.pojo.ArrowType;
+import org.apache.arrow.vector.types.pojo.Field;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
@@ -238,6 +240,50 @@ public class FlightSqlMetadataOrderTest {
}
}
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void tableSchemasHonorTheMapRepresentation(boolean asList) throws
Exception {
+ ConnectContext ctx = context(false);
+ ctx.getSessionVariable().setArrowFlightSqlMapAsList(asList);
+ TColumnDesc map = new TColumnDesc("m",
TPrimitiveType.MAP).setIsAllowNull(true);
+ map.setChildren(Arrays.asList(new TColumnDesc("key",
TPrimitiveType.STRING).setIsAllowNull(true),
+ new TColumnDesc("value",
TPrimitiveType.INT).setIsAllowNull(true)));
+ TColumnDesc array = new TColumnDesc("a",
TPrimitiveType.ARRAY).setIsAllowNull(true)
+ .setChildren(Collections.singletonList(map));
+ try (MockedStatic<ExecuteEnv> executeEnv =
Mockito.mockStatic(ExecuteEnv.class);
+ MockedConstruction<FrontendServiceImpl> services =
Mockito.mockConstruction(FrontendServiceImpl.class,
+ (service, construction) -> {
+
Mockito.when(service.getDbNames(Mockito.any(TGetDbsParams.class),
Mockito.eq(false)))
+ .thenReturn(new
TGetDbsResult().setDbs(Collections.singletonList("db"))
+
.setCatalogs(Collections.singletonList("internal")));
+
Mockito.when(service.listTableStatus(Mockito.any(TGetTablesParams.class),
Mockito.eq(false)))
+ .thenReturn(new
TListTableStatusResult().setTables(Collections.singletonList(
+ new
TTableStatus().setName("maps").setType("BASE TABLE"))));
+
Mockito.when(service.describeTables(Mockito.any(TDescribeTablesParams.class),
+ Mockito.eq(false))).thenReturn(new
TDescribeTablesResult()
+ .setColumns(Arrays.asList(new
TColumnDef(map), new TColumnDef(array)))
+
.setTablesOffset(Collections.singletonList(2)));
+ });
+ RootAllocator allocator = new RootAllocator();
+ VectorSchemaRoot root =
VectorSchemaRoot.create(Schemas.GET_TABLES_SCHEMA, allocator)) {
+ FlightSqlSchemaHelper helper = new FlightSqlSchemaHelper(ctx);
+
helper.setParameterForGetTables(CommandGetTables.newBuilder().setIncludeSchema(true).build());
+ root.allocateNew();
+ helper.getTables(root);
+ Assertions.assertEquals(1, root.getRowCount());
+ byte[] bytes = ((VarBinaryVector)
root.getVector("table_schema")).get(0);
+ List<Field> fields = MessageSerializer.deserializeSchema(
+ new ReadChannel(Channels.newChannel(new
ByteArrayInputStream(bytes)))).getFields();
+ for (Field field : Arrays.asList(fields.get(0),
fields.get(1).getChildren().get(0))) {
+ Assertions.assertEquals(asList ? new ArrowType.List() : new
ArrowType.Map(false), field.getType());
+ Field entries = field.getChildren().get(0);
+ Assertions.assertEquals("entries", entries.getName());
+ Assertions.assertFalse(entries.isNullable());
+ Assertions.assertEquals(asList,
entries.getChildren().get(0).isNullable());
+ }
+ }
+ }
+
private static ConnectContext context(boolean mappedRole) {
ConnectContext ctx = new ConnectContext();
ctx.setCurrentUserIdentity(UserIdentity.createAnalyzedUserIdentWithIp("metadata_user",
"%"));
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/arrowflight/FlightSqlSchemaHelperCatalogTest.java
b/fe/fe-core/src/test/java/org/apache/doris/arrowflight/FlightSqlSchemaHelperCatalogTest.java
index a7c242a8309..dbb8c5e8c30 100644
---
a/fe/fe-core/src/test/java/org/apache/doris/arrowflight/FlightSqlSchemaHelperCatalogTest.java
+++
b/fe/fe-core/src/test/java/org/apache/doris/arrowflight/FlightSqlSchemaHelperCatalogTest.java
@@ -25,6 +25,7 @@ import
org.apache.doris.mysql.privilege.AccessControllerManager;
import org.apache.doris.mysql.privilege.PrivPredicate;
import org.apache.doris.qe.ConnectContext;
import org.apache.doris.qe.GlobalVariable;
+import org.apache.doris.qe.SessionVariable;
import org.apache.doris.service.ExecuteEnv;
import org.apache.doris.service.FrontendServiceImpl;
import org.apache.doris.thrift.TColumnDef;
@@ -99,6 +100,7 @@ public class FlightSqlSchemaHelperCatalogTest {
private void checkMetadata(String catalog, List<String> expectedCatalogs,
boolean tables, boolean includeSchema,
boolean showFullName, String pattern) throws Exception {
ConnectContext ctx = Mockito.mock(ConnectContext.class);
+ Mockito.when(ctx.getSessionVariable()).thenReturn(new
SessionVariable());
Mockito.when(ctx.getCurrentUserIdentity()).thenReturn(UserIdentity.ROOT);
Mockito.when(ctx.getCurrentUserIdentityForRpc()).thenReturn(UserIdentity.ROOT.toThrift());
Env env = Mockito.mock(Env.class);
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/planner/ResultSinkMetadataTest.java
b/fe/fe-core/src/test/java/org/apache/doris/planner/ResultSinkMetadataTest.java
index d41c1062155..f5a01257049 100644
---
a/fe/fe-core/src/test/java/org/apache/doris/planner/ResultSinkMetadataTest.java
+++
b/fe/fe-core/src/test/java/org/apache/doris/planner/ResultSinkMetadataTest.java
@@ -35,4 +35,19 @@ class ResultSinkMetadataTest {
.toThrift().getResultSink();
Assertions.assertFalse(mysql.isSetEnableArrowTypeMetadata());
}
+
+ @Test
+ void mapRepresentationIsOptionalAndSpecificToFlight() {
+ Assertions.assertFalse(new TResultSink().isArrowFlightSqlMapAsList());
+ TResultSink defaultFlight = new ResultSink(new PlanNodeId(0),
TResultSinkType.ARROW_FLIGHT_PROTOCOL)
+ .toThrift().getResultSink();
+ Assertions.assertFalse(defaultFlight.isArrowFlightSqlMapAsList());
+ TResultSink optedIn = new ResultSink(new PlanNodeId(0),
TResultSinkType.ARROW_FLIGHT_PROTOCOL, true)
+ .toThrift().getResultSink();
+ Assertions.assertTrue(optedIn.isSetArrowFlightSqlMapAsList());
+ Assertions.assertTrue(optedIn.isArrowFlightSqlMapAsList());
+ TResultSink mysql = new ResultSink(new PlanNodeId(0),
TResultSinkType.MYSQL_PROTOCOL, true)
+ .toThrift().getResultSink();
+ Assertions.assertFalse(mysql.isSetArrowFlightSqlMapAsList());
+ }
}
diff --git a/gensrc/thrift/DataSinks.thrift b/gensrc/thrift/DataSinks.thrift
index d56746a66bc..a2df96d96bb 100644
--- a/gensrc/thrift/DataSinks.thrift
+++ b/gensrc/thrift/DataSinks.thrift
@@ -241,6 +241,8 @@ struct TResultSink {
3: optional TFetchOption fetch_option;
// Absent for old FEs, whose Flight schema comparison requires legacy
field metadata.
4: optional bool enable_arrow_type_metadata = false;
+ // Query-wide Flight representation that preserves nullable Doris MAP keys.
+ 5: optional bool arrow_flight_sql_map_as_list = false;
}
struct TResultFileSink {
diff --git
a/regression-test/data/arrow_flight_sql_p0/test_flight_map_nullable_keys.out
b/regression-test/data/arrow_flight_sql_p0/test_flight_map_nullable_keys.out
new file mode 100644
index 00000000000..b506478573f
--- /dev/null
+++ b/regression-test/data/arrow_flight_sql_p0/test_flight_map_nullable_keys.out
@@ -0,0 +1,30 @@
+-- This file is automatically generated. You should know what you did if you
want to edit this
+-- !arrow_flight_sql_default --
+1 {"a":10}
+
+-- !arrow_flight_sql_constant --
+[{"value":100}]
+
+-- !arrow_flight_sql_values --
+1 [{"key":"a", "value":10}]
+2 [{"value":100}, {"key":"b"}]
+3 []
+4 \N
+
+-- !arrow_flight_sql_nested --
+1 [[{"key":"a", "value":10}]] {"m":[{"key":"a", "value":10}]}
[{"key":"outer", "value":[{"key":"a", "value":10}]}]
+2 [[{"value":100}, {"key":"b"}]] {"m":[{"value":100}, {"key":"b"}]}
[{"key":"outer", "value":[{"value":100}, {"key":"b"}]}]
+3 [[]] {"m":[]} [{"key":"outer", "value":[]}]
+4 [null] {} [{"key":"outer"}]
+
+-- !arrow_flight_sql_empty --
+
+-- !arrow_flight_sql_prepared --
+[{"value":100}, {"key":"b"}]
+
+-- !arrow_flight_sql_serial --
+1 [{"key":"a", "value":10}]
+2 [{"value":100}, {"key":"b"}]
+3 []
+4 \N
+
diff --git
a/regression-test/suites/arrow_flight_sql_p0/test_flight_map_nullable_keys.groovy
b/regression-test/suites/arrow_flight_sql_p0/test_flight_map_nullable_keys.groovy
new file mode 100644
index 00000000000..006181e72ce
--- /dev/null
+++
b/regression-test/suites/arrow_flight_sql_p0/test_flight_map_nullable_keys.groovy
@@ -0,0 +1,58 @@
+// 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_flight_map_nullable_keys", "arrow_flight_sql") {
+ def flight = context.getArrowFlightSqlConnection()
+ jdbc_sql "DROP TABLE IF EXISTS flight_map_nullable_keys"
+ jdbc_sql """CREATE TABLE flight_map_nullable_keys (id INT, m MAP<STRING,
INT>)
+ DUPLICATE KEY(id) DISTRIBUTED BY HASH(id) BUCKETS 1
+ PROPERTIES ("replication_num" = "1")"""
+ jdbc_sql """INSERT INTO flight_map_nullable_keys VALUES
+ (1, MAP('a', 10)), (2, MAP(NULL, 100, 'b', NULL)),
+ (3, MAP_FROM_ARRAYS(CAST([] AS ARRAY<STRING>), CAST([] AS
ARRAY<INT>))), (4, NULL)"""
+ def originalMapPolicy = arrow_flight_sql("SHOW VARIABLES LIKE
'arrow_flight_sql_map_as_list'")[0][1]
+ def originalParallelSink = arrow_flight_sql("SHOW VARIABLES LIKE
'enable_parallel_result_sink'")[0][1]
+ arrow_flight_sql "SET arrow_flight_sql_map_as_list = false"
+ order_qt_arrow_flight_sql_default "SELECT id, m FROM
flight_map_nullable_keys WHERE id = 1"
+ try {
+ // TestAction reads the normal connection; temporarily use this
suite's Flight connection.
+ def originalConnection = context.threadLocalConn.get()
+ context.threadLocalConn.set(context.threadArrowFlightSqlConn.get())
+ try {
+ test {
+ sql "SELECT m FROM flight_map_nullable_keys WHERE id = 2",
false
+ exception "null value of map key"
+ }
+ } finally {
+ context.threadLocalConn.set(originalConnection)
+ }
+ arrow_flight_sql "SET arrow_flight_sql_map_as_list = true"
+ order_qt_arrow_flight_sql_constant "SELECT MAP(CAST(NULL AS STRING),
100) AS m"
+ order_qt_arrow_flight_sql_values "SELECT id, m FROM
flight_map_nullable_keys ORDER BY id"
+ order_qt_arrow_flight_sql_nested """SELECT id, ARRAY(m) AS a,
NAMED_STRUCT('m', m) AS s,
+ MAP('outer', m) AS nested_map FROM flight_map_nullable_keys ORDER
BY id"""
+ order_qt_arrow_flight_sql_empty "SELECT m FROM
flight_map_nullable_keys WHERE id < 0"
+ flight.prepareStatement("SELECT m FROM flight_map_nullable_keys WHERE
id = 2").withCloseable { statement ->
+ quickRunTest("arrow_flight_sql_prepared", statement, true)
+ }
+ arrow_flight_sql "SET enable_parallel_result_sink = false"
+ order_qt_arrow_flight_sql_serial "SELECT id, m FROM
flight_map_nullable_keys ORDER BY id"
+ } finally {
+ arrow_flight_sql "SET arrow_flight_sql_map_as_list =
${originalMapPolicy}"
+ arrow_flight_sql "SET enable_parallel_result_sink =
${originalParallelSink}"
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]