repo
stringclasses 1
value | pull_number
int64 14
6.65k
| instance_id
stringlengths 19
21
| issue_numbers
listlengths 1
2
| base_commit
stringlengths 40
40
| patch
stringlengths 505
226k
| test_patch
stringlengths 265
112k
| problem_statement
stringlengths 99
16.2k
| hints_text
stringlengths 0
33.2k
| created_at
stringlengths 20
20
| version
stringlengths 3
4
| environment_setup_commit
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|
apache/arrow-rs
| 6,649
|
apache__arrow-rs-6649
|
[
"6648"
] |
7bcc1ad988498def843180c6a4c95f9732f31a4b
|
diff --git a/parquet/src/record/reader.rs b/parquet/src/record/reader.rs
index 1f9128a8b4f..fd6ca7cdd57 100644
--- a/parquet/src/record/reader.rs
+++ b/parquet/src/record/reader.rs
@@ -138,7 +138,17 @@ impl TreeBuilder {
.column_descr_ptr();
let col_reader = row_group_reader.get_column_reader(orig_index)?;
let column = TripletIter::new(col_descr, col_reader, self.batch_size);
- Reader::PrimitiveReader(field, Box::new(column))
+ let reader = Reader::PrimitiveReader(field.clone(), Box::new(column));
+ if repetition == Repetition::REPEATED {
+ Reader::RepeatedReader(
+ field,
+ curr_def_level - 1,
+ curr_rep_level - 1,
+ Box::new(reader),
+ )
+ } else {
+ reader
+ }
} else {
match field.get_basic_info().converted_type() {
// List types
@@ -1688,6 +1698,131 @@ mod tests {
assert_eq!(rows, expected_rows);
}
+ #[test]
+ fn test_tree_reader_handle_primitive_repeated_fields_with_no_annotation() {
+ // In this test the REPEATED fields are primitives
+ let rows = test_file_reader_rows("repeated_primitive_no_list.parquet", None).unwrap();
+ let expected_rows = vec![
+ row![
+ (
+ "Int32_list".to_string(),
+ Field::ListInternal(make_list([0, 1, 2, 3].map(Field::Int).to_vec()))
+ ),
+ (
+ "String_list".to_string(),
+ Field::ListInternal(make_list(
+ ["foo", "zero", "one", "two"]
+ .map(|s| Field::Str(s.to_string()))
+ .to_vec()
+ ))
+ ),
+ (
+ "group_of_lists".to_string(),
+ group![
+ (
+ "Int32_list_in_group".to_string(),
+ Field::ListInternal(make_list([0, 1, 2, 3].map(Field::Int).to_vec()))
+ ),
+ (
+ "String_list_in_group".to_string(),
+ Field::ListInternal(make_list(
+ ["foo", "zero", "one", "two"]
+ .map(|s| Field::Str(s.to_string()))
+ .to_vec()
+ ))
+ )
+ ]
+ )
+ ],
+ row![
+ (
+ "Int32_list".to_string(),
+ Field::ListInternal(make_list(vec![]))
+ ),
+ (
+ "String_list".to_string(),
+ Field::ListInternal(make_list(
+ ["three"].map(|s| Field::Str(s.to_string())).to_vec()
+ ))
+ ),
+ (
+ "group_of_lists".to_string(),
+ group![
+ (
+ "Int32_list_in_group".to_string(),
+ Field::ListInternal(make_list(vec![]))
+ ),
+ (
+ "String_list_in_group".to_string(),
+ Field::ListInternal(make_list(
+ ["three"].map(|s| Field::Str(s.to_string())).to_vec()
+ ))
+ )
+ ]
+ )
+ ],
+ row![
+ (
+ "Int32_list".to_string(),
+ Field::ListInternal(make_list(vec![Field::Int(4)]))
+ ),
+ (
+ "String_list".to_string(),
+ Field::ListInternal(make_list(
+ ["four"].map(|s| Field::Str(s.to_string())).to_vec()
+ ))
+ ),
+ (
+ "group_of_lists".to_string(),
+ group![
+ (
+ "Int32_list_in_group".to_string(),
+ Field::ListInternal(make_list(vec![Field::Int(4)]))
+ ),
+ (
+ "String_list_in_group".to_string(),
+ Field::ListInternal(make_list(
+ ["four"].map(|s| Field::Str(s.to_string())).to_vec()
+ ))
+ )
+ ]
+ )
+ ],
+ row![
+ (
+ "Int32_list".to_string(),
+ Field::ListInternal(make_list([5, 6, 7, 8].map(Field::Int).to_vec()))
+ ),
+ (
+ "String_list".to_string(),
+ Field::ListInternal(make_list(
+ ["five", "six", "seven", "eight"]
+ .map(|s| Field::Str(s.to_string()))
+ .to_vec()
+ ))
+ ),
+ (
+ "group_of_lists".to_string(),
+ group![
+ (
+ "Int32_list_in_group".to_string(),
+ Field::ListInternal(make_list([5, 6, 7, 8].map(Field::Int).to_vec()))
+ ),
+ (
+ "String_list_in_group".to_string(),
+ Field::ListInternal(make_list(
+ ["five", "six", "seven", "eight"]
+ .map(|s| Field::Str(s.to_string()))
+ .to_vec()
+ ))
+ )
+ ]
+ )
+ ],
+ ];
+ assert_eq!(rows, expected_rows);
+ }
+
fn test_file_reader_rows(file_name: &str, schema: Option<Type>) -> Result<Vec<Row>> {
let file = get_test_file(file_name);
let file_reader: Box<dyn FileReader> = Box::new(SerializedFileReader::new(file)?);
|
diff --git a/parquet-testing b/parquet-testing
index 50af3d8ce20..550368ca77b 160000
--- a/parquet-testing
+++ b/parquet-testing
@@ -1,1 +1,1 @@
-Subproject commit 50af3d8ce206990d81014b1862e5ce7380dc3e08
+Subproject commit 550368ca77b97231efead39251a96bd6f8f08c6e
|
Primitive REPEATED fields not contained in LIST annotated groups aren't read as lists by record reader
**Describe the bug**
Primitive REPEATED fields not contained in LIST annotated groups should be read as lists according to the format but aren't.
**To Reproduce**
<!--
Steps to reproduce the behavior:
-->
**Expected behavior**
<!--
A clear and concise description of what you expected to happen.
-->
**Additional context**
<!--
Add any other context about the problem here.
-->
|
2024-10-29T23:41:15Z
|
53.2
|
7bcc1ad988498def843180c6a4c95f9732f31a4b
|
|
apache/arrow-rs
| 6,453
|
apache__arrow-rs-6453
|
[
"6282"
] |
f41c258246cd4bd9d89228cded9ed54dbd00faff
|
diff --git a/arrow-flight/examples/flight_sql_server.rs b/arrow-flight/examples/flight_sql_server.rs
index 81afecf85625..dd3a3943dd95 100644
--- a/arrow-flight/examples/flight_sql_server.rs
+++ b/arrow-flight/examples/flight_sql_server.rs
@@ -19,6 +19,7 @@ use arrow_flight::sql::server::PeekableFlightDataStream;
use arrow_flight::sql::DoPutPreparedStatementResult;
use base64::prelude::BASE64_STANDARD;
use base64::Engine;
+use core::str;
use futures::{stream, Stream, TryStreamExt};
use once_cell::sync::Lazy;
use prost::Message;
@@ -168,7 +169,7 @@ impl FlightSqlService for FlightSqlServiceImpl {
let bytes = BASE64_STANDARD
.decode(base64)
.map_err(|e| status!("authorization not decodable", e))?;
- let str = String::from_utf8(bytes).map_err(|e| status!("authorization not parsable", e))?;
+ let str = str::from_utf8(&bytes).map_err(|e| status!("authorization not parsable", e))?;
let parts: Vec<_> = str.split(':').collect();
let (user, pass) = match parts.as_slice() {
[user, pass] => (user, pass),
diff --git a/arrow-flight/src/bin/flight_sql_client.rs b/arrow-flight/src/bin/flight_sql_client.rs
index c334b95a9a96..8f0618f495bc 100644
--- a/arrow-flight/src/bin/flight_sql_client.rs
+++ b/arrow-flight/src/bin/flight_sql_client.rs
@@ -26,6 +26,7 @@ use arrow_flight::{
};
use arrow_schema::Schema;
use clap::{Parser, Subcommand};
+use core::str;
use futures::TryStreamExt;
use tonic::{
metadata::MetadataMap,
diff --git a/arrow-flight/src/decode.rs b/arrow-flight/src/decode.rs
index 5561f256ce01..7bafc384306b 100644
--- a/arrow-flight/src/decode.rs
+++ b/arrow-flight/src/decode.rs
@@ -388,11 +388,14 @@ struct FlightStreamState {
/// FlightData and the decoded payload (Schema, RecordBatch), if any
#[derive(Debug)]
pub struct DecodedFlightData {
+ /// The original FlightData message
pub inner: FlightData,
+ /// The decoded payload
pub payload: DecodedPayload,
}
impl DecodedFlightData {
+ /// Create a new DecodedFlightData with no payload
pub fn new_none(inner: FlightData) -> Self {
Self {
inner,
@@ -400,6 +403,7 @@ impl DecodedFlightData {
}
}
+ /// Create a new DecodedFlightData with a [`Schema`] payload
pub fn new_schema(inner: FlightData, schema: SchemaRef) -> Self {
Self {
inner,
@@ -407,6 +411,7 @@ impl DecodedFlightData {
}
}
+ /// Create a new [`DecodedFlightData`] with a [`RecordBatch`] payload
pub fn new_record_batch(inner: FlightData, batch: RecordBatch) -> Self {
Self {
inner,
@@ -414,7 +419,7 @@ impl DecodedFlightData {
}
}
- /// return the metadata field of the inner flight data
+ /// Return the metadata field of the inner flight data
pub fn app_metadata(&self) -> Bytes {
self.inner.app_metadata.clone()
}
diff --git a/arrow-flight/src/encode.rs b/arrow-flight/src/encode.rs
index 59fa8afd58d5..55bc9240321d 100644
--- a/arrow-flight/src/encode.rs
+++ b/arrow-flight/src/encode.rs
@@ -144,6 +144,7 @@ impl Default for FlightDataEncoderBuilder {
}
impl FlightDataEncoderBuilder {
+ /// Create a new [`FlightDataEncoderBuilder`].
pub fn new() -> Self {
Self::default()
}
@@ -1403,7 +1404,7 @@ mod tests {
let input_rows = batch.num_rows();
let split = split_batch_for_grpc_response(batch.clone(), max_flight_data_size_bytes);
- let sizes: Vec<_> = split.iter().map(|batch| batch.num_rows()).collect();
+ let sizes: Vec<_> = split.iter().map(RecordBatch::num_rows).collect();
let output_rows: usize = sizes.iter().sum();
assert_eq!(sizes, expected_sizes, "mismatch for {batch:?}");
diff --git a/arrow-flight/src/error.rs b/arrow-flight/src/error.rs
index ba979ca9f7a6..499706e1ede7 100644
--- a/arrow-flight/src/error.rs
+++ b/arrow-flight/src/error.rs
@@ -37,6 +37,7 @@ pub enum FlightError {
}
impl FlightError {
+ /// Generate a new `FlightError::ProtocolError` variant.
pub fn protocol(message: impl Into<String>) -> Self {
Self::ProtocolError(message.into())
}
@@ -98,6 +99,7 @@ impl From<FlightError> for tonic::Status {
}
}
+/// Result type for the Apache Arrow Flight crate
pub type Result<T> = std::result::Result<T, FlightError>;
#[cfg(test)]
diff --git a/arrow-flight/src/lib.rs b/arrow-flight/src/lib.rs
index 64e3ba01c5bd..9f18416c06ec 100644
--- a/arrow-flight/src/lib.rs
+++ b/arrow-flight/src/lib.rs
@@ -37,6 +37,7 @@
//!
//! [Flight SQL]: https://arrow.apache.org/docs/format/FlightSql.html
#![allow(rustdoc::invalid_html_tags)]
+#![warn(missing_docs)]
use arrow_ipc::{convert, writer, writer::EncodedData, writer::IpcWriteOptions};
use arrow_schema::{ArrowError, Schema};
@@ -52,6 +53,8 @@ type ArrowResult<T> = std::result::Result<T, ArrowError>;
#[allow(clippy::all)]
mod gen {
+ // Since this file is auto-generated, we suppress all warnings
+ #![allow(missing_docs)]
include!("arrow.flight.protocol.rs");
}
@@ -125,6 +128,7 @@ use flight_descriptor::DescriptorType;
/// SchemaAsIpc represents a pairing of a `Schema` with IpcWriteOptions
pub struct SchemaAsIpc<'a> {
+ /// Data type representing a schema and its IPC write options
pub pair: (&'a Schema, &'a IpcWriteOptions),
}
@@ -684,6 +688,7 @@ impl PollInfo {
}
impl<'a> SchemaAsIpc<'a> {
+ /// Create a new `SchemaAsIpc` from a `Schema` and `IpcWriteOptions`
pub fn new(schema: &'a Schema, options: &'a IpcWriteOptions) -> Self {
SchemaAsIpc {
pair: (schema, options),
diff --git a/arrow-flight/src/sql/client.rs b/arrow-flight/src/sql/client.rs
index ef52aa27ef50..e45e505b2b61 100644
--- a/arrow-flight/src/sql/client.rs
+++ b/arrow-flight/src/sql/client.rs
@@ -695,9 +695,11 @@ fn flight_error_to_arrow_error(err: FlightError) -> ArrowError {
}
}
-// A polymorphic structure to natively represent different types of data contained in `FlightData`
+/// A polymorphic structure to natively represent different types of data contained in `FlightData`
pub enum ArrowFlightData {
+ /// A record batch
RecordBatch(RecordBatch),
+ /// A schema
Schema(Schema),
}
diff --git a/arrow-flight/src/sql/metadata/sql_info.rs b/arrow-flight/src/sql/metadata/sql_info.rs
index 97304d3c872d..2ea30df7fc2f 100644
--- a/arrow-flight/src/sql/metadata/sql_info.rs
+++ b/arrow-flight/src/sql/metadata/sql_info.rs
@@ -331,7 +331,7 @@ impl SqlInfoUnionBuilder {
///
/// Servers constuct - usually static - [`SqlInfoData`] via the [`SqlInfoDataBuilder`],
/// and build responses using [`CommandGetSqlInfo::into_builder`]
-#[derive(Debug, Clone, PartialEq)]
+#[derive(Debug, Clone, PartialEq, Default)]
pub struct SqlInfoDataBuilder {
/// Use BTreeMap to ensure the values are sorted by value as
/// to make output consistent
@@ -341,17 +341,10 @@ pub struct SqlInfoDataBuilder {
infos: BTreeMap<u32, SqlInfoValue>,
}
-impl Default for SqlInfoDataBuilder {
- fn default() -> Self {
- Self::new()
- }
-}
-
impl SqlInfoDataBuilder {
+ /// Create a new SQL info builder
pub fn new() -> Self {
- Self {
- infos: BTreeMap::new(),
- }
+ Self::default()
}
/// register the specific sql metadata item
diff --git a/arrow-flight/src/sql/metadata/xdbc_info.rs b/arrow-flight/src/sql/metadata/xdbc_info.rs
index 2e635d3037bc..485bedaebfb0 100644
--- a/arrow-flight/src/sql/metadata/xdbc_info.rs
+++ b/arrow-flight/src/sql/metadata/xdbc_info.rs
@@ -41,24 +41,43 @@ use crate::sql::{CommandGetXdbcTypeInfo, Nullable, Searchable, XdbcDataType, Xdb
/// Data structure representing type information for xdbc types.
#[derive(Debug, Clone, Default)]
pub struct XdbcTypeInfo {
+ /// The name of the type
pub type_name: String,
+ /// The data type of the type
pub data_type: XdbcDataType,
+ /// The column size of the type
pub column_size: Option<i32>,
+ /// The prefix of the type
pub literal_prefix: Option<String>,
+ /// The suffix of the type
pub literal_suffix: Option<String>,
+ /// The create parameters of the type
pub create_params: Option<Vec<String>>,
+ /// The nullability of the type
pub nullable: Nullable,
+ /// Whether the type is case sensitive
pub case_sensitive: bool,
+ /// Whether the type is searchable
pub searchable: Searchable,
+ /// Whether the type is unsigned
pub unsigned_attribute: Option<bool>,
+ /// Whether the type has fixed precision and scale
pub fixed_prec_scale: bool,
+ /// Whether the type is auto-incrementing
pub auto_increment: Option<bool>,
+ /// The local type name of the type
pub local_type_name: Option<String>,
+ /// The minimum scale of the type
pub minimum_scale: Option<i32>,
+ /// The maximum scale of the type
pub maximum_scale: Option<i32>,
+ /// The SQL data type of the type
pub sql_data_type: XdbcDataType,
+ /// The optional datetime subcode of the type
pub datetime_subcode: Option<XdbcDatetimeSubcode>,
+ /// The number precision radix of the type
pub num_prec_radix: Option<i32>,
+ /// The interval precision of the type
pub interval_precision: Option<i32>,
}
@@ -93,16 +112,6 @@ impl XdbcTypeInfoData {
}
}
-pub struct XdbcTypeInfoDataBuilder {
- infos: Vec<XdbcTypeInfo>,
-}
-
-impl Default for XdbcTypeInfoDataBuilder {
- fn default() -> Self {
- Self::new()
- }
-}
-
/// A builder for [`XdbcTypeInfoData`] which is used to create [`CommandGetXdbcTypeInfo`] responses.
///
/// # Example
@@ -138,6 +147,16 @@ impl Default for XdbcTypeInfoDataBuilder {
/// // to access the underlying record batch
/// let batch = info_list.record_batch(None);
/// ```
+pub struct XdbcTypeInfoDataBuilder {
+ infos: Vec<XdbcTypeInfo>,
+}
+
+impl Default for XdbcTypeInfoDataBuilder {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl XdbcTypeInfoDataBuilder {
/// Create a new instance of [`XdbcTypeInfoDataBuilder`].
pub fn new() -> Self {
diff --git a/arrow-flight/src/sql/mod.rs b/arrow-flight/src/sql/mod.rs
index 453f608d353a..94bb96a4f852 100644
--- a/arrow-flight/src/sql/mod.rs
+++ b/arrow-flight/src/sql/mod.rs
@@ -43,9 +43,11 @@ use bytes::Bytes;
use paste::paste;
use prost::Message;
+#[allow(clippy::all)]
mod gen {
- #![allow(clippy::all)]
#![allow(rustdoc::unportable_markdown)]
+ // Since this file is auto-generated, we suppress all warnings
+ #![allow(missing_docs)]
include!("arrow.flight.protocol.sql.rs");
}
@@ -163,7 +165,9 @@ macro_rules! prost_message_ext {
/// ```
#[derive(Clone, Debug, PartialEq)]
pub enum Command {
- $($name($name),)*
+ $(
+ #[doc = concat!(stringify!($name), "variant")]
+ $name($name),)*
/// Any message that is not any FlightSQL command.
Unknown(Any),
@@ -297,10 +301,12 @@ pub struct Any {
}
impl Any {
+ /// Checks whether the message is of type `M`
pub fn is<M: ProstMessageExt>(&self) -> bool {
M::type_url() == self.type_url
}
+ /// Unpacks the contents of the message if it is of type `M`
pub fn unpack<M: ProstMessageExt>(&self) -> Result<Option<M>, ArrowError> {
if !self.is::<M>() {
return Ok(None);
@@ -310,6 +316,7 @@ impl Any {
Ok(Some(m))
}
+ /// Packs a message into an [`Any`] message
pub fn pack<M: ProstMessageExt>(message: &M) -> Result<Any, ArrowError> {
Ok(message.as_any())
}
diff --git a/arrow-flight/src/utils.rs b/arrow-flight/src/utils.rs
index 37d7ff9e7293..f6129ddfe248 100644
--- a/arrow-flight/src/utils.rs
+++ b/arrow-flight/src/utils.rs
@@ -160,9 +160,12 @@ pub fn batches_to_flight_data(
dictionaries.extend(encoded_dictionaries.into_iter().map(Into::into));
flight_data.push(encoded_batch.into());
}
- let mut stream = vec![schema_flight_data];
+
+ let mut stream = Vec::with_capacity(1 + dictionaries.len() + flight_data.len());
+
+ stream.push(schema_flight_data);
stream.extend(dictionaries);
stream.extend(flight_data);
- let flight_data: Vec<_> = stream.into_iter().collect();
+ let flight_data = stream;
Ok(flight_data)
}
diff --git a/arrow-ipc/src/convert.rs b/arrow-ipc/src/convert.rs
index 52c6a0d614d0..eef236529e10 100644
--- a/arrow-ipc/src/convert.rs
+++ b/arrow-ipc/src/convert.rs
@@ -133,6 +133,7 @@ pub fn schema_to_fb(schema: &Schema) -> FlatBufferBuilder<'_> {
IpcSchemaEncoder::new().schema_to_fb(schema)
}
+/// Push a key-value metadata into a FlatBufferBuilder and return [WIPOffset]
pub fn metadata_to_fb<'a>(
fbb: &mut FlatBufferBuilder<'a>,
metadata: &HashMap<String, String>,
@@ -152,7 +153,7 @@ pub fn metadata_to_fb<'a>(
fbb.create_vector(&custom_metadata)
}
-#[deprecated(since = "54.0.0", note = "Use `IpcSchemaConverter`.")]
+/// Adds a [Schema] to a flatbuffer and returns the offset
pub fn schema_to_fb_offset<'a>(
fbb: &mut FlatBufferBuilder<'a>,
schema: &Schema,
diff --git a/arrow-ipc/src/lib.rs b/arrow-ipc/src/lib.rs
index 4f35ffb60a9f..dde137153964 100644
--- a/arrow-ipc/src/lib.rs
+++ b/arrow-ipc/src/lib.rs
@@ -19,6 +19,7 @@
//!
//! [Arrow IPC Format]: https://arrow.apache.org/docs/format/Columnar.html#serialization-and-interprocess-communication-ipc
+#![warn(missing_docs)]
pub mod convert;
pub mod reader;
pub mod writer;
@@ -31,6 +32,7 @@ mod compression;
#[allow(clippy::redundant_static_lifetimes)]
#[allow(clippy::redundant_field_names)]
#[allow(non_camel_case_types)]
+#[allow(missing_docs)] // Because this is autogenerated
pub mod gen;
pub use self::gen::File::*;
diff --git a/arrow-ipc/src/writer.rs b/arrow-ipc/src/writer.rs
index b5cf20ef337f..f9256b4e8175 100644
--- a/arrow-ipc/src/writer.rs
+++ b/arrow-ipc/src/writer.rs
@@ -60,7 +60,7 @@ pub struct IpcWriteOptions {
/// Compression, if desired. Will result in a runtime error
/// if the corresponding feature is not enabled
batch_compression_type: Option<crate::CompressionType>,
- /// Flag indicating whether the writer should preserver the dictionary IDs defined in the
+ /// Flag indicating whether the writer should preserve the dictionary IDs defined in the
/// schema or generate unique dictionary IDs internally during encoding.
///
/// Defaults to `true`
@@ -135,6 +135,8 @@ impl IpcWriteOptions {
}
}
+ /// Return whether the writer is configured to preserve the dictionary IDs
+ /// defined in the schema
pub fn preserve_dict_id(&self) -> bool {
self.preserve_dict_id
}
@@ -200,6 +202,11 @@ impl Default for IpcWriteOptions {
pub struct IpcDataGenerator {}
impl IpcDataGenerator {
+ /// Converts a schema to an IPC message along with `dictionary_tracker`
+ /// and returns it encoded inside [EncodedData] as a flatbuffer
+ ///
+ /// Preferred method over [IpcDataGenerator::schema_to_bytes] since it's
+ /// deprecated since Arrow v54.0.0
pub fn schema_to_bytes_with_dictionary_tracker(
&self,
schema: &Schema,
@@ -234,6 +241,7 @@ impl IpcDataGenerator {
since = "54.0.0",
note = "Use `schema_to_bytes_with_dictionary_tracker` instead. This function signature of `schema_to_bytes_with_dictionary_tracker` in the next release."
)]
+ /// Converts a schema to an IPC message and returns it encoded inside [EncodedData] as a flatbuffer
pub fn schema_to_bytes(&self, schema: &Schema, write_options: &IpcWriteOptions) -> EncodedData {
let mut fbb = FlatBufferBuilder::new();
let schema = {
@@ -951,6 +959,7 @@ impl<W: Write> FileWriter<W> {
})
}
+ /// Adds a key-value pair to the [FileWriter]'s custom metadata
pub fn write_metadata(&mut self, key: impl Into<String>, value: impl Into<String>) {
self.custom_metadata.insert(key.into(), value.into());
}
diff --git a/arrow-json/src/writer.rs b/arrow-json/src/writer.rs
index 86d2e88d99f0..d973206ccf74 100644
--- a/arrow-json/src/writer.rs
+++ b/arrow-json/src/writer.rs
@@ -397,6 +397,7 @@ where
#[cfg(test)]
mod tests {
+ use core::str;
use std::fs::{read_to_string, File};
use std::io::{BufReader, Seek};
use std::sync::Arc;
@@ -1111,7 +1112,7 @@ mod tests {
}
}
- let result = String::from_utf8(buf).unwrap();
+ let result = str::from_utf8(&buf).unwrap();
let expected = read_to_string(test_file).unwrap();
for (r, e) in result.lines().zip(expected.lines()) {
let mut expected_json = serde_json::from_str::<Value>(e).unwrap();
@@ -1150,7 +1151,7 @@ mod tests {
fn json_writer_empty() {
let mut writer = ArrayWriter::new(vec![] as Vec<u8>);
writer.finish().unwrap();
- assert_eq!(String::from_utf8(writer.into_inner()).unwrap(), "");
+ assert_eq!(str::from_utf8(&writer.into_inner()).unwrap(), "");
}
#[test]
@@ -1279,7 +1280,7 @@ mod tests {
writer.write(&batch).unwrap();
}
- let result = String::from_utf8(buf).unwrap();
+ let result = str::from_utf8(&buf).unwrap();
let expected = read_to_string(test_file).unwrap();
for (r, e) in result.lines().zip(expected.lines()) {
let mut expected_json = serde_json::from_str::<Value>(e).unwrap();
@@ -1321,7 +1322,7 @@ mod tests {
writer.write_batches(&batches).unwrap();
}
- let result = String::from_utf8(buf).unwrap();
+ let result = str::from_utf8(&buf).unwrap();
let expected = read_to_string(test_file).unwrap();
// result is eq to 2 same batches
let expected = format!("{expected}\n{expected}");
diff --git a/arrow-schema/src/field.rs b/arrow-schema/src/field.rs
index fc4852a3d37d..b532ea8616b6 100644
--- a/arrow-schema/src/field.rs
+++ b/arrow-schema/src/field.rs
@@ -610,14 +610,14 @@ mod test {
#[test]
fn test_new_with_string() {
// Fields should allow owned Strings to support reuse
- let s = String::from("c1");
+ let s = "c1";
Field::new(s, DataType::Int64, false);
}
#[test]
fn test_new_dict_with_string() {
// Fields should allow owned Strings to support reuse
- let s = String::from("c1");
+ let s = "c1";
Field::new_dict(s, DataType::Int64, false, 4, false);
}
diff --git a/object_store/src/aws/builder.rs b/object_store/src/aws/builder.rs
index 75acb73e56a9..c52c3f8dfbd7 100644
--- a/object_store/src/aws/builder.rs
+++ b/object_store/src/aws/builder.rs
@@ -44,7 +44,6 @@ static DEFAULT_METADATA_ENDPOINT: &str = "http://169.254.169.254";
/// A specialized `Error` for object store-related errors
#[derive(Debug, Snafu)]
-#[allow(missing_docs)]
enum Error {
#[snafu(display("Missing bucket name"))]
MissingBucketName,
diff --git a/object_store/src/aws/client.rs b/object_store/src/aws/client.rs
index 6fe4889db176..7034a372e95f 100644
--- a/object_store/src/aws/client.rs
+++ b/object_store/src/aws/client.rs
@@ -65,7 +65,6 @@ const USER_DEFINED_METADATA_HEADER_PREFIX: &str = "x-amz-meta-";
/// A specialized `Error` for object store-related errors
#[derive(Debug, Snafu)]
-#[allow(missing_docs)]
pub(crate) enum Error {
#[snafu(display("Error performing DeleteObjects request: {}", source))]
DeleteObjectsRequest { source: crate::client::retry::Error },
diff --git a/object_store/src/aws/resolve.rs b/object_store/src/aws/resolve.rs
index 12c9f26d220b..4c7489316b6c 100644
--- a/object_store/src/aws/resolve.rs
+++ b/object_store/src/aws/resolve.rs
@@ -21,7 +21,6 @@ use snafu::{ensure, OptionExt, ResultExt, Snafu};
/// A specialized `Error` for object store-related errors
#[derive(Debug, Snafu)]
-#[allow(missing_docs)]
enum Error {
#[snafu(display("Bucket '{}' not found", bucket))]
BucketNotFound { bucket: String },
diff --git a/object_store/src/azure/builder.rs b/object_store/src/azure/builder.rs
index 35cedeafc049..1c4589ba1ec6 100644
--- a/object_store/src/azure/builder.rs
+++ b/object_store/src/azure/builder.rs
@@ -46,7 +46,6 @@ const MSI_ENDPOINT_ENV_KEY: &str = "IDENTITY_ENDPOINT";
/// A specialized `Error` for Azure builder-related errors
#[derive(Debug, Snafu)]
-#[allow(missing_docs)]
enum Error {
#[snafu(display("Unable parse source url. Url: {}, Error: {}", url, source))]
UnableToParseUrl {
diff --git a/object_store/src/azure/client.rs b/object_store/src/azure/client.rs
index 04990515543a..06d3fb5c8678 100644
--- a/object_store/src/azure/client.rs
+++ b/object_store/src/azure/client.rs
@@ -60,7 +60,6 @@ static TAGS_HEADER: HeaderName = HeaderName::from_static("x-ms-tags");
/// A specialized `Error` for object store-related errors
#[derive(Debug, Snafu)]
-#[allow(missing_docs)]
pub(crate) enum Error {
#[snafu(display("Error performing get request {}: {}", path, source))]
GetRequest {
diff --git a/object_store/src/client/get.rs b/object_store/src/client/get.rs
index 0fef5785c052..ae6a8d9deaae 100644
--- a/object_store/src/client/get.rs
+++ b/object_store/src/client/get.rs
@@ -96,7 +96,6 @@ impl ContentRange {
/// A specialized `Error` for get-related errors
#[derive(Debug, Snafu)]
-#[allow(missing_docs)]
enum GetResultError {
#[snafu(context(false))]
Header {
diff --git a/object_store/src/lib.rs b/object_store/src/lib.rs
index 8820983b2025..a0d83eb0b6dd 100644
--- a/object_store/src/lib.rs
+++ b/object_store/src/lib.rs
@@ -1224,78 +1224,116 @@ pub type Result<T, E = Error> = std::result::Result<T, E>;
/// A specialized `Error` for object store-related errors
#[derive(Debug, Snafu)]
-#[allow(missing_docs)]
#[non_exhaustive]
pub enum Error {
+ /// A fallback error type when no variant matches
#[snafu(display("Generic {} error: {}", store, source))]
Generic {
+ /// The store this error originated from
store: &'static str,
+ /// The wrapped error
source: Box<dyn std::error::Error + Send + Sync + 'static>,
},
+ /// Error when the object is not found at given location
#[snafu(display("Object at location {} not found: {}", path, source))]
NotFound {
+ /// The path to file
path: String,
+ /// The wrapped error
source: Box<dyn std::error::Error + Send + Sync + 'static>,
},
+ /// Error for invalid path
#[snafu(
display("Encountered object with invalid path: {}", source),
context(false)
)]
- InvalidPath { source: path::Error },
+ InvalidPath {
+ /// The wrapped error
+ source: path::Error,
+ },
+ /// Error when `tokio::spawn` failed
#[snafu(display("Error joining spawned task: {}", source), context(false))]
- JoinError { source: tokio::task::JoinError },
+ JoinError {
+ /// The wrapped error
+ source: tokio::task::JoinError,
+ },
+ /// Error when the attempted operation is not supported
#[snafu(display("Operation not supported: {}", source))]
NotSupported {
+ /// The wrapped error
source: Box<dyn std::error::Error + Send + Sync + 'static>,
},
+ /// Error when the object already exists
#[snafu(display("Object at location {} already exists: {}", path, source))]
AlreadyExists {
+ /// The path to the
path: String,
+ /// The wrapped error
source: Box<dyn std::error::Error + Send + Sync + 'static>,
},
+ /// Error when the required conditions failed for the operation
#[snafu(display("Request precondition failure for path {}: {}", path, source))]
Precondition {
+ /// The path to the file
path: String,
+ /// The wrapped error
source: Box<dyn std::error::Error + Send + Sync + 'static>,
},
+ /// Error when the object at the location isn't modified
#[snafu(display("Object at location {} not modified: {}", path, source))]
NotModified {
+ /// The path to the file
path: String,
+ /// The wrapped error
source: Box<dyn std::error::Error + Send + Sync + 'static>,
},
+ /// Error when an operation is not implemented
#[snafu(display("Operation not yet implemented."))]
NotImplemented,
+ /// Error when the used credentials don't have enough permission
+ /// to perform the requested operation
#[snafu(display(
"The operation lacked the necessary privileges to complete for path {}: {}",
path,
source
))]
PermissionDenied {
+ /// The path to the file
path: String,
+ /// The wrapped error
source: Box<dyn std::error::Error + Send + Sync + 'static>,
},
+ /// Error when the used credentials lack valid authentication
#[snafu(display(
"The operation lacked valid authentication credentials for path {}: {}",
path,
source
))]
Unauthenticated {
+ /// The path to the file
path: String,
+ /// The wrapped error
source: Box<dyn std::error::Error + Send + Sync + 'static>,
},
+ /// Error when a configuration key is invalid for the store used
#[snafu(display("Configuration key: '{}' is not valid for store '{}'.", key, store))]
- UnknownConfigurationKey { store: &'static str, key: String },
+ UnknownConfigurationKey {
+ /// The object store used
+ store: &'static str,
+ /// The configuration key used
+ key: String,
+ },
}
impl From<Error> for std::io::Error {
diff --git a/object_store/src/local.rs b/object_store/src/local.rs
index db4b4b05031e..ac10f332d743 100644
--- a/object_store/src/local.rs
+++ b/object_store/src/local.rs
@@ -44,7 +44,6 @@ use crate::{
/// A specialized `Error` for filesystem object store-related errors
#[derive(Debug, Snafu)]
-#[allow(missing_docs)]
pub(crate) enum Error {
#[snafu(display("File size for {} did not fit in a usize: {}", path, source))]
FileSizeOverflowedUsize {
diff --git a/object_store/src/memory.rs b/object_store/src/memory.rs
index 0d72983b0495..b458bdddfbf5 100644
--- a/object_store/src/memory.rs
+++ b/object_store/src/memory.rs
@@ -38,7 +38,6 @@ use crate::{GetOptions, PutPayload};
/// A specialized `Error` for in-memory object store-related errors
#[derive(Debug, Snafu)]
-#[allow(missing_docs)]
enum Error {
#[snafu(display("No data in memory found. Location: {path}"))]
NoDataInMemory { path: String },
diff --git a/object_store/src/path/mod.rs b/object_store/src/path/mod.rs
index 59e08e2eaba9..4c9bb5f05186 100644
--- a/object_store/src/path/mod.rs
+++ b/object_store/src/path/mod.rs
@@ -36,32 +36,57 @@ pub use parts::{InvalidPart, PathPart};
/// Error returned by [`Path::parse`]
#[derive(Debug, Snafu)]
-#[allow(missing_docs)]
#[non_exhaustive]
pub enum Error {
+ /// Error when there's an empty segment between two slashes `/` in the path
#[snafu(display("Path \"{}\" contained empty path segment", path))]
- EmptySegment { path: String },
+ EmptySegment {
+ /// The source path
+ path: String,
+ },
+ /// Error when an invalid segment is encountered in the given path
#[snafu(display("Error parsing Path \"{}\": {}", path, source))]
- BadSegment { path: String, source: InvalidPart },
+ BadSegment {
+ /// The source path
+ path: String,
+ /// The part containing the error
+ source: InvalidPart,
+ },
+ /// Error when path cannot be canonicalized
#[snafu(display("Failed to canonicalize path \"{}\": {}", path.display(), source))]
Canonicalize {
+ /// The source path
path: std::path::PathBuf,
+ /// The underlying error
source: std::io::Error,
},
+ /// Error when the path is not a valid URL
#[snafu(display("Unable to convert path \"{}\" to URL", path.display()))]
- InvalidPath { path: std::path::PathBuf },
+ InvalidPath {
+ /// The source path
+ path: std::path::PathBuf,
+ },
+ /// Error when a path contains non-unicode characters
#[snafu(display("Path \"{}\" contained non-unicode characters: {}", path, source))]
NonUnicode {
+ /// The source path
path: String,
+ /// The underlying `UTF8Error`
source: std::str::Utf8Error,
},
+ /// Error when the a path doesn't start with given prefix
#[snafu(display("Path {} does not start with prefix {}", path, prefix))]
- PrefixMismatch { path: String, prefix: String },
+ PrefixMismatch {
+ /// The source path
+ path: String,
+ /// The mismatched prefix
+ prefix: String,
+ },
}
/// A parsed path representation that can be safely written to object storage
diff --git a/parquet/src/compression.rs b/parquet/src/compression.rs
index edf675f1302a..ccc060250af4 100644
--- a/parquet/src/compression.rs
+++ b/parquet/src/compression.rs
@@ -298,6 +298,35 @@ mod gzip_codec {
pub use gzip_codec::*;
/// Represents a valid gzip compression level.
+///
+/// Defaults to 6.
+///
+/// * 0: least compression
+/// * 9: most compression (that other software can read)
+/// * 10: most compression (incompatible with other software, see below)
+/// #### WARNING:
+/// Level 10 compression can offer smallest file size,
+/// but Parquet files created with it will not be readable
+/// by other "standard" paquet readers.
+///
+/// Do **NOT** use level 10 if you need other software to
+/// be able to read the files. Read below for details.
+///
+/// ### IMPORTANT:
+/// There's often confusion about the compression levels in `flate2` vs `arrow`
+/// as highlighted in issue [#1011](https://github.com/apache/arrow-rs/issues/6282).
+///
+/// `flate2` supports two compression backends: `miniz_oxide` and `zlib`.
+///
+/// - `zlib` supports levels from 0 to 9.
+/// - `miniz_oxide` supports levels from 0 to 10.
+///
+/// `arrow` uses `flate` with `rust_backend` feature,
+/// which provides `miniz_oxide` as the backend.
+/// Therefore 0-10 levels are supported.
+///
+/// `flate2` documents this behavior properly with
+/// [this commit](https://github.com/rust-lang/flate2-rs/pull/430).
#[derive(Debug, Eq, PartialEq, Hash, Clone, Copy)]
pub struct GzipLevel(u32);
|
diff --git a/arrow-integration-test/src/lib.rs b/arrow-integration-test/src/lib.rs
index d1486fd5a153..ea5b545f2e81 100644
--- a/arrow-integration-test/src/lib.rs
+++ b/arrow-integration-test/src/lib.rs
@@ -21,6 +21,7 @@
//!
//! This is not a canonical format, but provides a human-readable way of verifying language implementations
+#![warn(missing_docs)]
use arrow_buffer::{IntervalDayTime, IntervalMonthDayNano, ScalarBuffer};
use hex::decode;
use num::BigInt;
@@ -49,8 +50,11 @@ pub use schema::*;
/// See <https://github.com/apache/arrow/blob/master/docs/source/format/Integration.rst#json-test-data-format>
#[derive(Deserialize, Serialize, Debug)]
pub struct ArrowJson {
+ /// The Arrow schema for JSON file
pub schema: ArrowJsonSchema,
+ /// The `RecordBatch`es in the JSON file
pub batches: Vec<ArrowJsonBatch>,
+ /// The dictionaries in the JSON file
#[serde(skip_serializing_if = "Option::is_none")]
pub dictionaries: Option<Vec<ArrowJsonDictionaryBatch>>,
}
@@ -60,7 +64,9 @@ pub struct ArrowJson {
/// Fields are left as JSON `Value` as they vary by `DataType`
#[derive(Deserialize, Serialize, Debug)]
pub struct ArrowJsonSchema {
+ /// An array of JSON fields
pub fields: Vec<ArrowJsonField>,
+ /// An array of metadata key-value pairs
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<Vec<HashMap<String, String>>>,
}
@@ -68,13 +74,20 @@ pub struct ArrowJsonSchema {
/// Fields are left as JSON `Value` as they vary by `DataType`
#[derive(Deserialize, Serialize, Debug)]
pub struct ArrowJsonField {
+ /// The name of the field
pub name: String,
+ /// The data type of the field,
+ /// can be any valid JSON value
#[serde(rename = "type")]
pub field_type: Value,
+ /// Whether the field is nullable
pub nullable: bool,
+ /// The children fields
pub children: Vec<ArrowJsonField>,
+ /// The dictionary for the field
#[serde(skip_serializing_if = "Option::is_none")]
pub dictionary: Option<ArrowJsonFieldDictionary>,
+ /// The metadata for the field, if any
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<Value>,
}
@@ -115,20 +128,28 @@ impl From<&Field> for ArrowJsonField {
}
}
+/// Represents a dictionary-encoded field in the Arrow JSON format
#[derive(Deserialize, Serialize, Debug)]
pub struct ArrowJsonFieldDictionary {
+ /// A unique identifier for the dictionary
pub id: i64,
+ /// The type of the dictionary index
#[serde(rename = "indexType")]
pub index_type: DictionaryIndexType,
+ /// Whether the dictionary is ordered
#[serde(rename = "isOrdered")]
pub is_ordered: bool,
}
+/// Type of an index for a dictionary-encoded field in the Arrow JSON format
#[derive(Deserialize, Serialize, Debug)]
pub struct DictionaryIndexType {
+ /// The name of the dictionary index type
pub name: String,
+ /// Whether the dictionary index type is signed
#[serde(rename = "isSigned")]
pub is_signed: bool,
+ /// The bit width of the dictionary index type
#[serde(rename = "bitWidth")]
pub bit_width: i64,
}
@@ -137,6 +158,7 @@ pub struct DictionaryIndexType {
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct ArrowJsonBatch {
count: usize,
+ /// The columns in the record batch
pub columns: Vec<ArrowJsonColumn>,
}
@@ -144,7 +166,9 @@ pub struct ArrowJsonBatch {
#[derive(Deserialize, Serialize, Debug, Clone)]
#[allow(non_snake_case)]
pub struct ArrowJsonDictionaryBatch {
+ /// The unique identifier for the dictionary
pub id: i64,
+ /// The data for the dictionary
pub data: ArrowJsonBatch,
}
@@ -152,15 +176,21 @@ pub struct ArrowJsonDictionaryBatch {
#[derive(Deserialize, Serialize, Clone, Debug)]
pub struct ArrowJsonColumn {
name: String,
+ /// The number of elements in the column
pub count: usize,
+ /// The validity bitmap to determine null values
#[serde(rename = "VALIDITY")]
pub validity: Option<Vec<u8>>,
+ /// The data values in the column
#[serde(rename = "DATA")]
pub data: Option<Vec<Value>>,
+ /// The offsets for variable-sized data types
#[serde(rename = "OFFSET")]
pub offset: Option<Vec<Value>>, // leaving as Value as 64-bit offsets are strings
+ /// The type id for union types
#[serde(rename = "TYPE_ID")]
pub type_id: Option<Vec<i8>>,
+ /// The children columns for nested types
pub children: Option<Vec<ArrowJsonColumn>>,
}
@@ -189,6 +219,7 @@ impl ArrowJson {
Ok(true)
}
+ /// Convert the stored dictionaries to `Vec[RecordBatch]`
pub fn get_record_batches(&self) -> Result<Vec<RecordBatch>> {
let schema = self.schema.to_arrow_schema()?;
@@ -275,6 +306,7 @@ impl ArrowJsonField {
}
}
+/// Generates a [`RecordBatch`] from an Arrow JSON batch, given a schema
pub fn record_batch_from_json(
schema: &Schema,
json_batch: ArrowJsonBatch,
@@ -877,6 +909,7 @@ pub fn array_from_json(
}
}
+/// Construct a [`DictionaryArray`] from a partially typed JSON column
pub fn dictionary_array_from_json(
field: &Field,
json_col: ArrowJsonColumn,
@@ -965,6 +998,7 @@ fn create_null_buf(json_col: &ArrowJsonColumn) -> Buffer {
}
impl ArrowJsonBatch {
+ /// Convert a [`RecordBatch`] to an [`ArrowJsonBatch`]
pub fn from_batch(batch: &RecordBatch) -> ArrowJsonBatch {
let mut json_batch = ArrowJsonBatch {
count: batch.num_rows(),
diff --git a/arrow-integration-testing/src/flight_client_scenarios/auth_basic_proto.rs b/arrow-integration-testing/src/flight_client_scenarios/auth_basic_proto.rs
index 376e31e15553..34c3c7706df5 100644
--- a/arrow-integration-testing/src/flight_client_scenarios/auth_basic_proto.rs
+++ b/arrow-integration-testing/src/flight_client_scenarios/auth_basic_proto.rs
@@ -15,6 +15,8 @@
// specific language governing permissions and limitations
// under the License.
+//! Scenario for testing basic auth.
+
use crate::{AUTH_PASSWORD, AUTH_USERNAME};
use arrow_flight::{flight_service_client::FlightServiceClient, BasicAuth, HandshakeRequest};
@@ -27,6 +29,7 @@ type Result<T = (), E = Error> = std::result::Result<T, E>;
type Client = FlightServiceClient<tonic::transport::Channel>;
+/// Run a scenario that tests basic auth.
pub async fn run_scenario(host: &str, port: u16) -> Result {
let url = format!("http://{host}:{port}");
let mut client = FlightServiceClient::connect(url).await?;
diff --git a/arrow-integration-testing/src/flight_client_scenarios/integration_test.rs b/arrow-integration-testing/src/flight_client_scenarios/integration_test.rs
index 1a6c4e28a76b..c8289ff446a0 100644
--- a/arrow-integration-testing/src/flight_client_scenarios/integration_test.rs
+++ b/arrow-integration-testing/src/flight_client_scenarios/integration_test.rs
@@ -15,6 +15,8 @@
// specific language governing permissions and limitations
// under the License.
+//! Integration tests for the Flight client.
+
use crate::open_json_file;
use std::collections::HashMap;
@@ -40,6 +42,7 @@ type Result<T = (), E = Error> = std::result::Result<T, E>;
type Client = FlightServiceClient<tonic::transport::Channel>;
+/// Run a scenario that uploads data to a Flight server and then downloads it back
pub async fn run_scenario(host: &str, port: u16, path: &str) -> Result {
let url = format!("http://{host}:{port}");
diff --git a/arrow-integration-testing/src/flight_client_scenarios/middleware.rs b/arrow-integration-testing/src/flight_client_scenarios/middleware.rs
index 3b71edf446a3..b826ad456055 100644
--- a/arrow-integration-testing/src/flight_client_scenarios/middleware.rs
+++ b/arrow-integration-testing/src/flight_client_scenarios/middleware.rs
@@ -15,6 +15,8 @@
// specific language governing permissions and limitations
// under the License.
+//! Scenario for testing middleware.
+
use arrow_flight::{
flight_descriptor::DescriptorType, flight_service_client::FlightServiceClient, FlightDescriptor,
};
@@ -24,6 +26,7 @@ use tonic::{Request, Status};
type Error = Box<dyn std::error::Error + Send + Sync + 'static>;
type Result<T = (), E = Error> = std::result::Result<T, E>;
+/// Run a scenario that tests middleware.
pub async fn run_scenario(host: &str, port: u16) -> Result {
let url = format!("http://{host}:{port}");
let conn = tonic::transport::Endpoint::new(url)?.connect().await?;
diff --git a/arrow-integration-testing/src/flight_client_scenarios.rs b/arrow-integration-testing/src/flight_client_scenarios/mod.rs
similarity index 93%
rename from arrow-integration-testing/src/flight_client_scenarios.rs
rename to arrow-integration-testing/src/flight_client_scenarios/mod.rs
index 66cced5f4c2e..c5794433764a 100644
--- a/arrow-integration-testing/src/flight_client_scenarios.rs
+++ b/arrow-integration-testing/src/flight_client_scenarios/mod.rs
@@ -15,6 +15,8 @@
// specific language governing permissions and limitations
// under the License.
+//! Collection of utilities for testing the Flight client.
+
pub mod auth_basic_proto;
pub mod integration_test;
pub mod middleware;
diff --git a/arrow-integration-testing/src/flight_server_scenarios/auth_basic_proto.rs b/arrow-integration-testing/src/flight_server_scenarios/auth_basic_proto.rs
index 20d868953664..5462e5bd674b 100644
--- a/arrow-integration-testing/src/flight_server_scenarios/auth_basic_proto.rs
+++ b/arrow-integration-testing/src/flight_server_scenarios/auth_basic_proto.rs
@@ -15,6 +15,8 @@
// specific language governing permissions and limitations
// under the License.
+//! Basic auth test for the Flight server.
+
use std::pin::Pin;
use std::sync::Arc;
@@ -35,6 +37,7 @@ use prost::Message;
use crate::{AUTH_PASSWORD, AUTH_USERNAME};
+/// Run a scenario that tests basic auth.
pub async fn scenario_setup(port: u16) -> Result {
let service = AuthBasicProtoScenarioImpl {
username: AUTH_USERNAME.into(),
@@ -52,6 +55,7 @@ pub async fn scenario_setup(port: u16) -> Result {
Ok(())
}
+/// Scenario for testing basic auth.
#[derive(Clone)]
pub struct AuthBasicProtoScenarioImpl {
username: Arc<str>,
diff --git a/arrow-integration-testing/src/flight_server_scenarios/integration_test.rs b/arrow-integration-testing/src/flight_server_scenarios/integration_test.rs
index 76eb9d880199..0c58fae93df5 100644
--- a/arrow-integration-testing/src/flight_server_scenarios/integration_test.rs
+++ b/arrow-integration-testing/src/flight_server_scenarios/integration_test.rs
@@ -15,6 +15,9 @@
// specific language governing permissions and limitations
// under the License.
+//! Integration tests for the Flight server.
+
+use core::str;
use std::collections::HashMap;
use std::pin::Pin;
use std::sync::Arc;
@@ -42,6 +45,7 @@ type TonicStream<T> = Pin<Box<dyn Stream<Item = T> + Send + Sync + 'static>>;
type Error = Box<dyn std::error::Error + Send + Sync + 'static>;
type Result<T = (), E = Error> = std::result::Result<T, E>;
+/// Run a scenario that tests integration testing.
pub async fn scenario_setup(port: u16) -> Result {
let addr = super::listen_on(port).await?;
@@ -65,6 +69,7 @@ struct IntegrationDataset {
chunks: Vec<RecordBatch>,
}
+/// Flight service implementation for integration testing
#[derive(Clone, Default)]
pub struct FlightServiceImpl {
server_location: String,
@@ -100,13 +105,13 @@ impl FlightService for FlightServiceImpl {
) -> Result<Response<Self::DoGetStream>, Status> {
let ticket = request.into_inner();
- let key = String::from_utf8(ticket.ticket.to_vec())
+ let key = str::from_utf8(&ticket.ticket)
.map_err(|e| Status::invalid_argument(format!("Invalid ticket: {e:?}")))?;
let uploaded_chunks = self.uploaded_chunks.lock().await;
let flight = uploaded_chunks
- .get(&key)
+ .get(key)
.ok_or_else(|| Status::not_found(format!("Could not find flight. {key}")))?;
let options = arrow::ipc::writer::IpcWriteOptions::default();
diff --git a/arrow-integration-testing/src/flight_server_scenarios/middleware.rs b/arrow-integration-testing/src/flight_server_scenarios/middleware.rs
index e8d9c521bb99..6685d45dffac 100644
--- a/arrow-integration-testing/src/flight_server_scenarios/middleware.rs
+++ b/arrow-integration-testing/src/flight_server_scenarios/middleware.rs
@@ -15,6 +15,8 @@
// specific language governing permissions and limitations
// under the License.
+//! Middleware test for the Flight server.
+
use std::pin::Pin;
use arrow_flight::{
@@ -31,6 +33,7 @@ type TonicStream<T> = Pin<Box<dyn Stream<Item = T> + Send + Sync + 'static>>;
type Error = Box<dyn std::error::Error + Send + Sync + 'static>;
type Result<T = (), E = Error> = std::result::Result<T, E>;
+/// Run a scenario that tests middleware.
pub async fn scenario_setup(port: u16) -> Result {
let service = MiddlewareScenarioImpl {};
let svc = FlightServiceServer::new(service);
@@ -44,6 +47,7 @@ pub async fn scenario_setup(port: u16) -> Result {
Ok(())
}
+/// Middleware interceptor for testing
#[derive(Clone, Default)]
pub struct MiddlewareScenarioImpl {}
diff --git a/arrow-integration-testing/src/flight_server_scenarios.rs b/arrow-integration-testing/src/flight_server_scenarios/mod.rs
similarity index 91%
rename from arrow-integration-testing/src/flight_server_scenarios.rs
rename to arrow-integration-testing/src/flight_server_scenarios/mod.rs
index 48d4e6045684..3833e1c6335c 100644
--- a/arrow-integration-testing/src/flight_server_scenarios.rs
+++ b/arrow-integration-testing/src/flight_server_scenarios/mod.rs
@@ -15,6 +15,7 @@
// specific language governing permissions and limitations
// under the License.
+//! Collection of utilities for testing the Flight server.
use std::net::SocketAddr;
use arrow_flight::{FlightEndpoint, Location, Ticket};
@@ -27,6 +28,7 @@ pub mod middleware;
type Error = Box<dyn std::error::Error + Send + Sync + 'static>;
type Result<T = (), E = Error> = std::result::Result<T, E>;
+/// Listen on a port and return the address
pub async fn listen_on(port: u16) -> Result<SocketAddr> {
let addr: SocketAddr = format!("0.0.0.0:{port}").parse()?;
@@ -36,6 +38,7 @@ pub async fn listen_on(port: u16) -> Result<SocketAddr> {
Ok(addr)
}
+/// Create a FlightEndpoint with a ticket and location
pub fn endpoint(ticket: &str, location_uri: impl Into<String>) -> FlightEndpoint {
FlightEndpoint {
ticket: Some(Ticket {
diff --git a/arrow-integration-testing/src/lib.rs b/arrow-integration-testing/src/lib.rs
index 4ce7b06a1888..ba8e3876c3e3 100644
--- a/arrow-integration-testing/src/lib.rs
+++ b/arrow-integration-testing/src/lib.rs
@@ -17,6 +17,7 @@
//! Common code used in the integration test binaries
+#![warn(missing_docs)]
use serde_json::Value;
use arrow::array::{Array, StructArray};
@@ -42,7 +43,9 @@ pub const AUTH_PASSWORD: &str = "flight";
pub mod flight_client_scenarios;
pub mod flight_server_scenarios;
+/// An Arrow file in JSON format
pub struct ArrowFile {
+ /// The schema of the file
pub schema: Schema,
// we can evolve this into a concrete Arrow type
// this is temporarily not being read from
@@ -51,12 +54,14 @@ pub struct ArrowFile {
}
impl ArrowFile {
+ /// Read a single [RecordBatch] from the file
pub fn read_batch(&self, batch_num: usize) -> Result<RecordBatch> {
let b = self.arrow_json["batches"].get(batch_num).unwrap();
let json_batch: ArrowJsonBatch = serde_json::from_value(b.clone()).unwrap();
record_batch_from_json(&self.schema, json_batch, Some(&self.dictionaries))
}
+ /// Read all [RecordBatch]es from the file
pub fn read_batches(&self) -> Result<Vec<RecordBatch>> {
self.arrow_json["batches"]
.as_array()
@@ -70,7 +75,7 @@ impl ArrowFile {
}
}
-// Canonicalize the names of map fields in a schema
+/// Canonicalize the names of map fields in a schema
pub fn canonicalize_schema(schema: &Schema) -> Schema {
let fields = schema
.fields()
@@ -107,6 +112,7 @@ pub fn canonicalize_schema(schema: &Schema) -> Schema {
Schema::new(fields).with_metadata(schema.metadata().clone())
}
+/// Read an Arrow file in JSON format
pub fn open_json_file(json_name: &str) -> Result<ArrowFile> {
let json_file = File::open(json_name)?;
let reader = BufReader::new(json_file);
@@ -157,10 +163,7 @@ pub fn read_gzip_json(version: &str, path: &str) -> ArrowJson {
arrow_json
}
-//
-// C Data Integration entrypoints
-//
-
+/// C Data Integration entrypoint to export the schema from a JSON file
fn cdata_integration_export_schema_from_json(
c_json_name: *const i8,
out: *mut FFI_ArrowSchema,
@@ -173,6 +176,7 @@ fn cdata_integration_export_schema_from_json(
Ok(())
}
+/// C Data Integration entrypoint to export a batch from a JSON file
fn cdata_integration_export_batch_from_json(
c_json_name: *const i8,
batch_num: c_int,
@@ -263,6 +267,7 @@ pub unsafe extern "C" fn arrow_rs_free_error(c_error: *mut i8) {
}
}
+/// A C-ABI for exporting an Arrow schema from a JSON file
#[no_mangle]
pub extern "C" fn arrow_rs_cdata_integration_export_schema_from_json(
c_json_name: *const i8,
@@ -272,6 +277,7 @@ pub extern "C" fn arrow_rs_cdata_integration_export_schema_from_json(
result_to_c_error(&r)
}
+/// A C-ABI to compare an Arrow schema against a JSON file
#[no_mangle]
pub extern "C" fn arrow_rs_cdata_integration_import_schema_and_compare_to_json(
c_json_name: *const i8,
@@ -281,6 +287,7 @@ pub extern "C" fn arrow_rs_cdata_integration_import_schema_and_compare_to_json(
result_to_c_error(&r)
}
+/// A C-ABI for exporting a RecordBatch from a JSON file
#[no_mangle]
pub extern "C" fn arrow_rs_cdata_integration_export_batch_from_json(
c_json_name: *const i8,
@@ -291,6 +298,7 @@ pub extern "C" fn arrow_rs_cdata_integration_export_batch_from_json(
result_to_c_error(&r)
}
+/// A C-ABI to compare a RecordBatch against a JSON file
#[no_mangle]
pub extern "C" fn arrow_rs_cdata_integration_import_batch_and_compare_to_json(
c_json_name: *const i8,
diff --git a/arrow/tests/array_cast.rs b/arrow/tests/array_cast.rs
index 0fd89cc2bff4..8f86cbeab717 100644
--- a/arrow/tests/array_cast.rs
+++ b/arrow/tests/array_cast.rs
@@ -179,7 +179,7 @@ fn test_can_cast_types() {
/// Create instances of arrays with varying types for cast tests
fn get_arrays_of_all_types() -> Vec<ArrayRef> {
- let tz_name = String::from("+08:00");
+ let tz_name = "+08:00";
let binary_data: Vec<&[u8]> = vec![b"foo", b"bar"];
vec![
Arc::new(BinaryArray::from(binary_data.clone())),
@@ -238,9 +238,9 @@ fn get_arrays_of_all_types() -> Vec<ArrayRef> {
Arc::new(TimestampMillisecondArray::from(vec![1000, 2000])),
Arc::new(TimestampMicrosecondArray::from(vec![1000, 2000])),
Arc::new(TimestampNanosecondArray::from(vec![1000, 2000])),
- Arc::new(TimestampSecondArray::from(vec![1000, 2000]).with_timezone(tz_name.clone())),
- Arc::new(TimestampMillisecondArray::from(vec![1000, 2000]).with_timezone(tz_name.clone())),
- Arc::new(TimestampMicrosecondArray::from(vec![1000, 2000]).with_timezone(tz_name.clone())),
+ Arc::new(TimestampSecondArray::from(vec![1000, 2000]).with_timezone(tz_name)),
+ Arc::new(TimestampMillisecondArray::from(vec![1000, 2000]).with_timezone(tz_name)),
+ Arc::new(TimestampMicrosecondArray::from(vec![1000, 2000]).with_timezone(tz_name)),
Arc::new(TimestampNanosecondArray::from(vec![1000, 2000]).with_timezone(tz_name)),
Arc::new(Date32Array::from(vec![1000, 2000])),
Arc::new(Date64Array::from(vec![1000, 2000])),
|
What is the highest compression level in gzip?
**Which part is this question about**
What is the highest compression level in gzip?
**Describe your question**
I see from other sources, including `flate2`, the highest compression level for gzip is 9 instead of 10. If we pass 10, it should be accepted by parquet but rejected by flate2. Am I getting misunderstanding somewhere?
```rust
impl CompressionLevel<u32> for GzipLevel {
const MINIMUM_LEVEL: u32 = 0;
const MAXIMUM_LEVEL: u32 = 10;
}
```
|
It seems flate2 documentation is wrong.
```rust
/// Returns an integer representing the compression level, typically on a
/// scale of 0-9
pub fn level(&self) -> u32 {
self.0
}
```
But internally, inside `DeflateBackend::make` they have `debug_assert!(level.level() <= 10);`. Using compression level up to 10 works fine but panics for bigger values.
@JakkuSakura After discussing with `flate2` maintainers, I've confirmed that it's actually a documentation issue, but there's a slight caveat as well. `flate2` supports both `miniz` and `zlib` backends, the former enabled by default.
For consistency with zlib (which supports up to 9), the documentation states the compression range as `0-9`, but 10 is supported miniz, enabled by default. If the backend is switched to `zlib`, then an attempt to use a compression level 10 will cause a panic.
I've opened a [pull request in flate2](https://github.com/rust-lang/flate2-rs/pull/427) to explicitly mention this in the docs, so that there's no confusion around this behavior. I hope this resolves your query?
One more thing to add here. Parquet (and the entire arrow project) uses `flate2` with `rust_backend` feature enabled. Which uses `miniz` backend, thereby supporting level 10 compression, aka `UBER COMPRESSION`. Flate2 still chooses to call 9 as the `best` level of compression because with 10 we might run into performance issues on the user's device.
The PR I created in `flate2` is merged. So the docs should mention this caveat very soon hopefully. But behaviorally speaking, using level = 10 in parquet shouldn't be a problem at all. Discretion is advised when using `flate2` separately.
@alamb @tustvold what do you think? And should we close this?
Maybe we can add a note to the arrow documentation with a link to flate2 and close this issuse?
Sounds like a good idea. I'll make this a part of #37 exercise itself.
@alamb @tustvold have a look please before I add anything to the docs.
https://github.com/rust-lang/flate2-rs/pull/427#issuecomment-2377460294 and https://github.com/rust-lang/flate2-rs/pull/429
> @alamb @tustvold have a look please before I add anything to the docs.
>
> [rust-lang/flate2-rs#427 (comment)](https://github.com/rust-lang/flate2-rs/pull/427#issuecomment-2377460294) and [rust-lang/flate2-rs#429](https://github.com/rust-lang/flate2-rs/pull/429)
I recommend linking to the docs added in https://github.com/rust-lang/flate2-rs/pull/430 -- they are pretty clear to me. Basically we can say the max is 10 but offer the caveat that nothing else will be able to read the parquet files
|
2024-09-25T04:27:02Z
|
53.0
|
f41c258246cd4bd9d89228cded9ed54dbd00faff
|
apache/arrow-rs
| 6,368
|
apache__arrow-rs-6368
|
[
"6366"
] |
0491294828a6480959ba3983355b415abbaf1174
|
diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml
index 1937fafe3a62..41edc1bb194e 100644
--- a/.github/workflows/integration.yml
+++ b/.github/workflows/integration.yml
@@ -48,7 +48,6 @@ on:
- arrow/**
jobs:
-
integration:
name: Archery test With other arrows
runs-on: ubuntu-latest
@@ -118,9 +117,9 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
- rust: [ stable ]
- # PyArrow 13 was the last version prior to introduction to Arrow PyCapsules
- pyarrow: [ "13", "14" ]
+ rust: [stable]
+ # PyArrow 15 was the first version to introduce StringView/BinaryView support
+ pyarrow: ["15", "16", "17"]
steps:
- uses: actions/checkout@v4
with:
diff --git a/arrow-array/src/ffi.rs b/arrow-array/src/ffi.rs
index 1d76ed62d365..a28b3f746115 100644
--- a/arrow-array/src/ffi.rs
+++ b/arrow-array/src/ffi.rs
@@ -193,6 +193,13 @@ fn bit_width(data_type: &DataType, i: usize) -> Result<usize> {
"The datatype \"{data_type:?}\" expects 3 buffers, but requested {i}. Please verify that the C data interface is correctly implemented."
)))
}
+ // Variable-sized views: have 3 or more buffers.
+ // Buffer 1 are the u128 views
+ // Buffers 2...N-1 are u8 byte buffers
+ (DataType::Utf8View, 1) | (DataType::BinaryView,1) => u128::BITS as _,
+ (DataType::Utf8View, _) | (DataType::BinaryView, _) => {
+ u8::BITS as _
+ }
// type ids. UnionArray doesn't have null bitmap so buffer index begins with 0.
(DataType::Union(_, _), 0) => i8::BITS as _,
// Only DenseUnion has 2nd buffer
@@ -300,7 +307,7 @@ impl<'a> ImportedArrowArray<'a> {
};
let data_layout = layout(&self.data_type);
- let buffers = self.buffers(data_layout.can_contain_null_mask)?;
+ let buffers = self.buffers(data_layout.can_contain_null_mask, data_layout.variadic)?;
let null_bit_buffer = if data_layout.can_contain_null_mask {
self.null_bit_buffer()
@@ -373,13 +380,30 @@ impl<'a> ImportedArrowArray<'a> {
/// returns all buffers, as organized by Rust (i.e. null buffer is skipped if it's present
/// in the spec of the type)
- fn buffers(&self, can_contain_null_mask: bool) -> Result<Vec<Buffer>> {
+ fn buffers(&self, can_contain_null_mask: bool, variadic: bool) -> Result<Vec<Buffer>> {
// + 1: skip null buffer
let buffer_begin = can_contain_null_mask as usize;
- (buffer_begin..self.array.num_buffers())
- .map(|index| {
- let len = self.buffer_len(index, &self.data_type)?;
+ let buffer_end = self.array.num_buffers() - usize::from(variadic);
+
+ let variadic_buffer_lens = if variadic {
+ // Each views array has 1 (optional) null buffer, 1 views buffer, 1 lengths buffer.
+ // Rest are variadic.
+ let num_variadic_buffers =
+ self.array.num_buffers() - (2 + usize::from(can_contain_null_mask));
+ if num_variadic_buffers == 0 {
+ &[]
+ } else {
+ let lengths = self.array.buffer(self.array.num_buffers() - 1);
+ // SAFETY: is lengths is non-null, then it must be valid for up to num_variadic_buffers.
+ unsafe { std::slice::from_raw_parts(lengths.cast::<i64>(), num_variadic_buffers) }
+ }
+ } else {
+ &[]
+ };
+ (buffer_begin..buffer_end)
+ .map(|index| {
+ let len = self.buffer_len(index, variadic_buffer_lens, &self.data_type)?;
match unsafe { create_buffer(self.owner.clone(), self.array, index, len) } {
Some(buf) => Ok(buf),
None if len == 0 => {
@@ -399,7 +423,12 @@ impl<'a> ImportedArrowArray<'a> {
/// Rust implementation uses fixed-sized buffers, which require knowledge of their `len`.
/// for variable-sized buffers, such as the second buffer of a stringArray, we need
/// to fetch offset buffer's len to build the second buffer.
- fn buffer_len(&self, i: usize, dt: &DataType) -> Result<usize> {
+ fn buffer_len(
+ &self,
+ i: usize,
+ variadic_buffer_lengths: &[i64],
+ dt: &DataType,
+ ) -> Result<usize> {
// Special handling for dictionary type as we only care about the key type in the case.
let data_type = match dt {
DataType::Dictionary(key_data_type, _) => key_data_type.as_ref(),
@@ -430,7 +459,7 @@ impl<'a> ImportedArrowArray<'a> {
}
// the len of the data buffer (buffer 2) equals the last value of the offset buffer (buffer 1)
- let len = self.buffer_len(1, dt)?;
+ let len = self.buffer_len(1, variadic_buffer_lengths, dt)?;
// first buffer is the null buffer => add(1)
// we assume that pointer is aligned for `i32`, as Utf8 uses `i32` offsets.
#[allow(clippy::cast_ptr_alignment)]
@@ -444,7 +473,7 @@ impl<'a> ImportedArrowArray<'a> {
}
// the len of the data buffer (buffer 2) equals the last value of the offset buffer (buffer 1)
- let len = self.buffer_len(1, dt)?;
+ let len = self.buffer_len(1, variadic_buffer_lengths, dt)?;
// first buffer is the null buffer => add(1)
// we assume that pointer is aligned for `i64`, as Large uses `i64` offsets.
#[allow(clippy::cast_ptr_alignment)]
@@ -452,6 +481,16 @@ impl<'a> ImportedArrowArray<'a> {
// get last offset
(unsafe { *offset_buffer.add(len / size_of::<i64>() - 1) }) as usize
}
+ // View types: these have variadic buffers.
+ // Buffer 1 is the views buffer, which stores 1 u128 per length of the array.
+ // Buffers 2..N-1 are the buffers holding the byte data. Their lengths are variable.
+ // Buffer N is of length (N - 2) and stores i64 containing the lengths of buffers 2..N-1
+ (DataType::Utf8View, 1) | (DataType::BinaryView, 1) => {
+ std::mem::size_of::<u128>() * length
+ }
+ (DataType::Utf8View, i) | (DataType::BinaryView, i) => {
+ variadic_buffer_lengths[i - 2] as usize
+ }
// buffer len of primitive types
_ => {
let bits = bit_width(data_type, i)?;
@@ -1229,18 +1268,18 @@ mod tests_from_ffi {
use arrow_data::ArrayData;
use arrow_schema::{DataType, Field};
- use crate::types::Int32Type;
+ use super::{ImportedArrowArray, Result};
+ use crate::builder::GenericByteViewBuilder;
+ use crate::types::{BinaryViewType, ByteViewType, Int32Type, StringViewType};
use crate::{
array::{
Array, BooleanArray, DictionaryArray, FixedSizeBinaryArray, FixedSizeListArray,
Int32Array, Int64Array, StringArray, StructArray, UInt32Array, UInt64Array,
},
ffi::{from_ffi, FFI_ArrowArray, FFI_ArrowSchema},
- make_array, ArrayRef, ListArray,
+ make_array, ArrayRef, GenericByteViewArray, ListArray,
};
- use super::{ImportedArrowArray, Result};
-
fn test_round_trip(expected: &ArrayData) -> Result<()> {
// here we export the array
let array = FFI_ArrowArray::new(expected);
@@ -1453,8 +1492,8 @@ mod tests_from_ffi {
owner: &array,
};
- let offset_buf_len = imported_array.buffer_len(1, &imported_array.data_type)?;
- let data_buf_len = imported_array.buffer_len(2, &imported_array.data_type)?;
+ let offset_buf_len = imported_array.buffer_len(1, &[], &imported_array.data_type)?;
+ let data_buf_len = imported_array.buffer_len(2, &[], &imported_array.data_type)?;
assert_eq!(offset_buf_len, 4);
assert_eq!(data_buf_len, 0);
@@ -1472,6 +1511,18 @@ mod tests_from_ffi {
StringArray::from(array)
}
+ fn roundtrip_byte_view_array<T: ByteViewType>(
+ array: GenericByteViewArray<T>,
+ ) -> GenericByteViewArray<T> {
+ let data = array.into_data();
+
+ let array = FFI_ArrowArray::new(&data);
+ let schema = FFI_ArrowSchema::try_from(data.data_type()).unwrap();
+
+ let array = unsafe { from_ffi(array, &schema) }.unwrap();
+ GenericByteViewArray::<T>::from(array)
+ }
+
fn extend_array(array: &dyn Array) -> ArrayRef {
let len = array.len();
let data = array.to_data();
@@ -1551,4 +1602,93 @@ mod tests_from_ffi {
&imported
);
}
+
+ /// Helper trait to allow us to use easily strings as either BinaryViewType::Native or
+ /// StringViewType::Native scalars.
+ trait NativeFromStr {
+ fn from_str(value: &str) -> &Self;
+ }
+
+ impl NativeFromStr for str {
+ fn from_str(value: &str) -> &Self {
+ value
+ }
+ }
+
+ impl NativeFromStr for [u8] {
+ fn from_str(value: &str) -> &Self {
+ value.as_bytes()
+ }
+ }
+
+ #[test]
+ fn test_round_trip_byte_view() {
+ fn test_case<T>()
+ where
+ T: ByteViewType,
+ T::Native: NativeFromStr,
+ {
+ macro_rules! run_test_case {
+ ($array:expr) => {{
+ // round-trip through C Data Interface
+ let len = $array.len();
+ let imported = roundtrip_byte_view_array($array);
+ assert_eq!(imported.len(), len);
+
+ let copied = extend_array(&imported);
+ assert_eq!(
+ copied
+ .as_any()
+ .downcast_ref::<GenericByteViewArray<T>>()
+ .unwrap(),
+ &imported
+ );
+ }};
+ }
+
+ // Empty test case.
+ let empty = GenericByteViewBuilder::<T>::new().finish();
+ run_test_case!(empty);
+
+ // All inlined strings test case.
+ let mut all_inlined = GenericByteViewBuilder::<T>::new();
+ all_inlined.append_value(T::Native::from_str("inlined1"));
+ all_inlined.append_value(T::Native::from_str("inlined2"));
+ all_inlined.append_value(T::Native::from_str("inlined3"));
+ let all_inlined = all_inlined.finish();
+ assert_eq!(all_inlined.data_buffers().len(), 0);
+ run_test_case!(all_inlined);
+
+ // some inlined + non-inlined, 1 variadic buffer.
+ let mixed_one_variadic = {
+ let mut builder = GenericByteViewBuilder::<T>::new();
+ builder.append_value(T::Native::from_str("inlined"));
+ let block_id =
+ builder.append_block(Buffer::from("non-inlined-string-buffer".as_bytes()));
+ builder.try_append_view(block_id, 0, 25).unwrap();
+ builder.finish()
+ };
+ assert_eq!(mixed_one_variadic.data_buffers().len(), 1);
+ run_test_case!(mixed_one_variadic);
+
+ // inlined + non-inlined, 2 variadic buffers.
+ let mixed_two_variadic = {
+ let mut builder = GenericByteViewBuilder::<T>::new();
+ builder.append_value(T::Native::from_str("inlined"));
+ let block_id =
+ builder.append_block(Buffer::from("non-inlined-string-buffer".as_bytes()));
+ builder.try_append_view(block_id, 0, 25).unwrap();
+
+ let block_id = builder
+ .append_block(Buffer::from("another-non-inlined-string-buffer".as_bytes()));
+ builder.try_append_view(block_id, 0, 33).unwrap();
+ builder.finish()
+ };
+ assert_eq!(mixed_two_variadic.data_buffers().len(), 2);
+ run_test_case!(mixed_two_variadic);
+ }
+
+ test_case::<StringViewType>();
+ test_case::<BinaryViewType>();
+ }
}
diff --git a/arrow-buffer/src/buffer/immutable.rs b/arrow-buffer/src/buffer/immutable.rs
index 7cd3552215f8..fef2f8008b2a 100644
--- a/arrow-buffer/src/buffer/immutable.rs
+++ b/arrow-buffer/src/buffer/immutable.rs
@@ -203,7 +203,9 @@ impl Buffer {
pub fn advance(&mut self, offset: usize) {
assert!(
offset <= self.length,
- "the offset of the new Buffer cannot exceed the existing length"
+ "the offset of the new Buffer cannot exceed the existing length: offset={} length={}",
+ offset,
+ self.length
);
self.length -= offset;
// Safety:
@@ -221,7 +223,8 @@ impl Buffer {
pub fn slice_with_length(&self, offset: usize, length: usize) -> Self {
assert!(
offset.saturating_add(length) <= self.length,
- "the offset of the new Buffer cannot exceed the existing length"
+ "the offset of the new Buffer cannot exceed the existing length: slice offset={offset} length={length} selflen={}",
+ self.length
);
// Safety:
// offset + length <= self.length
diff --git a/arrow-data/src/ffi.rs b/arrow-data/src/ffi.rs
index 3345595fac19..cd283d32662f 100644
--- a/arrow-data/src/ffi.rs
+++ b/arrow-data/src/ffi.rs
@@ -20,7 +20,7 @@
use crate::bit_mask::set_bits;
use crate::{layout, ArrayData};
use arrow_buffer::buffer::NullBuffer;
-use arrow_buffer::{Buffer, MutableBuffer};
+use arrow_buffer::{Buffer, MutableBuffer, ScalarBuffer};
use arrow_schema::DataType;
use std::ffi::c_void;
@@ -121,7 +121,7 @@ impl FFI_ArrowArray {
pub fn new(data: &ArrayData) -> Self {
let data_layout = layout(data.data_type());
- let buffers = if data_layout.can_contain_null_mask {
+ let mut buffers = if data_layout.can_contain_null_mask {
// * insert the null buffer at the start
// * make all others `Option<Buffer>`.
std::iter::once(align_nulls(data.offset(), data.nulls()))
@@ -132,7 +132,7 @@ impl FFI_ArrowArray {
};
// `n_buffers` is the number of buffers by the spec.
- let n_buffers = {
+ let mut n_buffers = {
data_layout.buffers.len() + {
// If the layout has a null buffer by Arrow spec.
// Note that even the array doesn't have a null buffer because it has
@@ -141,10 +141,22 @@ impl FFI_ArrowArray {
}
} as i64;
+ if data_layout.variadic {
+ // Save the lengths of all variadic buffers into a new buffer.
+ // The first buffer is `views`, and the rest are variadic.
+ let mut data_buffers_lengths = Vec::new();
+ for buffer in data.buffers().iter().skip(1) {
+ data_buffers_lengths.push(buffer.len() as i64);
+ n_buffers += 1;
+ }
+
+ buffers.push(Some(ScalarBuffer::from(data_buffers_lengths).into_inner()));
+ n_buffers += 1;
+ }
+
let buffers_ptr = buffers
.iter()
.flat_map(|maybe_buffer| match maybe_buffer {
- // note that `raw_data` takes into account the buffer's offset
Some(b) => Some(b.as_ptr() as *const c_void),
// This is for null buffer. We only put a null pointer for
// null buffer if by spec it can contain null mask.
diff --git a/arrow/src/pyarrow.rs b/arrow/src/pyarrow.rs
index 336398cbf22f..a7b593799835 100644
--- a/arrow/src/pyarrow.rs
+++ b/arrow/src/pyarrow.rs
@@ -354,7 +354,7 @@ impl FromPyArrow for RecordBatch {
validate_pycapsule(array_capsule, "arrow_array")?;
let schema_ptr = unsafe { schema_capsule.reference::<FFI_ArrowSchema>() };
- let ffi_array = unsafe { FFI_ArrowArray::from_raw(array_capsule.pointer() as _) };
+ let ffi_array = unsafe { FFI_ArrowArray::from_raw(array_capsule.pointer().cast()) };
let array_data = unsafe { ffi::from_ffi(ffi_array, schema_ptr) }.map_err(to_py_err)?;
if !matches!(array_data.data_type(), DataType::Struct(_)) {
return Err(PyTypeError::new_err(
|
diff --git a/arrow/tests/pyarrow.rs b/arrow/tests/pyarrow.rs
index a1c365c31798..d9ebd0daa1cd 100644
--- a/arrow/tests/pyarrow.rs
+++ b/arrow/tests/pyarrow.rs
@@ -18,6 +18,8 @@
use arrow::array::{ArrayRef, Int32Array, StringArray};
use arrow::pyarrow::{FromPyArrow, ToPyArrow};
use arrow::record_batch::RecordBatch;
+use arrow_array::builder::{BinaryViewBuilder, StringViewBuilder};
+use arrow_array::{Array, BinaryViewArray, StringViewArray};
use pyo3::Python;
use std::sync::Arc;
@@ -27,7 +29,9 @@ fn test_to_pyarrow() {
let a: ArrayRef = Arc::new(Int32Array::from(vec![1, 2]));
let b: ArrayRef = Arc::new(StringArray::from(vec!["a", "b"]));
- let input = RecordBatch::try_from_iter(vec![("a", a), ("b", b)]).unwrap();
+ // The "very long string" will not be inlined, and force the creation of a data buffer.
+ let c: ArrayRef = Arc::new(StringViewArray::from(vec!["short", "a very long string"]));
+ let input = RecordBatch::try_from_iter(vec![("a", a), ("b", b), ("c", c)]).unwrap();
println!("input: {:?}", input);
let res = Python::with_gil(|py| {
@@ -40,3 +44,66 @@ fn test_to_pyarrow() {
assert_eq!(input, res);
}
+
+#[test]
+fn test_to_pyarrow_byte_view() {
+ pyo3::prepare_freethreaded_python();
+
+ for num_variadic_buffers in 0..=2 {
+ let string_view: ArrayRef = Arc::new(string_view_column(num_variadic_buffers));
+ let binary_view: ArrayRef = Arc::new(binary_view_column(num_variadic_buffers));
+
+ let input = RecordBatch::try_from_iter(vec![
+ ("string_view", string_view),
+ ("binary_view", binary_view),
+ ])
+ .unwrap();
+
+ println!("input: {:?}", input);
+ let res = Python::with_gil(|py| {
+ let py_input = input.to_pyarrow(py)?;
+ let records = RecordBatch::from_pyarrow_bound(py_input.bind(py))?;
+ let py_records = records.to_pyarrow(py)?;
+ RecordBatch::from_pyarrow_bound(py_records.bind(py))
+ })
+ .unwrap();
+
+ assert_eq!(input, res);
+ }
+}
+
+fn binary_view_column(num_variadic_buffers: usize) -> BinaryViewArray {
+ let long_scalar = b"but soft what light through yonder window breaks".as_slice();
+ let mut builder = BinaryViewBuilder::new().with_fixed_block_size(long_scalar.len() as u32);
+ // Make sure there is at least one non-inlined value.
+ builder.append_value("inlined".as_bytes());
+
+ for _ in 0..num_variadic_buffers {
+ builder.append_value(long_scalar);
+ }
+
+ let result = builder.finish();
+
+ assert_eq!(result.data_buffers().len(), num_variadic_buffers);
+ assert_eq!(result.len(), num_variadic_buffers + 1);
+
+ result
+}
+
+fn string_view_column(num_variadic_buffers: usize) -> StringViewArray {
+ let long_scalar = "but soft what light through yonder window breaks";
+ let mut builder = StringViewBuilder::new().with_fixed_block_size(long_scalar.len() as u32);
+ // Make sure there is at least one non-inlined value.
+ builder.append_value("inlined");
+
+ for _ in 0..num_variadic_buffers {
+ builder.append_value(long_scalar);
+ }
+
+ let result = builder.finish();
+
+ assert_eq!(result.data_buffers().len(), num_variadic_buffers);
+ assert_eq!(result.len(), num_variadic_buffers + 1);
+
+ result
+}
|
Exporting Binary/Utf8View from arrow-rs to pyarrow fails
**Describe the bug**
Exporting binaryview arrow to pyarrow fails with
`Expected at least 3 buffers for imported type binary_view, ArrowArray struct has 2`
**To Reproduce**
Construct binaryview array and export it over c data interface to pyarrow
**Expected behavior**
Export should succeed without error
**Additional context**
I think there's ambiguity in the spec https://github.com/apache/arrow/issues/43989. However, regardless of that issue it seems that export binaryview array has to do a bit extra work to produce buffer lengths
|
2024-09-06T21:16:12Z
|
53.0
|
f41c258246cd4bd9d89228cded9ed54dbd00faff
|
|
apache/arrow-rs
| 6,332
|
apache__arrow-rs-6332
|
[
"6331"
] |
d4be752ef54ee30198d0aa1abd3838188482e992
|
diff --git a/arrow-flight/src/bin/flight_sql_client.rs b/arrow-flight/src/bin/flight_sql_client.rs
index 296efc1c308e..c334b95a9a96 100644
--- a/arrow-flight/src/bin/flight_sql_client.rs
+++ b/arrow-flight/src/bin/flight_sql_client.rs
@@ -20,7 +20,10 @@ use std::{sync::Arc, time::Duration};
use anyhow::{bail, Context, Result};
use arrow_array::{ArrayRef, Datum, RecordBatch, StringArray};
use arrow_cast::{cast_with_options, pretty::pretty_format_batches, CastOptions};
-use arrow_flight::{sql::client::FlightSqlServiceClient, FlightInfo};
+use arrow_flight::{
+ sql::{client::FlightSqlServiceClient, CommandGetDbSchemas, CommandGetTables},
+ FlightInfo,
+};
use arrow_schema::Schema;
use clap::{Parser, Subcommand};
use futures::TryStreamExt;
@@ -111,6 +114,51 @@ struct Args {
/// Different available commands.
#[derive(Debug, Subcommand)]
enum Command {
+ /// Get catalogs.
+ Catalogs,
+ /// Get db schemas for a catalog.
+ DbSchemas {
+ /// Name of a catalog.
+ ///
+ /// Required.
+ catalog: String,
+ /// Specifies a filter pattern for schemas to search for.
+ /// When no schema_filter is provided, the pattern will not be used to narrow the search.
+ /// In the pattern string, two special characters can be used to denote matching rules:
+ /// - "%" means to match any substring with 0 or more characters.
+ /// - "_" means to match any one character.
+ #[clap(short, long)]
+ db_schema_filter: Option<String>,
+ },
+ /// Get tables for a catalog.
+ Tables {
+ /// Name of a catalog.
+ ///
+ /// Required.
+ catalog: String,
+ /// Specifies a filter pattern for schemas to search for.
+ /// When no schema_filter is provided, the pattern will not be used to narrow the search.
+ /// In the pattern string, two special characters can be used to denote matching rules:
+ /// - "%" means to match any substring with 0 or more characters.
+ /// - "_" means to match any one character.
+ #[clap(short, long)]
+ db_schema_filter: Option<String>,
+ /// Specifies a filter pattern for tables to search for.
+ /// When no table_filter is provided, all tables matching other filters are searched.
+ /// In the pattern string, two special characters can be used to denote matching rules:
+ /// - "%" means to match any substring with 0 or more characters.
+ /// - "_" means to match any one character.
+ #[clap(short, long)]
+ table_filter: Option<String>,
+ /// Specifies a filter of table types which must match.
+ /// The table types depend on vendor/implementation. It is usually used to separate tables from views or system tables.
+ /// TABLE, VIEW, and SYSTEM TABLE are commonly supported.
+ #[clap(long)]
+ table_types: Vec<String>,
+ },
+ /// Get table types.
+ TableTypes,
+
/// Execute given statement.
StatementQuery {
/// SQL query.
@@ -150,6 +198,36 @@ async fn main() -> Result<()> {
.context("setup client")?;
let flight_info = match args.cmd {
+ Command::Catalogs => client.get_catalogs().await.context("get catalogs")?,
+ Command::DbSchemas {
+ catalog,
+ db_schema_filter,
+ } => client
+ .get_db_schemas(CommandGetDbSchemas {
+ catalog: Some(catalog),
+ db_schema_filter_pattern: db_schema_filter,
+ })
+ .await
+ .context("get db schemas")?,
+ Command::Tables {
+ catalog,
+ db_schema_filter,
+ table_filter,
+ table_types,
+ } => client
+ .get_tables(CommandGetTables {
+ catalog: Some(catalog),
+ db_schema_filter_pattern: db_schema_filter,
+ table_name_filter_pattern: table_filter,
+ table_types,
+ // Schema is returned as ipc encoded bytes.
+ // We do not support returning the schema as there is no trivial mechanism
+ // to display the information to the user.
+ include_schema: false,
+ })
+ .await
+ .context("get tables")?,
+ Command::TableTypes => client.get_table_types().await.context("get table types")?,
Command::StatementQuery { query } => client
.execute(query, None)
.await
diff --git a/arrow-flight/src/sql/metadata/mod.rs b/arrow-flight/src/sql/metadata/mod.rs
index 1e9881ffa70e..fd71149a3180 100644
--- a/arrow-flight/src/sql/metadata/mod.rs
+++ b/arrow-flight/src/sql/metadata/mod.rs
@@ -33,6 +33,7 @@
mod catalogs;
mod db_schemas;
mod sql_info;
+mod table_types;
mod tables;
mod xdbc_info;
diff --git a/arrow-flight/src/sql/metadata/table_types.rs b/arrow-flight/src/sql/metadata/table_types.rs
new file mode 100644
index 000000000000..54cfe6fe27a7
--- /dev/null
+++ b/arrow-flight/src/sql/metadata/table_types.rs
@@ -0,0 +1,158 @@
+// 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.
+
+//! [`GetTableTypesBuilder`] for building responses to [`CommandGetTableTypes`] queries.
+//!
+//! [`CommandGetTableTypes`]: crate::sql::CommandGetTableTypes
+
+use std::sync::Arc;
+
+use arrow_array::{builder::StringBuilder, ArrayRef, RecordBatch};
+use arrow_schema::{DataType, Field, Schema, SchemaRef};
+use arrow_select::take::take;
+use once_cell::sync::Lazy;
+
+use crate::error::*;
+use crate::sql::CommandGetTableTypes;
+
+use super::lexsort_to_indices;
+
+/// A builder for a [`CommandGetTableTypes`] response.
+///
+/// Builds rows like this:
+///
+/// * table_type: utf8,
+#[derive(Default)]
+pub struct GetTableTypesBuilder {
+ // array builder for table types
+ table_type: StringBuilder,
+}
+
+impl CommandGetTableTypes {
+ /// Create a builder suitable for constructing a response
+ pub fn into_builder(self) -> GetTableTypesBuilder {
+ self.into()
+ }
+}
+
+impl From<CommandGetTableTypes> for GetTableTypesBuilder {
+ fn from(_value: CommandGetTableTypes) -> Self {
+ Self::new()
+ }
+}
+
+impl GetTableTypesBuilder {
+ /// Create a new instance of [`GetTableTypesBuilder`]
+ pub fn new() -> Self {
+ Self {
+ table_type: StringBuilder::new(),
+ }
+ }
+
+ /// Append a row
+ pub fn append(&mut self, table_type: impl AsRef<str>) {
+ self.table_type.append_value(table_type);
+ }
+
+ /// builds a `RecordBatch` with the correct schema for a `CommandGetTableTypes` response
+ pub fn build(self) -> Result<RecordBatch> {
+ let schema = self.schema();
+ let Self { mut table_type } = self;
+
+ // Make the arrays
+ let table_type = table_type.finish();
+
+ let batch = RecordBatch::try_new(schema, vec![Arc::new(table_type) as ArrayRef])?;
+
+ // Order filtered results by table_type
+ let indices = lexsort_to_indices(batch.columns());
+ let columns = batch
+ .columns()
+ .iter()
+ .map(|c| take(c, &indices, None))
+ .collect::<std::result::Result<Vec<_>, _>>()?;
+
+ Ok(RecordBatch::try_new(batch.schema(), columns)?)
+ }
+
+ /// Return the schema of the RecordBatch that will be returned
+ /// from [`CommandGetTableTypes`]
+ pub fn schema(&self) -> SchemaRef {
+ get_table_types_schema()
+ }
+}
+
+fn get_table_types_schema() -> SchemaRef {
+ Arc::clone(&GET_TABLE_TYPES_SCHEMA)
+}
+
+/// The schema for [`CommandGetTableTypes`].
+static GET_TABLE_TYPES_SCHEMA: Lazy<SchemaRef> = Lazy::new(|| {
+ Arc::new(Schema::new(vec![Field::new(
+ "table_type",
+ DataType::Utf8,
+ false,
+ )]))
+});
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use arrow_array::StringArray;
+
+ fn get_ref_batch() -> RecordBatch {
+ RecordBatch::try_new(
+ get_table_types_schema(),
+ vec![Arc::new(StringArray::from(vec![
+ "a_table_type",
+ "b_table_type",
+ "c_table_type",
+ "d_table_type",
+ ])) as ArrayRef],
+ )
+ .unwrap()
+ }
+
+ #[test]
+ fn test_table_types_are_sorted() {
+ let ref_batch = get_ref_batch();
+
+ let mut builder = GetTableTypesBuilder::new();
+ builder.append("b_table_type");
+ builder.append("a_table_type");
+ builder.append("d_table_type");
+ builder.append("c_table_type");
+ let schema_batch = builder.build().unwrap();
+
+ assert_eq!(schema_batch, ref_batch)
+ }
+
+ #[test]
+ fn test_builder_from_query() {
+ let ref_batch = get_ref_batch();
+ let query = CommandGetTableTypes {};
+
+ let mut builder = query.into_builder();
+ builder.append("a_table_type");
+ builder.append("b_table_type");
+ builder.append("c_table_type");
+ builder.append("d_table_type");
+ let schema_batch = builder.build().unwrap();
+
+ assert_eq!(schema_batch, ref_batch)
+ }
+}
|
diff --git a/arrow-flight/tests/flight_sql_client_cli.rs b/arrow-flight/tests/flight_sql_client_cli.rs
index 168015d07e2d..6e1f6142c8b6 100644
--- a/arrow-flight/tests/flight_sql_client_cli.rs
+++ b/arrow-flight/tests/flight_sql_client_cli.rs
@@ -23,10 +23,12 @@ use crate::common::fixture::TestFixture;
use arrow_array::{ArrayRef, Int64Array, RecordBatch, StringArray};
use arrow_flight::{
decode::FlightRecordBatchStream,
+ encode::FlightDataEncoderBuilder,
flight_service_server::{FlightService, FlightServiceServer},
sql::{
server::{FlightSqlService, PeekableFlightDataStream},
ActionCreatePreparedStatementRequest, ActionCreatePreparedStatementResult, Any,
+ CommandGetCatalogs, CommandGetDbSchemas, CommandGetTableTypes, CommandGetTables,
CommandPreparedStatementQuery, CommandStatementQuery, DoPutPreparedStatementResult,
ProstMessageExt, SqlInfo,
},
@@ -85,6 +87,205 @@ async fn test_simple() {
);
}
+#[tokio::test]
+async fn test_get_catalogs() {
+ let test_server = FlightSqlServiceImpl::default();
+ let fixture = TestFixture::new(test_server.service()).await;
+ let addr = fixture.addr;
+
+ let stdout = tokio::task::spawn_blocking(move || {
+ Command::cargo_bin("flight_sql_client")
+ .unwrap()
+ .env_clear()
+ .env("RUST_BACKTRACE", "1")
+ .env("RUST_LOG", "warn")
+ .arg("--host")
+ .arg(addr.ip().to_string())
+ .arg("--port")
+ .arg(addr.port().to_string())
+ .arg("catalogs")
+ .assert()
+ .success()
+ .get_output()
+ .stdout
+ .clone()
+ })
+ .await
+ .unwrap();
+
+ fixture.shutdown_and_wait().await;
+
+ assert_eq!(
+ std::str::from_utf8(&stdout).unwrap().trim(),
+ "+--------------+\
+ \n| catalog_name |\
+ \n+--------------+\
+ \n| catalog_a |\
+ \n| catalog_b |\
+ \n+--------------+",
+ );
+}
+
+#[tokio::test]
+async fn test_get_db_schemas() {
+ let test_server = FlightSqlServiceImpl::default();
+ let fixture = TestFixture::new(test_server.service()).await;
+ let addr = fixture.addr;
+
+ let stdout = tokio::task::spawn_blocking(move || {
+ Command::cargo_bin("flight_sql_client")
+ .unwrap()
+ .env_clear()
+ .env("RUST_BACKTRACE", "1")
+ .env("RUST_LOG", "warn")
+ .arg("--host")
+ .arg(addr.ip().to_string())
+ .arg("--port")
+ .arg(addr.port().to_string())
+ .arg("db-schemas")
+ .arg("catalog_a")
+ .assert()
+ .success()
+ .get_output()
+ .stdout
+ .clone()
+ })
+ .await
+ .unwrap();
+
+ fixture.shutdown_and_wait().await;
+
+ assert_eq!(
+ std::str::from_utf8(&stdout).unwrap().trim(),
+ "+--------------+----------------+\
+ \n| catalog_name | db_schema_name |\
+ \n+--------------+----------------+\
+ \n| catalog_a | schema_1 |\
+ \n| catalog_a | schema_2 |\
+ \n+--------------+----------------+",
+ );
+}
+
+#[tokio::test]
+async fn test_get_tables() {
+ let test_server = FlightSqlServiceImpl::default();
+ let fixture = TestFixture::new(test_server.service()).await;
+ let addr = fixture.addr;
+
+ let stdout = tokio::task::spawn_blocking(move || {
+ Command::cargo_bin("flight_sql_client")
+ .unwrap()
+ .env_clear()
+ .env("RUST_BACKTRACE", "1")
+ .env("RUST_LOG", "warn")
+ .arg("--host")
+ .arg(addr.ip().to_string())
+ .arg("--port")
+ .arg(addr.port().to_string())
+ .arg("tables")
+ .arg("catalog_a")
+ .assert()
+ .success()
+ .get_output()
+ .stdout
+ .clone()
+ })
+ .await
+ .unwrap();
+
+ fixture.shutdown_and_wait().await;
+
+ assert_eq!(
+ std::str::from_utf8(&stdout).unwrap().trim(),
+ "+--------------+----------------+------------+------------+\
+ \n| catalog_name | db_schema_name | table_name | table_type |\
+ \n+--------------+----------------+------------+------------+\
+ \n| catalog_a | schema_1 | table_1 | TABLE |\
+ \n| catalog_a | schema_2 | table_2 | VIEW |\
+ \n+--------------+----------------+------------+------------+",
+ );
+}
+#[tokio::test]
+async fn test_get_tables_db_filter() {
+ let test_server = FlightSqlServiceImpl::default();
+ let fixture = TestFixture::new(test_server.service()).await;
+ let addr = fixture.addr;
+
+ let stdout = tokio::task::spawn_blocking(move || {
+ Command::cargo_bin("flight_sql_client")
+ .unwrap()
+ .env_clear()
+ .env("RUST_BACKTRACE", "1")
+ .env("RUST_LOG", "warn")
+ .arg("--host")
+ .arg(addr.ip().to_string())
+ .arg("--port")
+ .arg(addr.port().to_string())
+ .arg("tables")
+ .arg("catalog_a")
+ .arg("--db-schema-filter")
+ .arg("schema_2")
+ .assert()
+ .success()
+ .get_output()
+ .stdout
+ .clone()
+ })
+ .await
+ .unwrap();
+
+ fixture.shutdown_and_wait().await;
+
+ assert_eq!(
+ std::str::from_utf8(&stdout).unwrap().trim(),
+ "+--------------+----------------+------------+------------+\
+ \n| catalog_name | db_schema_name | table_name | table_type |\
+ \n+--------------+----------------+------------+------------+\
+ \n| catalog_a | schema_2 | table_2 | VIEW |\
+ \n+--------------+----------------+------------+------------+",
+ );
+}
+
+#[tokio::test]
+async fn test_get_tables_types() {
+ let test_server = FlightSqlServiceImpl::default();
+ let fixture = TestFixture::new(test_server.service()).await;
+ let addr = fixture.addr;
+
+ let stdout = tokio::task::spawn_blocking(move || {
+ Command::cargo_bin("flight_sql_client")
+ .unwrap()
+ .env_clear()
+ .env("RUST_BACKTRACE", "1")
+ .env("RUST_LOG", "warn")
+ .arg("--host")
+ .arg(addr.ip().to_string())
+ .arg("--port")
+ .arg(addr.port().to_string())
+ .arg("table-types")
+ .assert()
+ .success()
+ .get_output()
+ .stdout
+ .clone()
+ })
+ .await
+ .unwrap();
+
+ fixture.shutdown_and_wait().await;
+
+ assert_eq!(
+ std::str::from_utf8(&stdout).unwrap().trim(),
+ "+--------------+\
+ \n| table_type |\
+ \n+--------------+\
+ \n| SYSTEM_TABLE |\
+ \n| TABLE |\
+ \n| VIEW |\
+ \n+--------------+",
+ );
+}
+
const PREPARED_QUERY: &str = "SELECT * FROM table WHERE field = $1";
const PREPARED_STATEMENT_HANDLE: &str = "prepared_statement_handle";
const UPDATED_PREPARED_STATEMENT_HANDLE: &str = "updated_prepared_statement_handle";
@@ -278,6 +479,84 @@ impl FlightSqlService for FlightSqlServiceImpl {
Ok(resp)
}
+ async fn get_flight_info_catalogs(
+ &self,
+ query: CommandGetCatalogs,
+ request: Request<FlightDescriptor>,
+ ) -> Result<Response<FlightInfo>, Status> {
+ let flight_descriptor = request.into_inner();
+ let ticket = Ticket {
+ ticket: query.as_any().encode_to_vec().into(),
+ };
+ let endpoint = FlightEndpoint::new().with_ticket(ticket);
+
+ let flight_info = FlightInfo::new()
+ .try_with_schema(&query.into_builder().schema())
+ .unwrap()
+ .with_endpoint(endpoint)
+ .with_descriptor(flight_descriptor);
+
+ Ok(Response::new(flight_info))
+ }
+ async fn get_flight_info_schemas(
+ &self,
+ query: CommandGetDbSchemas,
+ request: Request<FlightDescriptor>,
+ ) -> Result<Response<FlightInfo>, Status> {
+ let flight_descriptor = request.into_inner();
+ let ticket = Ticket {
+ ticket: query.as_any().encode_to_vec().into(),
+ };
+ let endpoint = FlightEndpoint::new().with_ticket(ticket);
+
+ let flight_info = FlightInfo::new()
+ .try_with_schema(&query.into_builder().schema())
+ .unwrap()
+ .with_endpoint(endpoint)
+ .with_descriptor(flight_descriptor);
+
+ Ok(Response::new(flight_info))
+ }
+
+ async fn get_flight_info_tables(
+ &self,
+ query: CommandGetTables,
+ request: Request<FlightDescriptor>,
+ ) -> Result<Response<FlightInfo>, Status> {
+ let flight_descriptor = request.into_inner();
+ let ticket = Ticket {
+ ticket: query.as_any().encode_to_vec().into(),
+ };
+ let endpoint = FlightEndpoint::new().with_ticket(ticket);
+
+ let flight_info = FlightInfo::new()
+ .try_with_schema(&query.into_builder().schema())
+ .unwrap()
+ .with_endpoint(endpoint)
+ .with_descriptor(flight_descriptor);
+
+ Ok(Response::new(flight_info))
+ }
+
+ async fn get_flight_info_table_types(
+ &self,
+ query: CommandGetTableTypes,
+ request: Request<FlightDescriptor>,
+ ) -> Result<Response<FlightInfo>, Status> {
+ let flight_descriptor = request.into_inner();
+ let ticket = Ticket {
+ ticket: query.as_any().encode_to_vec().into(),
+ };
+ let endpoint = FlightEndpoint::new().with_ticket(ticket);
+
+ let flight_info = FlightInfo::new()
+ .try_with_schema(&query.into_builder().schema())
+ .unwrap()
+ .with_endpoint(endpoint)
+ .with_descriptor(flight_descriptor);
+
+ Ok(Response::new(flight_info))
+ }
async fn get_flight_info_statement(
&self,
query: CommandStatementQuery,
@@ -309,6 +588,109 @@ impl FlightSqlService for FlightSqlServiceImpl {
Ok(resp)
}
+ async fn do_get_catalogs(
+ &self,
+ query: CommandGetCatalogs,
+ _request: Request<Ticket>,
+ ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
+ let mut builder = query.into_builder();
+ for catalog_name in ["catalog_a", "catalog_b"] {
+ builder.append(catalog_name);
+ }
+ let schema = builder.schema();
+ let batch = builder.build();
+ let stream = FlightDataEncoderBuilder::new()
+ .with_schema(schema)
+ .build(futures::stream::once(async { batch }))
+ .map_err(Status::from);
+ Ok(Response::new(Box::pin(stream)))
+ }
+
+ async fn do_get_schemas(
+ &self,
+ query: CommandGetDbSchemas,
+ _request: Request<Ticket>,
+ ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
+ let mut builder = query.into_builder();
+ for (catalog_name, schema_name) in [
+ ("catalog_a", "schema_1"),
+ ("catalog_a", "schema_2"),
+ ("catalog_b", "schema_3"),
+ ] {
+ builder.append(catalog_name, schema_name);
+ }
+
+ let schema = builder.schema();
+ let batch = builder.build();
+ let stream = FlightDataEncoderBuilder::new()
+ .with_schema(schema)
+ .build(futures::stream::once(async { batch }))
+ .map_err(Status::from);
+ Ok(Response::new(Box::pin(stream)))
+ }
+
+ async fn do_get_tables(
+ &self,
+ query: CommandGetTables,
+ _request: Request<Ticket>,
+ ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
+ let mut builder = query.into_builder();
+ for (catalog_name, schema_name, table_name, table_type, schema) in [
+ (
+ "catalog_a",
+ "schema_1",
+ "table_1",
+ "TABLE",
+ Arc::new(Schema::empty()),
+ ),
+ (
+ "catalog_a",
+ "schema_2",
+ "table_2",
+ "VIEW",
+ Arc::new(Schema::empty()),
+ ),
+ (
+ "catalog_b",
+ "schema_3",
+ "table_3",
+ "TABLE",
+ Arc::new(Schema::empty()),
+ ),
+ ] {
+ builder
+ .append(catalog_name, schema_name, table_name, table_type, &schema)
+ .unwrap();
+ }
+
+ let schema = builder.schema();
+ let batch = builder.build();
+ let stream = FlightDataEncoderBuilder::new()
+ .with_schema(schema)
+ .build(futures::stream::once(async { batch }))
+ .map_err(Status::from);
+ Ok(Response::new(Box::pin(stream)))
+ }
+
+ async fn do_get_table_types(
+ &self,
+ query: CommandGetTableTypes,
+ _request: Request<Ticket>,
+ ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
+ let mut builder = query.into_builder();
+ for table_type in ["TABLE", "VIEW", "SYSTEM_TABLE"] {
+ builder.append(table_type);
+ }
+
+ let schema = builder.schema();
+ let batch = builder.build();
+ let stream = FlightDataEncoderBuilder::new()
+ .with_schema(schema)
+ .build(futures::stream::once(async { batch }))
+ .map_err(Status::from);
+ Ok(Response::new(Box::pin(stream)))
+ }
+
async fn do_put_prepared_statement_query(
&self,
_query: CommandPreparedStatementQuery,
|
Add Catalog DB Schema subcommands to `flight_sql_client`
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
When using the `flight_sql_client` it can be helpful to interrogate the Flight SQL server for information about available catalogs, db schemas and tables.
**Describe the solution you'd like**
Adding subcommands to the CLI that mirror the various FlightSQL commands about catalogs, schemas and tables.
**Describe alternatives you've considered**
We could support `SHOW ...` variant queries and map them to the FlightSQL commands, however this is likely not as portable as a direct mapping of CLI subcommand to FlightSQL command.
**Additional context**
I have PR in progress.
|
2024-08-29T19:02:56Z
|
53.0
|
f41c258246cd4bd9d89228cded9ed54dbd00faff
|
|
apache/arrow-rs
| 6,328
|
apache__arrow-rs-6328
|
[
"6179"
] |
678517018ddfd21b202a94df13b06dfa1ab8a378
|
diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml
index a1644ee49b8d..1b65c5057de1 100644
--- a/.github/workflows/rust.yml
+++ b/.github/workflows/rust.yml
@@ -100,6 +100,13 @@ jobs:
run: rustup component add rustfmt
- name: Format arrow
run: cargo fmt --all -- --check
+ - name: Format parquet
+ # Many modules in parquet are skipped, so check parquet separately. If this check fails, run:
+ # cargo fmt -p parquet -- --config skip_children=true `find ./parquet -name "*.rs" \! -name format.rs`
+ # from the top level arrow-rs directory and check in the result.
+ # https://github.com/apache/arrow-rs/issues/6179
+ working-directory: parquet
+ run: cargo fmt -p parquet -- --check --config skip_children=true `find . -name "*.rs" \! -name format.rs`
- name: Format object_store
working-directory: object_store
run: cargo fmt --all -- --check
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index a53604d0f6ae..e0adc18a9a60 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -160,6 +160,13 @@ PR be sure to run the following and check for lint issues:
cargo +stable fmt --all -- --check
```
+Note that currently the above will not check all source files in the parquet crate. To check all
+parquet files run the following from the top-level `arrow-rs` directory:
+
+```bash
+cargo fmt -p parquet -- --check --config skip_children=true `find . -name "*.rs" \! -name format.rs`
+```
+
## Breaking Changes
Our [release schedule] allows breaking API changes only in major releases.
diff --git a/parquet/src/arrow/array_reader/empty_array.rs b/parquet/src/arrow/array_reader/empty_array.rs
index 51673f2f8cf2..9aba08b4e853 100644
--- a/parquet/src/arrow/array_reader/empty_array.rs
+++ b/parquet/src/arrow/array_reader/empty_array.rs
@@ -17,9 +17,9 @@
use crate::arrow::array_reader::ArrayReader;
use crate::errors::Result;
-use arrow_schema::{DataType as ArrowType, Fields};
use arrow_array::{ArrayRef, StructArray};
use arrow_data::ArrayDataBuilder;
+use arrow_schema::{DataType as ArrowType, Fields};
use std::any::Any;
use std::sync::Arc;
diff --git a/parquet/src/arrow/array_reader/fixed_size_list_array.rs b/parquet/src/arrow/array_reader/fixed_size_list_array.rs
index 4cf68a06601c..75099d018fc9 100644
--- a/parquet/src/arrow/array_reader/fixed_size_list_array.rs
+++ b/parquet/src/arrow/array_reader/fixed_size_list_array.rs
@@ -138,7 +138,7 @@ impl ArrayReader for FixedSizeListArrayReader {
"Encountered misaligned row with length {} (expected length {})",
row_len,
self.fixed_size
- ))
+ ));
}
row_len = 0;
@@ -226,9 +226,7 @@ mod tests {
use super::*;
use crate::arrow::{
array_reader::{test_util::InMemoryArrayReader, ListArrayReader},
- arrow_reader::{
- ArrowReaderBuilder, ArrowReaderOptions, ParquetRecordBatchReader,
- },
+ arrow_reader::{ArrowReaderBuilder, ArrowReaderOptions, ParquetRecordBatchReader},
ArrowWriter,
};
use arrow::datatypes::{Field, Int32Type};
@@ -279,10 +277,7 @@ mod tests {
let mut list_array_reader = FixedSizeListArrayReader::new(
Box::new(item_array_reader),
3,
- ArrowType::FixedSizeList(
- Arc::new(Field::new("item", ArrowType::Int32, true)),
- 3,
- ),
+ ArrowType::FixedSizeList(Arc::new(Field::new("item", ArrowType::Int32, true)), 3),
2,
1,
true,
@@ -328,10 +323,7 @@ mod tests {
let mut list_array_reader = FixedSizeListArrayReader::new(
Box::new(item_array_reader),
2,
- ArrowType::FixedSizeList(
- Arc::new(Field::new("item", ArrowType::Int32, true)),
- 2,
- ),
+ ArrowType::FixedSizeList(Arc::new(Field::new("item", ArrowType::Int32, true)), 2),
1,
1,
false,
@@ -354,14 +346,10 @@ mod tests {
// [[4, 5]],
// [[null, null]],
// ]
- let l2_type = ArrowType::FixedSizeList(
- Arc::new(Field::new("item", ArrowType::Int32, true)),
- 2,
- );
- let l1_type = ArrowType::FixedSizeList(
- Arc::new(Field::new("item", l2_type.clone(), false)),
- 1,
- );
+ let l2_type =
+ ArrowType::FixedSizeList(Arc::new(Field::new("item", ArrowType::Int32, true)), 2);
+ let l1_type =
+ ArrowType::FixedSizeList(Arc::new(Field::new("item", l2_type.clone(), false)), 1);
let array = PrimitiveArray::<Int32Type>::from(vec![
None,
@@ -413,14 +401,8 @@ mod tests {
Some(vec![0, 0, 2, 0, 2, 0, 0, 2, 0, 2]),
);
- let l2 = FixedSizeListArrayReader::new(
- Box::new(item_array_reader),
- 2,
- l2_type,
- 4,
- 2,
- false,
- );
+ let l2 =
+ FixedSizeListArrayReader::new(Box::new(item_array_reader), 2, l2_type, 4, 2, false);
let mut l1 = FixedSizeListArrayReader::new(Box::new(l2), 1, l1_type, 3, 1, true);
let expected_1 = expected.slice(0, 2);
@@ -454,10 +436,7 @@ mod tests {
let mut list_array_reader = FixedSizeListArrayReader::new(
Box::new(item_array_reader),
0,
- ArrowType::FixedSizeList(
- Arc::new(Field::new("item", ArrowType::Int32, true)),
- 0,
- ),
+ ArrowType::FixedSizeList(Arc::new(Field::new("item", ArrowType::Int32, true)), 0),
2,
1,
true,
@@ -473,8 +452,7 @@ mod tests {
#[test]
fn test_nested_var_list() {
// [[[1, null, 3], null], [[4], []], [[5, 6], [null, null]], null]
- let mut builder =
- FixedSizeListBuilder::new(ListBuilder::new(Int32Builder::new()), 2);
+ let mut builder = FixedSizeListBuilder::new(ListBuilder::new(Int32Builder::new()), 2);
builder.values().append_value([Some(1), None, Some(3)]);
builder.values().append_null();
builder.append(true);
@@ -503,12 +481,9 @@ mod tests {
None,
]));
- let inner_type =
- ArrowType::List(Arc::new(Field::new("item", ArrowType::Int32, true)));
- let list_type = ArrowType::FixedSizeList(
- Arc::new(Field::new("item", inner_type.clone(), true)),
- 2,
- );
+ let inner_type = ArrowType::List(Arc::new(Field::new("item", ArrowType::Int32, true)));
+ let list_type =
+ ArrowType::FixedSizeList(Arc::new(Field::new("item", inner_type.clone(), true)), 2);
let item_array_reader = InMemoryArrayReader::new(
ArrowType::Int32,
@@ -517,22 +492,11 @@ mod tests {
Some(vec![0, 2, 2, 1, 0, 1, 0, 2, 1, 2, 0]),
);
- let inner_array_reader = ListArrayReader::<i32>::new(
- Box::new(item_array_reader),
- inner_type,
- 4,
- 2,
- true,
- );
+ let inner_array_reader =
+ ListArrayReader::<i32>::new(Box::new(item_array_reader), inner_type, 4, 2, true);
- let mut list_array_reader = FixedSizeListArrayReader::new(
- Box::new(inner_array_reader),
- 2,
- list_type,
- 2,
- 1,
- true,
- );
+ let mut list_array_reader =
+ FixedSizeListArrayReader::new(Box::new(inner_array_reader), 2, list_type, 2, 1, true);
let actual = list_array_reader.next_batch(1024).unwrap();
let actual = actual
.as_any()
@@ -564,21 +528,13 @@ mod tests {
);
// [null, 2, 3, null, 5]
- let primitive = PrimitiveArray::<Int32Type>::from_iter(vec![
- None,
- Some(2),
- Some(3),
- None,
- Some(5),
- ]);
+ let primitive =
+ PrimitiveArray::<Int32Type>::from_iter(vec![None, Some(2), Some(3), None, Some(5)]);
let schema = Arc::new(Schema::new(vec![
Field::new(
"list",
- ArrowType::FixedSizeList(
- Arc::new(Field::new("item", ArrowType::Int32, true)),
- 4,
- ),
+ ArrowType::FixedSizeList(Arc::new(Field::new("item", ArrowType::Int32, true)), 4),
true,
),
Field::new("primitive", ArrowType::Int32, true),
@@ -643,10 +599,7 @@ mod tests {
let schema = Arc::new(Schema::new(vec![Field::new(
"list",
- ArrowType::FixedSizeList(
- Arc::new(Field::new("item", ArrowType::Int32, true)),
- 4,
- ),
+ ArrowType::FixedSizeList(Arc::new(Field::new("item", ArrowType::Int32, true)), 4),
true,
)]));
diff --git a/parquet/src/arrow/array_reader/list_array.rs b/parquet/src/arrow/array_reader/list_array.rs
index e1752f30cea8..ebff3286bed5 100644
--- a/parquet/src/arrow/array_reader/list_array.rs
+++ b/parquet/src/arrow/array_reader/list_array.rs
@@ -125,8 +125,7 @@ impl<OffsetSize: OffsetSizeTrait> ArrayReader for ListArrayReader<OffsetSize> {
// lists, and for consistency we do the same for nulls.
// The output offsets for the computed ListArray
- let mut list_offsets: Vec<OffsetSize> =
- Vec::with_capacity(next_batch_array.len() + 1);
+ let mut list_offsets: Vec<OffsetSize> = Vec::with_capacity(next_batch_array.len() + 1);
// The validity mask of the computed ListArray if nullable
let mut validity = self
@@ -270,9 +269,7 @@ mod tests {
GenericListArray::<OffsetSize>::DATA_TYPE_CONSTRUCTOR(field)
}
- fn downcast<OffsetSize: OffsetSizeTrait>(
- array: &ArrayRef,
- ) -> &'_ GenericListArray<OffsetSize> {
+ fn downcast<OffsetSize: OffsetSizeTrait>(array: &ArrayRef) -> &'_ GenericListArray<OffsetSize> {
array
.as_any()
.downcast_ref::<GenericListArray<OffsetSize>>()
@@ -383,18 +380,12 @@ mod tests {
Some(vec![0, 3, 2, 2, 2, 1, 1, 1, 1, 3, 3, 2, 3, 3, 2, 0, 0, 0]),
);
- let l3 = ListArrayReader::<OffsetSize>::new(
- Box::new(item_array_reader),
- l3_type,
- 5,
- 3,
- true,
- );
+ let l3 =
+ ListArrayReader::<OffsetSize>::new(Box::new(item_array_reader), l3_type, 5, 3, true);
let l2 = ListArrayReader::<OffsetSize>::new(Box::new(l3), l2_type, 3, 2, false);
- let mut l1 =
- ListArrayReader::<OffsetSize>::new(Box::new(l2), l1_type, 2, 1, true);
+ let mut l1 = ListArrayReader::<OffsetSize>::new(Box::new(l2), l1_type, 2, 1, true);
let expected_1 = expected.slice(0, 2);
let expected_2 = expected.slice(2, 2);
@@ -560,8 +551,7 @@ mod tests {
.unwrap();
writer.close().unwrap();
- let file_reader: Arc<dyn FileReader> =
- Arc::new(SerializedFileReader::new(file).unwrap());
+ let file_reader: Arc<dyn FileReader> = Arc::new(SerializedFileReader::new(file).unwrap());
let file_metadata = file_reader.metadata().file_metadata();
let schema = file_metadata.schema_descr();
@@ -573,8 +563,7 @@ mod tests {
)
.unwrap();
- let mut array_reader =
- build_array_reader(fields.as_ref(), &mask, &file_reader).unwrap();
+ let mut array_reader = build_array_reader(fields.as_ref(), &mask, &file_reader).unwrap();
let batch = array_reader.next_batch(100).unwrap();
assert_eq!(batch.data_type(), array_reader.get_data_type());
@@ -584,9 +573,7 @@ mod tests {
"table_info",
ArrowType::List(Arc::new(Field::new(
"table_info",
- ArrowType::Struct(
- vec![Field::new("name", ArrowType::Binary, false)].into()
- ),
+ ArrowType::Struct(vec![Field::new("name", ArrowType::Binary, false)].into()),
false
))),
false
diff --git a/parquet/src/arrow/array_reader/map_array.rs b/parquet/src/arrow/array_reader/map_array.rs
index 9bfc047322a7..4bdec602ba4f 100644
--- a/parquet/src/arrow/array_reader/map_array.rs
+++ b/parquet/src/arrow/array_reader/map_array.rs
@@ -184,21 +184,19 @@ mod tests {
map_builder.append(true).expect("adding map entry");
// Create record batch
- let batch =
- RecordBatch::try_new(Arc::new(schema), vec![Arc::new(map_builder.finish())])
- .expect("create record batch");
+ let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(map_builder.finish())])
+ .expect("create record batch");
// Write record batch to file
let mut buffer = Vec::with_capacity(1024);
- let mut writer = ArrowWriter::try_new(&mut buffer, batch.schema(), None)
- .expect("creat file writer");
+ let mut writer =
+ ArrowWriter::try_new(&mut buffer, batch.schema(), None).expect("creat file writer");
writer.write(&batch).expect("writing file");
writer.close().expect("close writer");
// Read file
let reader = Bytes::from(buffer);
- let record_batch_reader =
- ParquetRecordBatchReader::try_new(reader, 1024).unwrap();
+ let record_batch_reader = ParquetRecordBatchReader::try_new(reader, 1024).unwrap();
for maybe_record_batch in record_batch_reader {
let record_batch = maybe_record_batch.expect("Getting current batch");
let col = record_batch.column(0);
diff --git a/parquet/src/arrow/array_reader/struct_array.rs b/parquet/src/arrow/array_reader/struct_array.rs
index 4af194774bfb..fb2f2f8928b9 100644
--- a/parquet/src/arrow/array_reader/struct_array.rs
+++ b/parquet/src/arrow/array_reader/struct_array.rs
@@ -112,10 +112,10 @@ impl ArrayReader for StructArrayReader {
.collect::<Result<Vec<_>>>()?;
// check that array child data has same size
- let children_array_len =
- children_array.first().map(|arr| arr.len()).ok_or_else(|| {
- general_err!("Struct array reader should have at least one child!")
- })?;
+ let children_array_len = children_array
+ .first()
+ .map(|arr| arr.len())
+ .ok_or_else(|| general_err!("Struct array reader should have at least one child!"))?;
let all_children_len_eq = children_array
.iter()
@@ -169,8 +169,7 @@ impl ArrayReader for StructArrayReader {
return Err(general_err!("Failed to decode level data for struct array"));
}
- array_data_builder =
- array_data_builder.null_bit_buffer(Some(bitmap_builder.into()));
+ array_data_builder = array_data_builder.null_bit_buffer(Some(bitmap_builder.into()));
}
let array_data = unsafe { array_data_builder.build_unchecked() };
@@ -282,13 +281,12 @@ mod tests {
// null,
// ]
- let expected_l =
- Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
- Some(vec![Some(1), Some(2), None]),
- Some(vec![]),
- None,
- None,
- ]));
+ let expected_l = Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
+ Some(vec![Some(1), Some(2), None]),
+ Some(vec![]),
+ None,
+ None,
+ ]));
let validity = Buffer::from([0b00000111]);
let struct_fields = vec![(
diff --git a/parquet/src/arrow/schema/complex.rs b/parquet/src/arrow/schema/complex.rs
index a5f6d242ef91..e487feabb848 100644
--- a/parquet/src/arrow/schema/complex.rs
+++ b/parquet/src/arrow/schema/complex.rs
@@ -41,7 +41,7 @@ pub struct ParquetField {
/// i.e. guaranteed to be > 0 for an element of list type
pub rep_level: i16,
/// The level at which this field is fully defined,
- /// i.e. guaranteed to be > 0 for a nullable type or child of a
+ /// i.e. guaranteed to be > 0 for a nullable type or child of a
/// nullable type
pub def_level: i16,
/// Whether this field is nullable
@@ -64,11 +64,7 @@ impl ParquetField {
rep_level: self.rep_level,
def_level: self.def_level,
nullable: false,
- arrow_type: DataType::List(Arc::new(Field::new(
- name,
- self.arrow_type.clone(),
- false,
- ))),
+ arrow_type: DataType::List(Arc::new(Field::new(name, self.arrow_type.clone(), false))),
field_type: ParquetFieldType::Group {
children: vec![self],
},
@@ -289,7 +285,7 @@ impl Visitor {
match map_key.get_basic_info().repetition() {
Repetition::REPEATED => {
- return Err(arrow_err!("Map keys cannot be repeated"));
+ return Err(arrow_err!("Map keys cannot be repeated"));
}
Repetition::REQUIRED | Repetition::OPTIONAL => {
// Relaxed check for having repetition REQUIRED as there exists
@@ -317,10 +313,7 @@ impl Visitor {
(Some(field), Some(&*fields[0]), Some(&*fields[1]), *sorted)
}
d => {
- return Err(arrow_err!(
- "Map data type should contain struct got {}",
- d
- ));
+ return Err(arrow_err!("Map data type should contain struct got {}", d));
}
},
Some(d) => {
@@ -416,9 +409,7 @@ impl Visitor {
let (def_level, nullable) = match list_type.get_basic_info().repetition() {
Repetition::REQUIRED => (context.def_level, false),
Repetition::OPTIONAL => (context.def_level + 1, true),
- Repetition::REPEATED => {
- return Err(arrow_err!("List type cannot be repeated"))
- }
+ Repetition::REPEATED => return Err(arrow_err!("List type cannot be repeated")),
};
let arrow_field = match &context.data_type {
@@ -542,11 +533,7 @@ impl Visitor {
///
/// The resulting [`Field`] will have the type dictated by `field`, a name
/// dictated by the `parquet_type`, and any metadata from `arrow_hint`
-fn convert_field(
- parquet_type: &Type,
- field: &ParquetField,
- arrow_hint: Option<&Field>,
-) -> Field {
+fn convert_field(parquet_type: &Type, field: &ParquetField, arrow_hint: Option<&Field>) -> Field {
let name = parquet_type.name();
let data_type = field.arrow_type.clone();
let nullable = field.nullable;
@@ -568,11 +555,14 @@ fn convert_field(
let basic_info = parquet_type.get_basic_info();
if basic_info.has_id() {
let mut meta = HashMap::with_capacity(1);
- meta.insert(PARQUET_FIELD_ID_META_KEY.to_string(), basic_info.id().to_string());
+ meta.insert(
+ PARQUET_FIELD_ID_META_KEY.to_string(),
+ basic_info.id().to_string(),
+ );
ret.set_metadata(meta);
}
ret
- },
+ }
}
}
diff --git a/parquet/src/arrow/schema/mod.rs b/parquet/src/arrow/schema/mod.rs
index a3528b6c8adb..fab8966952b2 100644
--- a/parquet/src/arrow/schema/mod.rs
+++ b/parquet/src/arrow/schema/mod.rs
@@ -1483,11 +1483,25 @@ mod tests {
),
Field::new("date", DataType::Date32, true),
Field::new("time_milli", DataType::Time32(TimeUnit::Millisecond), true),
- Field::new("time_milli_utc", DataType::Time32(TimeUnit::Millisecond), true)
- .with_metadata(HashMap::from_iter(vec![("adjusted_to_utc".to_string(), "".to_string())])),
+ Field::new(
+ "time_milli_utc",
+ DataType::Time32(TimeUnit::Millisecond),
+ true,
+ )
+ .with_metadata(HashMap::from_iter(vec![(
+ "adjusted_to_utc".to_string(),
+ "".to_string(),
+ )])),
Field::new("time_micro", DataType::Time64(TimeUnit::Microsecond), true),
- Field::new("time_micro_utc", DataType::Time64(TimeUnit::Microsecond), true)
- .with_metadata(HashMap::from_iter(vec![("adjusted_to_utc".to_string(), "".to_string())])),
+ Field::new(
+ "time_micro_utc",
+ DataType::Time64(TimeUnit::Microsecond),
+ true,
+ )
+ .with_metadata(HashMap::from_iter(vec![(
+ "adjusted_to_utc".to_string(),
+ "".to_string(),
+ )])),
Field::new(
"ts_milli",
DataType::Timestamp(TimeUnit::Millisecond, None),
diff --git a/parquet/src/compression.rs b/parquet/src/compression.rs
index 10560210e4e8..edf675f1302a 100644
--- a/parquet/src/compression.rs
+++ b/parquet/src/compression.rs
@@ -150,35 +150,47 @@ pub fn create_codec(codec: CodecType, _options: &CodecOptions) -> Result<Option<
CodecType::BROTLI(level) => {
#[cfg(any(feature = "brotli", test))]
return Ok(Some(Box::new(BrotliCodec::new(level))));
- Err(ParquetError::General("Disabled feature at compile time: brotli".into()))
- },
+ Err(ParquetError::General(
+ "Disabled feature at compile time: brotli".into(),
+ ))
+ }
CodecType::GZIP(level) => {
#[cfg(any(feature = "flate2", test))]
return Ok(Some(Box::new(GZipCodec::new(level))));
- Err(ParquetError::General("Disabled feature at compile time: flate2".into()))
- },
+ Err(ParquetError::General(
+ "Disabled feature at compile time: flate2".into(),
+ ))
+ }
CodecType::SNAPPY => {
#[cfg(any(feature = "snap", test))]
return Ok(Some(Box::new(SnappyCodec::new())));
- Err(ParquetError::General("Disabled feature at compile time: snap".into()))
- },
+ Err(ParquetError::General(
+ "Disabled feature at compile time: snap".into(),
+ ))
+ }
CodecType::LZ4 => {
#[cfg(any(feature = "lz4", test))]
return Ok(Some(Box::new(LZ4HadoopCodec::new(
_options.backward_compatible_lz4,
))));
- Err(ParquetError::General("Disabled feature at compile time: lz4".into()))
- },
+ Err(ParquetError::General(
+ "Disabled feature at compile time: lz4".into(),
+ ))
+ }
CodecType::ZSTD(level) => {
#[cfg(any(feature = "zstd", test))]
return Ok(Some(Box::new(ZSTDCodec::new(level))));
- Err(ParquetError::General("Disabled feature at compile time: zstd".into()))
- },
+ Err(ParquetError::General(
+ "Disabled feature at compile time: zstd".into(),
+ ))
+ }
CodecType::LZ4_RAW => {
#[cfg(any(feature = "lz4", test))]
return Ok(Some(Box::new(LZ4RawCodec::new())));
- Err(ParquetError::General("Disabled feature at compile time: lz4".into()))
- },
+ Err(ParquetError::General(
+ "Disabled feature at compile time: lz4".into(),
+ ))
+ }
CodecType::UNCOMPRESSED => Ok(None),
_ => Err(nyi_err!("The codec type {} is not supported yet", codec)),
}
diff --git a/parquet/src/encodings/encoding/dict_encoder.rs b/parquet/src/encodings/encoding/dict_encoder.rs
index 98283b574ebb..8efb845219d3 100644
--- a/parquet/src/encodings/encoding/dict_encoder.rs
+++ b/parquet/src/encodings/encoding/dict_encoder.rs
@@ -148,7 +148,6 @@ impl<T: DataType> DictEncoder<T> {
fn bit_width(&self) -> u8 {
num_required_bits(self.num_entries().saturating_sub(1) as u64)
}
-
}
impl<T: DataType> Encoder<T> for DictEncoder<T> {
diff --git a/parquet/src/encodings/levels.rs b/parquet/src/encodings/levels.rs
index 8d4e48ba16bd..6f662b614fca 100644
--- a/parquet/src/encodings/levels.rs
+++ b/parquet/src/encodings/levels.rs
@@ -27,11 +27,7 @@ use crate::util::bit_util::{ceil, num_required_bits, BitWriter};
/// repetition/definition level and number of total buffered values (includes null
/// values).
#[inline]
-pub fn max_buffer_size(
- encoding: Encoding,
- max_level: i16,
- num_buffered_values: usize,
-) -> usize {
+pub fn max_buffer_size(encoding: Encoding, max_level: i16, num_buffered_values: usize) -> usize {
let bit_width = num_required_bits(max_level as u64);
match encoding {
Encoding::RLE => RleEncoder::max_buffer_size(bit_width, num_buffered_values),
diff --git a/parquet/src/encodings/rle.rs b/parquet/src/encodings/rle.rs
index 97a122941f17..e1ca8cd745e3 100644
--- a/parquet/src/encodings/rle.rs
+++ b/parquet/src/encodings/rle.rs
@@ -199,13 +199,9 @@ impl RleEncoder {
/// internal writer.
#[inline]
pub fn flush(&mut self) {
- if self.bit_packed_count > 0
- || self.repeat_count > 0
- || self.num_buffered_values > 0
- {
+ if self.bit_packed_count > 0 || self.repeat_count > 0 || self.num_buffered_values > 0 {
let all_repeat = self.bit_packed_count == 0
- && (self.repeat_count == self.num_buffered_values
- || self.num_buffered_values == 0);
+ && (self.repeat_count == self.num_buffered_values || self.num_buffered_values == 0);
if self.repeat_count > 0 && all_repeat {
self.flush_rle_run();
} else {
@@ -250,11 +246,8 @@ impl RleEncoder {
// Write the indicator byte to the reserved position in `bit_writer`
let num_groups = self.bit_packed_count / 8;
let indicator_byte = ((num_groups << 1) | 1) as u8;
- self.bit_writer.put_aligned_offset(
- indicator_byte,
- 1,
- self.indicator_byte_pos as usize,
- );
+ self.bit_writer
+ .put_aligned_offset(indicator_byte, 1, self.indicator_byte_pos as usize);
self.indicator_byte_pos = -1;
self.bit_packed_count = 0;
}
@@ -288,9 +281,7 @@ impl RleEncoder {
/// return the estimated memory size of this encoder.
pub(crate) fn estimated_memory_size(&self) -> usize {
- self.bit_writer.estimated_memory_size()
- + std::mem::size_of::<Self>()
-
+ self.bit_writer.estimated_memory_size() + std::mem::size_of::<Self>()
}
}
@@ -384,12 +375,10 @@ impl RleDecoder {
let mut values_read = 0;
while values_read < buffer.len() {
if self.rle_left > 0 {
- let num_values =
- cmp::min(buffer.len() - values_read, self.rle_left as usize);
+ let num_values = cmp::min(buffer.len() - values_read, self.rle_left as usize);
for i in 0..num_values {
- let repeated_value = T::try_from_le_slice(
- &self.current_value.as_mut().unwrap().to_ne_bytes(),
- )?;
+ let repeated_value =
+ T::try_from_le_slice(&self.current_value.as_mut().unwrap().to_ne_bytes())?;
buffer[values_read + i] = repeated_value;
}
self.rle_left -= num_values as u32;
@@ -397,8 +386,7 @@ impl RleDecoder {
} else if self.bit_packed_left > 0 {
let mut num_values =
cmp::min(buffer.len() - values_read, self.bit_packed_left as usize);
- let bit_reader =
- self.bit_reader.as_mut().expect("bit_reader should be set");
+ let bit_reader = self.bit_reader.as_mut().expect("bit_reader should be set");
num_values = bit_reader.get_batch::<T>(
&mut buffer[values_read..values_read + num_values],
@@ -424,15 +412,13 @@ impl RleDecoder {
let mut values_skipped = 0;
while values_skipped < num_values {
if self.rle_left > 0 {
- let num_values =
- cmp::min(num_values - values_skipped, self.rle_left as usize);
+ let num_values = cmp::min(num_values - values_skipped, self.rle_left as usize);
self.rle_left -= num_values as u32;
values_skipped += num_values;
} else if self.bit_packed_left > 0 {
let mut num_values =
cmp::min(num_values - values_skipped, self.bit_packed_left as usize);
- let bit_reader =
- self.bit_reader.as_mut().expect("bit_reader should be set");
+ let bit_reader = self.bit_reader.as_mut().expect("bit_reader should be set");
num_values = bit_reader.skip(num_values, self.bit_width as usize);
if num_values == 0 {
@@ -467,8 +453,7 @@ impl RleDecoder {
let index_buf = self.index_buf.get_or_insert_with(|| Box::new([0; 1024]));
if self.rle_left > 0 {
- let num_values =
- cmp::min(max_values - values_read, self.rle_left as usize);
+ let num_values = cmp::min(max_values - values_read, self.rle_left as usize);
let dict_idx = self.current_value.unwrap() as usize;
for i in 0..num_values {
buffer[values_read + i].clone_from(&dict[dict_idx]);
@@ -476,8 +461,7 @@ impl RleDecoder {
self.rle_left -= num_values as u32;
values_read += num_values;
} else if self.bit_packed_left > 0 {
- let bit_reader =
- self.bit_reader.as_mut().expect("bit_reader should be set");
+ let bit_reader = self.bit_reader.as_mut().expect("bit_reader should be set");
loop {
let to_read = index_buf
@@ -489,10 +473,8 @@ impl RleDecoder {
break;
}
- let num_values = bit_reader.get_batch::<i32>(
- &mut index_buf[..to_read],
- self.bit_width as usize,
- );
+ let num_values = bit_reader
+ .get_batch::<i32>(&mut index_buf[..to_read], self.bit_width as usize);
if num_values == 0 {
// Handle writers which truncate the final block
self.bit_packed_left = 0;
@@ -708,14 +690,10 @@ mod tests {
decoder.set_data(data.into());
let mut buffer = vec![""; 12];
let expected = vec![
- "ddd", "eee", "fff", "ddd", "eee", "fff", "ddd", "eee", "fff", "eee", "fff",
- "fff",
+ "ddd", "eee", "fff", "ddd", "eee", "fff", "ddd", "eee", "fff", "eee", "fff", "fff",
];
- let result = decoder.get_batch_with_dict::<&str>(
- dict.as_slice(),
- buffer.as_mut_slice(),
- 12,
- );
+ let result =
+ decoder.get_batch_with_dict::<&str>(dict.as_slice(), buffer.as_mut_slice(), 12);
assert!(result.is_ok());
assert_eq!(buffer, expected);
}
@@ -1042,8 +1020,7 @@ mod tests {
for _ in 0..niters {
values.clear();
let rng = thread_rng();
- let seed_vec: Vec<u8> =
- rng.sample_iter::<u8, _>(&Standard).take(seed_len).collect();
+ let seed_vec: Vec<u8> = rng.sample_iter::<u8, _>(&Standard).take(seed_len).collect();
let mut seed = [0u8; 32];
seed.copy_from_slice(&seed_vec[0..seed_len]);
let mut gen = rand::rngs::StdRng::from_seed(seed);
diff --git a/parquet/src/util/bit_util.rs b/parquet/src/util/bit_util.rs
index a17202254cd6..062f93270386 100644
--- a/parquet/src/util/bit_util.rs
+++ b/parquet/src/util/bit_util.rs
@@ -1027,7 +1027,10 @@ mod tests {
.collect();
// Generic values used to check against actual values read from `get_batch`.
- let expected_values: Vec<T> = values.iter().map(|v| T::try_from_le_slice(v.as_bytes()).unwrap()).collect();
+ let expected_values: Vec<T> = values
+ .iter()
+ .map(|v| T::try_from_le_slice(v.as_bytes()).unwrap())
+ .collect();
(0..total).for_each(|i| writer.put_value(values[i], num_bits));
diff --git a/parquet/src/util/interner.rs b/parquet/src/util/interner.rs
index f57fc3a71409..a804419b5da7 100644
--- a/parquet/src/util/interner.rs
+++ b/parquet/src/util/interner.rs
@@ -35,7 +35,7 @@ pub trait Storage {
/// Return an estimate of the memory used in this storage, in bytes
#[allow(dead_code)] // not used in parquet_derive, so is dead there
- fn estimated_memory_size(&self) -> usize;
+ fn estimated_memory_size(&self) -> usize;
}
/// A generic value interner supporting various different [`Storage`]
|
diff --git a/parquet/src/util/test_common/file_util.rs b/parquet/src/util/test_common/file_util.rs
index c2dcd677360d..6c031358e795 100644
--- a/parquet/src/util/test_common/file_util.rs
+++ b/parquet/src/util/test_common/file_util.rs
@@ -19,8 +19,7 @@ use std::{fs, path::PathBuf, str::FromStr};
/// Returns path to the test parquet file in 'data' directory
pub fn get_test_path(file_name: &str) -> PathBuf {
- let mut pathbuf =
- PathBuf::from_str(&arrow::util::test_util::parquet_test_data()).unwrap();
+ let mut pathbuf = PathBuf::from_str(&arrow::util::test_util::parquet_test_data()).unwrap();
pathbuf.push(file_name);
pathbuf
}
diff --git a/parquet/src/util/test_common/mod.rs b/parquet/src/util/test_common/mod.rs
index 504219ecae19..8cfc1e6dd423 100644
--- a/parquet/src/util/test_common/mod.rs
+++ b/parquet/src/util/test_common/mod.rs
@@ -21,4 +21,4 @@ pub mod page_util;
pub mod file_util;
#[cfg(test)]
-pub mod rand_gen;
\ No newline at end of file
+pub mod rand_gen;
diff --git a/parquet/src/util/test_common/rand_gen.rs b/parquet/src/util/test_common/rand_gen.rs
index a267c34840c1..ec80d3a593ae 100644
--- a/parquet/src/util/test_common/rand_gen.rs
+++ b/parquet/src/util/test_common/rand_gen.rs
@@ -173,8 +173,7 @@ pub fn make_pages<T: DataType>(
// Generate the current page
- let mut pb =
- DataPageBuilderImpl::new(desc.clone(), num_values_cur_page as u32, use_v2);
+ let mut pb = DataPageBuilderImpl::new(desc.clone(), num_values_cur_page as u32, use_v2);
if max_rep_level > 0 {
pb.add_rep_levels(max_rep_level, &rep_levels[level_range.clone()]);
}
|
Is cargo fmt no longer working properly in parquet crate
**Which part is this question about**
Code formatter.
**Describe your question**
I've noticed recently that running `cargo fmt` while I'm editing files doesn't always seem to catch problems. Running rustfmt directly will work. For instance, running `cargo fmt` on the parquet crate yields no output.
```
% cargo +stable fmt -p parquet -v -- --check
[bench (2021)] "/Users/seidl/src/arrow-rs/parquet/benches/arrow_reader.rs"
[bench (2021)] "/Users/seidl/src/arrow-rs/parquet/benches/arrow_statistics.rs"
[bench (2021)] "/Users/seidl/src/arrow-rs/parquet/benches/arrow_writer.rs"
[bench (2021)] "/Users/seidl/src/arrow-rs/parquet/benches/compression.rs"
[bench (2021)] "/Users/seidl/src/arrow-rs/parquet/benches/encoding.rs"
[bench (2021)] "/Users/seidl/src/arrow-rs/parquet/benches/metadata.rs"
[example (2021)] "/Users/seidl/src/arrow-rs/parquet/examples/async_read_parquet.rs"
[example (2021)] "/Users/seidl/src/arrow-rs/parquet/examples/read_parquet.rs"
[example (2021)] "/Users/seidl/src/arrow-rs/parquet/examples/read_with_rowgroup.rs"
[example (2021)] "/Users/seidl/src/arrow-rs/parquet/examples/write_parquet.rs"
[bin (2021)] "/Users/seidl/src/arrow-rs/parquet/src/bin/parquet-concat.rs"
[bin (2021)] "/Users/seidl/src/arrow-rs/parquet/src/bin/parquet-fromcsv.rs"
[bin (2021)] "/Users/seidl/src/arrow-rs/parquet/src/bin/parquet-index.rs"
[bin (2021)] "/Users/seidl/src/arrow-rs/parquet/src/bin/parquet-layout.rs"
[bin (2021)] "/Users/seidl/src/arrow-rs/parquet/src/bin/parquet-read.rs"
[bin (2021)] "/Users/seidl/src/arrow-rs/parquet/src/bin/parquet-rewrite.rs"
[bin (2021)] "/Users/seidl/src/arrow-rs/parquet/src/bin/parquet-rowcount.rs"
[bin (2021)] "/Users/seidl/src/arrow-rs/parquet/src/bin/parquet-schema.rs"
[bin (2021)] "/Users/seidl/src/arrow-rs/parquet/src/bin/parquet-show-bloom-filter.rs"
[lib (2021)] "/Users/seidl/src/arrow-rs/parquet/src/lib.rs"
[test (2021)] "/Users/seidl/src/arrow-rs/parquet/tests/arrow_reader/mod.rs"
[test (2021)] "/Users/seidl/src/arrow-rs/parquet/tests/arrow_writer_layout.rs"
rustfmt --edition 2021 --check /Users/seidl/src/arrow-rs/parquet/benches/arrow_reader.rs /Users/seidl/src/arrow-rs/parquet/benches/arrow_statistics.rs /Users/seidl/src/arrow-rs/parquet/benches/arrow_writer.rs /Users/seidl/src/arrow-rs/parquet/benches/compression.rs /Users/seidl/src/arrow-rs/parquet/benches/encoding.rs /Users/seidl/src/arrow-rs/parquet/benches/metadata.rs /Users/seidl/src/arrow-rs/parquet/examples/async_read_parquet.rs /Users/seidl/src/arrow-rs/parquet/examples/read_parquet.rs /Users/seidl/src/arrow-rs/parquet/examples/read_with_rowgroup.rs /Users/seidl/src/arrow-rs/parquet/examples/write_parquet.rs /Users/seidl/src/arrow-rs/parquet/src/bin/parquet-concat.rs /Users/seidl/src/arrow-rs/parquet/src/bin/parquet-fromcsv.rs /Users/seidl/src/arrow-rs/parquet/src/bin/parquet-index.rs /Users/seidl/src/arrow-rs/parquet/src/bin/parquet-layout.rs /Users/seidl/src/arrow-rs/parquet/src/bin/parquet-read.rs /Users/seidl/src/arrow-rs/parquet/src/bin/parquet-rewrite.rs /Users/seidl/src/arrow-rs/parquet/src/bin/parquet-rowcount.rs /Users/seidl/src/arrow-rs/parquet/src/bin/parquet-schema.rs /Users/seidl/src/arrow-rs/parquet/src/bin/parquet-show-bloom-filter.rs /Users/seidl/src/arrow-rs/parquet/src/lib.rs /Users/seidl/src/arrow-rs/parquet/tests/arrow_reader/mod.rs /Users/seidl/src/arrow-rs/parquet/tests/arrow_writer_layout.rs
%
```
But there are files that when run manually do (running the rustfmt command line above with the addition of `parquet/src/compression.rs`):
```
% rustfmt --edition 2021 --check /Users/seidl/src/arrow-rs/parquet/benches/arrow_reader.rs /Users/seidl/src/arrow-rs/parquet/benches/arrow_statistics.rs /Users/seidl/src/arrow-rs/parquet/benches/arrow_writer.rs /Users/seidl/src/arrow-rs/parquet/benches/compression.rs /Users/seidl/src/arrow-rs/parquet/benches/encoding.rs /Users/seidl/src/arrow-rs/parquet/benches/metadata.rs /Users/seidl/src/arrow-rs/parquet/examples/async_read_parquet.rs /Users/seidl/src/arrow-rs/parquet/examples/read_parquet.rs /Users/seidl/src/arrow-rs/parquet/examples/read_with_rowgroup.rs /Users/seidl/src/arrow-rs/parquet/examples/write_parquet.rs /Users/seidl/src/arrow-rs/parquet/src/bin/parquet-concat.rs /Users/seidl/src/arrow-rs/parquet/src/bin/parquet-fromcsv.rs /Users/seidl/src/arrow-rs/parquet/src/bin/parquet-index.rs /Users/seidl/src/arrow-rs/parquet/src/bin/parquet-layout.rs /Users/seidl/src/arrow-rs/parquet/src/bin/parquet-read.rs /Users/seidl/src/arrow-rs/parquet/src/bin/parquet-rewrite.rs /Users/seidl/src/arrow-rs/parquet/src/bin/parquet-rowcount.rs /Users/seidl/src/arrow-rs/parquet/src/bin/parquet-schema.rs /Users/seidl/src/arrow-rs/parquet/src/bin/parquet-show-bloom-filter.rs /Users/seidl/src/arrow-rs/parquet/src/lib.rs /Users/seidl/src/arrow-rs/parquet/tests/arrow_reader/mod.rs /Users/seidl/src/arrow-rs/parquet/tests/arrow_writer_layout.rs /Users/seidl/src/arrow-rs/parquet/src/compression.rs
Diff in /Users/seidl/src/arrow-rs/parquet/src/compression.rs at line 150:
CodecType::BROTLI(level) => {
#[cfg(any(feature = "brotli", test))]
return Ok(Some(Box::new(BrotliCodec::new(level))));
- Err(ParquetError::General("Disabled feature at compile time: brotli".into()))
- },
+ Err(ParquetError::General(
+ "Disabled feature at compile time: brotli".into(),
+ ))
+ }
CodecType::GZIP(level) => {
#[cfg(any(feature = "flate2", test))]
return Ok(Some(Box::new(GZipCodec::new(level))));
Diff in /Users/seidl/src/arrow-rs/parquet/src/compression.rs at line 158:
- Err(ParquetError::General("Disabled feature at compile time: flate2".into()))
- },
+ Err(ParquetError::General(
+ "Disabled feature at compile time: flate2".into(),
+ ))
+ }
CodecType::SNAPPY => {
#[cfg(any(feature = "snap", test))]
return Ok(Some(Box::new(SnappyCodec::new())));
Diff in /Users/seidl/src/arrow-rs/parquet/src/compression.rs at line 163:
- Err(ParquetError::General("Disabled feature at compile time: snap".into()))
- },
+ Err(ParquetError::General(
+ "Disabled feature at compile time: snap".into(),
+ ))
+ }
CodecType::LZ4 => {
#[cfg(any(feature = "lz4", test))]
return Ok(Some(Box::new(LZ4HadoopCodec::new(
Diff in /Users/seidl/src/arrow-rs/parquet/src/compression.rs at line 168:
_options.backward_compatible_lz4,
))));
- Err(ParquetError::General("Disabled feature at compile time: lz4".into()))
- },
+ Err(ParquetError::General(
+ "Disabled feature at compile time: lz4".into(),
+ ))
+ }
CodecType::ZSTD(level) => {
#[cfg(any(feature = "zstd", test))]
return Ok(Some(Box::new(ZSTDCodec::new(level))));
Diff in /Users/seidl/src/arrow-rs/parquet/src/compression.rs at line 175:
- Err(ParquetError::General("Disabled feature at compile time: zstd".into()))
- },
+ Err(ParquetError::General(
+ "Disabled feature at compile time: zstd".into(),
+ ))
+ }
CodecType::LZ4_RAW => {
#[cfg(any(feature = "lz4", test))]
return Ok(Some(Box::new(LZ4RawCodec::new())));
Diff in /Users/seidl/src/arrow-rs/parquet/src/compression.rs at line 180:
- Err(ParquetError::General("Disabled feature at compile time: lz4".into()))
- },
+ Err(ParquetError::General(
+ "Disabled feature at compile time: lz4".into(),
+ ))
+ }
CodecType::UNCOMPRESSED => Ok(None),
_ => Err(nyi_err!("The codec type {} is not supported yet", codec)),
}
%
```
**Additional context**
There are many reports of fmt silently failing, one such is https://github.com/rust-lang/rustfmt/issues/3008.
Has anyone else noticed this or is it something to do with my setup.
```
% cargo --version
cargo 1.80.0 (376290515 2024-07-16)
% rustfmt --version
rustfmt 1.7.0-stable (05147895 2024-07-21)
```
|
Fascinatingly, I am seeing the same thing
For example I deliberately introduced a formatting issue:
```
andrewlamb@Andrews-MacBook-Pro-2:~/Software/arrow-rs$ git diff
diff --git a/parquet/src/compression.rs b/parquet/src/compression.rs
index 10560210e4e..119af7e156f 100644
--- a/parquet/src/compression.rs
+++ b/parquet/src/compression.rs
@@ -15,6 +15,10 @@
// specific language governing permissions and limitations
// under the License.
+
+
+
+
//! Contains codec interface and supported codec implementations.
//!
//! See [`Compression`](crate::basic::Compression) enum for all available compression
```
And then when I ran fmt it didn't seem to fix it
```shell
andrewlamb@Andrews-MacBook-Pro-2:~/Software/arrow-rs$ cargo fmt
andrewlamb@Andrews-MacBook-Pro-2:~/Software/arrow-rs$ git diff
diff --git a/parquet/src/compression.rs b/parquet/src/compression.rs
index 10560210e4e..119af7e156f 100644
--- a/parquet/src/compression.rs
+++ b/parquet/src/compression.rs
@@ -15,6 +15,10 @@
// specific language governing permissions and limitations
// under the License.
+
+
+
+
//! Contains codec interface and supported codec implementations.
//!
//! See [`Compression`](crate::basic::Compression) enum for all available compression
```
```shell
andrewlamb@Andrews-MacBook-Pro-2:~/Software/arrow-rs$ cargo --version
cargo 1.80.0 (376290515 2024-07-16)
andrewlamb@Andrews-MacBook-Pro-2:~/Software/arrow-rs$ rustfmt --version
rustfmt 1.7.0-stable (05147895 2024-07-21)
andrewlamb@Andrews-MacBook-Pro-2:~/Software/arrow-rs$
```
Interestingly I found that removing this line:
https://github.com/apache/arrow-rs/blob/b72098fee551086b2b4eb4b131aeaf920cf7e4b3/parquet/src/lib.rs#L121
Make `cargo fmt` come back
Though it looks like (I) added that line 3 months ago: https://github.com/apache/arrow-rs/commit/98784bd059653cdc316454380ac93a34d53089fd 🤔
It's the first time for me to know `#[rustfmt::skip]` :laughing:
I tried reverting #5727 and still no output :(
Still tracking this. Here's a list of non-compliant files in the parquet source (`format.rs` is expected).
```
% rustfmt --check -l `find . -name "*.rs"` |sort|uniq
/Users/seidl2/src/arrow-rs/parquet/src/arrow/array_reader/empty_array.rs
/Users/seidl2/src/arrow-rs/parquet/src/arrow/array_reader/fixed_size_list_array.rs
/Users/seidl2/src/arrow-rs/parquet/src/arrow/array_reader/list_array.rs
/Users/seidl2/src/arrow-rs/parquet/src/arrow/array_reader/map_array.rs
/Users/seidl2/src/arrow-rs/parquet/src/arrow/array_reader/struct_array.rs
/Users/seidl2/src/arrow-rs/parquet/src/arrow/schema/complex.rs
/Users/seidl2/src/arrow-rs/parquet/src/arrow/schema/mod.rs
/Users/seidl2/src/arrow-rs/parquet/src/compression.rs
/Users/seidl2/src/arrow-rs/parquet/src/encodings/encoding/dict_encoder.rs
/Users/seidl2/src/arrow-rs/parquet/src/encodings/levels.rs
/Users/seidl2/src/arrow-rs/parquet/src/encodings/rle.rs
/Users/seidl2/src/arrow-rs/parquet/src/format.rs
/Users/seidl2/src/arrow-rs/parquet/src/util/bit_util.rs
/Users/seidl2/src/arrow-rs/parquet/src/util/interner.rs
/Users/seidl2/src/arrow-rs/parquet/src/util/test_common/file_util.rs
/Users/seidl2/src/arrow-rs/parquet/src/util/test_common/mod.rs
/Users/seidl2/src/arrow-rs/parquet/src/util/test_common/rand_gen.rs
```
Ah, so apparently rustfmt will not format modules that are declared in macros, such as those in the `experimental!` macro https://github.com/apache/arrow-rs/blob/a937869f892dc12c4730189e216bf3bd48c2561d/parquet/src/lib.rs#L132-L137
There is an open issue for this https://github.com/rust-lang/rustfmt/issues/3253
One workaround is to tack a list of files to format to the end of the commandline
```
cargo +stable fmt --all --check -- `find parquet -name "*.rs" \! -name format.rs`
```
Perhaps something like this could be added to `.github/workflows/rust.yml`.
Edit: this has also been a problem in DataFusion https://github.com/apache/datafusion/pull/9367. I don't know if a similar solution would work here.
|
2024-08-29T16:36:10Z
|
52.2
|
678517018ddfd21b202a94df13b06dfa1ab8a378
|
apache/arrow-rs
| 6,320
|
apache__arrow-rs-6320
|
[
"6318"
] |
a937869f892dc12c4730189e216bf3bd48c2561d
|
diff --git a/arrow/src/pyarrow.rs b/arrow/src/pyarrow.rs
index 43cdb4fe0919..336398cbf22f 100644
--- a/arrow/src/pyarrow.rs
+++ b/arrow/src/pyarrow.rs
@@ -59,7 +59,7 @@ use std::convert::{From, TryFrom};
use std::ptr::{addr_of, addr_of_mut};
use std::sync::Arc;
-use arrow_array::{RecordBatchIterator, RecordBatchReader, StructArray};
+use arrow_array::{RecordBatchIterator, RecordBatchOptions, RecordBatchReader, StructArray};
use pyo3::exceptions::{PyTypeError, PyValueError};
use pyo3::ffi::Py_uintptr_t;
use pyo3::import_exception;
@@ -361,6 +361,7 @@ impl FromPyArrow for RecordBatch {
"Expected Struct type from __arrow_c_array.",
));
}
+ let options = RecordBatchOptions::default().with_row_count(Some(array_data.len()));
let array = StructArray::from(array_data);
// StructArray does not embed metadata from schema. We need to override
// the output schema with the schema from the capsule.
@@ -371,7 +372,7 @@ impl FromPyArrow for RecordBatch {
0,
"Cannot convert nullable StructArray to RecordBatch, see StructArray documentation"
);
- return RecordBatch::try_new(schema, columns).map_err(to_py_err);
+ return RecordBatch::try_new_with_options(schema, columns, &options).map_err(to_py_err);
}
validate_class("RecordBatch", value)?;
@@ -386,7 +387,14 @@ impl FromPyArrow for RecordBatch {
.map(|a| Ok(make_array(ArrayData::from_pyarrow_bound(&a)?)))
.collect::<PyResult<_>>()?;
- let batch = RecordBatch::try_new(schema, arrays).map_err(to_py_err)?;
+ let row_count = value
+ .getattr("num_rows")
+ .ok()
+ .and_then(|x| x.extract().ok());
+ let options = RecordBatchOptions::default().with_row_count(row_count);
+
+ let batch =
+ RecordBatch::try_new_with_options(schema, arrays, &options).map_err(to_py_err)?;
Ok(batch)
}
}
|
diff --git a/arrow-pyarrow-integration-testing/tests/test_sql.py b/arrow-pyarrow-integration-testing/tests/test_sql.py
index 5320d0a5343e..3b46d5729a1f 100644
--- a/arrow-pyarrow-integration-testing/tests/test_sql.py
+++ b/arrow-pyarrow-integration-testing/tests/test_sql.py
@@ -476,6 +476,29 @@ def test_tensor_array():
del b
+
+def test_empty_recordbatch_with_row_count():
+ """
+ A pyarrow.RecordBatch with no columns but with `num_rows` set.
+
+ `datafusion-python` gets this as the result of a `count(*)` query.
+ """
+
+ # Create an empty schema with no fields
+ batch = pa.RecordBatch.from_pydict({"a": [1, 2, 3, 4]}).select([])
+ num_rows = 4
+ assert batch.num_rows == num_rows
+ assert batch.num_columns == 0
+
+ b = rust.round_trip_record_batch(batch)
+ assert b == batch
+ assert b.schema == batch.schema
+ assert b.schema.metadata == batch.schema.metadata
+
+ assert b.num_rows == batch.num_rows
+
+ del b
+
def test_record_batch_reader():
"""
Python -> Rust -> Python
|
Allow converting empty `pyarrow.RecordBatch` to `arrow::RecordBatch`
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
`datafusion-python` currently errors when calling `select count(*) from t` when `t` is a `pyarrow.Dataset`.
The resulting `pyarrow.RecordBatch` contains no rows and has a schema with no columns, but it does have `num_rows` set to the correct number.
**Describe the solution you'd like**
Support was added to arrow-rs in https://github.com/apache/arrow-rs/pull/1552 for a `RecordBatch` with zero columns but non zero row count.
I'd like `impl FromPyArrow for RecordBatch` to use this functionality.
https://github.com/apache/arrow-rs/blob/b711f23a136e0b094a70a4aafb020d4bb9f60619/arrow/src/pyarrow.rs#L334-L392
**Additional Context**
datafusion-python issue: https://github.com/apache/datafusion-python/issues/800
|
2024-08-28T17:30:36Z
|
52.2
|
678517018ddfd21b202a94df13b06dfa1ab8a378
|
|
apache/arrow-rs
| 6,295
|
apache__arrow-rs-6295
|
[
"3577"
] |
8c956a9f9ab26c14072740cce64c2b99cb039b13
|
diff --git a/parquet/src/encodings/rle.rs b/parquet/src/encodings/rle.rs
index 581f14b3c99a..97a122941f17 100644
--- a/parquet/src/encodings/rle.rs
+++ b/parquet/src/encodings/rle.rs
@@ -20,7 +20,6 @@ use std::{cmp, mem::size_of};
use bytes::Bytes;
use crate::errors::{ParquetError, Result};
-use crate::util::bit_util::from_le_slice;
use crate::util::bit_util::{self, BitReader, BitWriter, FromBytes};
/// Rle/Bit-Packing Hybrid Encoding
@@ -356,13 +355,13 @@ impl RleDecoder {
}
let value = if self.rle_left > 0 {
- let rle_value = from_le_slice(
+ let rle_value = T::try_from_le_slice(
&self
.current_value
.as_mut()
.expect("current_value should be Some")
.to_ne_bytes(),
- );
+ )?;
self.rle_left -= 1;
rle_value
} else {
@@ -388,9 +387,9 @@ impl RleDecoder {
let num_values =
cmp::min(buffer.len() - values_read, self.rle_left as usize);
for i in 0..num_values {
- let repeated_value = from_le_slice(
+ let repeated_value = T::try_from_le_slice(
&self.current_value.as_mut().unwrap().to_ne_bytes(),
- );
+ )?;
buffer[values_read + i] = repeated_value;
}
self.rle_left -= num_values as u32;
diff --git a/parquet/src/file/page_index/index.rs b/parquet/src/file/page_index/index.rs
index 0c23e4aa38b8..662ba45621ab 100644
--- a/parquet/src/file/page_index/index.rs
+++ b/parquet/src/file/page_index/index.rs
@@ -23,7 +23,6 @@ use crate::data_type::{AsBytes, ByteArray, FixedLenByteArray, Int96};
use crate::errors::ParquetError;
use crate::file::metadata::LevelHistogram;
use crate::format::{BoundaryOrder, ColumnIndex};
-use crate::util::bit_util::from_le_slice;
use std::fmt::Debug;
/// Typed statistics for one data page
@@ -192,7 +191,7 @@ impl<T: ParquetValueType> NativeIndex<T> {
let indexes = index
.min_values
.iter()
- .zip(index.max_values.into_iter())
+ .zip(index.max_values.iter())
.zip(index.null_pages.into_iter())
.zip(null_counts.into_iter())
.zip(rep_hists.into_iter())
@@ -205,9 +204,10 @@ impl<T: ParquetValueType> NativeIndex<T> {
let (min, max) = if is_null {
(None, None)
} else {
- let min = min.as_slice();
- let max = max.as_slice();
- (Some(from_le_slice::<T>(min)), Some(from_le_slice::<T>(max)))
+ (
+ Some(T::try_from_le_slice(min)?),
+ Some(T::try_from_le_slice(max)?),
+ )
};
Ok(PageIndex {
min,
@@ -321,4 +321,29 @@ mod tests {
assert_eq!(page_index.repetition_level_histogram(), None);
assert_eq!(page_index.definition_level_histogram(), None);
}
+
+ #[test]
+ fn test_invalid_column_index() {
+ let column_index = ColumnIndex {
+ null_pages: vec![true, false],
+ min_values: vec![
+ vec![],
+ vec![], // this shouldn't be empty as null_pages[1] is false
+ ],
+ max_values: vec![
+ vec![],
+ vec![], // this shouldn't be empty as null_pages[1] is false
+ ],
+ null_counts: None,
+ repetition_level_histograms: None,
+ definition_level_histograms: None,
+ boundary_order: BoundaryOrder::UNORDERED,
+ };
+
+ let err = NativeIndex::<i32>::try_new(column_index).unwrap_err();
+ assert_eq!(
+ err.to_string(),
+ "Parquet error: error converting value, expected 4 bytes got 0"
+ );
+ }
}
diff --git a/parquet/src/file/serialized_reader.rs b/parquet/src/file/serialized_reader.rs
index 0a3e51931867..b8ee4001a99c 100644
--- a/parquet/src/file/serialized_reader.rs
+++ b/parquet/src/file/serialized_reader.rs
@@ -781,7 +781,6 @@ mod tests {
use crate::file::writer::SerializedFileWriter;
use crate::record::RowAccessor;
use crate::schema::parser::parse_message_type;
- use crate::util::bit_util::from_le_slice;
use crate::util::test_common::file_util::{get_test_file, get_test_path};
use super::*;
@@ -1537,8 +1536,8 @@ mod tests {
assert_eq!(row_group_index.indexes.len(), page_size);
assert_eq!(row_group_index.boundary_order, boundary_order);
row_group_index.indexes.iter().all(|x| {
- x.min.as_ref().unwrap() >= &from_le_slice::<T>(min_max.0)
- && x.max.as_ref().unwrap() <= &from_le_slice::<T>(min_max.1)
+ x.min.as_ref().unwrap() >= &T::try_from_le_slice(min_max.0).unwrap()
+ && x.max.as_ref().unwrap() <= &T::try_from_le_slice(min_max.1).unwrap()
});
}
diff --git a/parquet/src/file/statistics.rs b/parquet/src/file/statistics.rs
index 680c75d6b2e5..854900f1edb9 100644
--- a/parquet/src/file/statistics.rs
+++ b/parquet/src/file/statistics.rs
@@ -47,7 +47,7 @@ use crate::basic::Type;
use crate::data_type::private::ParquetValueType;
use crate::data_type::*;
use crate::errors::{ParquetError, Result};
-use crate::util::bit_util::from_le_slice;
+use crate::util::bit_util::FromBytes;
pub(crate) mod private {
use super::*;
@@ -186,14 +186,18 @@ pub fn from_thrift(
// INT96 statistics may not be correct, because comparison is signed
// byte-wise, not actual timestamps. It is recommended to ignore
// min/max statistics for INT96 columns.
- let min = min.map(|data| {
+ let min = if let Some(data) = min {
assert_eq!(data.len(), 12);
- from_le_slice::<Int96>(&data)
- });
- let max = max.map(|data| {
+ Some(Int96::try_from_le_slice(&data)?)
+ } else {
+ None
+ };
+ let max = if let Some(data) = max {
assert_eq!(data.len(), 12);
- from_le_slice::<Int96>(&data)
- });
+ Some(Int96::try_from_le_slice(&data)?)
+ } else {
+ None
+ };
Statistics::int96(min, max, distinct_count, null_count, old_format)
}
Type::FLOAT => Statistics::float(
diff --git a/parquet/src/util/bit_util.rs b/parquet/src/util/bit_util.rs
index adbf45014c9d..a17202254cd6 100644
--- a/parquet/src/util/bit_util.rs
+++ b/parquet/src/util/bit_util.rs
@@ -23,12 +23,6 @@ use crate::data_type::{AsBytes, ByteArray, FixedLenByteArray, Int96};
use crate::errors::{ParquetError, Result};
use crate::util::bit_pack::{unpack16, unpack32, unpack64, unpack8};
-#[inline]
-pub fn from_le_slice<T: FromBytes>(bs: &[u8]) -> T {
- // TODO: propagate the error (#3577)
- T::try_from_le_slice(bs).unwrap()
-}
-
#[inline]
fn array_from_slice<const N: usize>(bs: &[u8]) -> Result<[u8; N]> {
// Need to slice as may be called with zero-padded values
@@ -91,15 +85,22 @@ unsafe impl FromBytes for Int96 {
type Buffer = [u8; 12];
fn try_from_le_slice(b: &[u8]) -> Result<Self> {
- Ok(Self::from_le_bytes(array_from_slice(b)?))
+ let bs: [u8; 12] = array_from_slice(b)?;
+ let mut i = Int96::new();
+ i.set_data(
+ u32::try_from_le_slice(&bs[0..4])?,
+ u32::try_from_le_slice(&bs[4..8])?,
+ u32::try_from_le_slice(&bs[8..12])?,
+ );
+ Ok(i)
}
fn from_le_bytes(bs: Self::Buffer) -> Self {
let mut i = Int96::new();
i.set_data(
- from_le_slice(&bs[0..4]),
- from_le_slice(&bs[4..8]),
- from_le_slice(&bs[8..12]),
+ u32::try_from_le_slice(&bs[0..4]).unwrap(),
+ u32::try_from_le_slice(&bs[4..8]).unwrap(),
+ u32::try_from_le_slice(&bs[8..12]).unwrap(),
);
i
}
@@ -438,7 +439,7 @@ impl BitReader {
}
// TODO: better to avoid copying here
- Some(from_le_slice(v.as_bytes()))
+ T::try_from_le_slice(v.as_bytes()).ok()
}
/// Read multiple values from their packed representation where each element is represented
@@ -1026,7 +1027,7 @@ mod tests {
.collect();
// Generic values used to check against actual values read from `get_batch`.
- let expected_values: Vec<T> = values.iter().map(|v| from_le_slice(v.as_bytes())).collect();
+ let expected_values: Vec<T> = values.iter().map(|v| T::try_from_le_slice(v.as_bytes()).unwrap()).collect();
(0..total).for_each(|i| writer.put_value(values[i], num_bits));
|
diff --git a/parquet/tests/arrow_reader/bad_data.rs b/parquet/tests/arrow_reader/bad_data.rs
index 6e325f119710..cbd5d4d3b29e 100644
--- a/parquet/tests/arrow_reader/bad_data.rs
+++ b/parquet/tests/arrow_reader/bad_data.rs
@@ -134,3 +134,28 @@ fn read_file(name: &str) -> Result<usize, ParquetError> {
}
Ok(num_rows)
}
+
+#[cfg(feature = "async")]
+#[tokio::test]
+async fn bad_metadata_err() {
+ use bytes::Bytes;
+ use parquet::arrow::async_reader::MetadataLoader;
+
+ let metadata_buffer = Bytes::from_static(include_bytes!("bad_raw_metadata.bin"));
+
+ let metadata_length = metadata_buffer.len();
+
+ let mut reader = std::io::Cursor::new(&metadata_buffer);
+ let mut loader = MetadataLoader::load(&mut reader, metadata_length, None)
+ .await
+ .unwrap();
+ loader.load_page_index(false, false).await.unwrap();
+ loader.load_page_index(false, true).await.unwrap();
+
+ let err = loader.load_page_index(true, false).await.unwrap_err();
+
+ assert_eq!(
+ err.to_string(),
+ "Parquet error: error converting value, expected 4 bytes got 0"
+ );
+}
diff --git a/parquet/tests/arrow_reader/bad_raw_metadata.bin b/parquet/tests/arrow_reader/bad_raw_metadata.bin
new file mode 100644
index 000000000000..47f9aa1c092b
Binary files /dev/null and b/parquet/tests/arrow_reader/bad_raw_metadata.bin differ
|
Don't Panic on Invalid Parquet Statistics
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
<!--
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
(This section helps Arrow developers understand the context and *why* for this feature, in addition to the *what*)
-->
Invalid statistics will currently result in the parquet reader panicking, we should instead return an error
**Describe the solution you'd like**
<!--
A clear and concise description of what you want to happen.
-->
**Describe alternatives you've considered**
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
|
2024-08-23T19:10:39Z
|
52.2
|
678517018ddfd21b202a94df13b06dfa1ab8a378
|
|
apache/arrow-rs
| 6,290
|
apache__arrow-rs-6290
|
[
"6289"
] |
ebcc4a585136cd1d9696c38c41f71c9ced181f57
|
diff --git a/parquet/Cargo.toml b/parquet/Cargo.toml
index b97b2a571646..1d38e67a0f02 100644
--- a/parquet/Cargo.toml
+++ b/parquet/Cargo.toml
@@ -68,6 +68,7 @@ twox-hash = { version = "1.6", default-features = false }
paste = { version = "1.0" }
half = { version = "2.1", default-features = false, features = ["num-traits"] }
sysinfo = { version = "0.31.2", optional = true, default-features = false, features = ["system"] }
+crc32fast = { version = "1.4.2", optional = true, default-features = false }
[dev-dependencies]
base64 = { version = "0.22", default-features = false, features = ["std"] }
@@ -117,6 +118,8 @@ object_store = ["dep:object_store", "async"]
zstd = ["dep:zstd", "zstd-sys"]
# Display memory in example/write_parquet.rs
sysinfo = ["dep:sysinfo"]
+# Verify 32-bit CRC checksum when decoding parquet pages
+crc = ["dep:crc32fast"]
[[example]]
name = "read_parquet"
diff --git a/parquet/README.md b/parquet/README.md
index 0360d15db14f..a0441ee6026d 100644
--- a/parquet/README.md
+++ b/parquet/README.md
@@ -60,6 +60,7 @@ The `parquet` crate provides the following features which may be enabled in your
- `zstd` (default) - support for parquet using `zstd` compression
- `snap` (default) - support for parquet using `snappy` compression
- `cli` - parquet [CLI tools](https://github.com/apache/arrow-rs/tree/master/parquet/src/bin)
+- `crc` - enables functionality to automatically verify checksums of each page (if present) when decoding
- `experimental` - Experimental APIs which may change, even between minor releases
## Parquet Feature Status
@@ -82,4 +83,4 @@ The `parquet` crate provides the following features which may be enabled in your
## License
-Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0.
+Licensed under the Apache License, Version 2.0: <http://www.apache.org/licenses/LICENSE-2.0>.
diff --git a/parquet/src/file/serialized_reader.rs b/parquet/src/file/serialized_reader.rs
index 6fb0f78c1613..b253b73a4fa0 100644
--- a/parquet/src/file/serialized_reader.rs
+++ b/parquet/src/file/serialized_reader.rs
@@ -390,6 +390,15 @@ pub(crate) fn decode_page(
physical_type: Type,
decompressor: Option<&mut Box<dyn Codec>>,
) -> Result<Page> {
+ // Verify the 32-bit CRC checksum of the page
+ #[cfg(feature = "crc")]
+ if let Some(expected_crc) = page_header.crc {
+ let crc = crc32fast::hash(&buffer);
+ if crc != expected_crc as u32 {
+ return Err(general_err!("Page CRC checksum mismatch"));
+ }
+ }
+
// When processing data page v2, depending on enabled compression for the
// page, we should account for uncompressed data ('offset') of
// repetition and definition levels.
|
diff --git a/parquet/tests/arrow_reader/checksum.rs b/parquet/tests/arrow_reader/checksum.rs
new file mode 100644
index 000000000000..c60908d8b95d
--- /dev/null
+++ b/parquet/tests/arrow_reader/checksum.rs
@@ -0,0 +1,73 @@
+// 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.
+
+//! This file contains an end to end test for verifying checksums when reading parquet files.
+
+use std::path::PathBuf;
+
+use arrow::util::test_util::parquet_test_data;
+use parquet::arrow::arrow_reader::ArrowReaderBuilder;
+
+#[test]
+fn test_datapage_v1_corrupt_checksum() {
+ let errors = read_file_batch_errors("datapage_v1-corrupt-checksum.parquet");
+ assert_eq!(errors, [
+ Err("Parquet argument error: Parquet error: Page CRC checksum mismatch".to_string()),
+ Ok(()),
+ Ok(()),
+ Err("Parquet argument error: Parquet error: Page CRC checksum mismatch".to_string()),
+ Err("Parquet argument error: Parquet error: Not all children array length are the same!".to_string())
+ ]);
+}
+
+#[test]
+fn test_datapage_v1_uncompressed_checksum() {
+ let errors = read_file_batch_errors("datapage_v1-uncompressed-checksum.parquet");
+ assert_eq!(errors, [Ok(()), Ok(()), Ok(()), Ok(()), Ok(())]);
+}
+
+#[test]
+fn test_datapage_v1_snappy_compressed_checksum() {
+ let errors = read_file_batch_errors("datapage_v1-snappy-compressed-checksum.parquet");
+ assert_eq!(errors, [Ok(()), Ok(()), Ok(()), Ok(()), Ok(())]);
+}
+
+#[test]
+fn test_plain_dict_uncompressed_checksum() {
+ let errors = read_file_batch_errors("plain-dict-uncompressed-checksum.parquet");
+ assert_eq!(errors, [Ok(())]);
+}
+#[test]
+fn test_rle_dict_snappy_checksum() {
+ let errors = read_file_batch_errors("rle-dict-snappy-checksum.parquet");
+ assert_eq!(errors, [Ok(())]);
+}
+
+/// Reads a file and returns a vector with one element per record batch.
+/// The record batch data is replaced with () and errors are stringified.
+fn read_file_batch_errors(name: &str) -> Vec<Result<(), String>> {
+ let path = PathBuf::from(parquet_test_data()).join(name);
+ println!("Reading file: {:?}", path);
+ let file = std::fs::File::open(&path).unwrap();
+ let reader = ArrowReaderBuilder::try_new(file).unwrap().build().unwrap();
+ reader
+ .map(|x| match x {
+ Ok(_) => Ok(()),
+ Err(e) => Err(e.to_string()),
+ })
+ .collect()
+}
diff --git a/parquet/tests/arrow_reader/mod.rs b/parquet/tests/arrow_reader/mod.rs
index cc4c8f3c977b..0e6783583cd5 100644
--- a/parquet/tests/arrow_reader/mod.rs
+++ b/parquet/tests/arrow_reader/mod.rs
@@ -36,6 +36,8 @@ use std::sync::Arc;
use tempfile::NamedTempFile;
mod bad_data;
+#[cfg(feature = "crc")]
+mod checksum;
mod statistics;
// returns a struct array with columns "int32_col", "float32_col" and "float64_col" with the specified values
|
Optionally verify 32-bit CRC checksum when decoding parquet pages
Currently the PageHeader::crc is never used
|
2024-08-22T23:28:20Z
|
53.0
|
f41c258246cd4bd9d89228cded9ed54dbd00faff
|
|
apache/arrow-rs
| 6,269
|
apache__arrow-rs-6269
|
[
"6268"
] |
acdd27a66ac7b5e07816dc648db00532110fb89a
|
diff --git a/parquet_derive/src/lib.rs b/parquet_derive/src/lib.rs
index 16b6a6699e2d..9c93e2cca978 100644
--- a/parquet_derive/src/lib.rs
+++ b/parquet_derive/src/lib.rs
@@ -146,10 +146,10 @@ pub fn parquet_record_writer(input: proc_macro::TokenStream) -> proc_macro::Toke
/// Derive flat, simple RecordReader implementations. Works by parsing
/// a struct tagged with `#[derive(ParquetRecordReader)]` and emitting
/// the correct writing code for each field of the struct. Column readers
-/// are generated in the order they are defined.
+/// are generated by matching names in the schema to the names in the struct.
///
-/// It is up to the programmer to keep the order of the struct
-/// fields lined up with the schema.
+/// It is up to the programmer to ensure the names in the struct
+/// fields line up with the schema.
///
/// Example:
///
@@ -189,7 +189,6 @@ pub fn parquet_record_reader(input: proc_macro::TokenStream) -> proc_macro::Toke
let field_names: Vec<_> = fields.iter().map(|f| f.ident.clone()).collect();
let reader_snippets: Vec<proc_macro2::TokenStream> =
field_infos.iter().map(|x| x.reader_snippet()).collect();
- let i: Vec<_> = (0..reader_snippets.len()).collect();
let derived_for = input.ident;
let generics = input.generics;
@@ -206,6 +205,12 @@ pub fn parquet_record_reader(input: proc_macro::TokenStream) -> proc_macro::Toke
let mut row_group_reader = row_group_reader;
+ // key: parquet file column name, value: column index
+ let mut name_to_index = std::collections::HashMap::new();
+ for (idx, col) in row_group_reader.metadata().schema_descr().columns().iter().enumerate() {
+ name_to_index.insert(col.name().to_string(), idx);
+ }
+
for _ in 0..num_records {
self.push(#derived_for {
#(
@@ -218,7 +223,14 @@ pub fn parquet_record_reader(input: proc_macro::TokenStream) -> proc_macro::Toke
#(
{
- if let Ok(mut column_reader) = row_group_reader.get_column_reader(#i) {
+ let idx: usize = match name_to_index.get(stringify!(#field_names)) {
+ Some(&col_idx) => col_idx,
+ None => {
+ let error_msg = format!("column name '{}' is not found in parquet file!", stringify!(#field_names));
+ return Err(::parquet::errors::ParquetError::General(error_msg));
+ }
+ };
+ if let Ok(mut column_reader) = row_group_reader.get_column_reader(idx) {
#reader_snippets
} else {
return Err(::parquet::errors::ParquetError::General("Failed to get next column".into()))
|
diff --git a/parquet_derive_test/src/lib.rs b/parquet_derive_test/src/lib.rs
index e7c7896cb7f3..2cd69d03d731 100644
--- a/parquet_derive_test/src/lib.rs
+++ b/parquet_derive_test/src/lib.rs
@@ -73,9 +73,9 @@ struct APartiallyCompleteRecord {
struct APartiallyOptionalRecord {
pub bool: bool,
pub string: String,
- pub maybe_i16: Option<i16>,
- pub maybe_i32: Option<i32>,
- pub maybe_u64: Option<u64>,
+ pub i16: Option<i16>,
+ pub i32: Option<i32>,
+ pub u64: Option<u64>,
pub isize: isize,
pub float: f32,
pub double: f64,
@@ -85,6 +85,22 @@ struct APartiallyOptionalRecord {
pub byte_vec: Vec<u8>,
}
+// This struct removes several fields from the "APartiallyCompleteRecord",
+// and it shuffles the fields.
+// we should still be able to load it from APartiallyCompleteRecord parquet file
+#[derive(PartialEq, ParquetRecordReader, Debug)]
+struct APrunedRecord {
+ pub bool: bool,
+ pub string: String,
+ pub byte_vec: Vec<u8>,
+ pub float: f32,
+ pub double: f64,
+ pub i16: i16,
+ pub i32: i32,
+ pub u64: u64,
+ pub isize: isize,
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -240,12 +256,12 @@ mod tests {
#[test]
fn test_parquet_derive_read_optional_but_valid_column() {
let file = get_temp_file("test_parquet_derive_read_optional", &[]);
- let drs: Vec<APartiallyOptionalRecord> = vec![APartiallyOptionalRecord {
+ let drs = vec![APartiallyOptionalRecord {
bool: true,
string: "a string".into(),
- maybe_i16: Some(-45),
- maybe_i32: Some(456),
- maybe_u64: Some(4563424),
+ i16: Some(-45),
+ i32: Some(456),
+ u64: Some(4563424),
isize: -365,
float: 3.5,
double: f64::NAN,
@@ -273,9 +289,57 @@ mod tests {
let mut row_group = reader.get_row_group(0).unwrap();
out.read_from_row_group(&mut *row_group, 1).unwrap();
- assert_eq!(drs[0].maybe_i16.unwrap(), out[0].i16);
- assert_eq!(drs[0].maybe_i32.unwrap(), out[0].i32);
- assert_eq!(drs[0].maybe_u64.unwrap(), out[0].u64);
+ assert_eq!(drs[0].i16.unwrap(), out[0].i16);
+ assert_eq!(drs[0].i32.unwrap(), out[0].i32);
+ assert_eq!(drs[0].u64.unwrap(), out[0].u64);
+ }
+
+ #[test]
+ fn test_parquet_derive_read_pruned_and_shuffled_columns() {
+ let file = get_temp_file("test_parquet_derive_read_pruned", &[]);
+ let drs = vec![APartiallyCompleteRecord {
+ bool: true,
+ string: "a string".into(),
+ i16: -45,
+ i32: 456,
+ u64: 4563424,
+ isize: -365,
+ float: 3.5,
+ double: f64::NAN,
+ now: chrono::Utc::now().naive_local(),
+ date: chrono::naive::NaiveDate::from_ymd_opt(2015, 3, 14).unwrap(),
+ uuid: uuid::Uuid::new_v4(),
+ byte_vec: vec![0x65, 0x66, 0x67],
+ }];
+
+ let generated_schema = drs.as_slice().schema().unwrap();
+
+ let props = Default::default();
+ let mut writer =
+ SerializedFileWriter::new(file.try_clone().unwrap(), generated_schema, props).unwrap();
+
+ let mut row_group = writer.next_row_group().unwrap();
+ drs.as_slice().write_to_row_group(&mut row_group).unwrap();
+ row_group.close().unwrap();
+ writer.close().unwrap();
+
+ use parquet::file::{reader::FileReader, serialized_reader::SerializedFileReader};
+ let reader = SerializedFileReader::new(file).unwrap();
+ let mut out: Vec<APrunedRecord> = Vec::new();
+
+ let mut row_group = reader.get_row_group(0).unwrap();
+ out.read_from_row_group(&mut *row_group, 1).unwrap();
+
+ assert_eq!(drs[0].bool, out[0].bool);
+ assert_eq!(drs[0].string, out[0].string);
+ assert_eq!(drs[0].byte_vec, out[0].byte_vec);
+ assert_eq!(drs[0].float, out[0].float);
+ assert!(drs[0].double.is_nan());
+ assert!(out[0].double.is_nan());
+ assert_eq!(drs[0].i16, out[0].i16);
+ assert_eq!(drs[0].i32, out[0].i32);
+ assert_eq!(drs[0].u64, out[0].u64);
+ assert_eq!(drs[0].isize, out[0].isize);
}
/// Returns file handle for a temp file in 'target' directory with a provided content
|
parquet_derive: support reading selected columns from parquet file
# Feature Description
I'm effectively using `parquet_derive` in my project, and I found that there are two inconvenient constraints:
1. The `ParquetRecordReader` enforces the struct to organize fields exactly in the **same order** in the parquet file.
2. The `ParquetRecordReader` enforces the struct to parse **all fields** in the parquet file. "all" might be exaggerating, but it is what happens if you want to get the last column, even only the last column.
As describe in its document:
> Derive flat, simple RecordReader implementations. Works by parsing a struct tagged with #[derive(ParquetRecordReader)] and emitting the correct writing code for each field of the struct. Column readers are generated in the order they are defined.
In my use cases (and I believe these are common requests), user should be able to read pruned parquet file, and they should have the freedom to re-organize fields' ordering in decoded struct.
# My Solution
I introduced a `HashMap` to map field name to its index. Of course, it assumes field name is unique, and this is always true since the current `parquet_derive` macro is applied to a flat struct without nesting.
# Pros and Cons
Obviously removing those two constraints makes `parquet_derive` a more handy tool.
But it has some implied changes:
- previously, since the `ParquetRecordReader` relies only on the index of fields, it allows that a field is named as `abc` to implicitly rename itself to `bcd` in the encoded struct. After this change, user must guarantee that the field name in `ParquetRecordReader` to exist in parquet columns.
- I think it is more intuitive and more natural to constrain the "field name" rather than "index", if we use `ParquetRecordReader` to derive a decoder macro.
- allowing reading partial parquet file may improve the performance for some users, but introducing a `HashMap` in the parser may slowdown the function a bit.
- when the `num_records` in a single parsing call is large enough, the cost of `HashMap` lookup is negligible.
Both implied changes seem to have a more positive impact than negative impact. Please review if this is a reasonable feature request.
|
2024-08-18T14:39:49Z
|
52.2
|
678517018ddfd21b202a94df13b06dfa1ab8a378
|
|
apache/arrow-rs
| 6,204
|
apache__arrow-rs-6204
|
[
"6203"
] |
db239e5b3aa05985b0149187c8b93b88e2285b48
|
diff --git a/parquet/benches/arrow_reader.rs b/parquet/benches/arrow_reader.rs
index 814e75c249bf..18e16f0a4297 100644
--- a/parquet/benches/arrow_reader.rs
+++ b/parquet/benches/arrow_reader.rs
@@ -20,6 +20,7 @@ use arrow::datatypes::DataType;
use arrow_schema::Field;
use criterion::measurement::WallTime;
use criterion::{criterion_group, criterion_main, BenchmarkGroup, Criterion};
+use half::f16;
use num::FromPrimitive;
use num_bigint::BigInt;
use parquet::arrow::array_reader::{
@@ -65,6 +66,8 @@ fn build_test_schema() -> SchemaDescPtr {
}
REQUIRED BYTE_ARRAY mandatory_binary_leaf;
OPTIONAL BYTE_ARRAY optional_binary_leaf;
+ REQUIRED FIXED_LEN_BYTE_ARRAY (2) mandatory_f16_leaf (Float16);
+ OPTIONAL FIXED_LEN_BYTE_ARRAY (2) optional_f16_leaf (Float16);
}
";
parse_message_type(message_type)
@@ -84,6 +87,64 @@ pub fn seedable_rng() -> StdRng {
StdRng::seed_from_u64(42)
}
+// support byte array for float16
+fn build_encoded_f16_bytes_page_iterator<T>(
+ column_desc: ColumnDescPtr,
+ null_density: f32,
+ encoding: Encoding,
+ min: f32,
+ max: f32,
+) -> impl PageIterator + Clone
+where
+ T: parquet::data_type::DataType,
+ T::T: From<Vec<u8>>,
+{
+ let max_def_level = column_desc.max_def_level();
+ let max_rep_level = column_desc.max_rep_level();
+ let rep_levels = vec![0; VALUES_PER_PAGE];
+ let mut rng = seedable_rng();
+ let mut pages: Vec<Vec<parquet::column::page::Page>> = Vec::new();
+ for _i in 0..NUM_ROW_GROUPS {
+ let mut column_chunk_pages = Vec::new();
+ for _j in 0..PAGES_PER_GROUP {
+ // generate page
+ let mut values = Vec::with_capacity(VALUES_PER_PAGE);
+ let mut def_levels = Vec::with_capacity(VALUES_PER_PAGE);
+ for _k in 0..VALUES_PER_PAGE {
+ let def_level = if rng.gen::<f32>() < null_density {
+ max_def_level - 1
+ } else {
+ max_def_level
+ };
+ if def_level == max_def_level {
+ // create the Float16 value
+ let value = f16::from_f32(rng.gen_range(min..max));
+ // Float16 in parquet is stored little-endian
+ let bytes = match column_desc.physical_type() {
+ Type::FIXED_LEN_BYTE_ARRAY => {
+ // Float16 annotates FIXED_LEN_BYTE_ARRAY(2)
+ assert_eq!(column_desc.type_length(), 2);
+ value.to_le_bytes().to_vec()
+ }
+ _ => unimplemented!(),
+ };
+ let value = T::T::from(bytes);
+ values.push(value);
+ }
+ def_levels.push(def_level);
+ }
+ let mut page_builder =
+ DataPageBuilderImpl::new(column_desc.clone(), values.len() as u32, true);
+ page_builder.add_rep_levels(max_rep_level, &rep_levels);
+ page_builder.add_def_levels(max_def_level, &def_levels);
+ page_builder.add_values::<T>(encoding, &values);
+ column_chunk_pages.push(page_builder.consume());
+ }
+ pages.push(column_chunk_pages);
+ }
+ InMemoryPageIterator::new(pages)
+}
+
// support byte array for decimal
fn build_encoded_decimal_bytes_page_iterator<T>(
column_desc: ColumnDescPtr,
@@ -494,6 +555,19 @@ fn create_primitive_array_reader(
}
}
+fn create_f16_by_bytes_reader(
+ page_iterator: impl PageIterator + 'static,
+ column_desc: ColumnDescPtr,
+) -> Box<dyn ArrayReader> {
+ let physical_type = column_desc.physical_type();
+ match physical_type {
+ Type::FIXED_LEN_BYTE_ARRAY => {
+ make_fixed_len_byte_array_reader(Box::new(page_iterator), column_desc, None).unwrap()
+ }
+ _ => unimplemented!(),
+ }
+}
+
fn create_decimal_by_bytes_reader(
page_iterator: impl PageIterator + 'static,
column_desc: ColumnDescPtr,
@@ -616,6 +690,131 @@ fn bench_byte_decimal<T>(
});
}
+fn bench_byte_stream_split_f16<T>(
+ group: &mut BenchmarkGroup<WallTime>,
+ mandatory_column_desc: &ColumnDescPtr,
+ optional_column_desc: &ColumnDescPtr,
+ min: f32,
+ max: f32,
+) where
+ T: parquet::data_type::DataType,
+ T::T: From<Vec<u8>>,
+{
+ let mut count: usize = 0;
+
+ // byte_stream_split encoded, no NULLs
+ let data = build_encoded_f16_bytes_page_iterator::<T>(
+ mandatory_column_desc.clone(),
+ 0.0,
+ Encoding::BYTE_STREAM_SPLIT,
+ min,
+ max,
+ );
+ group.bench_function("byte_stream_split encoded, mandatory, no NULLs", |b| {
+ b.iter(|| {
+ let array_reader =
+ create_f16_by_bytes_reader(data.clone(), mandatory_column_desc.clone());
+ count = bench_array_reader(array_reader);
+ });
+ assert_eq!(count, EXPECTED_VALUE_COUNT);
+ });
+
+ let data = build_encoded_f16_bytes_page_iterator::<T>(
+ optional_column_desc.clone(),
+ 0.0,
+ Encoding::BYTE_STREAM_SPLIT,
+ min,
+ max,
+ );
+ group.bench_function("byte_stream_split encoded, optional, no NULLs", |b| {
+ b.iter(|| {
+ let array_reader =
+ create_f16_by_bytes_reader(data.clone(), optional_column_desc.clone());
+ count = bench_array_reader(array_reader);
+ });
+ assert_eq!(count, EXPECTED_VALUE_COUNT);
+ });
+
+ let data = build_encoded_f16_bytes_page_iterator::<T>(
+ optional_column_desc.clone(),
+ 0.5,
+ Encoding::BYTE_STREAM_SPLIT,
+ min,
+ max,
+ );
+ group.bench_function("byte_stream_split encoded, optional, half NULLs", |b| {
+ b.iter(|| {
+ let array_reader =
+ create_f16_by_bytes_reader(data.clone(), optional_column_desc.clone());
+ count = bench_array_reader(array_reader);
+ });
+ assert_eq!(count, EXPECTED_VALUE_COUNT);
+ });
+}
+
+fn bench_byte_stream_split_decimal<T>(
+ group: &mut BenchmarkGroup<WallTime>,
+ mandatory_column_desc: &ColumnDescPtr,
+ optional_column_desc: &ColumnDescPtr,
+ min: i128,
+ max: i128,
+) where
+ T: parquet::data_type::DataType,
+ T::T: From<Vec<u8>>,
+{
+ let mut count: usize = 0;
+
+ // byte_stream_split encoded, no NULLs
+ let data = build_encoded_decimal_bytes_page_iterator::<T>(
+ mandatory_column_desc.clone(),
+ 0.0,
+ Encoding::BYTE_STREAM_SPLIT,
+ min,
+ max,
+ );
+ group.bench_function("byte_stream_split encoded, mandatory, no NULLs", |b| {
+ b.iter(|| {
+ let array_reader =
+ create_decimal_by_bytes_reader(data.clone(), mandatory_column_desc.clone());
+ count = bench_array_reader(array_reader);
+ });
+ assert_eq!(count, EXPECTED_VALUE_COUNT);
+ });
+
+ let data = build_encoded_decimal_bytes_page_iterator::<T>(
+ optional_column_desc.clone(),
+ 0.0,
+ Encoding::BYTE_STREAM_SPLIT,
+ min,
+ max,
+ );
+ group.bench_function("byte_stream_split encoded, optional, no NULLs", |b| {
+ b.iter(|| {
+ let array_reader =
+ create_decimal_by_bytes_reader(data.clone(), optional_column_desc.clone());
+ count = bench_array_reader(array_reader);
+ });
+ assert_eq!(count, EXPECTED_VALUE_COUNT);
+ });
+
+ // half null
+ let data = build_encoded_decimal_bytes_page_iterator::<T>(
+ optional_column_desc.clone(),
+ 0.5,
+ Encoding::BYTE_STREAM_SPLIT,
+ min,
+ max,
+ );
+ group.bench_function("byte_stream_split encoded, optional, half NULLs", |b| {
+ b.iter(|| {
+ let array_reader =
+ create_decimal_by_bytes_reader(data.clone(), optional_column_desc.clone());
+ count = bench_array_reader(array_reader);
+ });
+ assert_eq!(count, EXPECTED_VALUE_COUNT);
+ });
+}
+
fn bench_primitive<T>(
group: &mut BenchmarkGroup<WallTime>,
mandatory_column_desc: &ColumnDescPtr,
@@ -797,6 +996,35 @@ fn bench_primitive<T>(
});
}
+fn byte_stream_split_benches(c: &mut Criterion) {
+ let schema = build_test_schema();
+
+ let mut group = c.benchmark_group("arrow_array_reader/BYTE_STREAM_SPLIT/Decimal128Array");
+ let mandatory_decimal4_leaf_desc = schema.column(12);
+ let optional_decimal4_leaf_desc = schema.column(13);
+ bench_byte_stream_split_decimal::<FixedLenByteArrayType>(
+ &mut group,
+ &mandatory_decimal4_leaf_desc,
+ &optional_decimal4_leaf_desc,
+ // precision is 16: the max is 9999999999999999
+ 9999999999999000,
+ 9999999999999999,
+ );
+ group.finish();
+
+ let mut group = c.benchmark_group("arrow_array_reader/BYTE_STREAM_SPLIT/Float16Array");
+ let mandatory_f16_leaf_desc = schema.column(17);
+ let optional_f16_leaf_desc = schema.column(18);
+ bench_byte_stream_split_f16::<FixedLenByteArrayType>(
+ &mut group,
+ &mandatory_f16_leaf_desc,
+ &optional_f16_leaf_desc,
+ -1.0,
+ 1.0,
+ );
+ group.finish();
+}
+
fn decimal_benches(c: &mut Criterion) {
let schema = build_test_schema();
// parquet int32, logical type decimal(8,2)
@@ -1334,5 +1562,10 @@ fn add_benches(c: &mut Criterion) {
});
}
-criterion_group!(benches, add_benches, decimal_benches,);
+criterion_group!(
+ benches,
+ add_benches,
+ decimal_benches,
+ byte_stream_split_benches,
+);
criterion_main!(benches);
diff --git a/parquet/benches/encoding.rs b/parquet/benches/encoding.rs
index 80befe8dadff..bc18a49da2a4 100644
--- a/parquet/benches/encoding.rs
+++ b/parquet/benches/encoding.rs
@@ -16,15 +16,23 @@
// under the License.
use criterion::*;
+use half::f16;
use parquet::basic::Encoding;
-use parquet::data_type::{DataType, DoubleType, FloatType};
+use parquet::data_type::{
+ DataType, DoubleType, FixedLenByteArray, FixedLenByteArrayType, FloatType,
+};
use parquet::decoding::{get_decoder, Decoder};
use parquet::encoding::get_encoder;
use parquet::schema::types::{ColumnDescPtr, ColumnDescriptor, ColumnPath, Type};
use rand::prelude::*;
use std::sync::Arc;
-fn bench_typed<T: DataType>(c: &mut Criterion, values: &[T::T], encoding: Encoding) {
+fn bench_typed<T: DataType>(
+ c: &mut Criterion,
+ values: &[T::T],
+ encoding: Encoding,
+ type_length: i32,
+) {
let name = format!(
"dtype={}, encoding={:?}",
std::any::type_name::<T::T>(),
@@ -33,6 +41,7 @@ fn bench_typed<T: DataType>(c: &mut Criterion, values: &[T::T], encoding: Encodi
let column_desc_ptr = ColumnDescPtr::new(ColumnDescriptor::new(
Arc::new(
Type::primitive_type_builder("", T::get_physical_type())
+ .with_length(type_length)
.build()
.unwrap(),
),
@@ -68,15 +77,25 @@ fn criterion_benchmark(c: &mut Criterion) {
let mut rng = StdRng::seed_from_u64(0);
let n = 16 * 1024;
+ let mut f16s = Vec::new();
let mut f32s = Vec::new();
let mut f64s = Vec::new();
+ let mut d128s = Vec::new();
for _ in 0..n {
+ f16s.push(FixedLenByteArray::from(
+ f16::from_f32(rng.gen::<f32>()).to_le_bytes().to_vec(),
+ ));
f32s.push(rng.gen::<f32>());
f64s.push(rng.gen::<f64>());
+ d128s.push(FixedLenByteArray::from(
+ rng.gen::<i128>().to_be_bytes().to_vec(),
+ ));
}
- bench_typed::<FloatType>(c, &f32s, Encoding::BYTE_STREAM_SPLIT);
- bench_typed::<DoubleType>(c, &f64s, Encoding::BYTE_STREAM_SPLIT);
+ bench_typed::<FloatType>(c, &f32s, Encoding::BYTE_STREAM_SPLIT, 0);
+ bench_typed::<DoubleType>(c, &f64s, Encoding::BYTE_STREAM_SPLIT, 0);
+ bench_typed::<FixedLenByteArrayType>(c, &f16s, Encoding::BYTE_STREAM_SPLIT, 2);
+ bench_typed::<FixedLenByteArrayType>(c, &d128s, Encoding::BYTE_STREAM_SPLIT, 16);
}
criterion_group!(benches, criterion_benchmark);
|
diff --git a/parquet/src/util/test_common/page_util.rs b/parquet/src/util/test_common/page_util.rs
index 3db43aef0eec..a1709efa92b3 100644
--- a/parquet/src/util/test_common/page_util.rs
+++ b/parquet/src/util/test_common/page_util.rs
@@ -51,13 +51,14 @@ pub struct DataPageBuilderImpl {
rep_levels_byte_len: u32,
def_levels_byte_len: u32,
datapage_v2: bool,
+ type_width: i32,
}
impl DataPageBuilderImpl {
// `num_values` is the number of non-null values to put in the data page.
// `datapage_v2` flag is used to indicate if the generated data page should use V2
// format or not.
- pub fn new(_desc: ColumnDescPtr, num_values: u32, datapage_v2: bool) -> Self {
+ pub fn new(desc: ColumnDescPtr, num_values: u32, datapage_v2: bool) -> Self {
DataPageBuilderImpl {
encoding: None,
num_values,
@@ -65,6 +66,7 @@ impl DataPageBuilderImpl {
rep_levels_byte_len: 0,
def_levels_byte_len: 0,
datapage_v2,
+ type_width: desc.type_length(),
}
}
@@ -111,7 +113,7 @@ impl DataPageBuilder for DataPageBuilderImpl {
// Create test column descriptor.
let desc = {
let ty = SchemaType::primitive_type_builder("t", T::get_physical_type())
- .with_length(0)
+ .with_length(self.type_width)
.build()
.unwrap();
Arc::new(ColumnDescriptor::new(
|
Add benchmarks for `BYTE_STREAM_SPLIT` encoded Parquet `FIXED_LEN_BYTE_ARRAY` data
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
#6159 added support for using `BYTE_STREAM_SPLIT` with `FIXED_LEN_BYTE_ARRAY` primitive types. While some effort was put into optimizing the encoding path, the decoding path is largely unoptimized (and seemingly quite slow). It would be nice to have some benchmarks for the new encodings to guide future optimization efforts.
**Describe the solution you'd like**
Benchmarks for `Float16/FIXED_LEN_BYTE_ARRAY(2)` and `DECIMAL/FIXED_LEN_BYTE_ARRAY(16)` would be a good start for some likely to be used data types.
**Describe alternatives you've considered**
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
**Additional context**
See https://github.com/apache/arrow-rs/pull/6159#discussion_r1702333489 and following.
|
2024-08-06T22:53:02Z
|
52.2
|
678517018ddfd21b202a94df13b06dfa1ab8a378
|
|
apache/arrow-rs
| 6,190
|
apache__arrow-rs-6190
|
[
"6185"
] |
e6bd74b2c381e67a2b08e15fc23672f8317436c4
|
diff --git a/parquet/src/arrow/arrow_reader/statistics.rs b/parquet/src/arrow/arrow_reader/statistics.rs
index c42f92838c8c..369ea4a47e57 100644
--- a/parquet/src/arrow/arrow_reader/statistics.rs
+++ b/parquet/src/arrow/arrow_reader/statistics.rs
@@ -17,6 +17,8 @@
//! [`StatisticsConverter`] to convert statistics in parquet format to arrow [`ArrayRef`].
+/// Notice that all the corresponding tests are in
+/// `arrow-rs/parquet/tests/arrow_reader/statistics.rs`.
use crate::arrow::buffer::bit_util::sign_extend_be;
use crate::arrow::parquet_column;
use crate::data_type::{ByteArray, FixedLenByteArray};
@@ -1568,1130 +1570,3 @@ impl<'a> StatisticsConverter<'a> {
new_null_array(data_type, num_row_groups)
}
}
-
-#[cfg(test)]
-mod test {
- use super::*;
- use crate::arrow::arrow_reader::ArrowReaderBuilder;
- use crate::arrow::arrow_writer::ArrowWriter;
- use crate::file::metadata::{ParquetMetaData, RowGroupMetaData};
- use crate::file::properties::{EnabledStatistics, WriterProperties};
- use arrow::compute::kernels::cast_utils::Parser;
- use arrow::datatypes::{i256, Date32Type, Date64Type};
- use arrow::util::test_util::parquet_test_data;
- use arrow_array::{
- new_empty_array, new_null_array, Array, ArrayRef, BinaryArray, BinaryViewArray,
- BooleanArray, Date32Array, Date64Array, Decimal128Array, Decimal256Array, Float32Array,
- Float64Array, Int16Array, Int32Array, Int64Array, Int8Array, LargeBinaryArray, RecordBatch,
- StringArray, StringViewArray, StructArray, TimestampNanosecondArray,
- };
- use arrow_schema::{DataType, Field, SchemaRef};
- use bytes::Bytes;
- use std::path::PathBuf;
- use std::sync::Arc;
- // TODO error cases (with parquet statistics that are mismatched in expected type)
-
- #[test]
- fn roundtrip_empty() {
- let empty_bool_array = new_empty_array(&DataType::Boolean);
- Test {
- input: empty_bool_array.clone(),
- expected_min: empty_bool_array.clone(),
- expected_max: empty_bool_array.clone(),
- }
- .run()
- }
-
- #[test]
- fn roundtrip_bool() {
- Test {
- input: bool_array([
- // row group 1
- Some(true),
- None,
- Some(true),
- // row group 2
- Some(true),
- Some(false),
- None,
- // row group 3
- None,
- None,
- None,
- ]),
- expected_min: bool_array([Some(true), Some(false), None]),
- expected_max: bool_array([Some(true), Some(true), None]),
- }
- .run()
- }
-
- #[test]
- fn roundtrip_int32() {
- Test {
- input: i32_array([
- // row group 1
- Some(1),
- None,
- Some(3),
- // row group 2
- Some(0),
- Some(5),
- None,
- // row group 3
- None,
- None,
- None,
- ]),
- expected_min: i32_array([Some(1), Some(0), None]),
- expected_max: i32_array([Some(3), Some(5), None]),
- }
- .run()
- }
-
- #[test]
- fn roundtrip_int64() {
- Test {
- input: i64_array([
- // row group 1
- Some(1),
- None,
- Some(3),
- // row group 2
- Some(0),
- Some(5),
- None,
- // row group 3
- None,
- None,
- None,
- ]),
- expected_min: i64_array([Some(1), Some(0), None]),
- expected_max: i64_array(vec![Some(3), Some(5), None]),
- }
- .run()
- }
-
- #[test]
- fn roundtrip_f32() {
- Test {
- input: f32_array([
- // row group 1
- Some(1.0),
- None,
- Some(3.0),
- // row group 2
- Some(-1.0),
- Some(5.0),
- None,
- // row group 3
- None,
- None,
- None,
- ]),
- expected_min: f32_array([Some(1.0), Some(-1.0), None]),
- expected_max: f32_array([Some(3.0), Some(5.0), None]),
- }
- .run()
- }
-
- #[test]
- fn roundtrip_f64() {
- Test {
- input: f64_array([
- // row group 1
- Some(1.0),
- None,
- Some(3.0),
- // row group 2
- Some(-1.0),
- Some(5.0),
- None,
- // row group 3
- None,
- None,
- None,
- ]),
- expected_min: f64_array([Some(1.0), Some(-1.0), None]),
- expected_max: f64_array([Some(3.0), Some(5.0), None]),
- }
- .run()
- }
-
- #[test]
- fn roundtrip_timestamp() {
- Test {
- input: timestamp_seconds_array(
- [
- // row group 1
- Some(1),
- None,
- Some(3),
- // row group 2
- Some(9),
- Some(5),
- None,
- // row group 3
- None,
- None,
- None,
- ],
- None,
- ),
- expected_min: timestamp_seconds_array([Some(1), Some(5), None], None),
- expected_max: timestamp_seconds_array([Some(3), Some(9), None], None),
- }
- .run();
-
- Test {
- input: timestamp_milliseconds_array(
- [
- // row group 1
- Some(1),
- None,
- Some(3),
- // row group 2
- Some(9),
- Some(5),
- None,
- // row group 3
- None,
- None,
- None,
- ],
- None,
- ),
- expected_min: timestamp_milliseconds_array([Some(1), Some(5), None], None),
- expected_max: timestamp_milliseconds_array([Some(3), Some(9), None], None),
- }
- .run();
-
- Test {
- input: timestamp_microseconds_array(
- [
- // row group 1
- Some(1),
- None,
- Some(3),
- // row group 2
- Some(9),
- Some(5),
- None,
- // row group 3
- None,
- None,
- None,
- ],
- None,
- ),
- expected_min: timestamp_microseconds_array([Some(1), Some(5), None], None),
- expected_max: timestamp_microseconds_array([Some(3), Some(9), None], None),
- }
- .run();
-
- Test {
- input: timestamp_nanoseconds_array(
- [
- // row group 1
- Some(1),
- None,
- Some(3),
- // row group 2
- Some(9),
- Some(5),
- None,
- // row group 3
- None,
- None,
- None,
- ],
- None,
- ),
- expected_min: timestamp_nanoseconds_array([Some(1), Some(5), None], None),
- expected_max: timestamp_nanoseconds_array([Some(3), Some(9), None], None),
- }
- .run()
- }
-
- #[test]
- fn roundtrip_timestamp_timezoned() {
- Test {
- input: timestamp_seconds_array(
- [
- // row group 1
- Some(1),
- None,
- Some(3),
- // row group 2
- Some(9),
- Some(5),
- None,
- // row group 3
- None,
- None,
- None,
- ],
- Some("UTC"),
- ),
- expected_min: timestamp_seconds_array([Some(1), Some(5), None], Some("UTC")),
- expected_max: timestamp_seconds_array([Some(3), Some(9), None], Some("UTC")),
- }
- .run();
-
- Test {
- input: timestamp_milliseconds_array(
- [
- // row group 1
- Some(1),
- None,
- Some(3),
- // row group 2
- Some(9),
- Some(5),
- None,
- // row group 3
- None,
- None,
- None,
- ],
- Some("UTC"),
- ),
- expected_min: timestamp_milliseconds_array([Some(1), Some(5), None], Some("UTC")),
- expected_max: timestamp_milliseconds_array([Some(3), Some(9), None], Some("UTC")),
- }
- .run();
-
- Test {
- input: timestamp_microseconds_array(
- [
- // row group 1
- Some(1),
- None,
- Some(3),
- // row group 2
- Some(9),
- Some(5),
- None,
- // row group 3
- None,
- None,
- None,
- ],
- Some("UTC"),
- ),
- expected_min: timestamp_microseconds_array([Some(1), Some(5), None], Some("UTC")),
- expected_max: timestamp_microseconds_array([Some(3), Some(9), None], Some("UTC")),
- }
- .run();
-
- Test {
- input: timestamp_nanoseconds_array(
- [
- // row group 1
- Some(1),
- None,
- Some(3),
- // row group 2
- Some(9),
- Some(5),
- None,
- // row group 3
- None,
- None,
- None,
- ],
- Some("UTC"),
- ),
- expected_min: timestamp_nanoseconds_array([Some(1), Some(5), None], Some("UTC")),
- expected_max: timestamp_nanoseconds_array([Some(3), Some(9), None], Some("UTC")),
- }
- .run()
- }
-
- #[test]
- fn roundtrip_decimal() {
- Test {
- input: Arc::new(
- Decimal128Array::from(vec![
- // row group 1
- Some(100),
- None,
- Some(22000),
- // row group 2
- Some(500000),
- Some(330000),
- None,
- // row group 3
- None,
- None,
- None,
- ])
- .with_precision_and_scale(9, 2)
- .unwrap(),
- ),
- expected_min: Arc::new(
- Decimal128Array::from(vec![Some(100), Some(330000), None])
- .with_precision_and_scale(9, 2)
- .unwrap(),
- ),
- expected_max: Arc::new(
- Decimal128Array::from(vec![Some(22000), Some(500000), None])
- .with_precision_and_scale(9, 2)
- .unwrap(),
- ),
- }
- .run();
-
- Test {
- input: Arc::new(
- Decimal256Array::from(vec![
- // row group 1
- Some(i256::from(100)),
- None,
- Some(i256::from(22000)),
- // row group 2
- Some(i256::MAX),
- Some(i256::MIN),
- None,
- // row group 3
- None,
- None,
- None,
- ])
- .with_precision_and_scale(76, 76)
- .unwrap(),
- ),
- expected_min: Arc::new(
- Decimal256Array::from(vec![Some(i256::from(100)), Some(i256::MIN), None])
- .with_precision_and_scale(76, 76)
- .unwrap(),
- ),
- expected_max: Arc::new(
- Decimal256Array::from(vec![Some(i256::from(22000)), Some(i256::MAX), None])
- .with_precision_and_scale(76, 76)
- .unwrap(),
- ),
- }
- .run()
- }
-
- #[test]
- fn roundtrip_utf8() {
- Test {
- input: utf8_array([
- // row group 1
- Some("A"),
- None,
- Some("Q"),
- // row group 2
- Some("ZZ"),
- Some("AA"),
- None,
- // row group 3
- None,
- None,
- None,
- ]),
- expected_min: utf8_array([Some("A"), Some("AA"), None]),
- expected_max: utf8_array([Some("Q"), Some("ZZ"), None]),
- }
- .run()
- }
-
- #[test]
- fn roundtrip_string_view() {
- Test {
- input: string_view_array([
- // row group 1
- Some("A"),
- None,
- Some("Q"),
- // row group 2
- Some("ZZ"),
- Some("A_longerthan12"),
- None,
- // row group 3
- Some("A_longerthan12"),
- None,
- None,
- ]),
- expected_min: string_view_array([
- Some("A"),
- Some("A_longerthan12"),
- Some("A_longerthan12"),
- ]),
- expected_max: string_view_array([Some("Q"), Some("ZZ"), Some("A_longerthan12")]),
- }
- .run()
- }
-
- #[test]
- fn roundtrip_binary_view() {
- let input: Vec<Option<&[u8]>> = vec![
- // row group 1
- Some(b"A"),
- None,
- Some(b"Q"),
- // row group 2
- Some(b"ZZ"),
- Some(b"A_longerthan12"),
- None,
- // row group 3
- Some(b"A_longerthan12"),
- None,
- None,
- ];
-
- let expected_min: Vec<Option<&[u8]>> =
- vec![Some(b"A"), Some(b"A_longerthan12"), Some(b"A_longerthan12")];
- let expected_max: Vec<Option<&[u8]>> =
- vec![Some(b"Q"), Some(b"ZZ"), Some(b"A_longerthan12")];
-
- let array = binary_view_array(input);
-
- Test {
- input: array,
- expected_min: binary_view_array(expected_min),
- expected_max: binary_view_array(expected_max),
- }
- .run()
- }
-
- #[test]
- fn roundtrip_struct() {
- let mut test = Test {
- input: struct_array(vec![
- // row group 1
- (Some(true), Some(1)),
- (None, None),
- (Some(true), Some(3)),
- // row group 2
- (Some(true), Some(0)),
- (Some(false), Some(5)),
- (None, None),
- // row group 3
- (None, None),
- (None, None),
- (None, None),
- ]),
- expected_min: struct_array(vec![
- (Some(true), Some(1)),
- (Some(true), Some(0)),
- (None, None),
- ]),
-
- expected_max: struct_array(vec![
- (Some(true), Some(3)),
- (Some(true), Some(0)),
- (None, None),
- ]),
- };
- // Due to https://github.com/apache/datafusion/issues/8334,
- // statistics for struct arrays are not supported
- test.expected_min = new_null_array(test.input.data_type(), test.expected_min.len());
- test.expected_max = new_null_array(test.input.data_type(), test.expected_min.len());
- test.run()
- }
-
- #[test]
- fn roundtrip_binary() {
- Test {
- input: Arc::new(BinaryArray::from_opt_vec(vec![
- // row group 1
- Some(b"A"),
- None,
- Some(b"Q"),
- // row group 2
- Some(b"ZZ"),
- Some(b"AA"),
- None,
- // row group 3
- None,
- None,
- None,
- ])),
- expected_min: Arc::new(BinaryArray::from_opt_vec(vec![
- Some(b"A"),
- Some(b"AA"),
- None,
- ])),
- expected_max: Arc::new(BinaryArray::from_opt_vec(vec![
- Some(b"Q"),
- Some(b"ZZ"),
- None,
- ])),
- }
- .run()
- }
-
- #[test]
- fn roundtrip_date32() {
- Test {
- input: date32_array(vec![
- // row group 1
- Some("2021-01-01"),
- None,
- Some("2021-01-03"),
- // row group 2
- Some("2021-01-01"),
- Some("2021-01-05"),
- None,
- // row group 3
- None,
- None,
- None,
- ]),
- expected_min: date32_array(vec![Some("2021-01-01"), Some("2021-01-01"), None]),
- expected_max: date32_array(vec![Some("2021-01-03"), Some("2021-01-05"), None]),
- }
- .run()
- }
-
- #[test]
- fn roundtrip_date64() {
- Test {
- input: date64_array(vec![
- // row group 1
- Some("2021-01-01"),
- None,
- Some("2021-01-03"),
- // row group 2
- Some("2021-01-01"),
- Some("2021-01-05"),
- None,
- // row group 3
- None,
- None,
- None,
- ]),
- expected_min: date64_array(vec![Some("2021-01-01"), Some("2021-01-01"), None]),
- expected_max: date64_array(vec![Some("2021-01-03"), Some("2021-01-05"), None]),
- }
- .run()
- }
-
- #[test]
- fn roundtrip_large_binary_array() {
- let input: Vec<Option<&[u8]>> = vec![
- // row group 1
- Some(b"A"),
- None,
- Some(b"Q"),
- // row group 2
- Some(b"ZZ"),
- Some(b"AA"),
- None,
- // row group 3
- None,
- None,
- None,
- ];
-
- let expected_min: Vec<Option<&[u8]>> = vec![Some(b"A"), Some(b"AA"), None];
- let expected_max: Vec<Option<&[u8]>> = vec![Some(b"Q"), Some(b"ZZ"), None];
-
- Test {
- input: large_binary_array(input),
- expected_min: large_binary_array(expected_min),
- expected_max: large_binary_array(expected_max),
- }
- .run();
- }
-
- #[test]
- fn struct_and_non_struct() {
- // Ensures that statistics for an array that appears *after* a struct
- // array are not wrong
- let struct_col = struct_array(vec![
- // row group 1
- (Some(true), Some(1)),
- (None, None),
- (Some(true), Some(3)),
- ]);
- let int_col = i32_array([Some(100), Some(200), Some(300)]);
- let expected_min = i32_array([Some(100)]);
- let expected_max = i32_array(vec![Some(300)]);
-
- // use a name that shadows a name in the struct column
- match struct_col.data_type() {
- DataType::Struct(fields) => {
- assert_eq!(fields.get(1).unwrap().name(), "int_col")
- }
- _ => panic!("unexpected data type for struct column"),
- };
-
- let input_batch =
- RecordBatch::try_from_iter([("struct_col", struct_col), ("int_col", int_col)]).unwrap();
-
- let schema = input_batch.schema();
-
- let metadata = parquet_metadata(schema.clone(), input_batch);
- let parquet_schema = metadata.file_metadata().schema_descr();
-
- // read the int_col statistics
- let (idx, _) = parquet_column(parquet_schema, &schema, "int_col").unwrap();
- assert_eq!(idx, 2);
-
- let row_groups = metadata.row_groups();
- let converter = StatisticsConverter::try_new("int_col", &schema, parquet_schema).unwrap();
-
- let min = converter.row_group_mins(row_groups.iter()).unwrap();
- assert_eq!(
- &min,
- &expected_min,
- "Min. Statistics\n\n{}\n\n",
- DisplayStats(row_groups)
- );
-
- let max = converter.row_group_maxes(row_groups.iter()).unwrap();
- assert_eq!(
- &max,
- &expected_max,
- "Max. Statistics\n\n{}\n\n",
- DisplayStats(row_groups)
- );
- }
-
- #[test]
- fn nan_in_stats() {
- // /parquet-testing/data/nan_in_stats.parquet
- // row_groups: 1
- // "x": Double({min: Some(1.0), max: Some(NaN), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
-
- TestFile::new("nan_in_stats.parquet")
- .with_column(ExpectedColumn {
- name: "x",
- expected_min: Arc::new(Float64Array::from(vec![Some(1.0)])),
- expected_max: Arc::new(Float64Array::from(vec![Some(f64::NAN)])),
- })
- .run();
- }
-
- #[test]
- fn alltypes_plain() {
- // /parquet-testing/data/datapage_v1-snappy-compressed-checksum.parquet
- // row_groups: 1
- // (has no statistics)
- TestFile::new("alltypes_plain.parquet")
- // No column statistics should be read as NULL, but with the right type
- .with_column(ExpectedColumn {
- name: "id",
- expected_min: i32_array([None]),
- expected_max: i32_array([None]),
- })
- .with_column(ExpectedColumn {
- name: "bool_col",
- expected_min: bool_array([None]),
- expected_max: bool_array([None]),
- })
- .run();
- }
-
- #[test]
- fn alltypes_tiny_pages() {
- // /parquet-testing/data/alltypes_tiny_pages.parquet
- // row_groups: 1
- // "id": Int32({min: Some(0), max: Some(7299), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
- // "bool_col": Boolean({min: Some(false), max: Some(true), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
- // "tinyint_col": Int32({min: Some(0), max: Some(9), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
- // "smallint_col": Int32({min: Some(0), max: Some(9), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
- // "int_col": Int32({min: Some(0), max: Some(9), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
- // "bigint_col": Int64({min: Some(0), max: Some(90), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
- // "float_col": Float({min: Some(0.0), max: Some(9.9), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
- // "double_col": Double({min: Some(0.0), max: Some(90.89999999999999), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
- // "date_string_col": ByteArray({min: Some(ByteArray { data: "01/01/09" }), max: Some(ByteArray { data: "12/31/10" }), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
- // "string_col": ByteArray({min: Some(ByteArray { data: "0" }), max: Some(ByteArray { data: "9" }), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
- // "timestamp_col": Int96({min: None, max: None, distinct_count: None, null_count: 0, min_max_deprecated: true, min_max_backwards_compatible: true})
- // "year": Int32({min: Some(2009), max: Some(2010), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
- // "month": Int32({min: Some(1), max: Some(12), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
- TestFile::new("alltypes_tiny_pages.parquet")
- .with_column(ExpectedColumn {
- name: "id",
- expected_min: i32_array([Some(0)]),
- expected_max: i32_array([Some(7299)]),
- })
- .with_column(ExpectedColumn {
- name: "bool_col",
- expected_min: bool_array([Some(false)]),
- expected_max: bool_array([Some(true)]),
- })
- .with_column(ExpectedColumn {
- name: "tinyint_col",
- expected_min: i8_array([Some(0)]),
- expected_max: i8_array([Some(9)]),
- })
- .with_column(ExpectedColumn {
- name: "smallint_col",
- expected_min: i16_array([Some(0)]),
- expected_max: i16_array([Some(9)]),
- })
- .with_column(ExpectedColumn {
- name: "int_col",
- expected_min: i32_array([Some(0)]),
- expected_max: i32_array([Some(9)]),
- })
- .with_column(ExpectedColumn {
- name: "bigint_col",
- expected_min: i64_array([Some(0)]),
- expected_max: i64_array([Some(90)]),
- })
- .with_column(ExpectedColumn {
- name: "float_col",
- expected_min: f32_array([Some(0.0)]),
- expected_max: f32_array([Some(9.9)]),
- })
- .with_column(ExpectedColumn {
- name: "double_col",
- expected_min: f64_array([Some(0.0)]),
- expected_max: f64_array([Some(90.89999999999999)]),
- })
- .with_column(ExpectedColumn {
- name: "date_string_col",
- expected_min: utf8_array([Some("01/01/09")]),
- expected_max: utf8_array([Some("12/31/10")]),
- })
- .with_column(ExpectedColumn {
- name: "string_col",
- expected_min: utf8_array([Some("0")]),
- expected_max: utf8_array([Some("9")]),
- })
- // File has no min/max for timestamp_col
- .with_column(ExpectedColumn {
- name: "timestamp_col",
- expected_min: timestamp_nanoseconds_array([None], None),
- expected_max: timestamp_nanoseconds_array([None], None),
- })
- .with_column(ExpectedColumn {
- name: "year",
- expected_min: i32_array([Some(2009)]),
- expected_max: i32_array([Some(2010)]),
- })
- .with_column(ExpectedColumn {
- name: "month",
- expected_min: i32_array([Some(1)]),
- expected_max: i32_array([Some(12)]),
- })
- .run();
- }
-
- #[test]
- fn fixed_length_decimal_legacy() {
- // /parquet-testing/data/fixed_length_decimal_legacy.parquet
- // row_groups: 1
- // "value": FixedLenByteArray({min: Some(FixedLenByteArray(ByteArray { data: Some(ByteBufferPtr { data: b"\0\0\0\0\0\xc8" }) })), max: Some(FixedLenByteArray(ByteArray { data: "\0\0\0\0\t`" })), distinct_count: None, null_count: 0, min_max_deprecated: true, min_max_backwards_compatible: true})
-
- TestFile::new("fixed_length_decimal_legacy.parquet")
- .with_column(ExpectedColumn {
- name: "value",
- expected_min: Arc::new(
- Decimal128Array::from(vec![Some(200)])
- .with_precision_and_scale(13, 2)
- .unwrap(),
- ),
- expected_max: Arc::new(
- Decimal128Array::from(vec![Some(2400)])
- .with_precision_and_scale(13, 2)
- .unwrap(),
- ),
- })
- .run();
- }
-
- const ROWS_PER_ROW_GROUP: usize = 3;
-
- /// Writes the input batch into a parquet file, with every every three rows as
- /// their own row group, and compares the min/maxes to the expected values
- struct Test {
- input: ArrayRef,
- expected_min: ArrayRef,
- expected_max: ArrayRef,
- }
-
- impl Test {
- fn run(self) {
- let Self {
- input,
- expected_min,
- expected_max,
- } = self;
-
- let input_batch = RecordBatch::try_from_iter([("c1", input)]).unwrap();
-
- let schema = input_batch.schema();
-
- let metadata = parquet_metadata(schema.clone(), input_batch);
- let parquet_schema = metadata.file_metadata().schema_descr();
-
- let row_groups = metadata.row_groups();
-
- for field in schema.fields() {
- if field.data_type().is_nested() {
- let lookup = parquet_column(parquet_schema, &schema, field.name());
- assert_eq!(lookup, None);
- continue;
- }
-
- let converter =
- StatisticsConverter::try_new(field.name(), &schema, parquet_schema).unwrap();
-
- assert_eq!(converter.arrow_field, field.as_ref());
-
- let mins = converter.row_group_mins(row_groups.iter()).unwrap();
- assert_eq!(
- &mins,
- &expected_min,
- "Min. Statistics\n\n{}\n\n",
- DisplayStats(row_groups)
- );
-
- let maxes = converter.row_group_maxes(row_groups.iter()).unwrap();
- assert_eq!(
- &maxes,
- &expected_max,
- "Max. Statistics\n\n{}\n\n",
- DisplayStats(row_groups)
- );
- }
- }
- }
-
- /// Write the specified batches out as parquet and return the metadata
- fn parquet_metadata(schema: SchemaRef, batch: RecordBatch) -> Arc<ParquetMetaData> {
- let props = WriterProperties::builder()
- .set_statistics_enabled(EnabledStatistics::Chunk)
- .set_max_row_group_size(ROWS_PER_ROW_GROUP)
- .build();
-
- let mut buffer = Vec::new();
- let mut writer = ArrowWriter::try_new(&mut buffer, schema, Some(props)).unwrap();
- writer.write(&batch).unwrap();
- writer.close().unwrap();
-
- let reader = ArrowReaderBuilder::try_new(Bytes::from(buffer)).unwrap();
- reader.metadata().clone()
- }
-
- /// Formats the statistics nicely for display
- struct DisplayStats<'a>(&'a [RowGroupMetaData]);
- impl<'a> std::fmt::Display for DisplayStats<'a> {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let row_groups = self.0;
- writeln!(f, " row_groups: {}", row_groups.len())?;
- for rg in row_groups {
- for col in rg.columns() {
- if let Some(statistics) = col.statistics() {
- writeln!(f, " {}: {:?}", col.column_path(), statistics)?;
- }
- }
- }
- Ok(())
- }
- }
-
- struct ExpectedColumn {
- name: &'static str,
- expected_min: ArrayRef,
- expected_max: ArrayRef,
- }
-
- /// Reads statistics out of the specified, and compares them to the expected values
- struct TestFile {
- file_name: &'static str,
- expected_columns: Vec<ExpectedColumn>,
- }
-
- impl TestFile {
- fn new(file_name: &'static str) -> Self {
- Self {
- file_name,
- expected_columns: Vec::new(),
- }
- }
-
- fn with_column(mut self, column: ExpectedColumn) -> Self {
- self.expected_columns.push(column);
- self
- }
-
- /// Reads the specified parquet file and validates that the expected min/max
- /// values for the specified columns are as expected.
- fn run(self) {
- let path = PathBuf::from(parquet_test_data()).join(self.file_name);
- let file = std::fs::File::open(path).unwrap();
- let reader = ArrowReaderBuilder::try_new(file).unwrap();
- let arrow_schema = reader.schema();
- let metadata = reader.metadata();
- let row_groups = metadata.row_groups();
- let parquet_schema = metadata.file_metadata().schema_descr();
-
- for expected_column in self.expected_columns {
- let ExpectedColumn {
- name,
- expected_min,
- expected_max,
- } = expected_column;
-
- let converter =
- StatisticsConverter::try_new(name, arrow_schema, parquet_schema).unwrap();
-
- // test accessors on the converter
- let parquet_column_index =
- parquet_column(parquet_schema, arrow_schema, name).map(|(idx, _field)| idx);
- assert_eq!(converter.parquet_column_index(), parquet_column_index);
- assert_eq!(converter.arrow_field().name(), name);
-
- let actual_min = converter.row_group_mins(row_groups.iter()).unwrap();
- assert_eq!(&expected_min, &actual_min, "column {name}");
-
- let actual_max = converter.row_group_maxes(row_groups.iter()).unwrap();
- assert_eq!(&expected_max, &actual_max, "column {name}");
- }
- }
- }
-
- fn bool_array(input: impl IntoIterator<Item = Option<bool>>) -> ArrayRef {
- let array: BooleanArray = input.into_iter().collect();
- Arc::new(array)
- }
-
- fn i8_array(input: impl IntoIterator<Item = Option<i8>>) -> ArrayRef {
- let array: Int8Array = input.into_iter().collect();
- Arc::new(array)
- }
-
- fn i16_array(input: impl IntoIterator<Item = Option<i16>>) -> ArrayRef {
- let array: Int16Array = input.into_iter().collect();
- Arc::new(array)
- }
-
- fn i32_array(input: impl IntoIterator<Item = Option<i32>>) -> ArrayRef {
- let array: Int32Array = input.into_iter().collect();
- Arc::new(array)
- }
-
- fn i64_array(input: impl IntoIterator<Item = Option<i64>>) -> ArrayRef {
- let array: Int64Array = input.into_iter().collect();
- Arc::new(array)
- }
-
- fn f32_array(input: impl IntoIterator<Item = Option<f32>>) -> ArrayRef {
- let array: Float32Array = input.into_iter().collect();
- Arc::new(array)
- }
-
- fn f64_array(input: impl IntoIterator<Item = Option<f64>>) -> ArrayRef {
- let array: Float64Array = input.into_iter().collect();
- Arc::new(array)
- }
-
- fn timestamp_seconds_array(
- input: impl IntoIterator<Item = Option<i64>>,
- timzezone: Option<&str>,
- ) -> ArrayRef {
- let array: TimestampSecondArray = input.into_iter().collect();
- match timzezone {
- Some(tz) => Arc::new(array.with_timezone(tz)),
- None => Arc::new(array),
- }
- }
-
- fn timestamp_milliseconds_array(
- input: impl IntoIterator<Item = Option<i64>>,
- timzezone: Option<&str>,
- ) -> ArrayRef {
- let array: TimestampMillisecondArray = input.into_iter().collect();
- match timzezone {
- Some(tz) => Arc::new(array.with_timezone(tz)),
- None => Arc::new(array),
- }
- }
-
- fn timestamp_microseconds_array(
- input: impl IntoIterator<Item = Option<i64>>,
- timzezone: Option<&str>,
- ) -> ArrayRef {
- let array: TimestampMicrosecondArray = input.into_iter().collect();
- match timzezone {
- Some(tz) => Arc::new(array.with_timezone(tz)),
- None => Arc::new(array),
- }
- }
-
- fn timestamp_nanoseconds_array(
- input: impl IntoIterator<Item = Option<i64>>,
- timzezone: Option<&str>,
- ) -> ArrayRef {
- let array: TimestampNanosecondArray = input.into_iter().collect();
- match timzezone {
- Some(tz) => Arc::new(array.with_timezone(tz)),
- None => Arc::new(array),
- }
- }
-
- fn utf8_array<'a>(input: impl IntoIterator<Item = Option<&'a str>>) -> ArrayRef {
- let array: StringArray = input
- .into_iter()
- .map(|s| s.map(|s| s.to_string()))
- .collect();
- Arc::new(array)
- }
-
- // returns a struct array with columns "bool_col" and "int_col" with the specified values
- fn struct_array(input: Vec<(Option<bool>, Option<i32>)>) -> ArrayRef {
- let boolean: BooleanArray = input.iter().map(|(b, _i)| b).collect();
- let int: Int32Array = input.iter().map(|(_b, i)| i).collect();
-
- let nullable = true;
- let struct_array = StructArray::from(vec![
- (
- Arc::new(Field::new("bool_col", DataType::Boolean, nullable)),
- Arc::new(boolean) as ArrayRef,
- ),
- (
- Arc::new(Field::new("int_col", DataType::Int32, nullable)),
- Arc::new(int) as ArrayRef,
- ),
- ]);
- Arc::new(struct_array)
- }
-
- fn date32_array<'a>(input: impl IntoIterator<Item = Option<&'a str>>) -> ArrayRef {
- let array = Date32Array::from(
- input
- .into_iter()
- .map(|s| Date32Type::parse(s.unwrap_or_default()))
- .collect::<Vec<_>>(),
- );
- Arc::new(array)
- }
-
- fn date64_array<'a>(input: impl IntoIterator<Item = Option<&'a str>>) -> ArrayRef {
- let array = Date64Array::from(
- input
- .into_iter()
- .map(|s| Date64Type::parse(s.unwrap_or_default()))
- .collect::<Vec<_>>(),
- );
- Arc::new(array)
- }
-
- fn large_binary_array<'a>(input: impl IntoIterator<Item = Option<&'a [u8]>>) -> ArrayRef {
- let array = LargeBinaryArray::from(input.into_iter().collect::<Vec<Option<&[u8]>>>());
-
- Arc::new(array)
- }
-
- fn string_view_array<'a>(input: impl IntoIterator<Item = Option<&'a str>>) -> ArrayRef {
- let array: StringViewArray = input
- .into_iter()
- .map(|s| s.map(|s| s.to_string()))
- .collect();
-
- Arc::new(array)
- }
-
- fn binary_view_array(input: Vec<Option<&[u8]>>) -> ArrayRef {
- let array = BinaryViewArray::from(input.into_iter().collect::<Vec<Option<&[u8]>>>());
-
- Arc::new(array)
- }
-}
|
diff --git a/parquet-testing b/parquet-testing
index 1ba34478f535..9b48ff4f94dc 160000
--- a/parquet-testing
+++ b/parquet-testing
@@ -1,1 +1,1 @@
-Subproject commit 1ba34478f535c89382263c42c675a9af4f57f2dd
+Subproject commit 9b48ff4f94dc5e89592d46a119884dbb88100884
diff --git a/parquet/tests/arrow_reader/statistics.rs b/parquet/tests/arrow_reader/statistics.rs
index 75a73ac1309f..384be83d30e3 100644
--- a/parquet/tests/arrow_reader/statistics.rs
+++ b/parquet/tests/arrow_reader/statistics.rs
@@ -2195,3 +2195,430 @@ async fn test_column_non_existent() {
}
.run_with_schema(&schema);
}
+
+/// The following tests were initially in `arrow-rs/parquet/src/arrow/arrow_reader/statistics.rs`.
+/// Part of them was moved here to avoid confusion and duplication,
+/// including edge conditions and data file validations for only `row_group` statistics.
+#[cfg(test)]
+mod test {
+ use super::*;
+ use arrow::util::test_util::parquet_test_data;
+ use arrow_array::{
+ new_empty_array, ArrayRef, BooleanArray, Decimal128Array, Float32Array, Float64Array,
+ Int16Array, Int32Array, Int64Array, Int8Array, RecordBatch, StringArray,
+ TimestampNanosecondArray,
+ };
+ use arrow_schema::{DataType, SchemaRef, TimeUnit};
+ use bytes::Bytes;
+ use parquet::arrow::parquet_column;
+ use parquet::file::metadata::{ParquetMetaData, RowGroupMetaData};
+ use std::path::PathBuf;
+ use std::sync::Arc;
+ // TODO error cases (with parquet statistics that are mismatched in expected type)
+
+ #[test]
+ fn roundtrip_empty() {
+ let all_types = vec![
+ DataType::Null,
+ DataType::Boolean,
+ DataType::Int8,
+ DataType::Int16,
+ DataType::Int32,
+ DataType::Int64,
+ DataType::UInt8,
+ DataType::UInt16,
+ DataType::UInt32,
+ DataType::UInt64,
+ DataType::Float16,
+ DataType::Float32,
+ DataType::Float64,
+ DataType::Timestamp(TimeUnit::Second, None),
+ DataType::Date32,
+ DataType::Date64,
+ // Skip types that don't support statistics
+ // DataType::Time32(Second),
+ // DataType::Time64(Second),
+ // DataType::Duration(Second),
+ // DataType::Interval(IntervalUnit),
+ DataType::Binary,
+ DataType::FixedSizeBinary(0),
+ DataType::LargeBinary,
+ DataType::BinaryView,
+ DataType::Utf8,
+ DataType::LargeUtf8,
+ DataType::Utf8View,
+ // DataType::List(FieldRef),
+ // DataType::ListView(FieldRef),
+ // DataType::FixedSizeList(FieldRef, i32),
+ // DataType::LargeList(FieldRef),
+ // DataType::LargeListView(FieldRef),
+ // DataType::Struct(Fields),
+ // DataType::Union(UnionFields, UnionMode),
+ // DataType::Dictionary(Box<DataType>, Box<DataType>),
+ // DataType::Decimal128(u8, i8),
+ // DataType::Decimal256(u8, i8),
+ // DataType::Map(FieldRef, bool),
+ // DataType::RunEndEncoded(FieldRef, FieldRef),
+ ];
+ for data_type in all_types {
+ let empty_array = new_empty_array(&data_type);
+ Test {
+ input: empty_array.clone(),
+ expected_min: empty_array.clone(),
+ expected_max: empty_array,
+ }
+ .run();
+ }
+ }
+
+ #[test]
+ fn nan_in_stats() {
+ // /parquet-testing/data/nan_in_stats.parquet
+ // row_groups: 1
+ // "x": Double({min: Some(1.0), max: Some(NaN), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
+
+ TestFile::new("nan_in_stats.parquet")
+ .with_column(ExpectedColumn {
+ name: "x",
+ expected_min: Arc::new(Float64Array::from(vec![Some(1.0)])),
+ expected_max: Arc::new(Float64Array::from(vec![Some(f64::NAN)])),
+ })
+ .run();
+ }
+
+ #[test]
+ fn alltypes_plain() {
+ // /parquet-testing/data/datapage_v1-snappy-compressed-checksum.parquet
+ // row_groups: 1
+ // (has no statistics)
+ TestFile::new("alltypes_plain.parquet")
+ // No column statistics should be read as NULL, but with the right type
+ .with_column(ExpectedColumn {
+ name: "id",
+ expected_min: i32_array([None]),
+ expected_max: i32_array([None]),
+ })
+ .with_column(ExpectedColumn {
+ name: "bool_col",
+ expected_min: bool_array([None]),
+ expected_max: bool_array([None]),
+ })
+ .run();
+ }
+
+ #[test]
+ fn alltypes_tiny_pages() {
+ // /parquet-testing/data/alltypes_tiny_pages.parquet
+ // row_groups: 1
+ // "id": Int32({min: Some(0), max: Some(7299), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
+ // "bool_col": Boolean({min: Some(false), max: Some(true), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
+ // "tinyint_col": Int32({min: Some(0), max: Some(9), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
+ // "smallint_col": Int32({min: Some(0), max: Some(9), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
+ // "int_col": Int32({min: Some(0), max: Some(9), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
+ // "bigint_col": Int64({min: Some(0), max: Some(90), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
+ // "float_col": Float({min: Some(0.0), max: Some(9.9), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
+ // "double_col": Double({min: Some(0.0), max: Some(90.89999999999999), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
+ // "date_string_col": ByteArray({min: Some(ByteArray { data: "01/01/09" }), max: Some(ByteArray { data: "12/31/10" }), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
+ // "string_col": ByteArray({min: Some(ByteArray { data: "0" }), max: Some(ByteArray { data: "9" }), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
+ // "timestamp_col": Int96({min: None, max: None, distinct_count: None, null_count: 0, min_max_deprecated: true, min_max_backwards_compatible: true})
+ // "year": Int32({min: Some(2009), max: Some(2010), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
+ // "month": Int32({min: Some(1), max: Some(12), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
+ TestFile::new("alltypes_tiny_pages.parquet")
+ .with_column(ExpectedColumn {
+ name: "id",
+ expected_min: i32_array([Some(0)]),
+ expected_max: i32_array([Some(7299)]),
+ })
+ .with_column(ExpectedColumn {
+ name: "bool_col",
+ expected_min: bool_array([Some(false)]),
+ expected_max: bool_array([Some(true)]),
+ })
+ .with_column(ExpectedColumn {
+ name: "tinyint_col",
+ expected_min: i8_array([Some(0)]),
+ expected_max: i8_array([Some(9)]),
+ })
+ .with_column(ExpectedColumn {
+ name: "smallint_col",
+ expected_min: i16_array([Some(0)]),
+ expected_max: i16_array([Some(9)]),
+ })
+ .with_column(ExpectedColumn {
+ name: "int_col",
+ expected_min: i32_array([Some(0)]),
+ expected_max: i32_array([Some(9)]),
+ })
+ .with_column(ExpectedColumn {
+ name: "bigint_col",
+ expected_min: i64_array([Some(0)]),
+ expected_max: i64_array([Some(90)]),
+ })
+ .with_column(ExpectedColumn {
+ name: "float_col",
+ expected_min: f32_array([Some(0.0)]),
+ expected_max: f32_array([Some(9.9)]),
+ })
+ .with_column(ExpectedColumn {
+ name: "double_col",
+ expected_min: f64_array([Some(0.0)]),
+ expected_max: f64_array([Some(90.89999999999999)]),
+ })
+ .with_column(ExpectedColumn {
+ name: "date_string_col",
+ expected_min: utf8_array([Some("01/01/09")]),
+ expected_max: utf8_array([Some("12/31/10")]),
+ })
+ .with_column(ExpectedColumn {
+ name: "string_col",
+ expected_min: utf8_array([Some("0")]),
+ expected_max: utf8_array([Some("9")]),
+ })
+ // File has no min/max for timestamp_col
+ .with_column(ExpectedColumn {
+ name: "timestamp_col",
+ expected_min: timestamp_nanoseconds_array([None], None),
+ expected_max: timestamp_nanoseconds_array([None], None),
+ })
+ .with_column(ExpectedColumn {
+ name: "year",
+ expected_min: i32_array([Some(2009)]),
+ expected_max: i32_array([Some(2010)]),
+ })
+ .with_column(ExpectedColumn {
+ name: "month",
+ expected_min: i32_array([Some(1)]),
+ expected_max: i32_array([Some(12)]),
+ })
+ .run();
+ }
+
+ #[test]
+ fn fixed_length_decimal_legacy() {
+ // /parquet-testing/data/fixed_length_decimal_legacy.parquet
+ // row_groups: 1
+ // "value": FixedLenByteArray({min: Some(FixedLenByteArray(ByteArray { data: Some(ByteBufferPtr { data: b"\0\0\0\0\0\xc8" }) })), max: Some(FixedLenByteArray(ByteArray { data: "\0\0\0\0\t`" })), distinct_count: None, null_count: 0, min_max_deprecated: true, min_max_backwards_compatible: true})
+
+ TestFile::new("fixed_length_decimal_legacy.parquet")
+ .with_column(ExpectedColumn {
+ name: "value",
+ expected_min: Arc::new(
+ Decimal128Array::from(vec![Some(200)])
+ .with_precision_and_scale(13, 2)
+ .unwrap(),
+ ),
+ expected_max: Arc::new(
+ Decimal128Array::from(vec![Some(2400)])
+ .with_precision_and_scale(13, 2)
+ .unwrap(),
+ ),
+ })
+ .run();
+ }
+
+ const ROWS_PER_ROW_GROUP: usize = 3;
+
+ /// Writes the input batch into a parquet file, with every every three rows as
+ /// their own row group, and compares the min/maxes to the expected values
+ struct Test {
+ input: ArrayRef,
+ expected_min: ArrayRef,
+ expected_max: ArrayRef,
+ }
+
+ impl Test {
+ fn run(self) {
+ let Self {
+ input,
+ expected_min,
+ expected_max,
+ } = self;
+
+ let input_batch = RecordBatch::try_from_iter([("c1", input)]).unwrap();
+
+ let schema = input_batch.schema();
+
+ let metadata = parquet_metadata(schema.clone(), input_batch);
+ let parquet_schema = metadata.file_metadata().schema_descr();
+
+ let row_groups = metadata.row_groups();
+
+ for field in schema.fields() {
+ if field.data_type().is_nested() {
+ let lookup = parquet_column(parquet_schema, &schema, field.name());
+ assert_eq!(lookup, None);
+ continue;
+ }
+
+ let converter =
+ StatisticsConverter::try_new(field.name(), &schema, parquet_schema).unwrap();
+
+ assert_eq!(converter.arrow_field(), field.as_ref());
+
+ let mins = converter.row_group_mins(row_groups.iter()).unwrap();
+ assert_eq!(
+ &mins,
+ &expected_min,
+ "Min. Statistics\n\n{}\n\n",
+ DisplayStats(row_groups)
+ );
+
+ let maxes = converter.row_group_maxes(row_groups.iter()).unwrap();
+ assert_eq!(
+ &maxes,
+ &expected_max,
+ "Max. Statistics\n\n{}\n\n",
+ DisplayStats(row_groups)
+ );
+ }
+ }
+ }
+
+ /// Write the specified batches out as parquet and return the metadata
+ fn parquet_metadata(schema: SchemaRef, batch: RecordBatch) -> Arc<ParquetMetaData> {
+ let props = WriterProperties::builder()
+ .set_statistics_enabled(EnabledStatistics::Chunk)
+ .set_max_row_group_size(ROWS_PER_ROW_GROUP)
+ .build();
+
+ let mut buffer = Vec::new();
+ let mut writer = ArrowWriter::try_new(&mut buffer, schema, Some(props)).unwrap();
+ writer.write(&batch).unwrap();
+ writer.close().unwrap();
+
+ let reader = ArrowReaderBuilder::try_new(Bytes::from(buffer)).unwrap();
+ reader.metadata().clone()
+ }
+
+ /// Formats the statistics nicely for display
+ struct DisplayStats<'a>(&'a [RowGroupMetaData]);
+ impl<'a> std::fmt::Display for DisplayStats<'a> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let row_groups = self.0;
+ writeln!(f, " row_groups: {}", row_groups.len())?;
+ for rg in row_groups {
+ for col in rg.columns() {
+ if let Some(statistics) = col.statistics() {
+ writeln!(f, " {}: {:?}", col.column_path(), statistics)?;
+ }
+ }
+ }
+ Ok(())
+ }
+ }
+
+ struct ExpectedColumn {
+ name: &'static str,
+ expected_min: ArrayRef,
+ expected_max: ArrayRef,
+ }
+
+ /// Reads statistics out of the specified, and compares them to the expected values
+ struct TestFile {
+ file_name: &'static str,
+ expected_columns: Vec<ExpectedColumn>,
+ }
+
+ impl TestFile {
+ fn new(file_name: &'static str) -> Self {
+ Self {
+ file_name,
+ expected_columns: Vec::new(),
+ }
+ }
+
+ fn with_column(mut self, column: ExpectedColumn) -> Self {
+ self.expected_columns.push(column);
+ self
+ }
+
+ /// Reads the specified parquet file and validates that the expected min/max
+ /// values for the specified columns are as expected.
+ fn run(self) {
+ let path = PathBuf::from(parquet_test_data()).join(self.file_name);
+ let file = File::open(path).unwrap();
+ let reader = ArrowReaderBuilder::try_new(file).unwrap();
+ let arrow_schema = reader.schema();
+ let metadata = reader.metadata();
+ let row_groups = metadata.row_groups();
+ let parquet_schema = metadata.file_metadata().schema_descr();
+
+ for expected_column in self.expected_columns {
+ let ExpectedColumn {
+ name,
+ expected_min,
+ expected_max,
+ } = expected_column;
+
+ let converter =
+ StatisticsConverter::try_new(name, arrow_schema, parquet_schema).unwrap();
+
+ // test accessors on the converter
+ let parquet_column_index =
+ parquet_column(parquet_schema, arrow_schema, name).map(|(idx, _field)| idx);
+ assert_eq!(converter.parquet_column_index(), parquet_column_index);
+ assert_eq!(converter.arrow_field().name(), name);
+
+ let actual_min = converter.row_group_mins(row_groups.iter()).unwrap();
+ assert_eq!(&expected_min, &actual_min, "column {name}");
+
+ let actual_max = converter.row_group_maxes(row_groups.iter()).unwrap();
+ assert_eq!(&expected_max, &actual_max, "column {name}");
+ }
+ }
+ }
+
+ fn bool_array(input: impl IntoIterator<Item = Option<bool>>) -> ArrayRef {
+ let array: BooleanArray = input.into_iter().collect();
+ Arc::new(array)
+ }
+
+ fn i8_array(input: impl IntoIterator<Item = Option<i8>>) -> ArrayRef {
+ let array: Int8Array = input.into_iter().collect();
+ Arc::new(array)
+ }
+
+ fn i16_array(input: impl IntoIterator<Item = Option<i16>>) -> ArrayRef {
+ let array: Int16Array = input.into_iter().collect();
+ Arc::new(array)
+ }
+
+ fn i32_array(input: impl IntoIterator<Item = Option<i32>>) -> ArrayRef {
+ let array: Int32Array = input.into_iter().collect();
+ Arc::new(array)
+ }
+
+ fn i64_array(input: impl IntoIterator<Item = Option<i64>>) -> ArrayRef {
+ let array: Int64Array = input.into_iter().collect();
+ Arc::new(array)
+ }
+
+ fn f32_array(input: impl IntoIterator<Item = Option<f32>>) -> ArrayRef {
+ let array: Float32Array = input.into_iter().collect();
+ Arc::new(array)
+ }
+
+ fn f64_array(input: impl IntoIterator<Item = Option<f64>>) -> ArrayRef {
+ let array: Float64Array = input.into_iter().collect();
+ Arc::new(array)
+ }
+
+ fn timestamp_nanoseconds_array(
+ input: impl IntoIterator<Item = Option<i64>>,
+ timzezone: Option<&str>,
+ ) -> ArrayRef {
+ let array: TimestampNanosecondArray = input.into_iter().collect();
+ match timzezone {
+ Some(tz) => Arc::new(array.with_timezone(tz)),
+ None => Arc::new(array),
+ }
+ }
+
+ fn utf8_array<'a>(input: impl IntoIterator<Item = Option<&'a str>>) -> ArrayRef {
+ let array: StringArray = input
+ .into_iter()
+ .map(|s| s.map(|s| s.to_string()))
+ .collect();
+ Arc::new(array)
+ }
+}
diff --git a/testing b/testing
index e270341fb5f3..735ae7128d57 160000
--- a/testing
+++ b/testing
@@ -1,1 +1,1 @@
-Subproject commit e270341fb5f3ff785410e6286cc42898e9d6a99c
+Subproject commit 735ae7128d571398dd798d7ff004adebeb342883
|
Remove test duplication in parquet statistics tets
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
When adding additional support to the statistics converter as @Kev1n8 did in https://github.com/apache/arrow-rs/pull/6181 the presence of two sets of tests is quite confusing about where to add tests for the new test
There are tests in both
* https://github.com/apache/arrow-rs/blob/master/parquet/src/arrow/arrow_reader/statistics.rs
* https://github.com/apache/arrow-rs/blob/master/parquet/tests/arrow_reader/statistics.rs
**Describe the solution you'd like**
I would like to remove the rundant tests
**Describe alternatives you've considered**
I think the clearest alternateive is to move all the tests from https://github.com/apache/arrow-rs/blob/master/parquet/src/arrow/arrow_reader/statistics.rs to https://github.com/apache/arrow-rs/blob/master/parquet/tests/arrow_reader/statistics.rs
We should only move the non duplicated tests.
So that means something like:
- [ ] Leave a comment with a note about where the tests are in https://github.com/apache/arrow-rs/blob/master/parquet/src/arrow/arrow_reader/statistics.rs
- [ ] Keep edge condition tests https://github.com/apache/arrow-rs/blob/f2de2cd3c8a8496e1f96e58b50786227bfe915f7/parquet/src/arrow/arrow_reader/statistics.rs#L1513-L1522
- [ ] Remove tests in https://github.com/apache/arrow-rs/blob/f2de2cd3c8a8496e1f96e58b50786227bfe915f7/parquet/src/arrow/arrow_reader/statistics.rs#L1548-L2113 that have corresponding coverage
- [ ] Keep data file validation: https://github.com/apache/arrow-rs/blob/f2de2cd3c8a8496e1f96e58b50786227bfe915f7/parquet/src/arrow/arrow_reader/statistics.rs#L2115-L2235
- [ ] Port fixed length decimal legacy: https://github.com/apache/arrow-rs/blob/f2de2cd3c8a8496e1f96e58b50786227bfe915f7/parquet/src/arrow/arrow_reader/statistics.rs#L2237-L2258
**Additional context**
This duplication is a historical artifact of how this code was developed in DataFusion and then it got brought over when @efredine ported the work in https://github.com/apache/arrow-rs/pull/6046
|
take
|
2024-08-03T18:36:40Z
|
52.2
|
678517018ddfd21b202a94df13b06dfa1ab8a378
|
apache/arrow-rs
| 6,181
|
apache__arrow-rs-6181
|
[
"6164"
] |
ede5a64628e0a0df3d900cc0df17649f6bed9af0
|
diff --git a/parquet/src/arrow/arrow_reader/statistics.rs b/parquet/src/arrow/arrow_reader/statistics.rs
index 6a1434bce906..c42f92838c8c 100644
--- a/parquet/src/arrow/arrow_reader/statistics.rs
+++ b/parquet/src/arrow/arrow_reader/statistics.rs
@@ -26,7 +26,8 @@ use crate::file::page_index::index::{Index, PageIndex};
use crate::file::statistics::Statistics as ParquetStatistics;
use crate::schema::types::SchemaDescriptor;
use arrow_array::builder::{
- BooleanBuilder, FixedSizeBinaryBuilder, LargeStringBuilder, StringBuilder,
+ BinaryViewBuilder, BooleanBuilder, FixedSizeBinaryBuilder, LargeStringBuilder, StringBuilder,
+ StringViewBuilder,
};
use arrow_array::{
new_empty_array, new_null_array, ArrayRef, BinaryArray, BooleanArray, Date32Array, Date64Array,
@@ -446,14 +447,43 @@ macro_rules! get_statistics {
},
DataType::Dictionary(_, value_type) => {
[<$stat_type_prefix:lower _ statistics>](value_type, $iterator)
+ },
+ DataType::Utf8View => {
+ let iterator = [<$stat_type_prefix ByteArrayStatsIterator>]::new($iterator);
+ let mut builder = StringViewBuilder::new();
+ for x in iterator {
+ let Some(x) = x else {
+ builder.append_null(); // no statistics value
+ continue;
+ };
+
+ let Ok(x) = std::str::from_utf8(x) else {
+ builder.append_null();
+ continue;
+ };
+
+ builder.append_value(x);
+ }
+ Ok(Arc::new(builder.finish()))
+ },
+ DataType::BinaryView => {
+ let iterator = [<$stat_type_prefix ByteArrayStatsIterator>]::new($iterator);
+ let mut builder = BinaryViewBuilder::new();
+ for x in iterator {
+ let Some(x) = x else {
+ builder.append_null(); // no statistics value
+ continue;
+ };
+
+ builder.append_value(x);
+ }
+ Ok(Arc::new(builder.finish()))
}
DataType::Map(_,_) |
DataType::Duration(_) |
DataType::Interval(_) |
DataType::Null |
- DataType::BinaryView |
- DataType::Utf8View |
DataType::List(_) |
DataType::ListView(_) |
DataType::FixedSizeList(_, _) |
@@ -919,7 +949,7 @@ macro_rules! get_data_page_statistics {
}
})
},
- Some(DataType::FixedSizeBinary(size)) => {
+ Some(DataType::FixedSizeBinary(size)) => {
let mut builder = FixedSizeBinaryBuilder::new(*size);
let iterator = [<$stat_type_prefix FixedLenByteArrayDataPageStatsIterator>]::new($iterator);
for x in iterator {
@@ -943,7 +973,58 @@ macro_rules! get_data_page_statistics {
}
Ok(Arc::new(builder.finish()))
},
- _ => unimplemented!()
+ Some(DataType::Utf8View) => {
+ let mut builder = StringViewBuilder::new();
+ let iterator = [<$stat_type_prefix ByteArrayDataPageStatsIterator>]::new($iterator);
+ for x in iterator {
+ for x in x.into_iter() {
+ let Some(x) = x else {
+ builder.append_null(); // no statistics value
+ continue;
+ };
+
+ let Ok(x) = std::str::from_utf8(x.data()) else {
+ builder.append_null();
+ continue;
+ };
+
+ builder.append_value(x);
+ }
+ }
+ Ok(Arc::new(builder.finish()))
+ },
+ Some(DataType::BinaryView) => {
+ let mut builder = BinaryViewBuilder::new();
+ let iterator = [<$stat_type_prefix ByteArrayDataPageStatsIterator>]::new($iterator);
+ for x in iterator {
+ for x in x.into_iter() {
+ let Some(x) = x else {
+ builder.append_null(); // no statistics value
+ continue;
+ };
+
+ builder.append_value(x);
+ }
+ }
+ Ok(Arc::new(builder.finish()))
+ },
+ Some(DataType::Null) |
+ Some(DataType::Duration(_)) |
+ Some(DataType::Interval(_)) |
+ Some(DataType::List(_)) |
+ Some(DataType::ListView(_)) |
+ Some(DataType::FixedSizeList(_, _)) |
+ Some(DataType::LargeList(_)) |
+ Some(DataType::LargeListView(_)) |
+ Some(DataType::Struct(_)) |
+ Some(DataType::Union(_, _)) |
+ Some(DataType::Map(_, _)) |
+ Some(DataType::RunEndEncoded(_, _)) => {
+ let len = $iterator.count();
+ // don't know how to extract statistics, so return a null array
+ Ok(new_null_array($data_type.unwrap(), len))
+ },
+ None => unimplemented!() // not sure how to handle this
}
}
}
@@ -1499,10 +1580,10 @@ mod test {
use arrow::datatypes::{i256, Date32Type, Date64Type};
use arrow::util::test_util::parquet_test_data;
use arrow_array::{
- new_empty_array, new_null_array, Array, ArrayRef, BinaryArray, BooleanArray, Date32Array,
- Date64Array, Decimal128Array, Decimal256Array, Float32Array, Float64Array, Int16Array,
- Int32Array, Int64Array, Int8Array, LargeBinaryArray, RecordBatch, StringArray, StructArray,
- TimestampNanosecondArray,
+ new_empty_array, new_null_array, Array, ArrayRef, BinaryArray, BinaryViewArray,
+ BooleanArray, Date32Array, Date64Array, Decimal128Array, Decimal256Array, Float32Array,
+ Float64Array, Int16Array, Int32Array, Int64Array, Int8Array, LargeBinaryArray, RecordBatch,
+ StringArray, StringViewArray, StructArray, TimestampNanosecondArray,
};
use arrow_schema::{DataType, Field, SchemaRef};
use bytes::Bytes;
@@ -1916,6 +1997,65 @@ mod test {
.run()
}
+ #[test]
+ fn roundtrip_string_view() {
+ Test {
+ input: string_view_array([
+ // row group 1
+ Some("A"),
+ None,
+ Some("Q"),
+ // row group 2
+ Some("ZZ"),
+ Some("A_longerthan12"),
+ None,
+ // row group 3
+ Some("A_longerthan12"),
+ None,
+ None,
+ ]),
+ expected_min: string_view_array([
+ Some("A"),
+ Some("A_longerthan12"),
+ Some("A_longerthan12"),
+ ]),
+ expected_max: string_view_array([Some("Q"), Some("ZZ"), Some("A_longerthan12")]),
+ }
+ .run()
+ }
+
+ #[test]
+ fn roundtrip_binary_view() {
+ let input: Vec<Option<&[u8]>> = vec![
+ // row group 1
+ Some(b"A"),
+ None,
+ Some(b"Q"),
+ // row group 2
+ Some(b"ZZ"),
+ Some(b"A_longerthan12"),
+ None,
+ // row group 3
+ Some(b"A_longerthan12"),
+ None,
+ None,
+ ];
+
+ let expected_min: Vec<Option<&[u8]>> =
+ vec![Some(b"A"), Some(b"A_longerthan12"), Some(b"A_longerthan12")];
+ let expected_max: Vec<Option<&[u8]>> =
+ vec![Some(b"Q"), Some(b"ZZ"), Some(b"A_longerthan12")];
+
+ let array = binary_view_array(input);
+
+ Test {
+ input: array,
+ expected_min: binary_view_array(expected_min),
+ expected_max: binary_view_array(expected_max),
+ }
+ .run()
+ }
+
#[test]
fn roundtrip_struct() {
let mut test = Test {
@@ -2539,4 +2679,19 @@ mod test {
Arc::new(array)
}
+
+ fn string_view_array<'a>(input: impl IntoIterator<Item = Option<&'a str>>) -> ArrayRef {
+ let array: StringViewArray = input
+ .into_iter()
+ .map(|s| s.map(|s| s.to_string()))
+ .collect();
+
+ Arc::new(array)
+ }
+
+ fn binary_view_array(input: Vec<Option<&[u8]>>) -> ArrayRef {
+ let array = BinaryViewArray::from(input.into_iter().collect::<Vec<Option<&[u8]>>>());
+
+ Arc::new(array)
+ }
}
|
diff --git a/parquet/tests/arrow_reader/mod.rs b/parquet/tests/arrow_reader/mod.rs
index 4f63a505488c..7e979dcf3ec0 100644
--- a/parquet/tests/arrow_reader/mod.rs
+++ b/parquet/tests/arrow_reader/mod.rs
@@ -17,13 +17,13 @@
use arrow_array::types::{Int32Type, Int8Type};
use arrow_array::{
- Array, ArrayRef, BinaryArray, BooleanArray, Date32Array, Date64Array, Decimal128Array,
- Decimal256Array, DictionaryArray, FixedSizeBinaryArray, Float16Array, Float32Array,
- Float64Array, Int16Array, Int32Array, Int64Array, Int8Array, LargeBinaryArray,
- LargeStringArray, RecordBatch, StringArray, StructArray, Time32MillisecondArray,
- Time32SecondArray, Time64MicrosecondArray, Time64NanosecondArray, TimestampMicrosecondArray,
- TimestampMillisecondArray, TimestampNanosecondArray, TimestampSecondArray, UInt16Array,
- UInt32Array, UInt64Array, UInt8Array,
+ Array, ArrayRef, BinaryArray, BinaryViewArray, BooleanArray, Date32Array, Date64Array,
+ Decimal128Array, Decimal256Array, DictionaryArray, FixedSizeBinaryArray, Float16Array,
+ Float32Array, Float64Array, Int16Array, Int32Array, Int64Array, Int8Array, LargeBinaryArray,
+ LargeStringArray, RecordBatch, StringArray, StringViewArray, StructArray,
+ Time32MillisecondArray, Time32SecondArray, Time64MicrosecondArray, Time64NanosecondArray,
+ TimestampMicrosecondArray, TimestampMillisecondArray, TimestampNanosecondArray,
+ TimestampSecondArray, UInt16Array, UInt32Array, UInt64Array, UInt8Array,
};
use arrow_buffer::i256;
use arrow_schema::{DataType, Field, Schema, TimeUnit};
@@ -88,6 +88,8 @@ enum Scenario {
PeriodsInColumnNames,
StructArray,
UTF8,
+ UTF8View,
+ BinaryView,
}
fn make_boolean_batch(v: Vec<Option<bool>>) -> RecordBatch {
@@ -589,6 +591,16 @@ fn make_utf8_batch(value: Vec<Option<&str>>) -> RecordBatch {
.unwrap()
}
+fn make_utf8_view_batch(value: Vec<Option<&str>>) -> RecordBatch {
+ let utf8_view = StringViewArray::from(value);
+ RecordBatch::try_from_iter(vec![("utf8_view", Arc::new(utf8_view) as _)]).unwrap()
+}
+
+fn make_binary_view_batch(value: Vec<Option<&[u8]>>) -> RecordBatch {
+ let binary_view = BinaryViewArray::from(value);
+ RecordBatch::try_from_iter(vec![("binary_view", Arc::new(binary_view) as _)]).unwrap()
+}
+
fn make_dict_batch() -> RecordBatch {
let values = [
Some("abc"),
@@ -972,6 +984,35 @@ fn create_data_batch(scenario: Scenario) -> Vec<RecordBatch> {
make_utf8_batch(vec![Some("e"), Some("f"), Some("g"), Some("h"), Some("i")]),
]
}
+ Scenario::UTF8View => {
+ // Make utf8_view batch including string length <12 and >12 bytes
+ // as the internal representation of StringView is differed for strings
+ // shorter and longer than that length
+ vec![
+ make_utf8_view_batch(vec![Some("a"), Some("b"), Some("c"), Some("d"), None]),
+ make_utf8_view_batch(vec![Some("a"), Some("e_longerthan12"), None, None, None]),
+ make_utf8_view_batch(vec![
+ Some("e_longerthan12"),
+ Some("f_longerthan12"),
+ Some("g_longerthan12"),
+ Some("h_longerthan12"),
+ Some("i_longerthan12"),
+ ]),
+ ]
+ }
+ Scenario::BinaryView => {
+ vec![
+ make_binary_view_batch(vec![Some(b"a"), Some(b"b"), Some(b"c"), Some(b"d"), None]),
+ make_binary_view_batch(vec![Some(b"a"), Some(b"e_longerthan12"), None, None, None]),
+ make_binary_view_batch(vec![
+ Some(b"e_longerthan12"),
+ Some(b"f_longerthan12"),
+ Some(b"g_longerthan12"),
+ Some(b"h_longerthan12"),
+ Some(b"i_longerthan12"),
+ ]),
+ ]
+ }
}
}
diff --git a/parquet/tests/arrow_reader/statistics.rs b/parquet/tests/arrow_reader/statistics.rs
index 5702967ffdf4..75a73ac1309f 100644
--- a/parquet/tests/arrow_reader/statistics.rs
+++ b/parquet/tests/arrow_reader/statistics.rs
@@ -29,11 +29,11 @@ use arrow::datatypes::{
TimestampNanosecondType, TimestampSecondType,
};
use arrow_array::{
- make_array, new_null_array, Array, ArrayRef, BinaryArray, BooleanArray, Date32Array,
- Date64Array, Decimal128Array, Decimal256Array, FixedSizeBinaryArray, Float16Array,
+ make_array, new_null_array, Array, ArrayRef, BinaryArray, BinaryViewArray, BooleanArray,
+ Date32Array, Date64Array, Decimal128Array, Decimal256Array, FixedSizeBinaryArray, Float16Array,
Float32Array, Float64Array, Int16Array, Int32Array, Int64Array, Int8Array, LargeBinaryArray,
- LargeStringArray, RecordBatch, StringArray, Time32MillisecondArray, Time32SecondArray,
- Time64MicrosecondArray, Time64NanosecondArray, TimestampMicrosecondArray,
+ LargeStringArray, RecordBatch, StringArray, StringViewArray, Time32MillisecondArray,
+ Time32SecondArray, Time64MicrosecondArray, Time64NanosecondArray, TimestampMicrosecondArray,
TimestampMillisecondArray, TimestampNanosecondArray, TimestampSecondArray, UInt16Array,
UInt32Array, UInt64Array, UInt8Array,
};
@@ -2059,6 +2059,60 @@ async fn test_utf8() {
.run();
}
+// UTF8View
+#[tokio::test]
+async fn test_utf8_view() {
+ let reader = TestReader {
+ scenario: Scenario::UTF8View,
+ row_per_group: 5,
+ }
+ .build()
+ .await;
+
+ // test for utf8_view
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(StringViewArray::from(vec!["a", "a", "e_longerthan12"])),
+ expected_max: Arc::new(StringViewArray::from(vec![
+ "d",
+ "e_longerthan12",
+ "i_longerthan12",
+ ])),
+ expected_null_counts: UInt64Array::from(vec![1, 3, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 5, 5])),
+ column_name: "utf8_view",
+ check: Check::Both,
+ }
+ .run()
+}
+
+// BinaryView
+#[tokio::test]
+async fn test_binary_view() {
+ let reader = TestReader {
+ scenario: Scenario::BinaryView,
+ row_per_group: 5,
+ }
+ .build()
+ .await;
+
+ let expected_min: Vec<Option<&[u8]>> = vec![Some(b"a"), Some(b"a"), Some(b"e_longerthan12")];
+ let expected_max: Vec<Option<&[u8]>> =
+ vec![Some(b"d"), Some(b"e_longerthan12"), Some(b"i_longerthan12")];
+
+ // test for utf8_view
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(BinaryViewArray::from(expected_min)),
+ expected_max: Arc::new(BinaryViewArray::from(expected_max)),
+ expected_null_counts: UInt64Array::from(vec![1, 3, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 5, 5])),
+ column_name: "binary_view",
+ check: Check::Both,
+ }
+ .run()
+}
+
////// Files with missing statistics ///////
#[tokio::test]
|
Add support for `StringView` and `BinaryView` statistics in `StatisticsConverter`
Part of https://github.com/apache/arrow-rs/issues/6163
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
@efredine recently added support for extracting statistics from parquet files as arrays in https://github.com/apache/arrow-rs/pull/6046 using `StatisticsConverter`
During development we have also added support for `StringViewArray` and `BinaryViewArray` in https://github.com/apache/arrow-rs/issues/5374
Currently there is no way to read StringViewArray and BinaryViewArray statistics and it actually panics if you try to read data page level statistics as I found on https://github.com/apache/datafusion/pull/11723
```
not implemented
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
External error: query failed: DataFusion error: Join Error
caused by
```
**Describe the solution you'd like**
1. Implement the ability to extract parquet statistics as `StringView` and `BinaryView`
2. Remove the panic caused by `unimplemented!` at https://github.com/apache/arrow-rs/blob/2905ce6796cad396241fc50164970dbf1237440a/parquet/src/arrow/arrow_reader/statistics.rs#L946
The code is in https://github.com/apache/arrow-rs/blob/master/parquet/src/arrow/arrow_reader/statistics.rs
**Describe alternatives you've considered**
You can avoid the panic by following the model of this: https://github.com/apache/arrow-rs/blob/2905ce6796cad396241fc50164970dbf1237440a/parquet/src/arrow/arrow_reader/statistics.rs#L465-L467
Then, you can probably write a test followig the model of utf8 and binary
https://github.com/apache/arrow-rs/blob/2905ce6796cad396241fc50164970dbf1237440a/parquet/src/arrow/arrow_reader/statistics.rs#L1897-L1917
https://github.com/apache/arrow-rs/blob/2905ce6796cad396241fc50164970dbf1237440a/parquet/src/arrow/arrow_reader/statistics.rs#L1956-L1984
And then implement the missing pieces of code (use `StringViewBuilder` / `BinaryViewBuilder` instead of `StringBuilder` / `BinaryBuilder`)
I have a hacky version in https://github.com/apache/datafusion/pull/11753 that looks something like
```rust
DataType::Utf8View => {
let iterator = [<$stat_type_prefix ByteArrayStatsIterator>]::new($iterator);
let mut builder = StringViewBuilder::new();
for x in iterator {
let Some(x) = x else {
builder.append_null(); // no statistics value
continue;
};
let Ok(x) = std::str::from_utf8(x) else {
log::debug!("Utf8 statistics is a non-UTF8 value, ignoring it.");
builder.append_null();
continue;
};
builder.append_value(x);
}
Ok(Arc::new(builder.finish()))
},
```
**Additional context**
|
I think this would be a good first issue as it has a detailed description and existing patterns to follow
take
Can i work on this issue?
|
2024-08-02T09:39:07Z
|
52.2
|
678517018ddfd21b202a94df13b06dfa1ab8a378
|
apache/arrow-rs
| 6,159
|
apache__arrow-rs-6159
|
[
"6048"
] |
bf1a9ec7faa1e271681317572098c4d83297c3a9
|
diff --git a/parquet/benches/encoding.rs b/parquet/benches/encoding.rs
index bdbca3567a2b..80befe8dadff 100644
--- a/parquet/benches/encoding.rs
+++ b/parquet/benches/encoding.rs
@@ -30,30 +30,30 @@ fn bench_typed<T: DataType>(c: &mut Criterion, values: &[T::T], encoding: Encodi
std::any::type_name::<T::T>(),
encoding
);
+ let column_desc_ptr = ColumnDescPtr::new(ColumnDescriptor::new(
+ Arc::new(
+ Type::primitive_type_builder("", T::get_physical_type())
+ .build()
+ .unwrap(),
+ ),
+ 0,
+ 0,
+ ColumnPath::new(vec![]),
+ ));
c.bench_function(&format!("encoding: {}", name), |b| {
b.iter(|| {
- let mut encoder = get_encoder::<T>(encoding).unwrap();
+ let mut encoder = get_encoder::<T>(encoding, &column_desc_ptr).unwrap();
encoder.put(values).unwrap();
encoder.flush_buffer().unwrap();
});
});
- let mut encoder = get_encoder::<T>(encoding).unwrap();
+ let mut encoder = get_encoder::<T>(encoding, &column_desc_ptr).unwrap();
encoder.put(values).unwrap();
let encoded = encoder.flush_buffer().unwrap();
println!("{} encoded as {} bytes", name, encoded.len(),);
let mut buffer = vec![T::T::default(); values.len()];
- let column_desc_ptr = ColumnDescPtr::new(ColumnDescriptor::new(
- Arc::new(
- Type::primitive_type_builder("", T::get_physical_type())
- .build()
- .unwrap(),
- ),
- 0,
- 0,
- ColumnPath::new(vec![]),
- ));
c.bench_function(&format!("decoding: {}", name), |b| {
b.iter(|| {
let mut decoder: Box<dyn Decoder<T>> =
diff --git a/parquet/src/arrow/array_reader/fixed_len_byte_array.rs b/parquet/src/arrow/array_reader/fixed_len_byte_array.rs
index a9159bb47125..8098f3240a3c 100644
--- a/parquet/src/arrow/array_reader/fixed_len_byte_array.rs
+++ b/parquet/src/arrow/array_reader/fixed_len_byte_array.rs
@@ -341,6 +341,10 @@ impl ColumnValueDecoder for ValueDecoder {
Encoding::DELTA_BYTE_ARRAY => Decoder::Delta {
decoder: DeltaByteArrayDecoder::new(data)?,
},
+ Encoding::BYTE_STREAM_SPLIT => Decoder::ByteStreamSplit {
+ buf: data,
+ offset: 0,
+ },
_ => {
return Err(general_err!(
"unsupported encoding for fixed length byte array: {}",
@@ -400,6 +404,20 @@ impl ColumnValueDecoder for ValueDecoder {
Ok(())
})
}
+ Decoder::ByteStreamSplit { buf, offset } => {
+ // we have n=`byte_length` streams of length `buf.len/byte_length`
+ // to read value i, we need the i'th byte from each of the streams
+ // so `offset` should be the value offset, not the byte offset
+ let total_values = buf.len() / self.byte_length;
+ let to_read = num_values.min(total_values - *offset);
+ out.buffer.reserve(to_read * self.byte_length);
+
+ // now read the n streams and reassemble values into the output buffer
+ read_byte_stream_split(&mut out.buffer, buf, *offset, to_read, self.byte_length);
+
+ *offset += to_read;
+ Ok(to_read)
+ }
}
}
@@ -412,6 +430,32 @@ impl ColumnValueDecoder for ValueDecoder {
}
Decoder::Dict { decoder } => decoder.skip(num_values),
Decoder::Delta { decoder } => decoder.skip(num_values),
+ Decoder::ByteStreamSplit { offset, buf } => {
+ let total_values = buf.len() / self.byte_length;
+ let to_read = num_values.min(total_values - *offset);
+ *offset += to_read;
+ Ok(to_read)
+ }
+ }
+ }
+}
+
+// `src` is an array laid out like a NxM matrix where N == `data_width` and
+// M == total_values_in_src. Each "row" of the matrix is a stream of bytes, with stream `i`
+// containing the `ith` byte for each value. Each "column" is a single value.
+// This will reassemble `num_values` values by reading columns of the matrix starting at
+// `offset`. Values will be appended to `dst`.
+fn read_byte_stream_split(
+ dst: &mut Vec<u8>,
+ src: &mut Bytes,
+ offset: usize,
+ num_values: usize,
+ data_width: usize,
+) {
+ let stride = src.len() / data_width;
+ for i in 0..num_values {
+ for j in 0..data_width {
+ dst.push(src[offset + j * stride + i]);
}
}
}
@@ -420,6 +464,7 @@ enum Decoder {
Plain { buf: Bytes, offset: usize },
Dict { decoder: DictIndexDecoder },
Delta { decoder: DeltaByteArrayDecoder },
+ ByteStreamSplit { buf: Bytes, offset: usize },
}
#[cfg(test)]
diff --git a/parquet/src/arrow/arrow_reader/mod.rs b/parquet/src/arrow/arrow_reader/mod.rs
index c696763d63d2..a0302fa86b3b 100644
--- a/parquet/src/arrow/arrow_reader/mod.rs
+++ b/parquet/src/arrow/arrow_reader/mod.rs
@@ -1059,6 +1059,7 @@ mod tests {
Encoding::PLAIN,
Encoding::RLE_DICTIONARY,
Encoding::DELTA_BINARY_PACKED,
+ Encoding::BYTE_STREAM_SPLIT,
],
);
run_single_column_reader_tests::<Int64Type, _, Int64Type>(
@@ -1070,6 +1071,7 @@ mod tests {
Encoding::PLAIN,
Encoding::RLE_DICTIONARY,
Encoding::DELTA_BINARY_PACKED,
+ Encoding::BYTE_STREAM_SPLIT,
],
);
run_single_column_reader_tests::<FloatType, _, FloatType>(
@@ -1641,6 +1643,86 @@ mod tests {
assert_eq!(row_count, 300);
}
+ #[test]
+ fn test_read_extended_byte_stream_split() {
+ let path = format!(
+ "{}/byte_stream_split_extended.gzip.parquet",
+ arrow::util::test_util::parquet_test_data(),
+ );
+ let file = File::open(path).unwrap();
+ let record_reader = ParquetRecordBatchReader::try_new(file, 128).unwrap();
+
+ let mut row_count = 0;
+ for batch in record_reader {
+ let batch = batch.unwrap();
+ row_count += batch.num_rows();
+
+ // 0,1 are f16
+ let f16_col = batch.column(0).as_primitive::<Float16Type>();
+ let f16_bss = batch.column(1).as_primitive::<Float16Type>();
+ assert_eq!(f16_col.len(), f16_bss.len());
+ f16_col
+ .iter()
+ .zip(f16_bss.iter())
+ .for_each(|(l, r)| assert_eq!(l.unwrap(), r.unwrap()));
+
+ // 2,3 are f32
+ let f32_col = batch.column(2).as_primitive::<Float32Type>();
+ let f32_bss = batch.column(3).as_primitive::<Float32Type>();
+ assert_eq!(f32_col.len(), f32_bss.len());
+ f32_col
+ .iter()
+ .zip(f32_bss.iter())
+ .for_each(|(l, r)| assert_eq!(l.unwrap(), r.unwrap()));
+
+ // 4,5 are f64
+ let f64_col = batch.column(4).as_primitive::<Float64Type>();
+ let f64_bss = batch.column(5).as_primitive::<Float64Type>();
+ assert_eq!(f64_col.len(), f64_bss.len());
+ f64_col
+ .iter()
+ .zip(f64_bss.iter())
+ .for_each(|(l, r)| assert_eq!(l.unwrap(), r.unwrap()));
+
+ // 6,7 are i32
+ let i32_col = batch.column(6).as_primitive::<types::Int32Type>();
+ let i32_bss = batch.column(7).as_primitive::<types::Int32Type>();
+ assert_eq!(i32_col.len(), i32_bss.len());
+ i32_col
+ .iter()
+ .zip(i32_bss.iter())
+ .for_each(|(l, r)| assert_eq!(l.unwrap(), r.unwrap()));
+
+ // 8,9 are i64
+ let i64_col = batch.column(8).as_primitive::<types::Int64Type>();
+ let i64_bss = batch.column(9).as_primitive::<types::Int64Type>();
+ assert_eq!(i64_col.len(), i64_bss.len());
+ i64_col
+ .iter()
+ .zip(i64_bss.iter())
+ .for_each(|(l, r)| assert_eq!(l.unwrap(), r.unwrap()));
+
+ // 10,11 are FLBA(5)
+ let flba_col = batch.column(10).as_fixed_size_binary();
+ let flba_bss = batch.column(11).as_fixed_size_binary();
+ assert_eq!(flba_col.len(), flba_bss.len());
+ flba_col
+ .iter()
+ .zip(flba_bss.iter())
+ .for_each(|(l, r)| assert_eq!(l.unwrap(), r.unwrap()));
+
+ // 12,13 are FLBA(4) (decimal(7,3))
+ let dec_col = batch.column(12).as_primitive::<Decimal128Type>();
+ let dec_bss = batch.column(13).as_primitive::<Decimal128Type>();
+ assert_eq!(dec_col.len(), dec_bss.len());
+ dec_col
+ .iter()
+ .zip(dec_bss.iter())
+ .for_each(|(l, r)| assert_eq!(l.unwrap(), r.unwrap()));
+ }
+ assert_eq!(row_count, 200);
+ }
+
#[test]
fn test_read_incorrect_map_schema_file() {
let testdata = arrow::util::test_util::parquet_test_data();
diff --git a/parquet/src/arrow/arrow_writer/mod.rs b/parquet/src/arrow/arrow_writer/mod.rs
index 8f7b514ccf71..856ecaa17fee 100644
--- a/parquet/src/arrow/arrow_writer/mod.rs
+++ b/parquet/src/arrow/arrow_writer/mod.rs
@@ -1796,7 +1796,11 @@ mod tests {
| DataType::UInt64
| DataType::UInt32
| DataType::UInt16
- | DataType::UInt8 => vec![Encoding::PLAIN, Encoding::DELTA_BINARY_PACKED],
+ | DataType::UInt8 => vec![
+ Encoding::PLAIN,
+ Encoding::DELTA_BINARY_PACKED,
+ Encoding::BYTE_STREAM_SPLIT,
+ ],
DataType::Float32 | DataType::Float64 => {
vec![Encoding::PLAIN, Encoding::BYTE_STREAM_SPLIT]
}
diff --git a/parquet/src/column/writer/encoder.rs b/parquet/src/column/writer/encoder.rs
index 9d01c09040de..7371c72a5896 100644
--- a/parquet/src/column/writer/encoder.rs
+++ b/parquet/src/column/writer/encoder.rs
@@ -191,6 +191,7 @@ impl<T: DataType> ColumnValueEncoder for ColumnValueEncoderImpl<T> {
props
.encoding(descr.path())
.unwrap_or_else(|| fallback_encoding(T::get_physical_type(), props)),
+ descr,
)?;
let statistics_enabled = props.statistics_enabled(descr.path());
diff --git a/parquet/src/encodings/decoding.rs b/parquet/src/encodings/decoding.rs
index b3dd13523794..16467b32dcaf 100644
--- a/parquet/src/encodings/decoding.rs
+++ b/parquet/src/encodings/decoding.rs
@@ -27,6 +27,9 @@ use super::rle::RleDecoder;
use crate::basic::*;
use crate::data_type::private::ParquetValueType;
use crate::data_type::*;
+use crate::encodings::decoding::byte_stream_split_decoder::{
+ ByteStreamSplitDecoder, VariableWidthByteStreamSplitDecoder,
+};
use crate::errors::{ParquetError, Result};
use crate::schema::types::ColumnDescPtr;
use crate::util::bit_util::{self, BitReader};
@@ -87,6 +90,7 @@ pub(crate) mod private {
encoding: Encoding,
) -> Result<Box<dyn Decoder<T>>> {
match encoding {
+ Encoding::BYTE_STREAM_SPLIT => Ok(Box::new(ByteStreamSplitDecoder::new())),
Encoding::DELTA_BINARY_PACKED => Ok(Box::new(DeltaBitPackDecoder::new())),
_ => get_decoder_default(descr, encoding),
}
@@ -99,6 +103,7 @@ pub(crate) mod private {
encoding: Encoding,
) -> Result<Box<dyn Decoder<T>>> {
match encoding {
+ Encoding::BYTE_STREAM_SPLIT => Ok(Box::new(ByteStreamSplitDecoder::new())),
Encoding::DELTA_BINARY_PACKED => Ok(Box::new(DeltaBitPackDecoder::new())),
_ => get_decoder_default(descr, encoding),
}
@@ -111,9 +116,7 @@ pub(crate) mod private {
encoding: Encoding,
) -> Result<Box<dyn Decoder<T>>> {
match encoding {
- Encoding::BYTE_STREAM_SPLIT => Ok(Box::new(
- byte_stream_split_decoder::ByteStreamSplitDecoder::new(),
- )),
+ Encoding::BYTE_STREAM_SPLIT => Ok(Box::new(ByteStreamSplitDecoder::new())),
_ => get_decoder_default(descr, encoding),
}
}
@@ -124,9 +127,7 @@ pub(crate) mod private {
encoding: Encoding,
) -> Result<Box<dyn Decoder<T>>> {
match encoding {
- Encoding::BYTE_STREAM_SPLIT => Ok(Box::new(
- byte_stream_split_decoder::ByteStreamSplitDecoder::new(),
- )),
+ Encoding::BYTE_STREAM_SPLIT => Ok(Box::new(ByteStreamSplitDecoder::new())),
_ => get_decoder_default(descr, encoding),
}
}
@@ -153,6 +154,9 @@ pub(crate) mod private {
encoding: Encoding,
) -> Result<Box<dyn Decoder<T>>> {
match encoding {
+ Encoding::BYTE_STREAM_SPLIT => Ok(Box::new(
+ VariableWidthByteStreamSplitDecoder::new(descr.type_length()),
+ )),
Encoding::DELTA_BYTE_ARRAY => Ok(Box::new(DeltaByteArrayDecoder::new())),
_ => get_decoder_default(descr, encoding),
}
@@ -1785,7 +1789,7 @@ mod tests {
],
vec![f32::from_le_bytes([0xA3, 0xB4, 0xC5, 0xD6])],
];
- test_byte_stream_split_decode::<FloatType>(data);
+ test_byte_stream_split_decode::<FloatType>(data, -1);
}
#[test]
@@ -1794,7 +1798,76 @@ mod tests {
f64::from_le_bytes([0, 1, 2, 3, 4, 5, 6, 7]),
f64::from_le_bytes([8, 9, 10, 11, 12, 13, 14, 15]),
]];
- test_byte_stream_split_decode::<DoubleType>(data);
+ test_byte_stream_split_decode::<DoubleType>(data, -1);
+ }
+
+ #[test]
+ fn test_byte_stream_split_multiple_i32() {
+ let data = vec![
+ vec![
+ i32::from_le_bytes([0xAA, 0xBB, 0xCC, 0xDD]),
+ i32::from_le_bytes([0x00, 0x11, 0x22, 0x33]),
+ ],
+ vec![i32::from_le_bytes([0xA3, 0xB4, 0xC5, 0xD6])],
+ ];
+ test_byte_stream_split_decode::<Int32Type>(data, -1);
+ }
+
+ #[test]
+ fn test_byte_stream_split_i64() {
+ let data = vec![vec![
+ i64::from_le_bytes([0, 1, 2, 3, 4, 5, 6, 7]),
+ i64::from_le_bytes([8, 9, 10, 11, 12, 13, 14, 15]),
+ ]];
+ test_byte_stream_split_decode::<Int64Type>(data, -1);
+ }
+
+ fn test_byte_stream_split_flba(type_width: usize) {
+ let data = vec![
+ vec![
+ FixedLenByteArrayType::gen(type_width as i32),
+ FixedLenByteArrayType::gen(type_width as i32),
+ ],
+ vec![FixedLenByteArrayType::gen(type_width as i32)],
+ ];
+ test_byte_stream_split_decode::<FixedLenByteArrayType>(data, type_width as i32);
+ }
+
+ #[test]
+ fn test_byte_stream_split_flba5() {
+ test_byte_stream_split_flba(5);
+ }
+
+ #[test]
+ fn test_byte_stream_split_flba16() {
+ test_byte_stream_split_flba(16);
+ }
+
+ #[test]
+ fn test_byte_stream_split_flba19() {
+ test_byte_stream_split_flba(19);
+ }
+
+ #[test]
+ #[should_panic(expected = "Mismatched FixedLenByteArray sizes: 4 != 5")]
+ fn test_byte_stream_split_flba_mismatch() {
+ let data = vec![
+ vec![
+ FixedLenByteArray::from(vec![0xAA, 0xAB, 0xAC, 0xAD, 0xAE]),
+ FixedLenByteArray::from(vec![0xBA, 0xBB, 0xBC, 0xBD, 0xBE]),
+ ],
+ vec![FixedLenByteArray::from(vec![0xCA, 0xCB, 0xCC, 0xCD])],
+ ];
+ test_byte_stream_split_decode::<FixedLenByteArrayType>(data, 5);
+ }
+
+ #[test]
+ #[should_panic(expected = "Input data length is not a multiple of type width 4")]
+ fn test_byte_stream_split_flba_bad_input() {
+ let mut decoder = VariableWidthByteStreamSplitDecoder::<FixedLenByteArrayType>::new(4);
+ decoder
+ .set_data(Bytes::from(vec![1, 2, 3, 4, 5]), 1)
+ .unwrap();
}
#[test]
@@ -1808,33 +1881,42 @@ mod tests {
);
}
+ #[test]
+ fn test_skip_byte_stream_split_ints() {
+ let block_data = vec![3, 4, 1, 5];
+ test_skip::<Int32Type>(block_data.clone(), Encoding::BYTE_STREAM_SPLIT, 2);
+ test_skip::<Int64Type>(
+ block_data.into_iter().map(|x| x as i64).collect(),
+ Encoding::BYTE_STREAM_SPLIT,
+ 100,
+ );
+ }
+
fn test_rle_value_decode<T: DataType>(data: Vec<Vec<T::T>>) {
- test_encode_decode::<T>(data, Encoding::RLE);
+ test_encode_decode::<T>(data, Encoding::RLE, -1);
}
fn test_delta_bit_packed_decode<T: DataType>(data: Vec<Vec<T::T>>) {
- test_encode_decode::<T>(data, Encoding::DELTA_BINARY_PACKED);
+ test_encode_decode::<T>(data, Encoding::DELTA_BINARY_PACKED, -1);
}
- fn test_byte_stream_split_decode<T: DataType>(data: Vec<Vec<T::T>>) {
- test_encode_decode::<T>(data, Encoding::BYTE_STREAM_SPLIT);
+ fn test_byte_stream_split_decode<T: DataType>(data: Vec<Vec<T::T>>, type_width: i32) {
+ test_encode_decode::<T>(data, Encoding::BYTE_STREAM_SPLIT, type_width);
}
fn test_delta_byte_array_decode(data: Vec<Vec<ByteArray>>) {
- test_encode_decode::<ByteArrayType>(data, Encoding::DELTA_BYTE_ARRAY);
+ test_encode_decode::<ByteArrayType>(data, Encoding::DELTA_BYTE_ARRAY, -1);
}
// Input data represents vector of data slices to write (test multiple `put()` calls)
// For example,
// vec![vec![1, 2, 3]] invokes `put()` once and writes {1, 2, 3}
// vec![vec![1, 2], vec![3]] invokes `put()` twice and writes {1, 2, 3}
- fn test_encode_decode<T: DataType>(data: Vec<Vec<T::T>>, encoding: Encoding) {
- // Type length should not really matter for encode/decode test,
- // otherwise change it based on type
- let col_descr = create_test_col_desc_ptr(-1, T::get_physical_type());
+ fn test_encode_decode<T: DataType>(data: Vec<Vec<T::T>>, encoding: Encoding, type_width: i32) {
+ let col_descr = create_test_col_desc_ptr(type_width, T::get_physical_type());
// Encode data
- let mut encoder = get_encoder::<T>(encoding).expect("get encoder");
+ let mut encoder = get_encoder::<T>(encoding, &col_descr).expect("get encoder");
for v in &data[..] {
encoder.put(&v[..]).expect("ok to encode");
@@ -1867,7 +1949,7 @@ mod tests {
let col_descr = create_test_col_desc_ptr(-1, T::get_physical_type());
// Encode data
- let mut encoder = get_encoder::<T>(encoding).expect("get encoder");
+ let mut encoder = get_encoder::<T>(encoding, &col_descr).expect("get encoder");
encoder.put(&data).expect("ok to encode");
diff --git a/parquet/src/encodings/decoding/byte_stream_split_decoder.rs b/parquet/src/encodings/decoding/byte_stream_split_decoder.rs
index 98841d21ec9e..9b2f43ace8a8 100644
--- a/parquet/src/encodings/decoding/byte_stream_split_decoder.rs
+++ b/parquet/src/encodings/decoding/byte_stream_split_decoder.rs
@@ -19,8 +19,9 @@ use std::marker::PhantomData;
use bytes::Bytes;
-use crate::basic::Encoding;
-use crate::data_type::{DataType, SliceAsBytes};
+use crate::basic::{Encoding, Type};
+use crate::data_type::private::ParquetValueType;
+use crate::data_type::{DataType, FixedLenByteArray, SliceAsBytes};
use crate::errors::{ParquetError, Result};
use super::Decoder;
@@ -62,6 +63,22 @@ fn join_streams_const<const TYPE_SIZE: usize>(
}
}
+// Like the above, but type_size is not known at compile time.
+fn join_streams_variable(
+ src: &[u8],
+ dst: &mut [u8],
+ stride: usize,
+ type_size: usize,
+ values_decoded: usize,
+) {
+ let sub_src = &src[values_decoded..];
+ for i in 0..dst.len() / type_size {
+ for j in 0..type_size {
+ dst[i * type_size + j] = sub_src[i + j * stride];
+ }
+ }
+}
+
impl<T: DataType> Decoder<T> for ByteStreamSplitDecoder<T> {
fn set_data(&mut self, data: Bytes, num_values: usize) -> Result<()> {
self.encoded_bytes = data;
@@ -76,7 +93,7 @@ impl<T: DataType> Decoder<T> for ByteStreamSplitDecoder<T> {
let num_values = buffer.len().min(total_remaining_values);
let buffer = &mut buffer[..num_values];
- // SAFETY: f32 and f64 has no constraints on their internal representation, so we can modify it as we want
+ // SAFETY: i/f32 and i/f64 has no constraints on their internal representation, so we can modify it as we want
let raw_out_bytes = unsafe { <T as DataType>::T::slice_as_bytes_mut(buffer) };
let type_size = T::get_type_size();
let stride = self.encoded_bytes.len() / type_size;
@@ -119,3 +136,126 @@ impl<T: DataType> Decoder<T> for ByteStreamSplitDecoder<T> {
Ok(to_skip)
}
}
+
+pub struct VariableWidthByteStreamSplitDecoder<T: DataType> {
+ _phantom: PhantomData<T>,
+ encoded_bytes: Bytes,
+ total_num_values: usize,
+ values_decoded: usize,
+ type_width: usize,
+}
+
+impl<T: DataType> VariableWidthByteStreamSplitDecoder<T> {
+ pub(crate) fn new(type_length: i32) -> Self {
+ Self {
+ _phantom: PhantomData,
+ encoded_bytes: Bytes::new(),
+ total_num_values: 0,
+ values_decoded: 0,
+ type_width: type_length as usize,
+ }
+ }
+}
+
+impl<T: DataType> Decoder<T> for VariableWidthByteStreamSplitDecoder<T> {
+ fn set_data(&mut self, data: Bytes, num_values: usize) -> Result<()> {
+ // Rough check that all data elements are the same length
+ if data.len() % self.type_width != 0 {
+ return Err(general_err!(
+ "Input data length is not a multiple of type width {}",
+ self.type_width
+ ));
+ }
+
+ match T::get_physical_type() {
+ Type::FIXED_LEN_BYTE_ARRAY => {
+ self.encoded_bytes = data;
+ self.total_num_values = num_values;
+ self.values_decoded = 0;
+ Ok(())
+ }
+ _ => Err(general_err!(
+ "VariableWidthByteStreamSplitDecoder only supports FixedLenByteArrayType"
+ )),
+ }
+ }
+
+ fn get(&mut self, buffer: &mut [<T as DataType>::T]) -> Result<usize> {
+ let total_remaining_values = self.values_left();
+ let num_values = buffer.len().min(total_remaining_values);
+ let buffer = &mut buffer[..num_values];
+ let type_size = self.type_width;
+
+ // Since this is FIXED_LEN_BYTE_ARRAY data, we can't use slice_as_bytes_mut. Instead we'll
+ // have to do some data copies.
+ let mut tmp_vec = vec![0_u8; num_values * type_size];
+ let raw_out_bytes = tmp_vec.as_mut_slice();
+
+ let stride = self.encoded_bytes.len() / type_size;
+ match type_size {
+ 2 => join_streams_const::<2>(
+ &self.encoded_bytes,
+ raw_out_bytes,
+ stride,
+ self.values_decoded,
+ ),
+ 4 => join_streams_const::<4>(
+ &self.encoded_bytes,
+ raw_out_bytes,
+ stride,
+ self.values_decoded,
+ ),
+ 8 => join_streams_const::<8>(
+ &self.encoded_bytes,
+ raw_out_bytes,
+ stride,
+ self.values_decoded,
+ ),
+ 16 => join_streams_const::<16>(
+ &self.encoded_bytes,
+ raw_out_bytes,
+ stride,
+ self.values_decoded,
+ ),
+ _ => join_streams_variable(
+ &self.encoded_bytes,
+ raw_out_bytes,
+ stride,
+ type_size,
+ self.values_decoded,
+ ),
+ }
+ self.values_decoded += num_values;
+
+ // create a buffer from the vec so far (and leave a new Vec in its place)
+ let vec_with_data = std::mem::take(&mut tmp_vec);
+ // convert Vec to Bytes (which is a ref counted wrapper)
+ let bytes_with_data = Bytes::from(vec_with_data);
+ for (i, bi) in buffer.iter_mut().enumerate().take(num_values) {
+ // Get a view into the data, without also copying the bytes
+ let data = bytes_with_data.slice(i * type_size..(i + 1) * type_size);
+ // TODO: perhaps add a `set_from_bytes` method to `DataType` to avoid downcasting
+ let bi = bi
+ .as_mut_any()
+ .downcast_mut::<FixedLenByteArray>()
+ .expect("Decoding fixed length byte array");
+ bi.set_data(data);
+ }
+
+ Ok(num_values)
+ }
+
+ fn values_left(&self) -> usize {
+ self.total_num_values - self.values_decoded
+ }
+
+ fn encoding(&self) -> Encoding {
+ Encoding::BYTE_STREAM_SPLIT
+ }
+
+ fn skip(&mut self, num_values: usize) -> Result<usize> {
+ let to_skip = usize::min(self.values_left(), num_values);
+ self.values_decoded += to_skip;
+ Ok(to_skip)
+ }
+}
diff --git a/parquet/src/encodings/encoding/byte_stream_split_encoder.rs b/parquet/src/encodings/encoding/byte_stream_split_encoder.rs
index 3d5ba4cc2d0b..0726c6b1c919 100644
--- a/parquet/src/encodings/encoding/byte_stream_split_encoder.rs
+++ b/parquet/src/encodings/encoding/byte_stream_split_encoder.rs
@@ -16,14 +16,14 @@
// under the License.
use crate::basic::{Encoding, Type};
-use crate::data_type::DataType;
-use crate::data_type::SliceAsBytes;
+use crate::data_type::{AsBytes, DataType, SliceAsBytes};
use crate::errors::{ParquetError, Result};
use super::Encoder;
-use bytes::Bytes;
+use bytes::{BufMut, Bytes};
+use std::cmp;
use std::marker::PhantomData;
pub struct ByteStreamSplitEncoder<T> {
@@ -40,7 +40,7 @@ impl<T: DataType> ByteStreamSplitEncoder<T> {
}
}
-// Here we assume src contains the full data (which it must, since we're
+// Here we assume src contains the full data (which it must, since we
// can only know where to split the streams once all data is collected).
// We iterate over the input bytes and write them to their strided output
// byte locations.
@@ -53,13 +53,28 @@ fn split_streams_const<const TYPE_SIZE: usize>(src: &[u8], dst: &mut [u8]) {
}
}
+// Like above, but type_size is not known at compile time.
+fn split_streams_variable(src: &[u8], dst: &mut [u8], type_size: usize) {
+ const BLOCK_SIZE: usize = 4;
+ let stride = src.len() / type_size;
+ for j in (0..type_size).step_by(BLOCK_SIZE) {
+ let jrange = cmp::min(BLOCK_SIZE, type_size - j);
+ for i in 0..stride {
+ for jj in 0..jrange {
+ dst[i + (j + jj) * stride] = src[i * type_size + j + jj];
+ }
+ }
+ }
+}
+
impl<T: DataType> Encoder<T> for ByteStreamSplitEncoder<T> {
fn put(&mut self, values: &[T::T]) -> Result<()> {
self.buffer
.extend(<T as DataType>::T::slice_as_bytes(values));
+
ensure_phys_ty!(
- Type::FLOAT | Type::DOUBLE,
- "ByteStreamSplitEncoder only supports FloatType or DoubleType"
+ Type::FLOAT | Type::DOUBLE | Type::INT32 | Type::INT64,
+ "ByteStreamSplitEncoder does not support Int96, Boolean, or ByteArray types"
);
Ok(())
@@ -96,3 +111,121 @@ impl<T: DataType> Encoder<T> for ByteStreamSplitEncoder<T> {
self.buffer.capacity() * std::mem::size_of::<u8>()
}
}
+
+pub struct VariableWidthByteStreamSplitEncoder<T> {
+ buffer: Vec<u8>,
+ type_width: usize,
+ _p: PhantomData<T>,
+}
+
+impl<T: DataType> VariableWidthByteStreamSplitEncoder<T> {
+ pub(crate) fn new(type_length: i32) -> Self {
+ Self {
+ buffer: Vec::new(),
+ type_width: type_length as usize,
+ _p: PhantomData,
+ }
+ }
+}
+
+fn put_fixed<T: DataType, const TYPE_SIZE: usize>(dst: &mut [u8], values: &[T::T]) {
+ let mut idx = 0;
+ values.iter().for_each(|x| {
+ let bytes = x.as_bytes();
+ if bytes.len() != TYPE_SIZE {
+ panic!(
+ "Mismatched FixedLenByteArray sizes: {} != {}",
+ bytes.len(),
+ TYPE_SIZE
+ );
+ }
+ dst[idx..(TYPE_SIZE + idx)].copy_from_slice(&bytes[..TYPE_SIZE]);
+ idx += TYPE_SIZE;
+ });
+}
+
+fn put_variable<T: DataType>(dst: &mut [u8], values: &[T::T], type_width: usize) {
+ let mut idx = 0;
+ values.iter().for_each(|x| {
+ let bytes = x.as_bytes();
+ if bytes.len() != type_width {
+ panic!(
+ "Mismatched FixedLenByteArray sizes: {} != {}",
+ bytes.len(),
+ type_width
+ );
+ }
+ dst[idx..idx + type_width].copy_from_slice(bytes);
+ idx += type_width;
+ });
+}
+
+impl<T: DataType> Encoder<T> for VariableWidthByteStreamSplitEncoder<T> {
+ fn put(&mut self, values: &[T::T]) -> Result<()> {
+ ensure_phys_ty!(
+ Type::FIXED_LEN_BYTE_ARRAY,
+ "VariableWidthByteStreamSplitEncoder only supports FixedLenByteArray types"
+ );
+
+ // FixedLenByteArray is implemented as ByteArray, so there may be gaps making
+ // slice_as_bytes untenable
+ let idx = self.buffer.len();
+ let data_len = values.len() * self.type_width;
+ // Ensure enough capacity for the new data
+ self.buffer.reserve(values.len() * self.type_width);
+ // ...and extend the size of buffer to allow direct access
+ self.buffer.put_bytes(0_u8, data_len);
+ // Get a slice of the buffer corresponding to the location of the new data
+ let out_buf = &mut self.buffer[idx..idx + data_len];
+
+ // Now copy `values` into the buffer. For `type_width` <= 8 use a fixed size when
+ // performing the copy as it is significantly faster.
+ match self.type_width {
+ 2 => put_fixed::<T, 2>(out_buf, values),
+ 3 => put_fixed::<T, 3>(out_buf, values),
+ 4 => put_fixed::<T, 4>(out_buf, values),
+ 5 => put_fixed::<T, 5>(out_buf, values),
+ 6 => put_fixed::<T, 6>(out_buf, values),
+ 7 => put_fixed::<T, 7>(out_buf, values),
+ 8 => put_fixed::<T, 8>(out_buf, values),
+ _ => put_variable::<T>(out_buf, values, self.type_width),
+ }
+
+ Ok(())
+ }
+
+ fn encoding(&self) -> Encoding {
+ Encoding::BYTE_STREAM_SPLIT
+ }
+
+ fn estimated_data_encoded_size(&self) -> usize {
+ self.buffer.len()
+ }
+
+ fn flush_buffer(&mut self) -> Result<Bytes> {
+ let mut encoded = vec![0; self.buffer.len()];
+ let type_size = match T::get_physical_type() {
+ Type::FIXED_LEN_BYTE_ARRAY => self.type_width,
+ _ => T::get_type_size(),
+ };
+ // split_streams_const() is faster up to type_width == 8
+ match type_size {
+ 2 => split_streams_const::<2>(&self.buffer, &mut encoded),
+ 3 => split_streams_const::<3>(&self.buffer, &mut encoded),
+ 4 => split_streams_const::<4>(&self.buffer, &mut encoded),
+ 5 => split_streams_const::<5>(&self.buffer, &mut encoded),
+ 6 => split_streams_const::<6>(&self.buffer, &mut encoded),
+ 7 => split_streams_const::<7>(&self.buffer, &mut encoded),
+ 8 => split_streams_const::<8>(&self.buffer, &mut encoded),
+ _ => split_streams_variable(&self.buffer, &mut encoded, type_size),
+ }
+
+ self.buffer.clear();
+ Ok(encoded.into())
+ }
+
+ /// return the estimated memory size of this encoder.
+ fn estimated_memory_size(&self) -> usize {
+ self.buffer.capacity() * std::mem::size_of::<u8>()
+ }
+}
diff --git a/parquet/src/encodings/encoding/mod.rs b/parquet/src/encodings/encoding/mod.rs
index ecc376712490..f6d94e03317d 100644
--- a/parquet/src/encodings/encoding/mod.rs
+++ b/parquet/src/encodings/encoding/mod.rs
@@ -24,8 +24,10 @@ use crate::data_type::private::ParquetValueType;
use crate::data_type::*;
use crate::encodings::rle::RleEncoder;
use crate::errors::{ParquetError, Result};
+use crate::schema::types::ColumnDescPtr;
use crate::util::bit_util::{num_required_bits, BitWriter};
+use byte_stream_split_encoder::{ByteStreamSplitEncoder, VariableWidthByteStreamSplitEncoder};
use bytes::Bytes;
pub use dict_encoder::DictEncoder;
@@ -78,7 +80,10 @@ pub trait Encoder<T: DataType>: Send {
/// Gets a encoder for the particular data type `T` and encoding `encoding`. Memory usage
/// for the encoder instance is tracked by `mem_tracker`.
-pub fn get_encoder<T: DataType>(encoding: Encoding) -> Result<Box<dyn Encoder<T>>> {
+pub fn get_encoder<T: DataType>(
+ encoding: Encoding,
+ descr: &ColumnDescPtr,
+) -> Result<Box<dyn Encoder<T>>> {
let encoder: Box<dyn Encoder<T>> = match encoding {
Encoding::PLAIN => Box::new(PlainEncoder::new()),
Encoding::RLE_DICTIONARY | Encoding::PLAIN_DICTIONARY => {
@@ -90,9 +95,12 @@ pub fn get_encoder<T: DataType>(encoding: Encoding) -> Result<Box<dyn Encoder<T>
Encoding::DELTA_BINARY_PACKED => Box::new(DeltaBitPackEncoder::new()),
Encoding::DELTA_LENGTH_BYTE_ARRAY => Box::new(DeltaLengthByteArrayEncoder::new()),
Encoding::DELTA_BYTE_ARRAY => Box::new(DeltaByteArrayEncoder::new()),
- Encoding::BYTE_STREAM_SPLIT => {
- Box::new(byte_stream_split_encoder::ByteStreamSplitEncoder::new())
- }
+ Encoding::BYTE_STREAM_SPLIT => match T::get_physical_type() {
+ Type::FIXED_LEN_BYTE_ARRAY => Box::new(VariableWidthByteStreamSplitEncoder::new(
+ descr.type_length(),
+ )),
+ _ => Box::new(ByteStreamSplitEncoder::new()),
+ },
e => return Err(nyi_err!("Encoding {} is not supported", e)),
};
Ok(encoder)
@@ -498,8 +506,7 @@ impl<T: DataType> Encoder<T> for DeltaBitPackEncoder<T> {
self.page_header_writer.estimated_memory_size()
+ self.bit_writer.estimated_memory_size()
+ self.deltas.capacity() * std::mem::size_of::<i64>()
- + std::mem::size_of::<Self>()
-
+ + std::mem::size_of::<Self>()
}
}
@@ -641,10 +648,7 @@ impl<T: DataType> Encoder<T> for DeltaLengthByteArrayEncoder<T> {
/// return the estimated memory size of this encoder.
fn estimated_memory_size(&self) -> usize {
- self.len_encoder.estimated_memory_size()
- + self.data.len()
- + std::mem::size_of::<Self>()
-
+ self.len_encoder.estimated_memory_size() + self.data.len() + std::mem::size_of::<Self>()
}
}
@@ -754,8 +758,7 @@ impl<T: DataType> Encoder<T> for DeltaByteArrayEncoder<T> {
fn estimated_memory_size(&self) -> usize {
self.prefix_len_encoder.estimated_memory_size()
+ self.suffix_writer.estimated_memory_size()
- + (self.previous.capacity() * std::mem::size_of::<u8>())
-
+ + (self.previous.capacity() * std::mem::size_of::<u8>())
}
}
@@ -767,28 +770,30 @@ mod tests {
use crate::encodings::decoding::{get_decoder, Decoder, DictDecoder, PlainDecoder};
use crate::schema::types::{ColumnDescPtr, ColumnDescriptor, ColumnPath, Type as SchemaType};
- use crate::util::test_common::rand_gen::{random_bytes, RandGen};
use crate::util::bit_util;
+ use crate::util::test_common::rand_gen::{random_bytes, RandGen};
const TEST_SET_SIZE: usize = 1024;
#[test]
fn test_get_encoders() {
// supported encodings
- create_and_check_encoder::<Int32Type>(Encoding::PLAIN, None);
- create_and_check_encoder::<Int32Type>(Encoding::DELTA_BINARY_PACKED, None);
- create_and_check_encoder::<Int32Type>(Encoding::DELTA_LENGTH_BYTE_ARRAY, None);
- create_and_check_encoder::<Int32Type>(Encoding::DELTA_BYTE_ARRAY, None);
- create_and_check_encoder::<BoolType>(Encoding::RLE, None);
+ create_and_check_encoder::<Int32Type>(0, Encoding::PLAIN, None);
+ create_and_check_encoder::<Int32Type>(0, Encoding::DELTA_BINARY_PACKED, None);
+ create_and_check_encoder::<Int32Type>(0, Encoding::DELTA_LENGTH_BYTE_ARRAY, None);
+ create_and_check_encoder::<Int32Type>(0, Encoding::DELTA_BYTE_ARRAY, None);
+ create_and_check_encoder::<BoolType>(0, Encoding::RLE, None);
// error when initializing
create_and_check_encoder::<Int32Type>(
+ 0,
Encoding::RLE_DICTIONARY,
Some(general_err!(
"Cannot initialize this encoding through this function"
)),
);
create_and_check_encoder::<Int32Type>(
+ 0,
Encoding::PLAIN_DICTIONARY,
Some(general_err!(
"Cannot initialize this encoding through this function"
@@ -798,6 +803,7 @@ mod tests {
// unsupported
#[allow(deprecated)]
create_and_check_encoder::<Int32Type>(
+ 0,
Encoding::BIT_PACKED,
Some(nyi_err!("Encoding BIT_PACKED is not supported")),
);
@@ -815,6 +821,7 @@ mod tests {
Int32Type::test(Encoding::PLAIN, TEST_SET_SIZE, -1);
Int32Type::test(Encoding::PLAIN_DICTIONARY, TEST_SET_SIZE, -1);
Int32Type::test(Encoding::DELTA_BINARY_PACKED, TEST_SET_SIZE, -1);
+ Int32Type::test(Encoding::BYTE_STREAM_SPLIT, TEST_SET_SIZE, -1);
}
#[test]
@@ -822,6 +829,7 @@ mod tests {
Int64Type::test(Encoding::PLAIN, TEST_SET_SIZE, -1);
Int64Type::test(Encoding::PLAIN_DICTIONARY, TEST_SET_SIZE, -1);
Int64Type::test(Encoding::DELTA_BINARY_PACKED, TEST_SET_SIZE, -1);
+ Int64Type::test(Encoding::BYTE_STREAM_SPLIT, TEST_SET_SIZE, -1);
}
#[test]
@@ -853,10 +861,11 @@ mod tests {
}
#[test]
- fn test_fixed_lenbyte_array() {
+ fn test_fixed_len_byte_array() {
FixedLenByteArrayType::test(Encoding::PLAIN, TEST_SET_SIZE, 100);
FixedLenByteArrayType::test(Encoding::PLAIN_DICTIONARY, TEST_SET_SIZE, 100);
FixedLenByteArrayType::test(Encoding::DELTA_BYTE_ARRAY, TEST_SET_SIZE, 100);
+ FixedLenByteArrayType::test(Encoding::BYTE_STREAM_SPLIT, TEST_SET_SIZE, 100);
}
#[test]
@@ -905,7 +914,7 @@ mod tests {
Encoding::PLAIN_DICTIONARY | Encoding::RLE_DICTIONARY => {
Box::new(create_test_dict_encoder::<T>(type_length))
}
- _ => create_test_encoder::<T>(encoding),
+ _ => create_test_encoder::<T>(type_length, encoding),
};
assert_eq!(encoder.estimated_data_encoded_size(), initial_size);
@@ -960,7 +969,7 @@ mod tests {
#[test]
fn test_byte_stream_split_example_f32() {
// Test data from https://github.com/apache/parquet-format/blob/2a481fe1aad64ff770e21734533bb7ef5a057dac/Encodings.md#byte-stream-split-byte_stream_split--9
- let mut encoder = create_test_encoder::<FloatType>(Encoding::BYTE_STREAM_SPLIT);
+ let mut encoder = create_test_encoder::<FloatType>(0, Encoding::BYTE_STREAM_SPLIT);
let mut decoder = create_test_decoder::<FloatType>(0, Encoding::BYTE_STREAM_SPLIT);
let input = vec![
@@ -989,7 +998,7 @@ mod tests {
// See: https://github.com/sunchao/parquet-rs/issues/47
#[test]
fn test_issue_47() {
- let mut encoder = create_test_encoder::<ByteArrayType>(Encoding::DELTA_BYTE_ARRAY);
+ let mut encoder = create_test_encoder::<ByteArrayType>(0, Encoding::DELTA_BYTE_ARRAY);
let mut decoder = create_test_decoder::<ByteArrayType>(0, Encoding::DELTA_BYTE_ARRAY);
let input = vec![
@@ -1039,7 +1048,7 @@ mod tests {
impl<T: DataType + RandGen<T>> EncodingTester<T> for T {
fn test_internal(enc: Encoding, total: usize, type_length: i32) -> Result<()> {
- let mut encoder = create_test_encoder::<T>(enc);
+ let mut encoder = create_test_encoder::<T>(type_length, enc);
let mut decoder = create_test_decoder::<T>(type_length, enc);
let mut values = <T as RandGen<T>>::gen_vec(type_length, total);
let mut result_data = vec![T::T::default(); total];
@@ -1137,8 +1146,13 @@ mod tests {
decoder.get(output)
}
- fn create_and_check_encoder<T: DataType>(encoding: Encoding, err: Option<ParquetError>) {
- let encoder = get_encoder::<T>(encoding);
+ fn create_and_check_encoder<T: DataType>(
+ type_length: i32,
+ encoding: Encoding,
+ err: Option<ParquetError>,
+ ) {
+ let desc = create_test_col_desc_ptr(type_length, T::get_physical_type());
+ let encoder = get_encoder::<T>(encoding, &desc);
match err {
Some(parquet_error) => {
assert_eq!(
@@ -1164,8 +1178,9 @@ mod tests {
))
}
- fn create_test_encoder<T: DataType>(enc: Encoding) -> Box<dyn Encoder<T>> {
- get_encoder(enc).unwrap()
+ fn create_test_encoder<T: DataType>(type_len: i32, enc: Encoding) -> Box<dyn Encoder<T>> {
+ let desc = create_test_col_desc_ptr(type_len, T::get_physical_type());
+ get_encoder(enc, &desc).unwrap()
}
fn create_test_decoder<T: DataType>(type_len: i32, enc: Encoding) -> Box<dyn Decoder<T>> {
diff --git a/parquet/src/file/serialized_reader.rs b/parquet/src/file/serialized_reader.rs
index 70aea6fd5ad3..07e80f7f6998 100644
--- a/parquet/src/file/serialized_reader.rs
+++ b/parquet/src/file/serialized_reader.rs
@@ -1765,4 +1765,42 @@ mod tests {
_ => unreachable!(),
}
}
+
+ #[test]
+ fn test_byte_stream_split_extended() {
+ let path = format!(
+ "{}/byte_stream_split_extended.gzip.parquet",
+ arrow::util::test_util::parquet_test_data(),
+ );
+ let file = File::open(path).unwrap();
+ let reader = Box::new(SerializedFileReader::new(file).expect("Failed to create reader"));
+
+ // Use full schema as projected schema
+ let mut iter = reader
+ .get_row_iter(None)
+ .expect("Failed to create row iterator");
+
+ let mut start = 0;
+ let end = reader.metadata().file_metadata().num_rows();
+
+ let check_row = |row: Result<Row, ParquetError>| {
+ assert!(row.is_ok());
+ let r = row.unwrap();
+ assert_eq!(r.get_float16(0).unwrap(), r.get_float16(1).unwrap());
+ assert_eq!(r.get_float(2).unwrap(), r.get_float(3).unwrap());
+ assert_eq!(r.get_double(4).unwrap(), r.get_double(5).unwrap());
+ assert_eq!(r.get_int(6).unwrap(), r.get_int(7).unwrap());
+ assert_eq!(r.get_long(8).unwrap(), r.get_long(9).unwrap());
+ assert_eq!(r.get_bytes(10).unwrap(), r.get_bytes(11).unwrap());
+ assert_eq!(r.get_decimal(12).unwrap(), r.get_decimal(13).unwrap());
+ };
+
+ while start < end {
+ match iter.next() {
+ Some(row) => check_row(row),
+ None => break,
+ };
+ start += 1;
+ }
+ }
}
diff --git a/parquet/src/file/writer.rs b/parquet/src/file/writer.rs
index 89aaf028d1b9..34a213443e14 100644
--- a/parquet/src/file/writer.rs
+++ b/parquet/src/file/writer.rs
@@ -826,9 +826,15 @@ impl<'a, W: Write + Send> PageWriter for SerializedPageWriter<'a, W> {
mod tests {
use super::*;
+ #[cfg(feature = "arrow")]
+ use arrow_array::RecordBatchReader;
use bytes::Bytes;
use std::fs::File;
+ #[cfg(feature = "arrow")]
+ use crate::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
+ #[cfg(feature = "arrow")]
+ use crate::arrow::ArrowWriter;
use crate::basic::{
ColumnOrder, Compression, ConvertedType, Encoding, LogicalType, Repetition, SortOrder, Type,
};
@@ -2075,4 +2081,115 @@ mod tests {
assert_eq!(offset_index[0].len(), 1);
assert!(offset_index[0][0].unencoded_byte_array_data_bytes.is_none());
}
+
+ #[test]
+ #[cfg(feature = "arrow")]
+ fn test_byte_stream_split_extended_roundtrip() {
+ let path = format!(
+ "{}/byte_stream_split_extended.gzip.parquet",
+ arrow::util::test_util::parquet_test_data(),
+ );
+ let file = File::open(path).unwrap();
+
+ // Read in test file and rewrite to tmp
+ let parquet_reader = ParquetRecordBatchReaderBuilder::try_new(file)
+ .expect("parquet open")
+ .build()
+ .expect("parquet open");
+
+ let file = tempfile::tempfile().unwrap();
+ let props = WriterProperties::builder()
+ .set_dictionary_enabled(false)
+ .set_column_encoding(
+ ColumnPath::from("float16_byte_stream_split"),
+ Encoding::BYTE_STREAM_SPLIT,
+ )
+ .set_column_encoding(
+ ColumnPath::from("float_byte_stream_split"),
+ Encoding::BYTE_STREAM_SPLIT,
+ )
+ .set_column_encoding(
+ ColumnPath::from("double_byte_stream_split"),
+ Encoding::BYTE_STREAM_SPLIT,
+ )
+ .set_column_encoding(
+ ColumnPath::from("int32_byte_stream_split"),
+ Encoding::BYTE_STREAM_SPLIT,
+ )
+ .set_column_encoding(
+ ColumnPath::from("int64_byte_stream_split"),
+ Encoding::BYTE_STREAM_SPLIT,
+ )
+ .set_column_encoding(
+ ColumnPath::from("flba5_byte_stream_split"),
+ Encoding::BYTE_STREAM_SPLIT,
+ )
+ .set_column_encoding(
+ ColumnPath::from("decimal_byte_stream_split"),
+ Encoding::BYTE_STREAM_SPLIT,
+ )
+ .build();
+
+ let mut parquet_writer = ArrowWriter::try_new(
+ file.try_clone().expect("cannot open file"),
+ parquet_reader.schema(),
+ Some(props),
+ )
+ .expect("create arrow writer");
+
+ for maybe_batch in parquet_reader {
+ let batch = maybe_batch.expect("reading batch");
+ parquet_writer.write(&batch).expect("writing data");
+ }
+
+ parquet_writer.close().expect("finalizing file");
+
+ let reader = SerializedFileReader::new(file).expect("Failed to create reader");
+ let filemeta = reader.metadata();
+
+ // Make sure byte_stream_split encoding was used
+ let check_encoding = |x: usize, filemeta: &ParquetMetaData| {
+ assert!(filemeta
+ .row_group(0)
+ .column(x)
+ .encodings()
+ .contains(&Encoding::BYTE_STREAM_SPLIT));
+ };
+
+ check_encoding(1, filemeta);
+ check_encoding(3, filemeta);
+ check_encoding(5, filemeta);
+ check_encoding(7, filemeta);
+ check_encoding(9, filemeta);
+ check_encoding(11, filemeta);
+ check_encoding(13, filemeta);
+
+ // Read back tmpfile and make sure all values are correct
+ let mut iter = reader
+ .get_row_iter(None)
+ .expect("Failed to create row iterator");
+
+ let mut start = 0;
+ let end = reader.metadata().file_metadata().num_rows();
+
+ let check_row = |row: Result<Row, ParquetError>| {
+ assert!(row.is_ok());
+ let r = row.unwrap();
+ assert_eq!(r.get_float16(0).unwrap(), r.get_float16(1).unwrap());
+ assert_eq!(r.get_float(2).unwrap(), r.get_float(3).unwrap());
+ assert_eq!(r.get_double(4).unwrap(), r.get_double(5).unwrap());
+ assert_eq!(r.get_int(6).unwrap(), r.get_int(7).unwrap());
+ assert_eq!(r.get_long(8).unwrap(), r.get_long(9).unwrap());
+ assert_eq!(r.get_bytes(10).unwrap(), r.get_bytes(11).unwrap());
+ assert_eq!(r.get_decimal(12).unwrap(), r.get_decimal(13).unwrap());
+ };
+
+ while start < end {
+ match iter.next() {
+ Some(row) => check_row(row),
+ None => break,
+ };
+ start += 1;
+ }
+ }
}
|
diff --git a/parquet/src/arrow/array_reader/test_util.rs b/parquet/src/arrow/array_reader/test_util.rs
index 05032920139b..a7ff8d6e41ba 100644
--- a/parquet/src/arrow/array_reader/test_util.rs
+++ b/parquet/src/arrow/array_reader/test_util.rs
@@ -46,7 +46,8 @@ pub fn utf8_column() -> ColumnDescPtr {
/// Encode `data` with the provided `encoding`
pub fn encode_byte_array(encoding: Encoding, data: &[ByteArray]) -> Bytes {
- let mut encoder = get_encoder::<ByteArrayType>(encoding).unwrap();
+ let desc = utf8_column();
+ let mut encoder = get_encoder::<ByteArrayType>(encoding, &desc).unwrap();
encoder.put(data).unwrap();
encoder.flush_buffer().unwrap()
diff --git a/parquet/src/util/test_common/page_util.rs b/parquet/src/util/test_common/page_util.rs
index 858fd8c23472..3db43aef0eec 100644
--- a/parquet/src/util/test_common/page_util.rs
+++ b/parquet/src/util/test_common/page_util.rs
@@ -24,9 +24,10 @@ use crate::data_type::DataType;
use crate::encodings::encoding::{get_encoder, Encoder};
use crate::encodings::levels::LevelEncoder;
use crate::errors::Result;
-use crate::schema::types::ColumnDescPtr;
+use crate::schema::types::{ColumnDescPtr, ColumnDescriptor, ColumnPath, Type as SchemaType};
use std::iter::Peekable;
use std::mem;
+use std::sync::Arc;
pub trait DataPageBuilder {
fn add_rep_levels(&mut self, max_level: i16, rep_levels: &[i16]);
@@ -107,9 +108,22 @@ impl DataPageBuilder for DataPageBuilderImpl {
self.num_values,
values.len()
);
+ // Create test column descriptor.
+ let desc = {
+ let ty = SchemaType::primitive_type_builder("t", T::get_physical_type())
+ .with_length(0)
+ .build()
+ .unwrap();
+ Arc::new(ColumnDescriptor::new(
+ Arc::new(ty),
+ 0,
+ 0,
+ ColumnPath::new(vec![]),
+ ))
+ };
self.encoding = Some(encoding);
let mut encoder: Box<dyn Encoder<T>> =
- get_encoder::<T>(encoding).expect("get_encoder() should be OK");
+ get_encoder::<T>(encoding, &desc).expect("get_encoder() should be OK");
encoder.put(values).expect("put() should be OK");
let encoded_values = encoder
.flush_buffer()
|
Extend support for BYTE_STREAM_SPLIT to FIXED_LEN_BYTE_ARRAY, INT32, and INT64 primitive types
Please correct me if I'm wrong! It seems arrow-rs has added BYTE_STREAM_SPLIT support for [float types](https://github.com/apache/arrow-rs/pull/5293), but not for other numerical data types like INT32.
Since then, the Parquet spec has been expanded to extend BYTE_STREAM_SPLIT encoding to other numerical primitive types: https://github.com/apache/parquet-format/pull/229. The C++ PoC is here: https://github.com/apache/arrow/pull/40094.
It would be good for arrow-rs to support BYTE_STREAM_SPLIT encoding additionally for FIXED_LEN_BYTE_ARRAY, INT32, and INT64.
|
@anjakefala are you working on this? If not I have some free cycles to devote to this.
@etseidl I am not! I would love it if you picked it up. =)
|
2024-07-30T17:56:20Z
|
52.2
|
678517018ddfd21b202a94df13b06dfa1ab8a378
|
apache/arrow-rs
| 6,075
|
apache__arrow-rs-6075
|
[
"6018"
] |
effccc13a9ef6e650049a160734d5ededb2a5383
|
diff --git a/arrow/Cargo.toml b/arrow/Cargo.toml
index 9d3c431b3048..b8f40e1b4b99 100644
--- a/arrow/Cargo.toml
+++ b/arrow/Cargo.toml
@@ -54,7 +54,7 @@ arrow-select = { workspace = true }
arrow-string = { workspace = true }
rand = { version = "0.8", default-features = false, features = ["std", "std_rng"], optional = true }
-pyo3 = { version = "0.21.1", default-features = false, optional = true }
+pyo3 = { version = "0.22.1", default-features = false, optional = true }
[package.metadata.docs.rs]
features = ["prettyprint", "ipc_compression", "ffi", "pyarrow"]
diff --git a/arrow/src/pyarrow.rs b/arrow/src/pyarrow.rs
index 1733067c738a..43cdb4fe0919 100644
--- a/arrow/src/pyarrow.rs
+++ b/arrow/src/pyarrow.rs
@@ -83,11 +83,6 @@ fn to_py_err(err: ArrowError) -> PyErr {
}
pub trait FromPyArrow: Sized {
- #[deprecated(since = "52.0.0", note = "Use from_pyarrow_bound")]
- fn from_pyarrow(value: &PyAny) -> PyResult<Self> {
- Self::from_pyarrow_bound(&value.as_borrowed())
- }
-
fn from_pyarrow_bound(value: &Bound<PyAny>) -> PyResult<Self>;
}
|
diff --git a/arrow-pyarrow-integration-testing/Cargo.toml b/arrow-pyarrow-integration-testing/Cargo.toml
index 6f07d42d88c1..0834f2d13384 100644
--- a/arrow-pyarrow-integration-testing/Cargo.toml
+++ b/arrow-pyarrow-integration-testing/Cargo.toml
@@ -34,4 +34,4 @@ crate-type = ["cdylib"]
[dependencies]
arrow = { path = "../arrow", features = ["pyarrow"] }
-pyo3 = { version = "0.21.1", features = ["extension-module"] }
+pyo3 = { version = "0.22", features = ["extension-module"] }
|
Update pyo3 requirement from 0.21.1 to 0.22.1
Updates the requirements on [pyo3](https://github.com/pyo3/pyo3) to permit the latest version.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a href="https://github.com/pyo3/pyo3/releases">pyo3's releases</a>.</em></p>
<blockquote>
<h2>PyO3 0.22.1</h2>
<p>This patch release improves some cases related to new functionality in PyO3 0.22.</p>
<p><code>PartialEq<bool></code> has been added for <code>Bound<'py, PyBool></code>.</p>
<p>The <code>#[pyo3(submodule)]</code> attribute has been added for declarative modules to stop submodules from generating an external C symbol for importing the submodule directly (which is typically never used). Declarative modules will also now correctly add items annotated with full-path attributes like <code>#[pyo3::prelude::pyfunction]</code>.</p>
<p>The <code>#[pyclass(eq)]</code> option will no longer raise a <code>TypeError</code> on comparison against types not in the signature.</p>
<p>A <code>#[setter]</code> in <code>#[pymethods]</code> with an <code>Option<T></code> input will no longer raise a deprecation warning.</p>
<p>A regression has been fixed in conversions for 128-bit integers on big-endian platforms.</p>
<p>Thank you to the following contributors for the improvements:</p>
<p><a href="https://github.com/alex"><code>@alex</code></a>
<a href="https://github.com/davidhewitt"><code>@davidhewitt</code></a>
<a href="https://github.com/jatoben"><code>@jatoben</code></a>
<a href="https://github.com/kylebarron"><code>@kylebarron</code></a>
<a href="https://github.com/musicinmybrain"><code>@musicinmybrain</code></a>
<a href="https://github.com/ngoldbaum"><code>@ngoldbaum</code></a>
<a href="https://github.com/Owen-CH-Leung"><code>@Owen-CH-Leung</code></a></p>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a href="https://github.com/PyO3/pyo3/blob/main/CHANGELOG.md">pyo3's changelog</a>.</em></p>
<blockquote>
<h2>[0.22.1] - 2024-07-06</h2>
<h3>Added</h3>
<ul>
<li>Add <code>#[pyo3(submodule)]</code> option for declarative <code>#[pymodule]</code>s. <a href="https://redirect.github.com/PyO3/pyo3/pull/4301">#4301</a></li>
<li>Implement <code>PartialEq<bool></code> for <code>Bound<'py, PyBool></code>. <a href="https://redirect.github.com/PyO3/pyo3/pull/4305">#4305</a></li>
</ul>
<h3>Fixed</h3>
<ul>
<li>Return <code>NotImplemented</code> instead of raising <code>TypeError</code> from generated equality method when comparing different types. <a href="https://redirect.github.com/PyO3/pyo3/pull/4287">#4287</a></li>
<li>Handle full-path <code>#[pyo3::prelude::pymodule]</code> and similar for <code>#[pyclass]</code> and <code>#[pyfunction]</code> in declarative modules.<a href="https://redirect.github.com/PyO3/pyo3/pull/4288">#4288</a></li>
<li>Fix 128-bit int regression on big-endian platforms with Python <3.13. <a href="https://redirect.github.com/PyO3/pyo3/pull/4291">#4291</a></li>
<li>Stop generating code that will never be covered with declarative modules. <a href="https://redirect.github.com/PyO3/pyo3/pull/4297">#4297</a></li>
<li>Fix invalid deprecation warning for trailing optional on <code>#[setter]</code> function. <a href="https://redirect.github.com/PyO3/pyo3/pull/4304">#4304</a></li>
</ul>
<h2>[0.22.0] - 2024-06-24</h2>
<h3>Packaging</h3>
<ul>
<li>Update <code>heck</code> dependency to 0.5. <a href="https://redirect.github.com/PyO3/pyo3/pull/3966">#3966</a></li>
<li>Extend range of supported versions of <code>chrono-tz</code> optional dependency to include version 0.10. <a href="https://redirect.github.com/PyO3/pyo3/pull/4061">#4061</a></li>
<li>Update MSRV to 1.63. <a href="https://redirect.github.com/PyO3/pyo3/pull/4129">#4129</a></li>
<li>Add optional <code>num-rational</code> feature to add conversions with Python's <code>fractions.Fraction</code>. <a href="https://redirect.github.com/PyO3/pyo3/pull/4148">#4148</a></li>
<li>Support Python 3.13. <a href="https://redirect.github.com/PyO3/pyo3/pull/4184">#4184</a></li>
</ul>
<h3>Added</h3>
<ul>
<li>Add <code>PyWeakref</code>, <code>PyWeakrefReference</code> and <code>PyWeakrefProxy</code>. <a href="https://redirect.github.com/PyO3/pyo3/pull/3835">#3835</a></li>
<li>Support <code>#[pyclass]</code> on enums that have tuple variants. <a href="https://redirect.github.com/PyO3/pyo3/pull/4072">#4072</a></li>
<li>Add support for scientific notation in <code>Decimal</code> conversion. <a href="https://redirect.github.com/PyO3/pyo3/pull/4079">#4079</a></li>
<li>Add <code>pyo3_disable_reference_pool</code> conditional compilation flag to avoid the overhead of the global reference pool at the cost of known limitations as explained in the performance section of the guide. <a href="https://redirect.github.com/PyO3/pyo3/pull/4095">#4095</a></li>
<li>Add <code>#[pyo3(constructor = (...))]</code> to customize the generated constructors for complex enum variants. <a href="https://redirect.github.com/PyO3/pyo3/pull/4158">#4158</a></li>
<li>Add <code>PyType::module</code>, which always matches Python <code>__module__</code>. <a href="https://redirect.github.com/PyO3/pyo3/pull/4196">#4196</a></li>
<li>Add <code>PyType::fully_qualified_name</code> which matches the "fully qualified name" defined in <a href="https://peps.python.org/pep-0737">PEP 737</a>. <a href="https://redirect.github.com/PyO3/pyo3/pull/4196">#4196</a></li>
<li>Add <code>PyTypeMethods::mro</code> and <code>PyTypeMethods::bases</code>. <a href="https://redirect.github.com/PyO3/pyo3/pull/4197">#4197</a></li>
<li>Add <code>#[pyclass(ord)]</code> to implement ordering based on <code>PartialOrd</code>. <a href="https://redirect.github.com/PyO3/pyo3/pull/4202">#4202</a></li>
<li>Implement <code>ToPyObject</code> and <code>IntoPy<PyObject></code> for <code>PyBackedStr</code> and <code>PyBackedBytes</code>. <a href="https://redirect.github.com/PyO3/pyo3/pull/4205">#4205</a></li>
<li>Add <code>#[pyclass(hash)]</code> option to implement <code>__hash__</code> in terms of the <code>Hash</code> implementation <a href="https://redirect.github.com/PyO3/pyo3/pull/4206">#4206</a></li>
<li>Add <code>#[pyclass(eq)]</code> option to generate <code>__eq__</code> based on <code>PartialEq</code>, and <code>#[pyclass(eq_int)]</code> for simple enums to implement equality based on their discriminants. <a href="https://redirect.github.com/PyO3/pyo3/pull/4210">#4210</a></li>
<li>Implement <code>From<Bound<'py, T>></code> for <code>PyClassInitializer<T></code>. <a href="https://redirect.github.com/PyO3/pyo3/pull/4214">#4214</a></li>
<li>Add <code>as_super</code> methods to <code>PyRef</code> and <code>PyRefMut</code> for accesing the base class by reference. <a href="https://redirect.github.com/PyO3/pyo3/pull/4219">#4219</a></li>
<li>Implement <code>PartialEq<str></code> for <code>Bound<'py, PyString></code>. <a href="https://redirect.github.com/PyO3/pyo3/pull/4245">#4245</a></li>
<li>Implement <code>PyModuleMethods::filename</code> on PyPy. <a href="https://redirect.github.com/PyO3/pyo3/pull/4249">#4249</a></li>
<li>Implement <code>PartialEq<[u8]></code> for <code>Bound<'py, PyBytes></code>. <a href="https://redirect.github.com/PyO3/pyo3/pull/4250">#4250</a></li>
<li>Add <code>pyo3_ffi::c_str</code> macro to create <code>&'static CStr</code> on Rust versions which don't have 1.77's <code>c""</code> literals. <a href="https://redirect.github.com/PyO3/pyo3/pull/4255">#4255</a></li>
<li>Support <code>bool</code> conversion with <code>numpy</code> 2.0's <code>numpy.bool</code> type <a href="https://redirect.github.com/PyO3/pyo3/pull/4258">#4258</a></li>
<li>Add <code>PyAnyMethods::{bitnot, matmul, floor_div, rem, divmod}</code>. <a href="https://redirect.github.com/PyO3/pyo3/pull/4264">#4264</a></li>
</ul>
<h3>Changed</h3>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a href="https://github.com/PyO3/pyo3/commit/59c4fa3f249aa19eb9cb80fe418298c8267c00b2"><code>59c4fa3</code></a> release: 0.22.1 (<a href="https://redirect.github.com/pyo3/pyo3/issues/4314">#4314</a>)</li>
<li><a href="https://github.com/PyO3/pyo3/commit/9afc38ae416bb750efd227e4f8b4302392c0d303"><code>9afc38a</code></a> fixes <a href="https://redirect.github.com/pyo3/pyo3/issues/4285">#4285</a> -- allow full-path to pymodule with nested declarative modules (#...</li>
<li><a href="https://github.com/PyO3/pyo3/commit/5860c4f7e9615afcf33b3905c95211d54242fad7"><code>5860c4f</code></a> implement PartialEq for Pybool & bool (<a href="https://redirect.github.com/pyo3/pyo3/issues/4305">#4305</a>)</li>
<li><a href="https://github.com/PyO3/pyo3/commit/0af02278342bada5c76bded787d4a7736cbdb96a"><code>0af0227</code></a> fix deprecation warning for trailing optional on <code>#[setter]</code> functions (<a href="https://redirect.github.com/pyo3/pyo3/issues/4304">#4304</a>)</li>
<li><a href="https://github.com/PyO3/pyo3/commit/ee9123a2d278dee8b461f9c3ee3235dee9c755c0"><code>ee9123a</code></a> Fix link in the contribution guide (<a href="https://redirect.github.com/pyo3/pyo3/issues/4306">#4306</a>)</li>
<li><a href="https://github.com/PyO3/pyo3/commit/ccd04475a30409f226a1e044239c6b7e35260e98"><code>ccd0447</code></a> refs <a href="https://redirect.github.com/pyo3/pyo3/issues/4286">#4286</a> -- allow setting submodule on declarative pymodules (<a href="https://redirect.github.com/pyo3/pyo3/issues/4301">#4301</a>)</li>
<li><a href="https://github.com/PyO3/pyo3/commit/f3603a0a483448c71f1811786257d070733540bf"><code>f3603a0</code></a> Avoid generating functions that are only ever const evaluated with declarativ...</li>
<li><a href="https://github.com/PyO3/pyo3/commit/872bd7e6f7390ff2035b1d164582aace33d69e76"><code>872bd7e</code></a> Add pyo3-arrow to README (<a href="https://redirect.github.com/pyo3/pyo3/issues/4302">#4302</a>)</li>
<li><a href="https://github.com/PyO3/pyo3/commit/8f7450e33d9edcab790d5b2ad303cbb81a86536e"><code>8f7450e</code></a> Fix 128-bit int regression on big-endian with Python <3.13 (<a href="https://redirect.github.com/pyo3/pyo3/issues/4291">#4291</a>)</li>
<li><a href="https://github.com/PyO3/pyo3/commit/7c2f5e80de3a08bacd125164178da5f739b1b379"><code>7c2f5e8</code></a> Don't raise <code>TypeError</code> from generated equality method (<a href="https://redirect.github.com/pyo3/pyo3/issues/4287">#4287</a>)</li>
<li>Additional commits viewable in <a href="https://github.com/pyo3/pyo3/compare/v0.21.1...v0.22.1">compare view</a></li>
</ul>
</details>
<br />
Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.
[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)
---
<details>
<summary>Dependabot commands and options</summary>
<br />
You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
</details>
|
2024-07-17T12:48:19Z
|
52.1
|
effccc13a9ef6e650049a160734d5ededb2a5383
|
|
apache/arrow-rs
| 6,046
|
apache__arrow-rs-6046
|
[
"4328"
] |
6d4e2f2ceaf423031b0bc72f54c547dd77a0ddbb
|
diff --git a/parquet/Cargo.toml b/parquet/Cargo.toml
index 2fb808e1ec8d..2cc12a81dea5 100644
--- a/parquet/Cargo.toml
+++ b/parquet/Cargo.toml
@@ -134,6 +134,11 @@ path = "./examples/read_with_rowgroup.rs"
name = "arrow_writer_layout"
required-features = ["arrow"]
+[[test]]
+name = "arrow_reader"
+required-features = ["arrow"]
+path = "./tests/arrow_reader/mod.rs"
+
[[bin]]
name = "parquet-read"
required-features = ["cli"]
@@ -180,6 +185,12 @@ name = "arrow_reader"
required-features = ["arrow", "test_common", "experimental"]
harness = false
+[[bench]]
+name = "arrow_statistics"
+required-features = ["arrow"]
+harness = false
+
+
[[bench]]
name = "compression"
required-features = ["experimental", "default"]
@@ -190,7 +201,6 @@ name = "encoding"
required-features = ["experimental", "default"]
harness = false
-
[[bench]]
name = "metadata"
harness = false
diff --git a/parquet/benches/arrow_statistics.rs b/parquet/benches/arrow_statistics.rs
new file mode 100644
index 000000000000..ebc2fb38a7ec
--- /dev/null
+++ b/parquet/benches/arrow_statistics.rs
@@ -0,0 +1,269 @@
+// 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.
+
+//! Benchmarks of benchmark for extracting arrow statistics from parquet
+
+use arrow::array::{ArrayRef, DictionaryArray, Float64Array, StringArray, UInt64Array};
+use arrow_array::{Int32Array, Int64Array, RecordBatch};
+use arrow_schema::{
+ DataType::{self, *},
+ Field, Schema,
+};
+use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
+use parquet::{arrow::arrow_reader::ArrowReaderOptions, file::properties::WriterProperties};
+use parquet::{
+ arrow::{arrow_reader::ArrowReaderBuilder, ArrowWriter},
+ file::properties::EnabledStatistics,
+};
+use std::sync::Arc;
+use tempfile::NamedTempFile;
+#[derive(Debug, Clone)]
+enum TestTypes {
+ UInt64,
+ Int64,
+ F64,
+ String,
+ Dictionary,
+}
+
+use parquet::arrow::arrow_reader::statistics::StatisticsConverter;
+use std::fmt;
+
+impl fmt::Display for TestTypes {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ match self {
+ TestTypes::UInt64 => write!(f, "UInt64"),
+ TestTypes::Int64 => write!(f, "Int64"),
+ TestTypes::F64 => write!(f, "F64"),
+ TestTypes::String => write!(f, "String"),
+ TestTypes::Dictionary => write!(f, "Dictionary(Int32, String)"),
+ }
+ }
+}
+
+fn create_parquet_file(
+ dtype: TestTypes,
+ row_groups: usize,
+ data_page_row_count_limit: &Option<usize>,
+) -> NamedTempFile {
+ let schema = match dtype {
+ TestTypes::UInt64 => Arc::new(Schema::new(vec![Field::new("col", DataType::UInt64, true)])),
+ TestTypes::Int64 => Arc::new(Schema::new(vec![Field::new("col", DataType::Int64, true)])),
+ TestTypes::F64 => Arc::new(Schema::new(vec![Field::new(
+ "col",
+ DataType::Float64,
+ true,
+ )])),
+ TestTypes::String => Arc::new(Schema::new(vec![Field::new("col", DataType::Utf8, true)])),
+ TestTypes::Dictionary => Arc::new(Schema::new(vec![Field::new(
+ "col",
+ DataType::Dictionary(Box::new(Int32), Box::new(Utf8)),
+ true,
+ )])),
+ };
+
+ let mut props = WriterProperties::builder().set_max_row_group_size(row_groups);
+ if let Some(limit) = data_page_row_count_limit {
+ props = props
+ .set_data_page_row_count_limit(*limit)
+ .set_statistics_enabled(EnabledStatistics::Page);
+ };
+ let props = props.build();
+
+ let file = tempfile::Builder::new()
+ .suffix(".parquet")
+ .tempfile()
+ .unwrap();
+ let mut writer =
+ ArrowWriter::try_new(file.reopen().unwrap(), schema.clone(), Some(props)).unwrap();
+
+ for _ in 0..row_groups {
+ let batch = match dtype {
+ TestTypes::UInt64 => make_uint64_batch(),
+ TestTypes::Int64 => make_int64_batch(),
+ TestTypes::F64 => make_f64_batch(),
+ TestTypes::String => make_string_batch(),
+ TestTypes::Dictionary => make_dict_batch(),
+ };
+ if data_page_row_count_limit.is_some() {
+ // Send batches one at a time. This allows the
+ // writer to apply the page limit, that is only
+ // checked on RecordBatch boundaries.
+ for i in 0..batch.num_rows() {
+ writer.write(&batch.slice(i, 1)).unwrap();
+ }
+ } else {
+ writer.write(&batch).unwrap();
+ }
+ }
+ writer.close().unwrap();
+ file
+}
+
+fn make_uint64_batch() -> RecordBatch {
+ let array: ArrayRef = Arc::new(UInt64Array::from(vec![
+ Some(1),
+ Some(2),
+ Some(3),
+ Some(4),
+ Some(5),
+ ]));
+ RecordBatch::try_new(
+ Arc::new(arrow::datatypes::Schema::new(vec![
+ arrow::datatypes::Field::new("col", UInt64, false),
+ ])),
+ vec![array],
+ )
+ .unwrap()
+}
+
+fn make_int64_batch() -> RecordBatch {
+ let array: ArrayRef = Arc::new(Int64Array::from(vec![
+ Some(1),
+ Some(2),
+ Some(3),
+ Some(4),
+ Some(5),
+ ]));
+ RecordBatch::try_new(
+ Arc::new(arrow::datatypes::Schema::new(vec![
+ arrow::datatypes::Field::new("col", Int64, false),
+ ])),
+ vec![array],
+ )
+ .unwrap()
+}
+
+fn make_f64_batch() -> RecordBatch {
+ let array: ArrayRef = Arc::new(Float64Array::from(vec![1.0, 2.0, 3.0, 4.0, 5.0]));
+ RecordBatch::try_new(
+ Arc::new(arrow::datatypes::Schema::new(vec![
+ arrow::datatypes::Field::new("col", Float64, false),
+ ])),
+ vec![array],
+ )
+ .unwrap()
+}
+
+fn make_string_batch() -> RecordBatch {
+ let array: ArrayRef = Arc::new(StringArray::from(vec!["a", "b", "c", "d", "e"]));
+ RecordBatch::try_new(
+ Arc::new(arrow::datatypes::Schema::new(vec![
+ arrow::datatypes::Field::new("col", Utf8, false),
+ ])),
+ vec![array],
+ )
+ .unwrap()
+}
+
+fn make_dict_batch() -> RecordBatch {
+ let keys = Int32Array::from(vec![0, 1, 2, 3, 4]);
+ let values = StringArray::from(vec!["a", "b", "c", "d", "e"]);
+ let array: ArrayRef = Arc::new(DictionaryArray::try_new(keys, Arc::new(values)).unwrap());
+ RecordBatch::try_new(
+ Arc::new(Schema::new(vec![Field::new(
+ "col",
+ Dictionary(Box::new(Int32), Box::new(Utf8)),
+ false,
+ )])),
+ vec![array],
+ )
+ .unwrap()
+}
+
+fn criterion_benchmark(c: &mut Criterion) {
+ let row_groups = 100;
+ use TestTypes::*;
+ let types = vec![Int64, UInt64, F64, String, Dictionary];
+ let data_page_row_count_limits = vec![None, Some(1)];
+
+ for dtype in types {
+ for data_page_row_count_limit in &data_page_row_count_limits {
+ let file = create_parquet_file(dtype.clone(), row_groups, data_page_row_count_limit);
+ let file = file.reopen().unwrap();
+ let options = ArrowReaderOptions::new().with_page_index(true);
+ let reader = ArrowReaderBuilder::try_new_with_options(file, options).unwrap();
+ let metadata = reader.metadata();
+ let row_groups = metadata.row_groups();
+ let row_group_indices: Vec<_> = (0..row_groups.len()).collect();
+
+ let statistic_type = if data_page_row_count_limit.is_some() {
+ "data page"
+ } else {
+ "row group"
+ };
+
+ let mut group = c.benchmark_group(format!(
+ "Extract {} statistics for {}",
+ statistic_type,
+ dtype.clone()
+ ));
+ group.bench_function(BenchmarkId::new("extract_statistics", dtype.clone()), |b| {
+ b.iter(|| {
+ let converter = StatisticsConverter::try_new(
+ "col",
+ reader.schema(),
+ reader.parquet_schema(),
+ )
+ .unwrap();
+
+ if data_page_row_count_limit.is_some() {
+ let column_page_index = reader
+ .metadata()
+ .column_index()
+ .expect("File should have column page indices");
+
+ let column_offset_index = reader
+ .metadata()
+ .offset_index()
+ .expect("File should have column offset indices");
+
+ let _ = converter.data_page_mins(
+ column_page_index,
+ column_offset_index,
+ &row_group_indices,
+ );
+ let _ = converter.data_page_maxes(
+ column_page_index,
+ column_offset_index,
+ &row_group_indices,
+ );
+ let _ = converter.data_page_null_counts(
+ column_page_index,
+ column_offset_index,
+ &row_group_indices,
+ );
+ let _ = converter.data_page_row_counts(
+ column_offset_index,
+ row_groups,
+ &row_group_indices,
+ );
+ } else {
+ let _ = converter.row_group_mins(row_groups.iter()).unwrap();
+ let _ = converter.row_group_maxes(row_groups.iter()).unwrap();
+ let _ = converter.row_group_null_counts(row_groups.iter()).unwrap();
+ let _ = converter.row_group_row_counts(row_groups.iter()).unwrap();
+ }
+ })
+ });
+ group.finish();
+ }
+ }
+}
+
+criterion_group!(benches, criterion_benchmark);
+criterion_main!(benches);
diff --git a/parquet/src/arrow/arrow_reader/mod.rs b/parquet/src/arrow/arrow_reader/mod.rs
index 71bb0b5e2ec0..e9edf7cb751d 100644
--- a/parquet/src/arrow/arrow_reader/mod.rs
+++ b/parquet/src/arrow/arrow_reader/mod.rs
@@ -42,6 +42,7 @@ use crate::schema::types::SchemaDescriptor;
mod filter;
mod selection;
+pub mod statistics;
/// Builder for constructing parquet readers into arrow.
///
diff --git a/parquet/src/arrow/arrow_reader/statistics.rs b/parquet/src/arrow/arrow_reader/statistics.rs
new file mode 100644
index 000000000000..d536792b827b
--- /dev/null
+++ b/parquet/src/arrow/arrow_reader/statistics.rs
@@ -0,0 +1,2536 @@
+// 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.
+
+//! [`StatisticsConverter`] to convert statistics in parquet format to arrow [`ArrayRef`].
+
+use crate::arrow::buffer::bit_util::sign_extend_be;
+use crate::arrow::parquet_column;
+use crate::data_type::{ByteArray, FixedLenByteArray};
+use crate::errors::{ParquetError, Result};
+use crate::file::metadata::{ParquetColumnIndex, ParquetOffsetIndex, RowGroupMetaData};
+use crate::file::page_index::index::{Index, PageIndex};
+use crate::file::statistics::Statistics as ParquetStatistics;
+use crate::schema::types::SchemaDescriptor;
+use arrow_array::builder::{
+ BooleanBuilder, FixedSizeBinaryBuilder, LargeStringBuilder, StringBuilder,
+};
+use arrow_array::{
+ new_empty_array, new_null_array, ArrayRef, BinaryArray, BooleanArray, Date32Array, Date64Array,
+ Decimal128Array, Decimal256Array, Float16Array, Float32Array, Float64Array, Int16Array,
+ Int32Array, Int64Array, Int8Array, LargeBinaryArray, Time32MillisecondArray, Time32SecondArray,
+ Time64MicrosecondArray, Time64NanosecondArray, TimestampMicrosecondArray,
+ TimestampMillisecondArray, TimestampNanosecondArray, TimestampSecondArray, UInt16Array,
+ UInt32Array, UInt64Array, UInt8Array,
+};
+use arrow_buffer::i256;
+use arrow_schema::{DataType, Field, Schema, TimeUnit};
+use half::f16;
+use paste::paste;
+use std::sync::Arc;
+
+// Convert the bytes array to i128.
+// The endian of the input bytes array must be big-endian.
+pub(crate) fn from_bytes_to_i128(b: &[u8]) -> i128 {
+ // The bytes array are from parquet file and must be the big-endian.
+ // The endian is defined by parquet format, and the reference document
+ // https://github.com/apache/parquet-format/blob/54e53e5d7794d383529dd30746378f19a12afd58/src/main/thrift/parquet.thrift#L66
+ i128::from_be_bytes(sign_extend_be::<16>(b))
+}
+
+// Convert the bytes array to i256.
+// The endian of the input bytes array must be big-endian.
+pub(crate) fn from_bytes_to_i256(b: &[u8]) -> i256 {
+ i256::from_be_bytes(sign_extend_be::<32>(b))
+}
+
+// Convert the bytes array to f16
+pub(crate) fn from_bytes_to_f16(b: &[u8]) -> Option<f16> {
+ match b {
+ [low, high] => Some(f16::from_be_bytes([*high, *low])),
+ _ => None,
+ }
+}
+
+/// Define an adapter iterator for extracting statistics from an iterator of
+/// `ParquetStatistics`
+///
+///
+/// Handles checking if the statistics are present and valid with the correct type.
+///
+/// Parameters:
+/// * `$iterator_type` is the name of the iterator type (e.g. `MinBooleanStatsIterator`)
+/// * `$func` is the function to call to get the value (e.g. `min` or `max`)
+/// * `$parquet_statistics_type` is the type of the statistics (e.g. `ParquetStatistics::Boolean`)
+/// * `$stat_value_type` is the type of the statistics value (e.g. `bool`)
+macro_rules! make_stats_iterator {
+ ($iterator_type:ident, $func:ident, $parquet_statistics_type:path, $stat_value_type:ty) => {
+ /// Maps an iterator of `ParquetStatistics` into an iterator of
+ /// `&$stat_value_type``
+ ///
+ /// Yielded elements:
+ /// * Some(stats) if valid
+ /// * None if the statistics are not present, not valid, or not $stat_value_type
+ struct $iterator_type<'a, I>
+ where
+ I: Iterator<Item = Option<&'a ParquetStatistics>>,
+ {
+ iter: I,
+ }
+
+ impl<'a, I> $iterator_type<'a, I>
+ where
+ I: Iterator<Item = Option<&'a ParquetStatistics>>,
+ {
+ /// Create a new iterator to extract the statistics
+ fn new(iter: I) -> Self {
+ Self { iter }
+ }
+ }
+
+ /// Implement the Iterator trait for the iterator
+ impl<'a, I> Iterator for $iterator_type<'a, I>
+ where
+ I: Iterator<Item = Option<&'a ParquetStatistics>>,
+ {
+ type Item = Option<&'a $stat_value_type>;
+
+ /// return the next statistics value
+ fn next(&mut self) -> Option<Self::Item> {
+ let next = self.iter.next();
+ next.map(|x| {
+ x.and_then(|stats| match stats {
+ $parquet_statistics_type(s) if stats.has_min_max_set() => Some(s.$func()),
+ _ => None,
+ })
+ })
+ }
+
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ self.iter.size_hint()
+ }
+ }
+ };
+}
+
+make_stats_iterator!(
+ MinBooleanStatsIterator,
+ min,
+ ParquetStatistics::Boolean,
+ bool
+);
+make_stats_iterator!(
+ MaxBooleanStatsIterator,
+ max,
+ ParquetStatistics::Boolean,
+ bool
+);
+make_stats_iterator!(MinInt32StatsIterator, min, ParquetStatistics::Int32, i32);
+make_stats_iterator!(MaxInt32StatsIterator, max, ParquetStatistics::Int32, i32);
+make_stats_iterator!(MinInt64StatsIterator, min, ParquetStatistics::Int64, i64);
+make_stats_iterator!(MaxInt64StatsIterator, max, ParquetStatistics::Int64, i64);
+make_stats_iterator!(MinFloatStatsIterator, min, ParquetStatistics::Float, f32);
+make_stats_iterator!(MaxFloatStatsIterator, max, ParquetStatistics::Float, f32);
+make_stats_iterator!(MinDoubleStatsIterator, min, ParquetStatistics::Double, f64);
+make_stats_iterator!(MaxDoubleStatsIterator, max, ParquetStatistics::Double, f64);
+make_stats_iterator!(
+ MinByteArrayStatsIterator,
+ min_bytes,
+ ParquetStatistics::ByteArray,
+ [u8]
+);
+make_stats_iterator!(
+ MaxByteArrayStatsIterator,
+ max_bytes,
+ ParquetStatistics::ByteArray,
+ [u8]
+);
+make_stats_iterator!(
+ MinFixedLenByteArrayStatsIterator,
+ min_bytes,
+ ParquetStatistics::FixedLenByteArray,
+ [u8]
+);
+make_stats_iterator!(
+ MaxFixedLenByteArrayStatsIterator,
+ max_bytes,
+ ParquetStatistics::FixedLenByteArray,
+ [u8]
+);
+
+/// Special iterator adapter for extracting i128 values from from an iterator of
+/// `ParquetStatistics`
+///
+/// Handles checking if the statistics are present and valid with the correct type.
+///
+/// Depending on the parquet file, the statistics for `Decimal128` can be stored as
+/// `Int32`, `Int64` or `ByteArray` or `FixedSizeByteArray` :mindblown:
+///
+/// This iterator handles all cases, extracting the values
+/// and converting it to `stat_value_type`.
+///
+/// Parameters:
+/// * `$iterator_type` is the name of the iterator type (e.g. `MinBooleanStatsIterator`)
+/// * `$func` is the function to call to get the value (e.g. `min` or `max`)
+/// * `$bytes_func` is the function to call to get the value as bytes (e.g. `min_bytes` or `max_bytes`)
+/// * `$stat_value_type` is the type of the statistics value (e.g. `i128`)
+/// * `convert_func` is the function to convert the bytes to stats value (e.g. `from_bytes_to_i128`)
+macro_rules! make_decimal_stats_iterator {
+ ($iterator_type:ident, $func:ident, $bytes_func:ident, $stat_value_type:ident, $convert_func: ident) => {
+ struct $iterator_type<'a, I>
+ where
+ I: Iterator<Item = Option<&'a ParquetStatistics>>,
+ {
+ iter: I,
+ }
+
+ impl<'a, I> $iterator_type<'a, I>
+ where
+ I: Iterator<Item = Option<&'a ParquetStatistics>>,
+ {
+ fn new(iter: I) -> Self {
+ Self { iter }
+ }
+ }
+
+ impl<'a, I> Iterator for $iterator_type<'a, I>
+ where
+ I: Iterator<Item = Option<&'a ParquetStatistics>>,
+ {
+ type Item = Option<$stat_value_type>;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ let next = self.iter.next();
+ next.map(|x| {
+ x.and_then(|stats| {
+ if !stats.has_min_max_set() {
+ return None;
+ }
+ match stats {
+ ParquetStatistics::Int32(s) => Some($stat_value_type::from(*s.$func())),
+ ParquetStatistics::Int64(s) => Some($stat_value_type::from(*s.$func())),
+ ParquetStatistics::ByteArray(s) => Some($convert_func(s.$bytes_func())),
+ ParquetStatistics::FixedLenByteArray(s) => {
+ Some($convert_func(s.$bytes_func()))
+ }
+ _ => None,
+ }
+ })
+ })
+ }
+
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ self.iter.size_hint()
+ }
+ }
+ };
+}
+
+make_decimal_stats_iterator!(
+ MinDecimal128StatsIterator,
+ min,
+ min_bytes,
+ i128,
+ from_bytes_to_i128
+);
+make_decimal_stats_iterator!(
+ MaxDecimal128StatsIterator,
+ max,
+ max_bytes,
+ i128,
+ from_bytes_to_i128
+);
+make_decimal_stats_iterator!(
+ MinDecimal256StatsIterator,
+ min,
+ min_bytes,
+ i256,
+ from_bytes_to_i256
+);
+make_decimal_stats_iterator!(
+ MaxDecimal256StatsIterator,
+ max,
+ max_bytes,
+ i256,
+ from_bytes_to_i256
+);
+
+/// Special macro to combine the statistics iterators for min and max using the [`mod@paste`] macro.
+/// This is used to avoid repeating the same code for min and max statistics extractions
+///
+/// Parameters:
+/// stat_type_prefix: The prefix of the statistics iterator type (e.g. `Min` or `Max`)
+/// data_type: The data type of the statistics (e.g. `DataType::Int32`)
+/// iterator: The iterator of [`ParquetStatistics`] to extract the statistics from.
+macro_rules! get_statistics {
+ ($stat_type_prefix: ident, $data_type: ident, $iterator: ident) => {
+ paste! {
+ match $data_type {
+ DataType::Boolean => Ok(Arc::new(BooleanArray::from_iter(
+ [<$stat_type_prefix BooleanStatsIterator>]::new($iterator).map(|x| x.copied()),
+ ))),
+ DataType::Int8 => Ok(Arc::new(Int8Array::from_iter(
+ [<$stat_type_prefix Int32StatsIterator>]::new($iterator).map(|x| {
+ x.and_then(|x| i8::try_from(*x).ok())
+ }),
+ ))),
+ DataType::Int16 => Ok(Arc::new(Int16Array::from_iter(
+ [<$stat_type_prefix Int32StatsIterator>]::new($iterator).map(|x| {
+ x.and_then(|x| i16::try_from(*x).ok())
+ }),
+ ))),
+ DataType::Int32 => Ok(Arc::new(Int32Array::from_iter(
+ [<$stat_type_prefix Int32StatsIterator>]::new($iterator).map(|x| x.copied()),
+ ))),
+ DataType::Int64 => Ok(Arc::new(Int64Array::from_iter(
+ [<$stat_type_prefix Int64StatsIterator>]::new($iterator).map(|x| x.copied()),
+ ))),
+ DataType::UInt8 => Ok(Arc::new(UInt8Array::from_iter(
+ [<$stat_type_prefix Int32StatsIterator>]::new($iterator).map(|x| {
+ x.and_then(|x| u8::try_from(*x).ok())
+ }),
+ ))),
+ DataType::UInt16 => Ok(Arc::new(UInt16Array::from_iter(
+ [<$stat_type_prefix Int32StatsIterator>]::new($iterator).map(|x| {
+ x.and_then(|x| u16::try_from(*x).ok())
+ }),
+ ))),
+ DataType::UInt32 => Ok(Arc::new(UInt32Array::from_iter(
+ [<$stat_type_prefix Int32StatsIterator>]::new($iterator).map(|x| x.map(|x| *x as u32)),
+ ))),
+ DataType::UInt64 => Ok(Arc::new(UInt64Array::from_iter(
+ [<$stat_type_prefix Int64StatsIterator>]::new($iterator).map(|x| x.map(|x| *x as u64)),
+ ))),
+ DataType::Float16 => Ok(Arc::new(Float16Array::from_iter(
+ [<$stat_type_prefix FixedLenByteArrayStatsIterator>]::new($iterator).map(|x| x.and_then(|x| {
+ from_bytes_to_f16(x)
+ })),
+ ))),
+ DataType::Float32 => Ok(Arc::new(Float32Array::from_iter(
+ [<$stat_type_prefix FloatStatsIterator>]::new($iterator).map(|x| x.copied()),
+ ))),
+ DataType::Float64 => Ok(Arc::new(Float64Array::from_iter(
+ [<$stat_type_prefix DoubleStatsIterator>]::new($iterator).map(|x| x.copied()),
+ ))),
+ DataType::Date32 => Ok(Arc::new(Date32Array::from_iter(
+ [<$stat_type_prefix Int32StatsIterator>]::new($iterator).map(|x| x.copied()),
+ ))),
+ DataType::Date64 => Ok(Arc::new(Date64Array::from_iter(
+ [<$stat_type_prefix Int32StatsIterator>]::new($iterator)
+ .map(|x| x.map(|x| i64::from(*x) * 24 * 60 * 60 * 1000)),
+ ))),
+ DataType::Timestamp(unit, timezone) =>{
+ let iter = [<$stat_type_prefix Int64StatsIterator>]::new($iterator).map(|x| x.copied());
+ Ok(match unit {
+ TimeUnit::Second => Arc::new(TimestampSecondArray::from_iter(iter).with_timezone_opt(timezone.clone())),
+ TimeUnit::Millisecond => Arc::new(TimestampMillisecondArray::from_iter(iter).with_timezone_opt(timezone.clone())),
+ TimeUnit::Microsecond => Arc::new(TimestampMicrosecondArray::from_iter(iter).with_timezone_opt(timezone.clone())),
+ TimeUnit::Nanosecond => Arc::new(TimestampNanosecondArray::from_iter(iter).with_timezone_opt(timezone.clone())),
+ })
+ },
+ DataType::Time32(unit) => {
+ Ok(match unit {
+ TimeUnit::Second => Arc::new(Time32SecondArray::from_iter(
+ [<$stat_type_prefix Int32StatsIterator>]::new($iterator).map(|x| x.copied()),
+ )),
+ TimeUnit::Millisecond => Arc::new(Time32MillisecondArray::from_iter(
+ [<$stat_type_prefix Int32StatsIterator>]::new($iterator).map(|x| x.copied()),
+ )),
+ _ => {
+ let len = $iterator.count();
+ // don't know how to extract statistics, so return a null array
+ new_null_array($data_type, len)
+ }
+ })
+ },
+ DataType::Time64(unit) => {
+ Ok(match unit {
+ TimeUnit::Microsecond => Arc::new(Time64MicrosecondArray::from_iter(
+ [<$stat_type_prefix Int64StatsIterator>]::new($iterator).map(|x| x.copied()),
+ )),
+ TimeUnit::Nanosecond => Arc::new(Time64NanosecondArray::from_iter(
+ [<$stat_type_prefix Int64StatsIterator>]::new($iterator).map(|x| x.copied()),
+ )),
+ _ => {
+ let len = $iterator.count();
+ // don't know how to extract statistics, so return a null array
+ new_null_array($data_type, len)
+ }
+ })
+ },
+ DataType::Binary => Ok(Arc::new(BinaryArray::from_iter(
+ [<$stat_type_prefix ByteArrayStatsIterator>]::new($iterator)
+ ))),
+ DataType::LargeBinary => Ok(Arc::new(LargeBinaryArray::from_iter(
+ [<$stat_type_prefix ByteArrayStatsIterator>]::new($iterator)
+ ))),
+ DataType::Utf8 => {
+ let iterator = [<$stat_type_prefix ByteArrayStatsIterator>]::new($iterator);
+ let mut builder = StringBuilder::new();
+ for x in iterator {
+ let Some(x) = x else {
+ builder.append_null(); // no statistics value
+ continue;
+ };
+
+ let Ok(x) = std::str::from_utf8(x) else {
+ builder.append_null();
+ continue;
+ };
+
+ builder.append_value(x);
+ }
+ Ok(Arc::new(builder.finish()))
+ },
+ DataType::LargeUtf8 => {
+ let iterator = [<$stat_type_prefix ByteArrayStatsIterator>]::new($iterator);
+ let mut builder = LargeStringBuilder::new();
+ for x in iterator {
+ let Some(x) = x else {
+ builder.append_null(); // no statistics value
+ continue;
+ };
+
+ let Ok(x) = std::str::from_utf8(x) else {
+ builder.append_null();
+ continue;
+ };
+
+ builder.append_value(x);
+ }
+ Ok(Arc::new(builder.finish()))
+ },
+ DataType::FixedSizeBinary(size) => {
+ let iterator = [<$stat_type_prefix FixedLenByteArrayStatsIterator>]::new($iterator);
+ let mut builder = FixedSizeBinaryBuilder::new(*size);
+ for x in iterator {
+ let Some(x) = x else {
+ builder.append_null(); // no statistics value
+ continue;
+ };
+
+ // ignore invalid values
+ if x.len().try_into() != Ok(*size){
+ builder.append_null();
+ continue;
+ }
+
+ builder.append_value(x).expect("ensure to append successfully here, because size have been checked before");
+ }
+ Ok(Arc::new(builder.finish()))
+ },
+ DataType::Decimal128(precision, scale) => {
+ let arr = Decimal128Array::from_iter(
+ [<$stat_type_prefix Decimal128StatsIterator>]::new($iterator)
+ ).with_precision_and_scale(*precision, *scale)?;
+ Ok(Arc::new(arr))
+ },
+ DataType::Decimal256(precision, scale) => {
+ let arr = Decimal256Array::from_iter(
+ [<$stat_type_prefix Decimal256StatsIterator>]::new($iterator)
+ ).with_precision_and_scale(*precision, *scale)?;
+ Ok(Arc::new(arr))
+ },
+ DataType::Dictionary(_, value_type) => {
+ [<$stat_type_prefix:lower _ statistics>](value_type, $iterator)
+ }
+
+ DataType::Map(_,_) |
+ DataType::Duration(_) |
+ DataType::Interval(_) |
+ DataType::Null |
+ DataType::BinaryView |
+ DataType::Utf8View |
+ DataType::List(_) |
+ DataType::ListView(_) |
+ DataType::FixedSizeList(_, _) |
+ DataType::LargeList(_) |
+ DataType::LargeListView(_) |
+ DataType::Struct(_) |
+ DataType::Union(_, _) |
+ DataType::RunEndEncoded(_, _) => {
+ let len = $iterator.count();
+ // don't know how to extract statistics, so return a null array
+ Ok(new_null_array($data_type, len))
+ }
+ }}}
+}
+
+macro_rules! make_data_page_stats_iterator {
+ ($iterator_type: ident, $func: expr, $index_type: path, $stat_value_type: ty) => {
+ struct $iterator_type<'a, I>
+ where
+ I: Iterator<Item = (usize, &'a Index)>,
+ {
+ iter: I,
+ }
+
+ impl<'a, I> $iterator_type<'a, I>
+ where
+ I: Iterator<Item = (usize, &'a Index)>,
+ {
+ fn new(iter: I) -> Self {
+ Self { iter }
+ }
+ }
+
+ impl<'a, I> Iterator for $iterator_type<'a, I>
+ where
+ I: Iterator<Item = (usize, &'a Index)>,
+ {
+ type Item = Vec<Option<$stat_value_type>>;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ let next = self.iter.next();
+ match next {
+ Some((len, index)) => match index {
+ $index_type(native_index) => Some(
+ native_index
+ .indexes
+ .iter()
+ .map(|x| $func(x))
+ .collect::<Vec<_>>(),
+ ),
+ // No matching `Index` found;
+ // thus no statistics that can be extracted.
+ // We return vec![None; len] to effectively
+ // create an arrow null-array with the length
+ // corresponding to the number of entries in
+ // `ParquetOffsetIndex` per row group per column.
+ _ => Some(vec![None; len]),
+ },
+ _ => None,
+ }
+ }
+
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ self.iter.size_hint()
+ }
+ }
+ };
+}
+
+make_data_page_stats_iterator!(
+ MinBooleanDataPageStatsIterator,
+ |x: &PageIndex<bool>| { x.min },
+ Index::BOOLEAN,
+ bool
+);
+make_data_page_stats_iterator!(
+ MaxBooleanDataPageStatsIterator,
+ |x: &PageIndex<bool>| { x.max },
+ Index::BOOLEAN,
+ bool
+);
+make_data_page_stats_iterator!(
+ MinInt32DataPageStatsIterator,
+ |x: &PageIndex<i32>| { x.min },
+ Index::INT32,
+ i32
+);
+make_data_page_stats_iterator!(
+ MaxInt32DataPageStatsIterator,
+ |x: &PageIndex<i32>| { x.max },
+ Index::INT32,
+ i32
+);
+make_data_page_stats_iterator!(
+ MinInt64DataPageStatsIterator,
+ |x: &PageIndex<i64>| { x.min },
+ Index::INT64,
+ i64
+);
+make_data_page_stats_iterator!(
+ MaxInt64DataPageStatsIterator,
+ |x: &PageIndex<i64>| { x.max },
+ Index::INT64,
+ i64
+);
+make_data_page_stats_iterator!(
+ MinFloat16DataPageStatsIterator,
+ |x: &PageIndex<FixedLenByteArray>| { x.min.clone() },
+ Index::FIXED_LEN_BYTE_ARRAY,
+ FixedLenByteArray
+);
+make_data_page_stats_iterator!(
+ MaxFloat16DataPageStatsIterator,
+ |x: &PageIndex<FixedLenByteArray>| { x.max.clone() },
+ Index::FIXED_LEN_BYTE_ARRAY,
+ FixedLenByteArray
+);
+make_data_page_stats_iterator!(
+ MinFloat32DataPageStatsIterator,
+ |x: &PageIndex<f32>| { x.min },
+ Index::FLOAT,
+ f32
+);
+make_data_page_stats_iterator!(
+ MaxFloat32DataPageStatsIterator,
+ |x: &PageIndex<f32>| { x.max },
+ Index::FLOAT,
+ f32
+);
+make_data_page_stats_iterator!(
+ MinFloat64DataPageStatsIterator,
+ |x: &PageIndex<f64>| { x.min },
+ Index::DOUBLE,
+ f64
+);
+make_data_page_stats_iterator!(
+ MaxFloat64DataPageStatsIterator,
+ |x: &PageIndex<f64>| { x.max },
+ Index::DOUBLE,
+ f64
+);
+make_data_page_stats_iterator!(
+ MinByteArrayDataPageStatsIterator,
+ |x: &PageIndex<ByteArray>| { x.min.clone() },
+ Index::BYTE_ARRAY,
+ ByteArray
+);
+make_data_page_stats_iterator!(
+ MaxByteArrayDataPageStatsIterator,
+ |x: &PageIndex<ByteArray>| { x.max.clone() },
+ Index::BYTE_ARRAY,
+ ByteArray
+);
+make_data_page_stats_iterator!(
+ MaxFixedLenByteArrayDataPageStatsIterator,
+ |x: &PageIndex<FixedLenByteArray>| { x.max.clone() },
+ Index::FIXED_LEN_BYTE_ARRAY,
+ FixedLenByteArray
+);
+
+make_data_page_stats_iterator!(
+ MinFixedLenByteArrayDataPageStatsIterator,
+ |x: &PageIndex<FixedLenByteArray>| { x.min.clone() },
+ Index::FIXED_LEN_BYTE_ARRAY,
+ FixedLenByteArray
+);
+
+macro_rules! get_decimal_page_stats_iterator {
+ ($iterator_type: ident, $func: ident, $stat_value_type: ident, $convert_func: ident) => {
+ struct $iterator_type<'a, I>
+ where
+ I: Iterator<Item = (usize, &'a Index)>,
+ {
+ iter: I,
+ }
+
+ impl<'a, I> $iterator_type<'a, I>
+ where
+ I: Iterator<Item = (usize, &'a Index)>,
+ {
+ fn new(iter: I) -> Self {
+ Self { iter }
+ }
+ }
+
+ impl<'a, I> Iterator for $iterator_type<'a, I>
+ where
+ I: Iterator<Item = (usize, &'a Index)>,
+ {
+ type Item = Vec<Option<$stat_value_type>>;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ let next = self.iter.next();
+ match next {
+ Some((len, index)) => match index {
+ Index::INT32(native_index) => Some(
+ native_index
+ .indexes
+ .iter()
+ .map(|x| x.$func.and_then(|x| Some($stat_value_type::from(x))))
+ .collect::<Vec<_>>(),
+ ),
+ Index::INT64(native_index) => Some(
+ native_index
+ .indexes
+ .iter()
+ .map(|x| x.$func.and_then(|x| Some($stat_value_type::from(x))))
+ .collect::<Vec<_>>(),
+ ),
+ Index::BYTE_ARRAY(native_index) => Some(
+ native_index
+ .indexes
+ .iter()
+ .map(|x| {
+ x.clone().$func.and_then(|x| Some($convert_func(x.data())))
+ })
+ .collect::<Vec<_>>(),
+ ),
+ Index::FIXED_LEN_BYTE_ARRAY(native_index) => Some(
+ native_index
+ .indexes
+ .iter()
+ .map(|x| {
+ x.clone().$func.and_then(|x| Some($convert_func(x.data())))
+ })
+ .collect::<Vec<_>>(),
+ ),
+ _ => Some(vec![None; len]),
+ },
+ _ => None,
+ }
+ }
+
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ self.iter.size_hint()
+ }
+ }
+ };
+}
+
+get_decimal_page_stats_iterator!(
+ MinDecimal128DataPageStatsIterator,
+ min,
+ i128,
+ from_bytes_to_i128
+);
+
+get_decimal_page_stats_iterator!(
+ MaxDecimal128DataPageStatsIterator,
+ max,
+ i128,
+ from_bytes_to_i128
+);
+
+get_decimal_page_stats_iterator!(
+ MinDecimal256DataPageStatsIterator,
+ min,
+ i256,
+ from_bytes_to_i256
+);
+
+get_decimal_page_stats_iterator!(
+ MaxDecimal256DataPageStatsIterator,
+ max,
+ i256,
+ from_bytes_to_i256
+);
+
+macro_rules! get_data_page_statistics {
+ ($stat_type_prefix: ident, $data_type: ident, $iterator: ident) => {
+ paste! {
+ match $data_type {
+ Some(DataType::Boolean) => {
+ let iterator = [<$stat_type_prefix BooleanDataPageStatsIterator>]::new($iterator);
+ let mut builder = BooleanBuilder::new();
+ for x in iterator {
+ for x in x.into_iter() {
+ let Some(x) = x else {
+ builder.append_null(); // no statistics value
+ continue;
+ };
+ builder.append_value(x);
+ }
+ }
+ Ok(Arc::new(builder.finish()))
+ },
+ Some(DataType::UInt8) => Ok(Arc::new(
+ UInt8Array::from_iter(
+ [<$stat_type_prefix Int32DataPageStatsIterator>]::new($iterator)
+ .map(|x| {
+ x.into_iter().map(|x| {
+ x.and_then(|x| u8::try_from(x).ok())
+ })
+ })
+ .flatten()
+ )
+ )),
+ Some(DataType::UInt16) => Ok(Arc::new(
+ UInt16Array::from_iter(
+ [<$stat_type_prefix Int32DataPageStatsIterator>]::new($iterator)
+ .map(|x| {
+ x.into_iter().map(|x| {
+ x.and_then(|x| u16::try_from(x).ok())
+ })
+ })
+ .flatten()
+ )
+ )),
+ Some(DataType::UInt32) => Ok(Arc::new(
+ UInt32Array::from_iter(
+ [<$stat_type_prefix Int32DataPageStatsIterator>]::new($iterator)
+ .map(|x| {
+ x.into_iter().map(|x| {
+ x.and_then(|x| Some(x as u32))
+ })
+ })
+ .flatten()
+ ))),
+ Some(DataType::UInt64) => Ok(Arc::new(
+ UInt64Array::from_iter(
+ [<$stat_type_prefix Int64DataPageStatsIterator>]::new($iterator)
+ .map(|x| {
+ x.into_iter().map(|x| {
+ x.and_then(|x| Some(x as u64))
+ })
+ })
+ .flatten()
+ ))),
+ Some(DataType::Int8) => Ok(Arc::new(
+ Int8Array::from_iter(
+ [<$stat_type_prefix Int32DataPageStatsIterator>]::new($iterator)
+ .map(|x| {
+ x.into_iter().map(|x| {
+ x.and_then(|x| i8::try_from(x).ok())
+ })
+ })
+ .flatten()
+ )
+ )),
+ Some(DataType::Int16) => Ok(Arc::new(
+ Int16Array::from_iter(
+ [<$stat_type_prefix Int32DataPageStatsIterator>]::new($iterator)
+ .map(|x| {
+ x.into_iter().map(|x| {
+ x.and_then(|x| i16::try_from(x).ok())
+ })
+ })
+ .flatten()
+ )
+ )),
+ Some(DataType::Int32) => Ok(Arc::new(Int32Array::from_iter([<$stat_type_prefix Int32DataPageStatsIterator>]::new($iterator).flatten()))),
+ Some(DataType::Int64) => Ok(Arc::new(Int64Array::from_iter([<$stat_type_prefix Int64DataPageStatsIterator>]::new($iterator).flatten()))),
+ Some(DataType::Float16) => Ok(Arc::new(
+ Float16Array::from_iter(
+ [<$stat_type_prefix Float16DataPageStatsIterator>]::new($iterator)
+ .map(|x| {
+ x.into_iter().map(|x| {
+ x.and_then(|x| from_bytes_to_f16(x.data()))
+ })
+ })
+ .flatten()
+ )
+ )),
+ Some(DataType::Float32) => Ok(Arc::new(Float32Array::from_iter([<$stat_type_prefix Float32DataPageStatsIterator>]::new($iterator).flatten()))),
+ Some(DataType::Float64) => Ok(Arc::new(Float64Array::from_iter([<$stat_type_prefix Float64DataPageStatsIterator>]::new($iterator).flatten()))),
+ Some(DataType::Binary) => Ok(Arc::new(BinaryArray::from_iter([<$stat_type_prefix ByteArrayDataPageStatsIterator>]::new($iterator).flatten()))),
+ Some(DataType::LargeBinary) => Ok(Arc::new(LargeBinaryArray::from_iter([<$stat_type_prefix ByteArrayDataPageStatsIterator>]::new($iterator).flatten()))),
+ Some(DataType::Utf8) => {
+ let mut builder = StringBuilder::new();
+ let iterator = [<$stat_type_prefix ByteArrayDataPageStatsIterator>]::new($iterator);
+ for x in iterator {
+ for x in x.into_iter() {
+ let Some(x) = x else {
+ builder.append_null(); // no statistics value
+ continue;
+ };
+
+ let Ok(x) = std::str::from_utf8(x.data()) else {
+ builder.append_null();
+ continue;
+ };
+
+ builder.append_value(x);
+ }
+ }
+ Ok(Arc::new(builder.finish()))
+ },
+ Some(DataType::LargeUtf8) => {
+ let mut builder = LargeStringBuilder::new();
+ let iterator = [<$stat_type_prefix ByteArrayDataPageStatsIterator>]::new($iterator);
+ for x in iterator {
+ for x in x.into_iter() {
+ let Some(x) = x else {
+ builder.append_null(); // no statistics value
+ continue;
+ };
+
+ let Ok(x) = std::str::from_utf8(x.data()) else {
+ builder.append_null();
+ continue;
+ };
+
+ builder.append_value(x);
+ }
+ }
+ Ok(Arc::new(builder.finish()))
+ },
+ Some(DataType::Dictionary(_, value_type)) => {
+ [<$stat_type_prefix:lower _ page_statistics>](Some(value_type), $iterator)
+ },
+ Some(DataType::Timestamp(unit, timezone)) => {
+ let iter = [<$stat_type_prefix Int64DataPageStatsIterator>]::new($iterator).flatten();
+ Ok(match unit {
+ TimeUnit::Second => Arc::new(TimestampSecondArray::from_iter(iter).with_timezone_opt(timezone.clone())),
+ TimeUnit::Millisecond => Arc::new(TimestampMillisecondArray::from_iter(iter).with_timezone_opt(timezone.clone())),
+ TimeUnit::Microsecond => Arc::new(TimestampMicrosecondArray::from_iter(iter).with_timezone_opt(timezone.clone())),
+ TimeUnit::Nanosecond => Arc::new(TimestampNanosecondArray::from_iter(iter).with_timezone_opt(timezone.clone())),
+ })
+ },
+ Some(DataType::Date32) => Ok(Arc::new(Date32Array::from_iter([<$stat_type_prefix Int32DataPageStatsIterator>]::new($iterator).flatten()))),
+ Some(DataType::Date64) => Ok(
+ Arc::new(
+ Date64Array::from_iter([<$stat_type_prefix Int32DataPageStatsIterator>]::new($iterator)
+ .map(|x| {
+ x.into_iter()
+ .map(|x| {
+ x.and_then(|x| i64::try_from(x).ok())
+ })
+ .map(|x| x.map(|x| x * 24 * 60 * 60 * 1000))
+ }).flatten()
+ )
+ )
+ ),
+ Some(DataType::Decimal128(precision, scale)) => Ok(Arc::new(
+ Decimal128Array::from_iter([<$stat_type_prefix Decimal128DataPageStatsIterator>]::new($iterator).flatten()).with_precision_and_scale(*precision, *scale)?)),
+ Some(DataType::Decimal256(precision, scale)) => Ok(Arc::new(
+ Decimal256Array::from_iter([<$stat_type_prefix Decimal256DataPageStatsIterator>]::new($iterator).flatten()).with_precision_and_scale(*precision, *scale)?)),
+ Some(DataType::Time32(unit)) => {
+ Ok(match unit {
+ TimeUnit::Second => Arc::new(Time32SecondArray::from_iter(
+ [<$stat_type_prefix Int32DataPageStatsIterator>]::new($iterator).flatten(),
+ )),
+ TimeUnit::Millisecond => Arc::new(Time32MillisecondArray::from_iter(
+ [<$stat_type_prefix Int32DataPageStatsIterator>]::new($iterator).flatten(),
+ )),
+ _ => {
+ // don't know how to extract statistics, so return an empty array
+ new_empty_array(&DataType::Time32(unit.clone()))
+ }
+ })
+ }
+ Some(DataType::Time64(unit)) => {
+ Ok(match unit {
+ TimeUnit::Microsecond => Arc::new(Time64MicrosecondArray::from_iter(
+ [<$stat_type_prefix Int64DataPageStatsIterator>]::new($iterator).flatten(),
+ )),
+ TimeUnit::Nanosecond => Arc::new(Time64NanosecondArray::from_iter(
+ [<$stat_type_prefix Int64DataPageStatsIterator>]::new($iterator).flatten(),
+ )),
+ _ => {
+ // don't know how to extract statistics, so return an empty array
+ new_empty_array(&DataType::Time64(unit.clone()))
+ }
+ })
+ },
+ Some(DataType::FixedSizeBinary(size)) => {
+ let mut builder = FixedSizeBinaryBuilder::new(*size);
+ let iterator = [<$stat_type_prefix FixedLenByteArrayDataPageStatsIterator>]::new($iterator);
+ for x in iterator {
+ for x in x.into_iter() {
+ let Some(x) = x else {
+ builder.append_null(); // no statistics value
+ continue;
+ };
+
+ if x.len() == *size as usize {
+ let _ = builder.append_value(x.data());
+ } else {
+ // log::debug!(
+ // "FixedSizeBinary({}) statistics is a binary of size {}, ignoring it.",
+ // size,
+ // x.len(),
+ // );
+ builder.append_null();
+ }
+ }
+ }
+ Ok(Arc::new(builder.finish()))
+ },
+ _ => unimplemented!()
+ }
+ }
+ }
+}
+/// Extracts the min statistics from an iterator of [`ParquetStatistics`] to an
+/// [`ArrayRef`]
+///
+/// This is an internal helper -- see [`StatisticsConverter`] for public API
+fn min_statistics<'a, I: Iterator<Item = Option<&'a ParquetStatistics>>>(
+ data_type: &DataType,
+ iterator: I,
+) -> Result<ArrayRef> {
+ get_statistics!(Min, data_type, iterator)
+}
+
+/// Extracts the max statistics from an iterator of [`ParquetStatistics`] to an [`ArrayRef`]
+///
+/// This is an internal helper -- see [`StatisticsConverter`] for public API
+fn max_statistics<'a, I: Iterator<Item = Option<&'a ParquetStatistics>>>(
+ data_type: &DataType,
+ iterator: I,
+) -> Result<ArrayRef> {
+ get_statistics!(Max, data_type, iterator)
+}
+
+/// Extracts the min statistics from an iterator
+/// of parquet page [`Index`]'es to an [`ArrayRef`]
+pub(crate) fn min_page_statistics<'a, I>(
+ data_type: Option<&DataType>,
+ iterator: I,
+) -> Result<ArrayRef>
+where
+ I: Iterator<Item = (usize, &'a Index)>,
+{
+ get_data_page_statistics!(Min, data_type, iterator)
+}
+
+/// Extracts the max statistics from an iterator
+/// of parquet page [`Index`]'es to an [`ArrayRef`]
+pub(crate) fn max_page_statistics<'a, I>(
+ data_type: Option<&DataType>,
+ iterator: I,
+) -> Result<ArrayRef>
+where
+ I: Iterator<Item = (usize, &'a Index)>,
+{
+ get_data_page_statistics!(Max, data_type, iterator)
+}
+
+/// Extracts the null count statistics from an iterator
+/// of parquet page [`Index`]'es to an [`ArrayRef`]
+///
+/// The returned Array is an [`UInt64Array`]
+pub(crate) fn null_counts_page_statistics<'a, I>(iterator: I) -> Result<UInt64Array>
+where
+ I: Iterator<Item = (usize, &'a Index)>,
+{
+ let iter = iterator.flat_map(|(len, index)| match index {
+ Index::NONE => vec![None; len],
+ Index::BOOLEAN(native_index) => native_index
+ .indexes
+ .iter()
+ .map(|x| x.null_count.map(|x| x as u64))
+ .collect::<Vec<_>>(),
+ Index::INT32(native_index) => native_index
+ .indexes
+ .iter()
+ .map(|x| x.null_count.map(|x| x as u64))
+ .collect::<Vec<_>>(),
+ Index::INT64(native_index) => native_index
+ .indexes
+ .iter()
+ .map(|x| x.null_count.map(|x| x as u64))
+ .collect::<Vec<_>>(),
+ Index::FLOAT(native_index) => native_index
+ .indexes
+ .iter()
+ .map(|x| x.null_count.map(|x| x as u64))
+ .collect::<Vec<_>>(),
+ Index::DOUBLE(native_index) => native_index
+ .indexes
+ .iter()
+ .map(|x| x.null_count.map(|x| x as u64))
+ .collect::<Vec<_>>(),
+ Index::FIXED_LEN_BYTE_ARRAY(native_index) => native_index
+ .indexes
+ .iter()
+ .map(|x| x.null_count.map(|x| x as u64))
+ .collect::<Vec<_>>(),
+ Index::BYTE_ARRAY(native_index) => native_index
+ .indexes
+ .iter()
+ .map(|x| x.null_count.map(|x| x as u64))
+ .collect::<Vec<_>>(),
+ _ => unimplemented!(),
+ });
+
+ Ok(UInt64Array::from_iter(iter))
+}
+
+/// Extracts Parquet statistics as Arrow arrays
+///
+/// This is used to convert Parquet statistics to Arrow [`ArrayRef`], with
+/// proper type conversions. This information can be used for pruning Parquet
+/// files, row groups, and data pages based on the statistics embedded in
+/// Parquet metadata.
+///
+/// # Schemas
+///
+/// The converter ues the schema of the Parquet file and the Arrow schema to
+/// convert the underlying statistics value (stored as a parquet value) into the
+/// corresponding Arrow value. For example, Decimals are stored as binary in
+/// parquet files and this structure handles mapping them to the `i128`
+/// representation used in Arrow.
+///
+/// Note: The Parquet schema and Arrow schema do not have to be identical (for
+/// example, the columns may be in different orders and one or the other schemas
+/// may have additional columns). The function [`parquet_column`] is used to
+/// match the column in the Parquet schema to the column in the Arrow schema.
+#[derive(Debug)]
+pub struct StatisticsConverter<'a> {
+ /// the index of the matched column in the Parquet schema
+ parquet_column_index: Option<usize>,
+ /// The field (with data type) of the column in the Arrow schema
+ arrow_field: &'a Field,
+}
+
+impl<'a> StatisticsConverter<'a> {
+ /// Return the index of the column in the Parquet schema, if any
+ ///
+ /// Returns `None` if the column is was present in the Arrow schema, but not
+ /// present in the parquet file
+ pub fn parquet_column_index(&self) -> Option<usize> {
+ self.parquet_column_index
+ }
+
+ /// Return the arrow schema's [`Field]` of the column in the Arrow schema
+ pub fn arrow_field(&self) -> &'a Field {
+ self.arrow_field
+ }
+
+ /// Returns a [`UInt64Array`] with row counts for each row group
+ ///
+ /// # Return Value
+ ///
+ /// The returned array has no nulls, and has one value for each row group.
+ /// Each value is the number of rows in the row group.
+ ///
+ /// # Example
+ /// ```no_run
+ /// # use arrow::datatypes::Schema;
+ /// # use arrow_array::{ArrayRef, UInt64Array};
+ /// # use parquet::arrow::arrow_reader::statistics::StatisticsConverter;
+ /// # use parquet::file::metadata::ParquetMetaData;
+ /// # fn get_parquet_metadata() -> ParquetMetaData { unimplemented!() }
+ /// # fn get_arrow_schema() -> Schema { unimplemented!() }
+ /// // Given the metadata for a parquet file and the arrow schema
+ /// let metadata: ParquetMetaData = get_parquet_metadata();
+ /// let arrow_schema: Schema = get_arrow_schema();
+ /// let parquet_schema = metadata.file_metadata().schema_descr();
+ /// // create a converter
+ /// let converter = StatisticsConverter::try_new("foo", &arrow_schema, parquet_schema)
+ /// .unwrap();
+ /// // get the row counts for each row group
+ /// let row_counts = converter.row_group_row_counts(metadata
+ /// .row_groups()
+ /// .iter()
+ /// ).unwrap();
+ /// // file had 2 row groups, with 1024 and 23 rows respectively
+ /// assert_eq!(row_counts, Some(UInt64Array::from(vec![1024, 23])));
+ /// ```
+ pub fn row_group_row_counts<I>(&self, metadatas: I) -> Result<Option<UInt64Array>>
+ where
+ I: IntoIterator<Item = &'a RowGroupMetaData>,
+ {
+ let Some(_) = self.parquet_column_index else {
+ return Ok(None);
+ };
+
+ let mut builder = UInt64Array::builder(10);
+ for metadata in metadatas.into_iter() {
+ let row_count = metadata.num_rows();
+ let row_count: u64 = row_count.try_into().map_err(|e| {
+ arrow_err!(format!(
+ "Parquet row count {row_count} too large to convert to u64: {e}"
+ ))
+ })?;
+ builder.append_value(row_count);
+ }
+ Ok(Some(builder.finish()))
+ }
+
+ /// Create a new `StatisticsConverter` to extract statistics for a column
+ ///
+ /// Note if there is no corresponding column in the parquet file, the returned
+ /// arrays will be null. This can happen if the column is in the arrow
+ /// schema but not in the parquet schema due to schema evolution.
+ ///
+ /// See example on [`Self::row_group_mins`] for usage
+ ///
+ /// # Errors
+ ///
+ /// * If the column is not found in the arrow schema
+ pub fn try_new<'b>(
+ column_name: &'b str,
+ arrow_schema: &'a Schema,
+ parquet_schema: &'a SchemaDescriptor,
+ ) -> Result<Self> {
+ // ensure the requested column is in the arrow schema
+ let Some((_idx, arrow_field)) = arrow_schema.column_with_name(column_name) else {
+ return Err(arrow_err!(format!(
+ "Column '{}' not found in schema for statistics conversion",
+ column_name
+ )));
+ };
+
+ // find the column in the parquet schema, if not, return a null array
+ let parquet_index = match parquet_column(parquet_schema, arrow_schema, column_name) {
+ Some((parquet_idx, matched_field)) => {
+ // sanity check that matching field matches the arrow field
+ if matched_field.as_ref() != arrow_field {
+ return Err(arrow_err!(format!(
+ "Matched column '{:?}' does not match original matched column '{:?}'",
+ matched_field, arrow_field
+ )));
+ }
+ Some(parquet_idx)
+ }
+ None => None,
+ };
+
+ Ok(Self {
+ parquet_column_index: parquet_index,
+ arrow_field,
+ })
+ }
+
+ /// Extract the minimum values from row group statistics in [`RowGroupMetaData`]
+ ///
+ /// # Return Value
+ ///
+ /// The returned array contains 1 value for each row group, in the same order as `metadatas`
+ ///
+ /// Each value is either
+ /// * the minimum value for the column
+ /// * a null value, if the statistics can not be extracted
+ ///
+ /// Note that a null value does NOT mean the min value was actually
+ /// `null` it means it the requested statistic is unknown
+ ///
+ /// # Errors
+ ///
+ /// Reasons for not being able to extract the statistics include:
+ /// * the column is not present in the parquet file
+ /// * statistics for the column are not present in the row group
+ /// * the stored statistic value can not be converted to the requested type
+ ///
+ /// # Example
+ /// ```no_run
+ /// # use std::sync::Arc;
+ /// # use arrow::datatypes::Schema;
+ /// # use arrow_array::{ArrayRef, Float64Array};
+ /// # use parquet::arrow::arrow_reader::statistics::StatisticsConverter;
+ /// # use parquet::file::metadata::ParquetMetaData;
+ /// # fn get_parquet_metadata() -> ParquetMetaData { unimplemented!() }
+ /// # fn get_arrow_schema() -> Schema { unimplemented!() }
+ /// // Given the metadata for a parquet file and the arrow schema
+ /// let metadata: ParquetMetaData = get_parquet_metadata();
+ /// let arrow_schema: Schema = get_arrow_schema();
+ /// let parquet_schema = metadata.file_metadata().schema_descr();
+ /// // create a converter
+ /// let converter = StatisticsConverter::try_new("foo", &arrow_schema, parquet_schema)
+ /// .unwrap();
+ /// // get the minimum value for the column "foo" in the parquet file
+ /// let min_values: ArrayRef = converter
+ /// .row_group_mins(metadata.row_groups().iter())
+ /// .unwrap();
+ /// // if "foo" is a Float64 value, the returned array will contain Float64 values
+ /// assert_eq!(min_values, Arc::new(Float64Array::from(vec![Some(1.0), Some(2.0)])) as _);
+ /// ```
+ pub fn row_group_mins<I>(&self, metadatas: I) -> Result<ArrayRef>
+ where
+ I: IntoIterator<Item = &'a RowGroupMetaData>,
+ {
+ let data_type = self.arrow_field.data_type();
+
+ let Some(parquet_index) = self.parquet_column_index else {
+ return Ok(self.make_null_array(data_type, metadatas));
+ };
+
+ let iter = metadatas
+ .into_iter()
+ .map(|x| x.column(parquet_index).statistics());
+ min_statistics(data_type, iter)
+ }
+
+ /// Extract the maximum values from row group statistics in [`RowGroupMetaData`]
+ ///
+ /// See docs on [`Self::row_group_mins`] for details
+ pub fn row_group_maxes<I>(&self, metadatas: I) -> Result<ArrayRef>
+ where
+ I: IntoIterator<Item = &'a RowGroupMetaData>,
+ {
+ let data_type = self.arrow_field.data_type();
+
+ let Some(parquet_index) = self.parquet_column_index else {
+ return Ok(self.make_null_array(data_type, metadatas));
+ };
+
+ let iter = metadatas
+ .into_iter()
+ .map(|x| x.column(parquet_index).statistics());
+ max_statistics(data_type, iter)
+ }
+
+ /// Extract the null counts from row group statistics in [`RowGroupMetaData`]
+ ///
+ /// See docs on [`Self::row_group_mins`] for details
+ pub fn row_group_null_counts<I>(&self, metadatas: I) -> Result<UInt64Array>
+ where
+ I: IntoIterator<Item = &'a RowGroupMetaData>,
+ {
+ let Some(parquet_index) = self.parquet_column_index else {
+ let num_row_groups = metadatas.into_iter().count();
+ return Ok(UInt64Array::from_iter(
+ std::iter::repeat(None).take(num_row_groups),
+ ));
+ };
+
+ let null_counts = metadatas
+ .into_iter()
+ .map(|x| x.column(parquet_index).statistics())
+ .map(|s| s.map(|s| s.null_count()));
+ Ok(UInt64Array::from_iter(null_counts))
+ }
+
+ /// Extract the minimum values from Data Page statistics.
+ ///
+ /// In Parquet files, in addition to the Column Chunk level statistics
+ /// (stored for each column for each row group) there are also
+ /// optional statistics stored for each data page, as part of
+ /// the [`ParquetColumnIndex`].
+ ///
+ /// Since a single Column Chunk is stored as one or more pages,
+ /// page level statistics can prune at a finer granularity.
+ ///
+ /// However since they are stored in a separate metadata
+ /// structure ([`Index`]) there is different code to extract them as
+ /// compared to arrow statistics.
+ ///
+ /// # Parameters:
+ ///
+ /// * `column_page_index`: The parquet column page indices, read from
+ /// `ParquetMetaData` column_index
+ ///
+ /// * `column_offset_index`: The parquet column offset indices, read from
+ /// `ParquetMetaData` offset_index
+ ///
+ /// * `row_group_indices`: The indices of the row groups, that are used to
+ /// extract the column page index and offset index on a per row group
+ /// per column basis.
+ ///
+ /// # Return Value
+ ///
+ /// The returned array contains 1 value for each `NativeIndex`
+ /// in the underlying `Index`es, in the same order as they appear
+ /// in `metadatas`.
+ ///
+ /// For example, if there are two `Index`es in `metadatas`:
+ /// 1. the first having `3` `PageIndex` entries
+ /// 2. the second having `2` `PageIndex` entries
+ ///
+ /// The returned array would have 5 rows.
+ ///
+ /// Each value is either:
+ /// * the minimum value for the page
+ /// * a null value, if the statistics can not be extracted
+ ///
+ /// Note that a null value does NOT mean the min value was actually
+ /// `null` it means it the requested statistic is unknown
+ ///
+ /// # Errors
+ ///
+ /// Reasons for not being able to extract the statistics include:
+ /// * the column is not present in the parquet file
+ /// * statistics for the pages are not present in the row group
+ /// * the stored statistic value can not be converted to the requested type
+ pub fn data_page_mins<I>(
+ &self,
+ column_page_index: &ParquetColumnIndex,
+ column_offset_index: &ParquetOffsetIndex,
+ row_group_indices: I,
+ ) -> Result<ArrayRef>
+ where
+ I: IntoIterator<Item = &'a usize>,
+ {
+ let data_type = self.arrow_field.data_type();
+
+ let Some(parquet_index) = self.parquet_column_index else {
+ return Ok(self.make_null_array(data_type, row_group_indices));
+ };
+
+ let iter = row_group_indices.into_iter().map(|rg_index| {
+ let column_page_index_per_row_group_per_column =
+ &column_page_index[*rg_index][parquet_index];
+ let num_data_pages = &column_offset_index[*rg_index][parquet_index].len();
+
+ (*num_data_pages, column_page_index_per_row_group_per_column)
+ });
+
+ min_page_statistics(Some(data_type), iter)
+ }
+
+ /// Extract the maximum values from Data Page statistics.
+ ///
+ /// See docs on [`Self::data_page_mins`] for details.
+ pub fn data_page_maxes<I>(
+ &self,
+ column_page_index: &ParquetColumnIndex,
+ column_offset_index: &ParquetOffsetIndex,
+ row_group_indices: I,
+ ) -> Result<ArrayRef>
+ where
+ I: IntoIterator<Item = &'a usize>,
+ {
+ let data_type = self.arrow_field.data_type();
+
+ let Some(parquet_index) = self.parquet_column_index else {
+ return Ok(self.make_null_array(data_type, row_group_indices));
+ };
+
+ let iter = row_group_indices.into_iter().map(|rg_index| {
+ let column_page_index_per_row_group_per_column =
+ &column_page_index[*rg_index][parquet_index];
+ let num_data_pages = &column_offset_index[*rg_index][parquet_index].len();
+
+ (*num_data_pages, column_page_index_per_row_group_per_column)
+ });
+
+ max_page_statistics(Some(data_type), iter)
+ }
+
+ /// Returns a [`UInt64Array`] with null counts for each data page.
+ ///
+ /// See docs on [`Self::data_page_mins`] for details.
+ pub fn data_page_null_counts<I>(
+ &self,
+ column_page_index: &ParquetColumnIndex,
+ column_offset_index: &ParquetOffsetIndex,
+ row_group_indices: I,
+ ) -> Result<UInt64Array>
+ where
+ I: IntoIterator<Item = &'a usize>,
+ {
+ let Some(parquet_index) = self.parquet_column_index else {
+ let num_row_groups = row_group_indices.into_iter().count();
+ return Ok(UInt64Array::from_iter(
+ std::iter::repeat(None).take(num_row_groups),
+ ));
+ };
+
+ let iter = row_group_indices.into_iter().map(|rg_index| {
+ let column_page_index_per_row_group_per_column =
+ &column_page_index[*rg_index][parquet_index];
+ let num_data_pages = &column_offset_index[*rg_index][parquet_index].len();
+
+ (*num_data_pages, column_page_index_per_row_group_per_column)
+ });
+ null_counts_page_statistics(iter)
+ }
+
+ /// Returns a [`UInt64Array`] with row counts for each data page.
+ ///
+ /// This function iterates over the given row group indexes and computes
+ /// the row count for each page in the specified column.
+ ///
+ /// # Parameters:
+ ///
+ /// * `column_offset_index`: The parquet column offset indices, read from
+ /// `ParquetMetaData` offset_index
+ ///
+ /// * `row_group_metadatas`: The metadata slice of the row groups, read
+ /// from `ParquetMetaData` row_groups
+ ///
+ /// * `row_group_indices`: The indices of the row groups, that are used to
+ /// extract the column offset index on a per row group per column basis.
+ ///
+ /// See docs on [`Self::data_page_mins`] for details.
+ pub fn data_page_row_counts<I>(
+ &self,
+ column_offset_index: &ParquetOffsetIndex,
+ row_group_metadatas: &'a [RowGroupMetaData],
+ row_group_indices: I,
+ ) -> Result<Option<UInt64Array>>
+ where
+ I: IntoIterator<Item = &'a usize>,
+ {
+ let Some(parquet_index) = self.parquet_column_index else {
+ // no matching column found in parquet_index;
+ // thus we cannot extract page_locations in order to determine
+ // the row count on a per DataPage basis.
+ return Ok(None);
+ };
+
+ let mut row_count_total = Vec::new();
+ for rg_idx in row_group_indices {
+ let page_locations = &column_offset_index[*rg_idx][parquet_index];
+
+ let row_count_per_page = page_locations
+ .windows(2)
+ .map(|loc| Some(loc[1].first_row_index as u64 - loc[0].first_row_index as u64));
+
+ // append the last page row count
+ let num_rows_in_row_group = &row_group_metadatas[*rg_idx].num_rows();
+ let row_count_per_page = row_count_per_page
+ .chain(std::iter::once(Some(
+ *num_rows_in_row_group as u64
+ - page_locations.last().unwrap().first_row_index as u64,
+ )))
+ .collect::<Vec<_>>();
+
+ row_count_total.extend(row_count_per_page);
+ }
+
+ Ok(Some(UInt64Array::from_iter(row_count_total)))
+ }
+
+ /// Returns a null array of data_type with one element per row group
+ fn make_null_array<I, A>(&self, data_type: &DataType, metadatas: I) -> ArrayRef
+ where
+ I: IntoIterator<Item = A>,
+ {
+ // column was in the arrow schema but not in the parquet schema, so return a null array
+ let num_row_groups = metadatas.into_iter().count();
+ new_null_array(data_type, num_row_groups)
+ }
+}
+
+#[cfg(test)]
+mod test {
+ use super::*;
+ use crate::arrow::arrow_reader::ArrowReaderBuilder;
+ use crate::arrow::arrow_writer::ArrowWriter;
+ use crate::file::metadata::{ParquetMetaData, RowGroupMetaData};
+ use crate::file::properties::{EnabledStatistics, WriterProperties};
+ use arrow::compute::kernels::cast_utils::Parser;
+ use arrow::datatypes::{i256, Date32Type, Date64Type};
+ use arrow::util::test_util::parquet_test_data;
+ use arrow_array::{
+ new_empty_array, new_null_array, Array, ArrayRef, BinaryArray, BooleanArray, Date32Array,
+ Date64Array, Decimal128Array, Decimal256Array, Float32Array, Float64Array, Int16Array,
+ Int32Array, Int64Array, Int8Array, LargeBinaryArray, RecordBatch, StringArray, StructArray,
+ TimestampNanosecondArray,
+ };
+ use arrow_schema::{DataType, Field, SchemaRef};
+ use bytes::Bytes;
+ use std::path::PathBuf;
+ use std::sync::Arc;
+ // TODO error cases (with parquet statistics that are mismatched in expected type)
+
+ #[test]
+ fn roundtrip_empty() {
+ let empty_bool_array = new_empty_array(&DataType::Boolean);
+ Test {
+ input: empty_bool_array.clone(),
+ expected_min: empty_bool_array.clone(),
+ expected_max: empty_bool_array.clone(),
+ }
+ .run()
+ }
+
+ #[test]
+ fn roundtrip_bool() {
+ Test {
+ input: bool_array([
+ // row group 1
+ Some(true),
+ None,
+ Some(true),
+ // row group 2
+ Some(true),
+ Some(false),
+ None,
+ // row group 3
+ None,
+ None,
+ None,
+ ]),
+ expected_min: bool_array([Some(true), Some(false), None]),
+ expected_max: bool_array([Some(true), Some(true), None]),
+ }
+ .run()
+ }
+
+ #[test]
+ fn roundtrip_int32() {
+ Test {
+ input: i32_array([
+ // row group 1
+ Some(1),
+ None,
+ Some(3),
+ // row group 2
+ Some(0),
+ Some(5),
+ None,
+ // row group 3
+ None,
+ None,
+ None,
+ ]),
+ expected_min: i32_array([Some(1), Some(0), None]),
+ expected_max: i32_array([Some(3), Some(5), None]),
+ }
+ .run()
+ }
+
+ #[test]
+ fn roundtrip_int64() {
+ Test {
+ input: i64_array([
+ // row group 1
+ Some(1),
+ None,
+ Some(3),
+ // row group 2
+ Some(0),
+ Some(5),
+ None,
+ // row group 3
+ None,
+ None,
+ None,
+ ]),
+ expected_min: i64_array([Some(1), Some(0), None]),
+ expected_max: i64_array(vec![Some(3), Some(5), None]),
+ }
+ .run()
+ }
+
+ #[test]
+ fn roundtrip_f32() {
+ Test {
+ input: f32_array([
+ // row group 1
+ Some(1.0),
+ None,
+ Some(3.0),
+ // row group 2
+ Some(-1.0),
+ Some(5.0),
+ None,
+ // row group 3
+ None,
+ None,
+ None,
+ ]),
+ expected_min: f32_array([Some(1.0), Some(-1.0), None]),
+ expected_max: f32_array([Some(3.0), Some(5.0), None]),
+ }
+ .run()
+ }
+
+ #[test]
+ fn roundtrip_f64() {
+ Test {
+ input: f64_array([
+ // row group 1
+ Some(1.0),
+ None,
+ Some(3.0),
+ // row group 2
+ Some(-1.0),
+ Some(5.0),
+ None,
+ // row group 3
+ None,
+ None,
+ None,
+ ]),
+ expected_min: f64_array([Some(1.0), Some(-1.0), None]),
+ expected_max: f64_array([Some(3.0), Some(5.0), None]),
+ }
+ .run()
+ }
+
+ #[test]
+ fn roundtrip_timestamp() {
+ Test {
+ input: timestamp_seconds_array(
+ [
+ // row group 1
+ Some(1),
+ None,
+ Some(3),
+ // row group 2
+ Some(9),
+ Some(5),
+ None,
+ // row group 3
+ None,
+ None,
+ None,
+ ],
+ None,
+ ),
+ expected_min: timestamp_seconds_array([Some(1), Some(5), None], None),
+ expected_max: timestamp_seconds_array([Some(3), Some(9), None], None),
+ }
+ .run();
+
+ Test {
+ input: timestamp_milliseconds_array(
+ [
+ // row group 1
+ Some(1),
+ None,
+ Some(3),
+ // row group 2
+ Some(9),
+ Some(5),
+ None,
+ // row group 3
+ None,
+ None,
+ None,
+ ],
+ None,
+ ),
+ expected_min: timestamp_milliseconds_array([Some(1), Some(5), None], None),
+ expected_max: timestamp_milliseconds_array([Some(3), Some(9), None], None),
+ }
+ .run();
+
+ Test {
+ input: timestamp_microseconds_array(
+ [
+ // row group 1
+ Some(1),
+ None,
+ Some(3),
+ // row group 2
+ Some(9),
+ Some(5),
+ None,
+ // row group 3
+ None,
+ None,
+ None,
+ ],
+ None,
+ ),
+ expected_min: timestamp_microseconds_array([Some(1), Some(5), None], None),
+ expected_max: timestamp_microseconds_array([Some(3), Some(9), None], None),
+ }
+ .run();
+
+ Test {
+ input: timestamp_nanoseconds_array(
+ [
+ // row group 1
+ Some(1),
+ None,
+ Some(3),
+ // row group 2
+ Some(9),
+ Some(5),
+ None,
+ // row group 3
+ None,
+ None,
+ None,
+ ],
+ None,
+ ),
+ expected_min: timestamp_nanoseconds_array([Some(1), Some(5), None], None),
+ expected_max: timestamp_nanoseconds_array([Some(3), Some(9), None], None),
+ }
+ .run()
+ }
+
+ #[test]
+ fn roundtrip_timestamp_timezoned() {
+ Test {
+ input: timestamp_seconds_array(
+ [
+ // row group 1
+ Some(1),
+ None,
+ Some(3),
+ // row group 2
+ Some(9),
+ Some(5),
+ None,
+ // row group 3
+ None,
+ None,
+ None,
+ ],
+ Some("UTC"),
+ ),
+ expected_min: timestamp_seconds_array([Some(1), Some(5), None], Some("UTC")),
+ expected_max: timestamp_seconds_array([Some(3), Some(9), None], Some("UTC")),
+ }
+ .run();
+
+ Test {
+ input: timestamp_milliseconds_array(
+ [
+ // row group 1
+ Some(1),
+ None,
+ Some(3),
+ // row group 2
+ Some(9),
+ Some(5),
+ None,
+ // row group 3
+ None,
+ None,
+ None,
+ ],
+ Some("UTC"),
+ ),
+ expected_min: timestamp_milliseconds_array([Some(1), Some(5), None], Some("UTC")),
+ expected_max: timestamp_milliseconds_array([Some(3), Some(9), None], Some("UTC")),
+ }
+ .run();
+
+ Test {
+ input: timestamp_microseconds_array(
+ [
+ // row group 1
+ Some(1),
+ None,
+ Some(3),
+ // row group 2
+ Some(9),
+ Some(5),
+ None,
+ // row group 3
+ None,
+ None,
+ None,
+ ],
+ Some("UTC"),
+ ),
+ expected_min: timestamp_microseconds_array([Some(1), Some(5), None], Some("UTC")),
+ expected_max: timestamp_microseconds_array([Some(3), Some(9), None], Some("UTC")),
+ }
+ .run();
+
+ Test {
+ input: timestamp_nanoseconds_array(
+ [
+ // row group 1
+ Some(1),
+ None,
+ Some(3),
+ // row group 2
+ Some(9),
+ Some(5),
+ None,
+ // row group 3
+ None,
+ None,
+ None,
+ ],
+ Some("UTC"),
+ ),
+ expected_min: timestamp_nanoseconds_array([Some(1), Some(5), None], Some("UTC")),
+ expected_max: timestamp_nanoseconds_array([Some(3), Some(9), None], Some("UTC")),
+ }
+ .run()
+ }
+
+ #[test]
+ fn roundtrip_decimal() {
+ Test {
+ input: Arc::new(
+ Decimal128Array::from(vec![
+ // row group 1
+ Some(100),
+ None,
+ Some(22000),
+ // row group 2
+ Some(500000),
+ Some(330000),
+ None,
+ // row group 3
+ None,
+ None,
+ None,
+ ])
+ .with_precision_and_scale(9, 2)
+ .unwrap(),
+ ),
+ expected_min: Arc::new(
+ Decimal128Array::from(vec![Some(100), Some(330000), None])
+ .with_precision_and_scale(9, 2)
+ .unwrap(),
+ ),
+ expected_max: Arc::new(
+ Decimal128Array::from(vec![Some(22000), Some(500000), None])
+ .with_precision_and_scale(9, 2)
+ .unwrap(),
+ ),
+ }
+ .run();
+
+ Test {
+ input: Arc::new(
+ Decimal256Array::from(vec![
+ // row group 1
+ Some(i256::from(100)),
+ None,
+ Some(i256::from(22000)),
+ // row group 2
+ Some(i256::MAX),
+ Some(i256::MIN),
+ None,
+ // row group 3
+ None,
+ None,
+ None,
+ ])
+ .with_precision_and_scale(76, 76)
+ .unwrap(),
+ ),
+ expected_min: Arc::new(
+ Decimal256Array::from(vec![Some(i256::from(100)), Some(i256::MIN), None])
+ .with_precision_and_scale(76, 76)
+ .unwrap(),
+ ),
+ expected_max: Arc::new(
+ Decimal256Array::from(vec![Some(i256::from(22000)), Some(i256::MAX), None])
+ .with_precision_and_scale(76, 76)
+ .unwrap(),
+ ),
+ }
+ .run()
+ }
+
+ #[test]
+ fn roundtrip_utf8() {
+ Test {
+ input: utf8_array([
+ // row group 1
+ Some("A"),
+ None,
+ Some("Q"),
+ // row group 2
+ Some("ZZ"),
+ Some("AA"),
+ None,
+ // row group 3
+ None,
+ None,
+ None,
+ ]),
+ expected_min: utf8_array([Some("A"), Some("AA"), None]),
+ expected_max: utf8_array([Some("Q"), Some("ZZ"), None]),
+ }
+ .run()
+ }
+
+ #[test]
+ fn roundtrip_struct() {
+ let mut test = Test {
+ input: struct_array(vec![
+ // row group 1
+ (Some(true), Some(1)),
+ (None, None),
+ (Some(true), Some(3)),
+ // row group 2
+ (Some(true), Some(0)),
+ (Some(false), Some(5)),
+ (None, None),
+ // row group 3
+ (None, None),
+ (None, None),
+ (None, None),
+ ]),
+ expected_min: struct_array(vec![
+ (Some(true), Some(1)),
+ (Some(true), Some(0)),
+ (None, None),
+ ]),
+
+ expected_max: struct_array(vec![
+ (Some(true), Some(3)),
+ (Some(true), Some(0)),
+ (None, None),
+ ]),
+ };
+ // Due to https://github.com/apache/datafusion/issues/8334,
+ // statistics for struct arrays are not supported
+ test.expected_min = new_null_array(test.input.data_type(), test.expected_min.len());
+ test.expected_max = new_null_array(test.input.data_type(), test.expected_min.len());
+ test.run()
+ }
+
+ #[test]
+ fn roundtrip_binary() {
+ Test {
+ input: Arc::new(BinaryArray::from_opt_vec(vec![
+ // row group 1
+ Some(b"A"),
+ None,
+ Some(b"Q"),
+ // row group 2
+ Some(b"ZZ"),
+ Some(b"AA"),
+ None,
+ // row group 3
+ None,
+ None,
+ None,
+ ])),
+ expected_min: Arc::new(BinaryArray::from_opt_vec(vec![
+ Some(b"A"),
+ Some(b"AA"),
+ None,
+ ])),
+ expected_max: Arc::new(BinaryArray::from_opt_vec(vec![
+ Some(b"Q"),
+ Some(b"ZZ"),
+ None,
+ ])),
+ }
+ .run()
+ }
+
+ #[test]
+ fn roundtrip_date32() {
+ Test {
+ input: date32_array(vec![
+ // row group 1
+ Some("2021-01-01"),
+ None,
+ Some("2021-01-03"),
+ // row group 2
+ Some("2021-01-01"),
+ Some("2021-01-05"),
+ None,
+ // row group 3
+ None,
+ None,
+ None,
+ ]),
+ expected_min: date32_array(vec![Some("2021-01-01"), Some("2021-01-01"), None]),
+ expected_max: date32_array(vec![Some("2021-01-03"), Some("2021-01-05"), None]),
+ }
+ .run()
+ }
+
+ #[test]
+ fn roundtrip_date64() {
+ Test {
+ input: date64_array(vec![
+ // row group 1
+ Some("2021-01-01"),
+ None,
+ Some("2021-01-03"),
+ // row group 2
+ Some("2021-01-01"),
+ Some("2021-01-05"),
+ None,
+ // row group 3
+ None,
+ None,
+ None,
+ ]),
+ expected_min: date64_array(vec![Some("2021-01-01"), Some("2021-01-01"), None]),
+ expected_max: date64_array(vec![Some("2021-01-03"), Some("2021-01-05"), None]),
+ }
+ .run()
+ }
+
+ #[test]
+ fn roundtrip_large_binary_array() {
+ let input: Vec<Option<&[u8]>> = vec![
+ // row group 1
+ Some(b"A"),
+ None,
+ Some(b"Q"),
+ // row group 2
+ Some(b"ZZ"),
+ Some(b"AA"),
+ None,
+ // row group 3
+ None,
+ None,
+ None,
+ ];
+
+ let expected_min: Vec<Option<&[u8]>> = vec![Some(b"A"), Some(b"AA"), None];
+ let expected_max: Vec<Option<&[u8]>> = vec![Some(b"Q"), Some(b"ZZ"), None];
+
+ Test {
+ input: large_binary_array(input),
+ expected_min: large_binary_array(expected_min),
+ expected_max: large_binary_array(expected_max),
+ }
+ .run();
+ }
+
+ #[test]
+ fn struct_and_non_struct() {
+ // Ensures that statistics for an array that appears *after* a struct
+ // array are not wrong
+ let struct_col = struct_array(vec![
+ // row group 1
+ (Some(true), Some(1)),
+ (None, None),
+ (Some(true), Some(3)),
+ ]);
+ let int_col = i32_array([Some(100), Some(200), Some(300)]);
+ let expected_min = i32_array([Some(100)]);
+ let expected_max = i32_array(vec![Some(300)]);
+
+ // use a name that shadows a name in the struct column
+ match struct_col.data_type() {
+ DataType::Struct(fields) => {
+ assert_eq!(fields.get(1).unwrap().name(), "int_col")
+ }
+ _ => panic!("unexpected data type for struct column"),
+ };
+
+ let input_batch =
+ RecordBatch::try_from_iter([("struct_col", struct_col), ("int_col", int_col)]).unwrap();
+
+ let schema = input_batch.schema();
+
+ let metadata = parquet_metadata(schema.clone(), input_batch);
+ let parquet_schema = metadata.file_metadata().schema_descr();
+
+ // read the int_col statistics
+ let (idx, _) = parquet_column(parquet_schema, &schema, "int_col").unwrap();
+ assert_eq!(idx, 2);
+
+ let row_groups = metadata.row_groups();
+ let converter = StatisticsConverter::try_new("int_col", &schema, parquet_schema).unwrap();
+
+ let min = converter.row_group_mins(row_groups.iter()).unwrap();
+ assert_eq!(
+ &min,
+ &expected_min,
+ "Min. Statistics\n\n{}\n\n",
+ DisplayStats(row_groups)
+ );
+
+ let max = converter.row_group_maxes(row_groups.iter()).unwrap();
+ assert_eq!(
+ &max,
+ &expected_max,
+ "Max. Statistics\n\n{}\n\n",
+ DisplayStats(row_groups)
+ );
+ }
+
+ #[test]
+ fn nan_in_stats() {
+ // /parquet-testing/data/nan_in_stats.parquet
+ // row_groups: 1
+ // "x": Double({min: Some(1.0), max: Some(NaN), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
+
+ TestFile::new("nan_in_stats.parquet")
+ .with_column(ExpectedColumn {
+ name: "x",
+ expected_min: Arc::new(Float64Array::from(vec![Some(1.0)])),
+ expected_max: Arc::new(Float64Array::from(vec![Some(f64::NAN)])),
+ })
+ .run();
+ }
+
+ #[test]
+ fn alltypes_plain() {
+ // /parquet-testing/data/datapage_v1-snappy-compressed-checksum.parquet
+ // row_groups: 1
+ // (has no statistics)
+ TestFile::new("alltypes_plain.parquet")
+ // No column statistics should be read as NULL, but with the right type
+ .with_column(ExpectedColumn {
+ name: "id",
+ expected_min: i32_array([None]),
+ expected_max: i32_array([None]),
+ })
+ .with_column(ExpectedColumn {
+ name: "bool_col",
+ expected_min: bool_array([None]),
+ expected_max: bool_array([None]),
+ })
+ .run();
+ }
+
+ #[test]
+ fn alltypes_tiny_pages() {
+ // /parquet-testing/data/alltypes_tiny_pages.parquet
+ // row_groups: 1
+ // "id": Int32({min: Some(0), max: Some(7299), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
+ // "bool_col": Boolean({min: Some(false), max: Some(true), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
+ // "tinyint_col": Int32({min: Some(0), max: Some(9), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
+ // "smallint_col": Int32({min: Some(0), max: Some(9), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
+ // "int_col": Int32({min: Some(0), max: Some(9), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
+ // "bigint_col": Int64({min: Some(0), max: Some(90), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
+ // "float_col": Float({min: Some(0.0), max: Some(9.9), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
+ // "double_col": Double({min: Some(0.0), max: Some(90.89999999999999), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
+ // "date_string_col": ByteArray({min: Some(ByteArray { data: "01/01/09" }), max: Some(ByteArray { data: "12/31/10" }), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
+ // "string_col": ByteArray({min: Some(ByteArray { data: "0" }), max: Some(ByteArray { data: "9" }), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
+ // "timestamp_col": Int96({min: None, max: None, distinct_count: None, null_count: 0, min_max_deprecated: true, min_max_backwards_compatible: true})
+ // "year": Int32({min: Some(2009), max: Some(2010), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
+ // "month": Int32({min: Some(1), max: Some(12), distinct_count: None, null_count: 0, min_max_deprecated: false, min_max_backwards_compatible: false})
+ TestFile::new("alltypes_tiny_pages.parquet")
+ .with_column(ExpectedColumn {
+ name: "id",
+ expected_min: i32_array([Some(0)]),
+ expected_max: i32_array([Some(7299)]),
+ })
+ .with_column(ExpectedColumn {
+ name: "bool_col",
+ expected_min: bool_array([Some(false)]),
+ expected_max: bool_array([Some(true)]),
+ })
+ .with_column(ExpectedColumn {
+ name: "tinyint_col",
+ expected_min: i8_array([Some(0)]),
+ expected_max: i8_array([Some(9)]),
+ })
+ .with_column(ExpectedColumn {
+ name: "smallint_col",
+ expected_min: i16_array([Some(0)]),
+ expected_max: i16_array([Some(9)]),
+ })
+ .with_column(ExpectedColumn {
+ name: "int_col",
+ expected_min: i32_array([Some(0)]),
+ expected_max: i32_array([Some(9)]),
+ })
+ .with_column(ExpectedColumn {
+ name: "bigint_col",
+ expected_min: i64_array([Some(0)]),
+ expected_max: i64_array([Some(90)]),
+ })
+ .with_column(ExpectedColumn {
+ name: "float_col",
+ expected_min: f32_array([Some(0.0)]),
+ expected_max: f32_array([Some(9.9)]),
+ })
+ .with_column(ExpectedColumn {
+ name: "double_col",
+ expected_min: f64_array([Some(0.0)]),
+ expected_max: f64_array([Some(90.89999999999999)]),
+ })
+ .with_column(ExpectedColumn {
+ name: "date_string_col",
+ expected_min: utf8_array([Some("01/01/09")]),
+ expected_max: utf8_array([Some("12/31/10")]),
+ })
+ .with_column(ExpectedColumn {
+ name: "string_col",
+ expected_min: utf8_array([Some("0")]),
+ expected_max: utf8_array([Some("9")]),
+ })
+ // File has no min/max for timestamp_col
+ .with_column(ExpectedColumn {
+ name: "timestamp_col",
+ expected_min: timestamp_nanoseconds_array([None], None),
+ expected_max: timestamp_nanoseconds_array([None], None),
+ })
+ .with_column(ExpectedColumn {
+ name: "year",
+ expected_min: i32_array([Some(2009)]),
+ expected_max: i32_array([Some(2010)]),
+ })
+ .with_column(ExpectedColumn {
+ name: "month",
+ expected_min: i32_array([Some(1)]),
+ expected_max: i32_array([Some(12)]),
+ })
+ .run();
+ }
+
+ #[test]
+ fn fixed_length_decimal_legacy() {
+ // /parquet-testing/data/fixed_length_decimal_legacy.parquet
+ // row_groups: 1
+ // "value": FixedLenByteArray({min: Some(FixedLenByteArray(ByteArray { data: Some(ByteBufferPtr { data: b"\0\0\0\0\0\xc8" }) })), max: Some(FixedLenByteArray(ByteArray { data: "\0\0\0\0\t`" })), distinct_count: None, null_count: 0, min_max_deprecated: true, min_max_backwards_compatible: true})
+
+ TestFile::new("fixed_length_decimal_legacy.parquet")
+ .with_column(ExpectedColumn {
+ name: "value",
+ expected_min: Arc::new(
+ Decimal128Array::from(vec![Some(200)])
+ .with_precision_and_scale(13, 2)
+ .unwrap(),
+ ),
+ expected_max: Arc::new(
+ Decimal128Array::from(vec![Some(2400)])
+ .with_precision_and_scale(13, 2)
+ .unwrap(),
+ ),
+ })
+ .run();
+ }
+
+ const ROWS_PER_ROW_GROUP: usize = 3;
+
+ /// Writes the input batch into a parquet file, with every every three rows as
+ /// their own row group, and compares the min/maxes to the expected values
+ struct Test {
+ input: ArrayRef,
+ expected_min: ArrayRef,
+ expected_max: ArrayRef,
+ }
+
+ impl Test {
+ fn run(self) {
+ let Self {
+ input,
+ expected_min,
+ expected_max,
+ } = self;
+
+ let input_batch = RecordBatch::try_from_iter([("c1", input)]).unwrap();
+
+ let schema = input_batch.schema();
+
+ let metadata = parquet_metadata(schema.clone(), input_batch);
+ let parquet_schema = metadata.file_metadata().schema_descr();
+
+ let row_groups = metadata.row_groups();
+
+ for field in schema.fields() {
+ if field.data_type().is_nested() {
+ let lookup = parquet_column(parquet_schema, &schema, field.name());
+ assert_eq!(lookup, None);
+ continue;
+ }
+
+ let converter =
+ StatisticsConverter::try_new(field.name(), &schema, parquet_schema).unwrap();
+
+ assert_eq!(converter.arrow_field, field.as_ref());
+
+ let mins = converter.row_group_mins(row_groups.iter()).unwrap();
+ assert_eq!(
+ &mins,
+ &expected_min,
+ "Min. Statistics\n\n{}\n\n",
+ DisplayStats(row_groups)
+ );
+
+ let maxes = converter.row_group_maxes(row_groups.iter()).unwrap();
+ assert_eq!(
+ &maxes,
+ &expected_max,
+ "Max. Statistics\n\n{}\n\n",
+ DisplayStats(row_groups)
+ );
+ }
+ }
+ }
+
+ /// Write the specified batches out as parquet and return the metadata
+ fn parquet_metadata(schema: SchemaRef, batch: RecordBatch) -> Arc<ParquetMetaData> {
+ let props = WriterProperties::builder()
+ .set_statistics_enabled(EnabledStatistics::Chunk)
+ .set_max_row_group_size(ROWS_PER_ROW_GROUP)
+ .build();
+
+ let mut buffer = Vec::new();
+ let mut writer = ArrowWriter::try_new(&mut buffer, schema, Some(props)).unwrap();
+ writer.write(&batch).unwrap();
+ writer.close().unwrap();
+
+ let reader = ArrowReaderBuilder::try_new(Bytes::from(buffer)).unwrap();
+ reader.metadata().clone()
+ }
+
+ /// Formats the statistics nicely for display
+ struct DisplayStats<'a>(&'a [RowGroupMetaData]);
+ impl<'a> std::fmt::Display for DisplayStats<'a> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let row_groups = self.0;
+ writeln!(f, " row_groups: {}", row_groups.len())?;
+ for rg in row_groups {
+ for col in rg.columns() {
+ if let Some(statistics) = col.statistics() {
+ writeln!(f, " {}: {:?}", col.column_path(), statistics)?;
+ }
+ }
+ }
+ Ok(())
+ }
+ }
+
+ struct ExpectedColumn {
+ name: &'static str,
+ expected_min: ArrayRef,
+ expected_max: ArrayRef,
+ }
+
+ /// Reads statistics out of the specified, and compares them to the expected values
+ struct TestFile {
+ file_name: &'static str,
+ expected_columns: Vec<ExpectedColumn>,
+ }
+
+ impl TestFile {
+ fn new(file_name: &'static str) -> Self {
+ Self {
+ file_name,
+ expected_columns: Vec::new(),
+ }
+ }
+
+ fn with_column(mut self, column: ExpectedColumn) -> Self {
+ self.expected_columns.push(column);
+ self
+ }
+
+ /// Reads the specified parquet file and validates that the expected min/max
+ /// values for the specified columns are as expected.
+ fn run(self) {
+ let path = PathBuf::from(parquet_test_data()).join(self.file_name);
+ let file = std::fs::File::open(path).unwrap();
+ let reader = ArrowReaderBuilder::try_new(file).unwrap();
+ let arrow_schema = reader.schema();
+ let metadata = reader.metadata();
+ let row_groups = metadata.row_groups();
+ let parquet_schema = metadata.file_metadata().schema_descr();
+
+ for expected_column in self.expected_columns {
+ let ExpectedColumn {
+ name,
+ expected_min,
+ expected_max,
+ } = expected_column;
+
+ let converter =
+ StatisticsConverter::try_new(name, arrow_schema, parquet_schema).unwrap();
+
+ // test accessors on the converter
+ let parquet_column_index =
+ parquet_column(parquet_schema, arrow_schema, name).map(|(idx, _field)| idx);
+ assert_eq!(converter.parquet_column_index(), parquet_column_index);
+ assert_eq!(converter.arrow_field().name(), name);
+
+ let actual_min = converter.row_group_mins(row_groups.iter()).unwrap();
+ assert_eq!(&expected_min, &actual_min, "column {name}");
+
+ let actual_max = converter.row_group_maxes(row_groups.iter()).unwrap();
+ assert_eq!(&expected_max, &actual_max, "column {name}");
+ }
+ }
+ }
+
+ fn bool_array(input: impl IntoIterator<Item = Option<bool>>) -> ArrayRef {
+ let array: BooleanArray = input.into_iter().collect();
+ Arc::new(array)
+ }
+
+ fn i8_array(input: impl IntoIterator<Item = Option<i8>>) -> ArrayRef {
+ let array: Int8Array = input.into_iter().collect();
+ Arc::new(array)
+ }
+
+ fn i16_array(input: impl IntoIterator<Item = Option<i16>>) -> ArrayRef {
+ let array: Int16Array = input.into_iter().collect();
+ Arc::new(array)
+ }
+
+ fn i32_array(input: impl IntoIterator<Item = Option<i32>>) -> ArrayRef {
+ let array: Int32Array = input.into_iter().collect();
+ Arc::new(array)
+ }
+
+ fn i64_array(input: impl IntoIterator<Item = Option<i64>>) -> ArrayRef {
+ let array: Int64Array = input.into_iter().collect();
+ Arc::new(array)
+ }
+
+ fn f32_array(input: impl IntoIterator<Item = Option<f32>>) -> ArrayRef {
+ let array: Float32Array = input.into_iter().collect();
+ Arc::new(array)
+ }
+
+ fn f64_array(input: impl IntoIterator<Item = Option<f64>>) -> ArrayRef {
+ let array: Float64Array = input.into_iter().collect();
+ Arc::new(array)
+ }
+
+ fn timestamp_seconds_array(
+ input: impl IntoIterator<Item = Option<i64>>,
+ timzezone: Option<&str>,
+ ) -> ArrayRef {
+ let array: TimestampSecondArray = input.into_iter().collect();
+ match timzezone {
+ Some(tz) => Arc::new(array.with_timezone(tz)),
+ None => Arc::new(array),
+ }
+ }
+
+ fn timestamp_milliseconds_array(
+ input: impl IntoIterator<Item = Option<i64>>,
+ timzezone: Option<&str>,
+ ) -> ArrayRef {
+ let array: TimestampMillisecondArray = input.into_iter().collect();
+ match timzezone {
+ Some(tz) => Arc::new(array.with_timezone(tz)),
+ None => Arc::new(array),
+ }
+ }
+
+ fn timestamp_microseconds_array(
+ input: impl IntoIterator<Item = Option<i64>>,
+ timzezone: Option<&str>,
+ ) -> ArrayRef {
+ let array: TimestampMicrosecondArray = input.into_iter().collect();
+ match timzezone {
+ Some(tz) => Arc::new(array.with_timezone(tz)),
+ None => Arc::new(array),
+ }
+ }
+
+ fn timestamp_nanoseconds_array(
+ input: impl IntoIterator<Item = Option<i64>>,
+ timzezone: Option<&str>,
+ ) -> ArrayRef {
+ let array: TimestampNanosecondArray = input.into_iter().collect();
+ match timzezone {
+ Some(tz) => Arc::new(array.with_timezone(tz)),
+ None => Arc::new(array),
+ }
+ }
+
+ fn utf8_array<'a>(input: impl IntoIterator<Item = Option<&'a str>>) -> ArrayRef {
+ let array: StringArray = input
+ .into_iter()
+ .map(|s| s.map(|s| s.to_string()))
+ .collect();
+ Arc::new(array)
+ }
+
+ // returns a struct array with columns "bool_col" and "int_col" with the specified values
+ fn struct_array(input: Vec<(Option<bool>, Option<i32>)>) -> ArrayRef {
+ let boolean: BooleanArray = input.iter().map(|(b, _i)| b).collect();
+ let int: Int32Array = input.iter().map(|(_b, i)| i).collect();
+
+ let nullable = true;
+ let struct_array = StructArray::from(vec![
+ (
+ Arc::new(Field::new("bool_col", DataType::Boolean, nullable)),
+ Arc::new(boolean) as ArrayRef,
+ ),
+ (
+ Arc::new(Field::new("int_col", DataType::Int32, nullable)),
+ Arc::new(int) as ArrayRef,
+ ),
+ ]);
+ Arc::new(struct_array)
+ }
+
+ fn date32_array<'a>(input: impl IntoIterator<Item = Option<&'a str>>) -> ArrayRef {
+ let array = Date32Array::from(
+ input
+ .into_iter()
+ .map(|s| Date32Type::parse(s.unwrap_or_default()))
+ .collect::<Vec<_>>(),
+ );
+ Arc::new(array)
+ }
+
+ fn date64_array<'a>(input: impl IntoIterator<Item = Option<&'a str>>) -> ArrayRef {
+ let array = Date64Array::from(
+ input
+ .into_iter()
+ .map(|s| Date64Type::parse(s.unwrap_or_default()))
+ .collect::<Vec<_>>(),
+ );
+ Arc::new(array)
+ }
+
+ fn large_binary_array<'a>(input: impl IntoIterator<Item = Option<&'a [u8]>>) -> ArrayRef {
+ let array = LargeBinaryArray::from(input.into_iter().collect::<Vec<Option<&[u8]>>>());
+
+ Arc::new(array)
+ }
+}
diff --git a/parquet/src/arrow/mod.rs b/parquet/src/arrow/mod.rs
index 950226aef721..5c36891434c3 100644
--- a/parquet/src/arrow/mod.rs
+++ b/parquet/src/arrow/mod.rs
@@ -114,6 +114,7 @@ pub use self::async_reader::ParquetRecordBatchStreamBuilder;
#[cfg(feature = "async")]
pub use self::async_writer::AsyncArrowWriter;
use crate::schema::types::SchemaDescriptor;
+use arrow_schema::{FieldRef, Schema};
pub use self::schema::{
arrow_to_parquet_schema, parquet_to_arrow_field_levels, parquet_to_arrow_schema,
@@ -210,3 +211,28 @@ impl ProjectionMask {
self.mask.as_ref().map(|m| m[leaf_idx]).unwrap_or(true)
}
}
+
+/// Lookups up the parquet column by name
+///
+/// Returns the parquet column index and the corresponding arrow field
+pub fn parquet_column<'a>(
+ parquet_schema: &SchemaDescriptor,
+ arrow_schema: &'a Schema,
+ name: &str,
+) -> Option<(usize, &'a FieldRef)> {
+ let (root_idx, field) = arrow_schema.fields.find(name)?;
+ if field.data_type().is_nested() {
+ // Nested fields are not supported and require non-trivial logic
+ // to correctly walk the parquet schema accounting for the
+ // logical type rules - <https://github.com/apache/parquet-format/blob/master/LogicalTypes.md>
+ //
+ // For example a ListArray could correspond to anything from 1 to 3 levels
+ // in the parquet schema
+ return None;
+ }
+
+ // This could be made more efficient (#TBD)
+ let parquet_idx = (0..parquet_schema.columns().len())
+ .find(|x| parquet_schema.get_column_root_idx(*x) == root_idx)?;
+ Some((parquet_idx, field))
+}
|
diff --git a/parquet/tests/arrow_reader/mod.rs b/parquet/tests/arrow_reader/mod.rs
new file mode 100644
index 000000000000..4f63a505488c
--- /dev/null
+++ b/parquet/tests/arrow_reader/mod.rs
@@ -0,0 +1,1003 @@
+// 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.
+
+use arrow_array::types::{Int32Type, Int8Type};
+use arrow_array::{
+ Array, ArrayRef, BinaryArray, BooleanArray, Date32Array, Date64Array, Decimal128Array,
+ Decimal256Array, DictionaryArray, FixedSizeBinaryArray, Float16Array, Float32Array,
+ Float64Array, Int16Array, Int32Array, Int64Array, Int8Array, LargeBinaryArray,
+ LargeStringArray, RecordBatch, StringArray, StructArray, Time32MillisecondArray,
+ Time32SecondArray, Time64MicrosecondArray, Time64NanosecondArray, TimestampMicrosecondArray,
+ TimestampMillisecondArray, TimestampNanosecondArray, TimestampSecondArray, UInt16Array,
+ UInt32Array, UInt64Array, UInt8Array,
+};
+use arrow_buffer::i256;
+use arrow_schema::{DataType, Field, Schema, TimeUnit};
+use chrono::Datelike;
+use chrono::{Duration, TimeDelta};
+use half::f16;
+use parquet::arrow::ArrowWriter;
+use parquet::file::properties::{EnabledStatistics, WriterProperties};
+use std::sync::Arc;
+use tempfile::NamedTempFile;
+
+mod statistics;
+
+// returns a struct array with columns "int32_col", "float32_col" and "float64_col" with the specified values
+fn struct_array(input: Vec<(Option<i32>, Option<f32>, Option<f64>)>) -> ArrayRef {
+ let int_32: Int32Array = input.iter().map(|(i, _, _)| i).collect();
+ let float_32: Float32Array = input.iter().map(|(_, f, _)| f).collect();
+ let float_64: Float64Array = input.iter().map(|(_, _, f)| f).collect();
+
+ let nullable = true;
+ let struct_array = StructArray::from(vec![
+ (
+ Arc::new(Field::new("int32_col", DataType::Int32, nullable)),
+ Arc::new(int_32) as ArrayRef,
+ ),
+ (
+ Arc::new(Field::new("float32_col", DataType::Float32, nullable)),
+ Arc::new(float_32) as ArrayRef,
+ ),
+ (
+ Arc::new(Field::new("float64_col", DataType::Float64, nullable)),
+ Arc::new(float_64) as ArrayRef,
+ ),
+ ]);
+ Arc::new(struct_array)
+}
+
+/// What data to use
+#[derive(Debug, Clone, Copy)]
+enum Scenario {
+ Boolean,
+ Timestamps,
+ Dates,
+ Int,
+ Int32Range,
+ UInt,
+ UInt32Range,
+ Time32Second,
+ Time32Millisecond,
+ Time64Nanosecond,
+ Time64Microsecond,
+ /// 7 Rows, for each i8, i16, i32, i64, u8, u16, u32, u64, f32, f64
+ /// -MIN, -100, -1, 0, 1, 100, MAX
+ NumericLimits,
+ Float16,
+ Float32,
+ Float64,
+ Decimal,
+ Decimal256,
+ ByteArray,
+ Dictionary,
+ PeriodsInColumnNames,
+ StructArray,
+ UTF8,
+}
+
+fn make_boolean_batch(v: Vec<Option<bool>>) -> RecordBatch {
+ let schema = Arc::new(Schema::new(vec![Field::new(
+ "bool",
+ DataType::Boolean,
+ true,
+ )]));
+ let array = Arc::new(BooleanArray::from(v)) as ArrayRef;
+ RecordBatch::try_new(schema, vec![array.clone()]).unwrap()
+}
+
+/// Return record batch with a few rows of data for all of the supported timestamp types
+/// values with the specified offset
+///
+/// Columns are named:
+/// "nanos" --> TimestampNanosecondArray
+/// "nanos_timezoned" --> TimestampNanosecondArray with timezone
+/// "micros" --> TimestampMicrosecondArray
+/// "micros_timezoned" --> TimestampMicrosecondArray with timezone
+/// "millis" --> TimestampMillisecondArray
+/// "millis_timezoned" --> TimestampMillisecondArray with timezone
+/// "seconds" --> TimestampSecondArray
+/// "seconds_timezoned" --> TimestampSecondArray with timezone
+/// "names" --> StringArray
+fn make_timestamp_batch(offset: Duration) -> RecordBatch {
+ let ts_strings = vec![
+ Some("2020-01-01T01:01:01.0000000000001"),
+ Some("2020-01-01T01:02:01.0000000000001"),
+ Some("2020-01-01T02:01:01.0000000000001"),
+ None,
+ Some("2020-01-02T01:01:01.0000000000001"),
+ ];
+
+ let tz_string = "Pacific/Efate";
+
+ let offset_nanos = offset.num_nanoseconds().expect("non overflow nanos");
+
+ let ts_nanos = ts_strings
+ .into_iter()
+ .map(|t| {
+ t.map(|t| {
+ offset_nanos
+ + t.parse::<chrono::NaiveDateTime>()
+ .unwrap()
+ .and_utc()
+ .timestamp_nanos_opt()
+ .unwrap()
+ })
+ })
+ .collect::<Vec<_>>();
+
+ let ts_micros = ts_nanos
+ .iter()
+ .map(|t| t.as_ref().map(|ts_nanos| ts_nanos / 1000))
+ .collect::<Vec<_>>();
+
+ let ts_millis = ts_nanos
+ .iter()
+ .map(|t| t.as_ref().map(|ts_nanos| ts_nanos / 1000000))
+ .collect::<Vec<_>>();
+
+ let ts_seconds = ts_nanos
+ .iter()
+ .map(|t| t.as_ref().map(|ts_nanos| ts_nanos / 1000000000))
+ .collect::<Vec<_>>();
+
+ let names = ts_nanos
+ .iter()
+ .enumerate()
+ .map(|(i, _)| format!("Row {i} + {offset}"))
+ .collect::<Vec<_>>();
+
+ let arr_nanos = TimestampNanosecondArray::from(ts_nanos.clone());
+ let arr_nanos_timezoned = TimestampNanosecondArray::from(ts_nanos).with_timezone(tz_string);
+ let arr_micros = TimestampMicrosecondArray::from(ts_micros.clone());
+ let arr_micros_timezoned = TimestampMicrosecondArray::from(ts_micros).with_timezone(tz_string);
+ let arr_millis = TimestampMillisecondArray::from(ts_millis.clone());
+ let arr_millis_timezoned = TimestampMillisecondArray::from(ts_millis).with_timezone(tz_string);
+ let arr_seconds = TimestampSecondArray::from(ts_seconds.clone());
+ let arr_seconds_timezoned = TimestampSecondArray::from(ts_seconds).with_timezone(tz_string);
+
+ let names = names.iter().map(|s| s.as_str()).collect::<Vec<_>>();
+ let arr_names = StringArray::from(names);
+
+ let schema = Schema::new(vec![
+ Field::new("nanos", arr_nanos.data_type().clone(), true),
+ Field::new(
+ "nanos_timezoned",
+ arr_nanos_timezoned.data_type().clone(),
+ true,
+ ),
+ Field::new("micros", arr_micros.data_type().clone(), true),
+ Field::new(
+ "micros_timezoned",
+ arr_micros_timezoned.data_type().clone(),
+ true,
+ ),
+ Field::new("millis", arr_millis.data_type().clone(), true),
+ Field::new(
+ "millis_timezoned",
+ arr_millis_timezoned.data_type().clone(),
+ true,
+ ),
+ Field::new("seconds", arr_seconds.data_type().clone(), true),
+ Field::new(
+ "seconds_timezoned",
+ arr_seconds_timezoned.data_type().clone(),
+ true,
+ ),
+ Field::new("name", arr_names.data_type().clone(), true),
+ ]);
+ let schema = Arc::new(schema);
+
+ RecordBatch::try_new(
+ schema,
+ vec![
+ Arc::new(arr_nanos),
+ Arc::new(arr_nanos_timezoned),
+ Arc::new(arr_micros),
+ Arc::new(arr_micros_timezoned),
+ Arc::new(arr_millis),
+ Arc::new(arr_millis_timezoned),
+ Arc::new(arr_seconds),
+ Arc::new(arr_seconds_timezoned),
+ Arc::new(arr_names),
+ ],
+ )
+ .unwrap()
+}
+
+/// Return record batch with i8, i16, i32, and i64 sequences
+///
+/// Columns are named
+/// "i8" -> Int8Array
+/// "i16" -> Int16Array
+/// "i32" -> Int32Array
+/// "i64" -> Int64Array
+fn make_int_batches(start: i8, end: i8) -> RecordBatch {
+ let schema = Arc::new(Schema::new(vec![
+ Field::new("i8", DataType::Int8, true),
+ Field::new("i16", DataType::Int16, true),
+ Field::new("i32", DataType::Int32, true),
+ Field::new("i64", DataType::Int64, true),
+ ]));
+ let v8: Vec<i8> = (start..end).collect();
+ let v16: Vec<i16> = (start as _..end as _).collect();
+ let v32: Vec<i32> = (start as _..end as _).collect();
+ let v64: Vec<i64> = (start as _..end as _).collect();
+ RecordBatch::try_new(
+ schema,
+ vec![
+ Arc::new(Int8Array::from(v8)) as ArrayRef,
+ Arc::new(Int16Array::from(v16)) as ArrayRef,
+ Arc::new(Int32Array::from(v32)) as ArrayRef,
+ Arc::new(Int64Array::from(v64)) as ArrayRef,
+ ],
+ )
+ .unwrap()
+}
+
+/// Return record batch with Time32Second, Time32Millisecond sequences
+fn make_time32_batches(scenario: Scenario, v: Vec<i32>) -> RecordBatch {
+ match scenario {
+ Scenario::Time32Second => {
+ let schema = Arc::new(Schema::new(vec![Field::new(
+ "second",
+ DataType::Time32(TimeUnit::Second),
+ true,
+ )]));
+ let array = Arc::new(Time32SecondArray::from(v)) as ArrayRef;
+ RecordBatch::try_new(schema, vec![array]).unwrap()
+ }
+ Scenario::Time32Millisecond => {
+ let schema = Arc::new(Schema::new(vec![Field::new(
+ "millisecond",
+ DataType::Time32(TimeUnit::Millisecond),
+ true,
+ )]));
+ let array = Arc::new(Time32MillisecondArray::from(v)) as ArrayRef;
+ RecordBatch::try_new(schema, vec![array]).unwrap()
+ }
+ _ => panic!("Unsupported scenario for Time32"),
+ }
+}
+
+/// Return record batch with Time64Microsecond, Time64Nanosecond sequences
+fn make_time64_batches(scenario: Scenario, v: Vec<i64>) -> RecordBatch {
+ match scenario {
+ Scenario::Time64Microsecond => {
+ let schema = Arc::new(Schema::new(vec![Field::new(
+ "microsecond",
+ DataType::Time64(TimeUnit::Microsecond),
+ true,
+ )]));
+ let array = Arc::new(Time64MicrosecondArray::from(v)) as ArrayRef;
+ RecordBatch::try_new(schema, vec![array]).unwrap()
+ }
+ Scenario::Time64Nanosecond => {
+ let schema = Arc::new(Schema::new(vec![Field::new(
+ "nanosecond",
+ DataType::Time64(TimeUnit::Nanosecond),
+ true,
+ )]));
+ let array = Arc::new(Time64NanosecondArray::from(v)) as ArrayRef;
+ RecordBatch::try_new(schema, vec![array]).unwrap()
+ }
+ _ => panic!("Unsupported scenario for Time64"),
+ }
+}
+/// Return record batch with u8, u16, u32, and u64 sequences
+///
+/// Columns are named
+/// "u8" -> UInt8Array
+/// "u16" -> UInt16Array
+/// "u32" -> UInt32Array
+/// "u64" -> UInt64Array
+fn make_uint_batches(start: u8, end: u8) -> RecordBatch {
+ let schema = Arc::new(Schema::new(vec![
+ Field::new("u8", DataType::UInt8, true),
+ Field::new("u16", DataType::UInt16, true),
+ Field::new("u32", DataType::UInt32, true),
+ Field::new("u64", DataType::UInt64, true),
+ ]));
+ let v8: Vec<u8> = (start..end).collect();
+ let v16: Vec<u16> = (start as _..end as _).collect();
+ let v32: Vec<u32> = (start as _..end as _).collect();
+ let v64: Vec<u64> = (start as _..end as _).collect();
+ RecordBatch::try_new(
+ schema,
+ vec![
+ Arc::new(UInt8Array::from(v8)) as ArrayRef,
+ Arc::new(UInt16Array::from(v16)) as ArrayRef,
+ Arc::new(UInt32Array::from(v32)) as ArrayRef,
+ Arc::new(UInt64Array::from(v64)) as ArrayRef,
+ ],
+ )
+ .unwrap()
+}
+
+fn make_int32_range(start: i32, end: i32) -> RecordBatch {
+ let schema = Arc::new(Schema::new(vec![Field::new("i", DataType::Int32, true)]));
+ let v = vec![start, end];
+ let array = Arc::new(Int32Array::from(v)) as ArrayRef;
+ RecordBatch::try_new(schema, vec![array.clone()]).unwrap()
+}
+
+fn make_uint32_range(start: u32, end: u32) -> RecordBatch {
+ let schema = Arc::new(Schema::new(vec![Field::new("u", DataType::UInt32, true)]));
+ let v = vec![start, end];
+ let array = Arc::new(UInt32Array::from(v)) as ArrayRef;
+ RecordBatch::try_new(schema, vec![array.clone()]).unwrap()
+}
+
+/// Return record batch with f64 vector
+///
+/// Columns are named
+/// "f" -> Float64Array
+fn make_f64_batch(v: Vec<f64>) -> RecordBatch {
+ let schema = Arc::new(Schema::new(vec![Field::new("f", DataType::Float64, true)]));
+ let array = Arc::new(Float64Array::from(v)) as ArrayRef;
+ RecordBatch::try_new(schema, vec![array.clone()]).unwrap()
+}
+
+fn make_f32_batch(v: Vec<f32>) -> RecordBatch {
+ let schema = Arc::new(Schema::new(vec![Field::new("f", DataType::Float32, true)]));
+ let array = Arc::new(Float32Array::from(v)) as ArrayRef;
+ RecordBatch::try_new(schema, vec![array.clone()]).unwrap()
+}
+
+fn make_f16_batch(v: Vec<f16>) -> RecordBatch {
+ let schema = Arc::new(Schema::new(vec![Field::new("f", DataType::Float16, true)]));
+ let array = Arc::new(Float16Array::from(v)) as ArrayRef;
+ RecordBatch::try_new(schema, vec![array.clone()]).unwrap()
+}
+
+/// Return record batch with decimal vector
+///
+/// Columns are named
+/// "decimal_col" -> DecimalArray
+fn make_decimal_batch(v: Vec<i128>, precision: u8, scale: i8) -> RecordBatch {
+ let schema = Arc::new(Schema::new(vec![Field::new(
+ "decimal_col",
+ DataType::Decimal128(precision, scale),
+ true,
+ )]));
+ let array = Arc::new(
+ Decimal128Array::from(v)
+ .with_precision_and_scale(precision, scale)
+ .unwrap(),
+ ) as ArrayRef;
+ RecordBatch::try_new(schema, vec![array.clone()]).unwrap()
+}
+
+/// Return record batch with decimal256 vector
+///
+/// Columns are named
+/// "decimal256_col" -> Decimal256Array
+fn make_decimal256_batch(v: Vec<i256>, precision: u8, scale: i8) -> RecordBatch {
+ let schema = Arc::new(Schema::new(vec![Field::new(
+ "decimal256_col",
+ DataType::Decimal256(precision, scale),
+ true,
+ )]));
+ let array = Arc::new(
+ Decimal256Array::from(v)
+ .with_precision_and_scale(precision, scale)
+ .unwrap(),
+ ) as ArrayRef;
+ RecordBatch::try_new(schema, vec![array]).unwrap()
+}
+
+/// Return record batch with a few rows of data for all of the supported date
+/// types with the specified offset (in days)
+///
+/// Columns are named:
+/// "date32" --> Date32Array
+/// "date64" --> Date64Array
+/// "names" --> StringArray
+fn make_date_batch(offset: Duration) -> RecordBatch {
+ let date_strings = vec![
+ Some("2020-01-01"),
+ Some("2020-01-02"),
+ Some("2020-01-03"),
+ None,
+ Some("2020-01-04"),
+ ];
+
+ let names = date_strings
+ .iter()
+ .enumerate()
+ .map(|(i, val)| format!("Row {i} + {offset}: {val:?}"))
+ .collect::<Vec<_>>();
+
+ // Copied from `cast.rs` cast kernel due to lack of temporal kernels
+ // https://github.com/apache/arrow-rs/issues/527
+ const EPOCH_DAYS_FROM_CE: i32 = 719_163;
+
+ let date_seconds = date_strings
+ .iter()
+ .map(|t| {
+ t.map(|t| {
+ let t = t.parse::<chrono::NaiveDate>().unwrap();
+ let t = t + offset;
+ t.num_days_from_ce() - EPOCH_DAYS_FROM_CE
+ })
+ })
+ .collect::<Vec<_>>();
+
+ let date_millis = date_strings
+ .into_iter()
+ .map(|t| {
+ t.map(|t| {
+ let t = t
+ .parse::<chrono::NaiveDate>()
+ .unwrap()
+ .and_time(chrono::NaiveTime::from_hms_opt(0, 0, 0).unwrap());
+ let t = t + offset;
+ t.and_utc().timestamp_millis()
+ })
+ })
+ .collect::<Vec<_>>();
+
+ let arr_date32 = Date32Array::from(date_seconds);
+ let arr_date64 = Date64Array::from(date_millis);
+
+ let names = names.iter().map(|s| s.as_str()).collect::<Vec<_>>();
+ let arr_names = StringArray::from(names);
+
+ let schema = Schema::new(vec![
+ Field::new("date32", arr_date32.data_type().clone(), true),
+ Field::new("date64", arr_date64.data_type().clone(), true),
+ Field::new("name", arr_names.data_type().clone(), true),
+ ]);
+ let schema = Arc::new(schema);
+
+ RecordBatch::try_new(
+ schema,
+ vec![
+ Arc::new(arr_date32),
+ Arc::new(arr_date64),
+ Arc::new(arr_names),
+ ],
+ )
+ .unwrap()
+}
+
+/// returns a batch with two columns (note "service.name" is the name
+/// of the column. It is *not* a table named service.name
+///
+/// name | service.name
+fn make_bytearray_batch(
+ name: &str,
+ string_values: Vec<&str>,
+ binary_values: Vec<&[u8]>,
+ fixedsize_values: Vec<&[u8; 3]>,
+ // i64 offset.
+ large_binary_values: Vec<&[u8]>,
+) -> RecordBatch {
+ let num_rows = string_values.len();
+ let name: StringArray = std::iter::repeat(Some(name)).take(num_rows).collect();
+ let service_string: StringArray = string_values.iter().map(Some).collect();
+ let service_binary: BinaryArray = binary_values.iter().map(Some).collect();
+ let service_fixedsize: FixedSizeBinaryArray = fixedsize_values
+ .iter()
+ .map(|value| Some(value.as_slice()))
+ .collect::<Vec<_>>()
+ .into();
+ let service_large_binary: LargeBinaryArray = large_binary_values.iter().map(Some).collect();
+
+ let schema = Schema::new(vec![
+ Field::new("name", name.data_type().clone(), true),
+ // note the column name has a period in it!
+ Field::new("service_string", service_string.data_type().clone(), true),
+ Field::new("service_binary", service_binary.data_type().clone(), true),
+ Field::new(
+ "service_fixedsize",
+ service_fixedsize.data_type().clone(),
+ true,
+ ),
+ Field::new(
+ "service_large_binary",
+ service_large_binary.data_type().clone(),
+ true,
+ ),
+ ]);
+ let schema = Arc::new(schema);
+
+ RecordBatch::try_new(
+ schema,
+ vec![
+ Arc::new(name),
+ Arc::new(service_string),
+ Arc::new(service_binary),
+ Arc::new(service_fixedsize),
+ Arc::new(service_large_binary),
+ ],
+ )
+ .unwrap()
+}
+
+/// returns a batch with two columns (note "service.name" is the name
+/// of the column. It is *not* a table named service.name
+///
+/// name | service.name
+fn make_names_batch(name: &str, service_name_values: Vec<&str>) -> RecordBatch {
+ let num_rows = service_name_values.len();
+ let name: StringArray = std::iter::repeat(Some(name)).take(num_rows).collect();
+ let service_name: StringArray = service_name_values.iter().map(Some).collect();
+
+ let schema = Schema::new(vec![
+ Field::new("name", name.data_type().clone(), true),
+ // note the column name has a period in it!
+ Field::new("service.name", service_name.data_type().clone(), true),
+ ]);
+ let schema = Arc::new(schema);
+
+ RecordBatch::try_new(schema, vec![Arc::new(name), Arc::new(service_name)]).unwrap()
+}
+
+fn make_numeric_limit_batch() -> RecordBatch {
+ let i8 = Int8Array::from(vec![i8::MIN, 100, -1, 0, 1, -100, i8::MAX]);
+ let i16 = Int16Array::from(vec![i16::MIN, 100, -1, 0, 1, -100, i16::MAX]);
+ let i32 = Int32Array::from(vec![i32::MIN, 100, -1, 0, 1, -100, i32::MAX]);
+ let i64 = Int64Array::from(vec![i64::MIN, 100, -1, 0, 1, -100, i64::MAX]);
+ let u8 = UInt8Array::from(vec![u8::MIN, 100, 1, 0, 1, 100, u8::MAX]);
+ let u16 = UInt16Array::from(vec![u16::MIN, 100, 1, 0, 1, 100, u16::MAX]);
+ let u32 = UInt32Array::from(vec![u32::MIN, 100, 1, 0, 1, 100, u32::MAX]);
+ let u64 = UInt64Array::from(vec![u64::MIN, 100, 1, 0, 1, 100, u64::MAX]);
+ let f32 = Float32Array::from(vec![f32::MIN, 100.0, -1.0, 0.0, 1.0, -100.0, f32::MAX]);
+ let f64 = Float64Array::from(vec![f64::MIN, 100.0, -1.0, 0.0, 1.0, -100.0, f64::MAX]);
+ let f32_nan = Float32Array::from(vec![f32::NAN, 100.0, -1.0, 0.0, 1.0, -100.0, f32::NAN]);
+ let f64_nan = Float64Array::from(vec![f64::NAN, 100.0, -1.0, 0.0, 1.0, -100.0, f64::NAN]);
+
+ RecordBatch::try_from_iter(vec![
+ ("i8", Arc::new(i8) as _),
+ ("i16", Arc::new(i16) as _),
+ ("i32", Arc::new(i32) as _),
+ ("i64", Arc::new(i64) as _),
+ ("u8", Arc::new(u8) as _),
+ ("u16", Arc::new(u16) as _),
+ ("u32", Arc::new(u32) as _),
+ ("u64", Arc::new(u64) as _),
+ ("f32", Arc::new(f32) as _),
+ ("f64", Arc::new(f64) as _),
+ ("f32_nan", Arc::new(f32_nan) as _),
+ ("f64_nan", Arc::new(f64_nan) as _),
+ ])
+ .unwrap()
+}
+
+fn make_utf8_batch(value: Vec<Option<&str>>) -> RecordBatch {
+ let utf8 = StringArray::from(value.clone());
+ let large_utf8 = LargeStringArray::from(value);
+ RecordBatch::try_from_iter(vec![
+ ("utf8", Arc::new(utf8) as _),
+ ("large_utf8", Arc::new(large_utf8) as _),
+ ])
+ .unwrap()
+}
+
+fn make_dict_batch() -> RecordBatch {
+ let values = [
+ Some("abc"),
+ Some("def"),
+ None,
+ Some("def"),
+ Some("abc"),
+ Some("fffff"),
+ Some("aaa"),
+ ];
+ let dict_i8_array = DictionaryArray::<Int8Type>::from_iter(values.iter().cloned());
+ let dict_i32_array = DictionaryArray::<Int32Type>::from_iter(values.iter().cloned());
+
+ // Dictionary array of integers
+ let int64_values = Int64Array::from(vec![0, -100, 100]);
+ let keys = Int8Array::from_iter([Some(0), Some(1), None, Some(0), Some(0), Some(2), Some(0)]);
+ let dict_i8_int_array =
+ DictionaryArray::<Int8Type>::try_new(keys, Arc::new(int64_values)).unwrap();
+
+ RecordBatch::try_from_iter(vec![
+ ("string_dict_i8", Arc::new(dict_i8_array) as _),
+ ("string_dict_i32", Arc::new(dict_i32_array) as _),
+ ("int_dict_i8", Arc::new(dict_i8_int_array) as _),
+ ])
+ .unwrap()
+}
+
+fn create_data_batch(scenario: Scenario) -> Vec<RecordBatch> {
+ match scenario {
+ Scenario::Boolean => {
+ vec![
+ make_boolean_batch(vec![Some(true), Some(false), Some(true), Some(false), None]),
+ make_boolean_batch(vec![
+ Some(false),
+ Some(false),
+ Some(false),
+ Some(false),
+ Some(false),
+ ]),
+ ]
+ }
+ Scenario::Timestamps => {
+ vec![
+ make_timestamp_batch(TimeDelta::try_seconds(0).unwrap()),
+ make_timestamp_batch(TimeDelta::try_seconds(10).unwrap()),
+ make_timestamp_batch(TimeDelta::try_minutes(10).unwrap()),
+ make_timestamp_batch(TimeDelta::try_days(10).unwrap()),
+ ]
+ }
+ Scenario::Dates => {
+ vec![
+ make_date_batch(TimeDelta::try_days(0).unwrap()),
+ make_date_batch(TimeDelta::try_days(10).unwrap()),
+ make_date_batch(TimeDelta::try_days(300).unwrap()),
+ make_date_batch(TimeDelta::try_days(3600).unwrap()),
+ ]
+ }
+ Scenario::Int => {
+ vec![
+ make_int_batches(-5, 0),
+ make_int_batches(-4, 1),
+ make_int_batches(0, 5),
+ make_int_batches(5, 10),
+ ]
+ }
+ Scenario::Int32Range => {
+ vec![make_int32_range(0, 10), make_int32_range(200000, 300000)]
+ }
+ Scenario::UInt => {
+ vec![
+ make_uint_batches(0, 5),
+ make_uint_batches(1, 6),
+ make_uint_batches(5, 10),
+ make_uint_batches(250, 255),
+ ]
+ }
+ Scenario::UInt32Range => {
+ vec![make_uint32_range(0, 10), make_uint32_range(200000, 300000)]
+ }
+ Scenario::NumericLimits => {
+ vec![make_numeric_limit_batch()]
+ }
+ Scenario::Float16 => {
+ vec![
+ make_f16_batch(
+ vec![-5.0, -4.0, -3.0, -2.0, -1.0]
+ .into_iter()
+ .map(f16::from_f32)
+ .collect(),
+ ),
+ make_f16_batch(
+ vec![-4.0, -3.0, -2.0, -1.0, 0.0]
+ .into_iter()
+ .map(f16::from_f32)
+ .collect(),
+ ),
+ make_f16_batch(
+ vec![0.0, 1.0, 2.0, 3.0, 4.0]
+ .into_iter()
+ .map(f16::from_f32)
+ .collect(),
+ ),
+ make_f16_batch(
+ vec![5.0, 6.0, 7.0, 8.0, 9.0]
+ .into_iter()
+ .map(f16::from_f32)
+ .collect(),
+ ),
+ ]
+ }
+ Scenario::Float32 => {
+ vec![
+ make_f32_batch(vec![-5.0, -4.0, -3.0, -2.0, -1.0]),
+ make_f32_batch(vec![-4.0, -3.0, -2.0, -1.0, 0.0]),
+ make_f32_batch(vec![0.0, 1.0, 2.0, 3.0, 4.0]),
+ make_f32_batch(vec![5.0, 6.0, 7.0, 8.0, 9.0]),
+ ]
+ }
+ Scenario::Float64 => {
+ vec![
+ make_f64_batch(vec![-5.0, -4.0, -3.0, -2.0, -1.0]),
+ make_f64_batch(vec![-4.0, -3.0, -2.0, -1.0, 0.0]),
+ make_f64_batch(vec![0.0, 1.0, 2.0, 3.0, 4.0]),
+ make_f64_batch(vec![5.0, 6.0, 7.0, 8.0, 9.0]),
+ ]
+ }
+ Scenario::Decimal => {
+ // decimal record batch
+ vec![
+ make_decimal_batch(vec![100, 200, 300, 400, 600], 9, 2),
+ make_decimal_batch(vec![-500, 100, 300, 400, 600], 9, 2),
+ make_decimal_batch(vec![2000, 3000, 3000, 4000, 6000], 9, 2),
+ ]
+ }
+ Scenario::Decimal256 => {
+ // decimal256 record batch
+ vec![
+ make_decimal256_batch(
+ vec![
+ i256::from(100),
+ i256::from(200),
+ i256::from(300),
+ i256::from(400),
+ i256::from(600),
+ ],
+ 9,
+ 2,
+ ),
+ make_decimal256_batch(
+ vec![
+ i256::from(-500),
+ i256::from(100),
+ i256::from(300),
+ i256::from(400),
+ i256::from(600),
+ ],
+ 9,
+ 2,
+ ),
+ make_decimal256_batch(
+ vec![
+ i256::from(2000),
+ i256::from(3000),
+ i256::from(3000),
+ i256::from(4000),
+ i256::from(6000),
+ ],
+ 9,
+ 2,
+ ),
+ ]
+ }
+ Scenario::ByteArray => {
+ // frontends first, then backends. All in order, except frontends 4 and 7
+ // are swapped to cause a statistics false positive on the 'fixed size' column.
+ vec![
+ make_bytearray_batch(
+ "all frontends",
+ vec![
+ "frontend one",
+ "frontend two",
+ "frontend three",
+ "frontend seven",
+ "frontend five",
+ ],
+ vec![
+ b"frontend one",
+ b"frontend two",
+ b"frontend three",
+ b"frontend seven",
+ b"frontend five",
+ ],
+ vec![b"fe1", b"fe2", b"fe3", b"fe7", b"fe5"],
+ vec![
+ b"frontend one",
+ b"frontend two",
+ b"frontend three",
+ b"frontend seven",
+ b"frontend five",
+ ],
+ ),
+ make_bytearray_batch(
+ "mixed",
+ vec![
+ "frontend six",
+ "frontend four",
+ "backend one",
+ "backend two",
+ "backend three",
+ ],
+ vec![
+ b"frontend six",
+ b"frontend four",
+ b"backend one",
+ b"backend two",
+ b"backend three",
+ ],
+ vec![b"fe6", b"fe4", b"be1", b"be2", b"be3"],
+ vec![
+ b"frontend six",
+ b"frontend four",
+ b"backend one",
+ b"backend two",
+ b"backend three",
+ ],
+ ),
+ make_bytearray_batch(
+ "all backends",
+ vec![
+ "backend four",
+ "backend five",
+ "backend six",
+ "backend seven",
+ "backend eight",
+ ],
+ vec![
+ b"backend four",
+ b"backend five",
+ b"backend six",
+ b"backend seven",
+ b"backend eight",
+ ],
+ vec![b"be4", b"be5", b"be6", b"be7", b"be8"],
+ vec![
+ b"backend four",
+ b"backend five",
+ b"backend six",
+ b"backend seven",
+ b"backend eight",
+ ],
+ ),
+ ]
+ }
+ Scenario::Dictionary => {
+ vec![make_dict_batch()]
+ }
+ Scenario::PeriodsInColumnNames => {
+ vec![
+ // all frontend
+ make_names_batch(
+ "HTTP GET / DISPATCH",
+ vec!["frontend", "frontend", "frontend", "frontend", "frontend"],
+ ),
+ // both frontend and backend
+ make_names_batch(
+ "HTTP PUT / DISPATCH",
+ vec!["frontend", "frontend", "backend", "backend", "backend"],
+ ),
+ // all backend
+ make_names_batch(
+ "HTTP GET / DISPATCH",
+ vec!["backend", "backend", "backend", "backend", "backend"],
+ ),
+ ]
+ }
+ Scenario::StructArray => {
+ let struct_array_data = struct_array(vec![
+ (Some(1), Some(6.0), Some(12.0)),
+ (Some(2), Some(8.5), None),
+ (None, Some(8.5), Some(14.0)),
+ ]);
+
+ let schema = Arc::new(Schema::new(vec![Field::new(
+ "struct",
+ struct_array_data.data_type().clone(),
+ true,
+ )]));
+ vec![RecordBatch::try_new(schema, vec![struct_array_data]).unwrap()]
+ }
+ Scenario::Time32Second => {
+ vec![
+ make_time32_batches(Scenario::Time32Second, vec![18506, 18507, 18508, 18509]),
+ make_time32_batches(Scenario::Time32Second, vec![18510, 18511, 18512, 18513]),
+ make_time32_batches(Scenario::Time32Second, vec![18514, 18515, 18516, 18517]),
+ make_time32_batches(Scenario::Time32Second, vec![18518, 18519, 18520, 18521]),
+ ]
+ }
+ Scenario::Time32Millisecond => {
+ vec![
+ make_time32_batches(
+ Scenario::Time32Millisecond,
+ vec![3600000, 3600001, 3600002, 3600003],
+ ),
+ make_time32_batches(
+ Scenario::Time32Millisecond,
+ vec![3600004, 3600005, 3600006, 3600007],
+ ),
+ make_time32_batches(
+ Scenario::Time32Millisecond,
+ vec![3600008, 3600009, 3600010, 3600011],
+ ),
+ make_time32_batches(
+ Scenario::Time32Millisecond,
+ vec![3600012, 3600013, 3600014, 3600015],
+ ),
+ ]
+ }
+ Scenario::Time64Microsecond => {
+ vec![
+ make_time64_batches(
+ Scenario::Time64Microsecond,
+ vec![1234567890123, 1234567890124, 1234567890125, 1234567890126],
+ ),
+ make_time64_batches(
+ Scenario::Time64Microsecond,
+ vec![1234567890127, 1234567890128, 1234567890129, 1234567890130],
+ ),
+ make_time64_batches(
+ Scenario::Time64Microsecond,
+ vec![1234567890131, 1234567890132, 1234567890133, 1234567890134],
+ ),
+ make_time64_batches(
+ Scenario::Time64Microsecond,
+ vec![1234567890135, 1234567890136, 1234567890137, 1234567890138],
+ ),
+ ]
+ }
+ Scenario::Time64Nanosecond => {
+ vec![
+ make_time64_batches(
+ Scenario::Time64Nanosecond,
+ vec![
+ 987654321012345,
+ 987654321012346,
+ 987654321012347,
+ 987654321012348,
+ ],
+ ),
+ make_time64_batches(
+ Scenario::Time64Nanosecond,
+ vec![
+ 987654321012349,
+ 987654321012350,
+ 987654321012351,
+ 987654321012352,
+ ],
+ ),
+ make_time64_batches(
+ Scenario::Time64Nanosecond,
+ vec![
+ 987654321012353,
+ 987654321012354,
+ 987654321012355,
+ 987654321012356,
+ ],
+ ),
+ make_time64_batches(
+ Scenario::Time64Nanosecond,
+ vec![
+ 987654321012357,
+ 987654321012358,
+ 987654321012359,
+ 987654321012360,
+ ],
+ ),
+ ]
+ }
+ Scenario::UTF8 => {
+ vec![
+ make_utf8_batch(vec![Some("a"), Some("b"), Some("c"), Some("d"), None]),
+ make_utf8_batch(vec![Some("e"), Some("f"), Some("g"), Some("h"), Some("i")]),
+ ]
+ }
+ }
+}
+
+/// Create a test parquet file with various data types
+async fn make_test_file_rg(scenario: Scenario, row_per_group: usize) -> NamedTempFile {
+ let mut output_file = tempfile::Builder::new()
+ .prefix("parquet_pruning")
+ .suffix(".parquet")
+ .tempfile()
+ .expect("tempfile creation");
+
+ let props = WriterProperties::builder()
+ .set_max_row_group_size(row_per_group)
+ .set_bloom_filter_enabled(true)
+ .set_statistics_enabled(EnabledStatistics::Page)
+ .build();
+
+ let batches = create_data_batch(scenario);
+ let schema = batches[0].schema();
+
+ let mut writer = ArrowWriter::try_new(&mut output_file, schema, Some(props)).unwrap();
+
+ for batch in batches {
+ writer.write(&batch).expect("writing batch");
+ }
+ writer.close().unwrap();
+
+ output_file
+}
diff --git a/parquet/tests/arrow_reader/statistics.rs b/parquet/tests/arrow_reader/statistics.rs
new file mode 100644
index 000000000000..5702967ffdf4
--- /dev/null
+++ b/parquet/tests/arrow_reader/statistics.rs
@@ -0,0 +1,2143 @@
+// 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.
+
+//! This file contains an end to end test of extracting statistics from parquet files.
+//! It writes data into a parquet file, reads statistics and verifies they are correct
+
+use std::default::Default;
+use std::fs::File;
+use std::sync::Arc;
+
+use super::{struct_array, Scenario};
+use arrow::compute::kernels::cast_utils::Parser;
+use arrow::datatypes::{
+ i256, Date32Type, Date64Type, TimestampMicrosecondType, TimestampMillisecondType,
+ TimestampNanosecondType, TimestampSecondType,
+};
+use arrow_array::{
+ make_array, new_null_array, Array, ArrayRef, BinaryArray, BooleanArray, Date32Array,
+ Date64Array, Decimal128Array, Decimal256Array, FixedSizeBinaryArray, Float16Array,
+ Float32Array, Float64Array, Int16Array, Int32Array, Int64Array, Int8Array, LargeBinaryArray,
+ LargeStringArray, RecordBatch, StringArray, Time32MillisecondArray, Time32SecondArray,
+ Time64MicrosecondArray, Time64NanosecondArray, TimestampMicrosecondArray,
+ TimestampMillisecondArray, TimestampNanosecondArray, TimestampSecondArray, UInt16Array,
+ UInt32Array, UInt64Array, UInt8Array,
+};
+use arrow_schema::{DataType, Field, Schema, TimeUnit};
+use half::f16;
+use parquet::arrow::arrow_reader::statistics::StatisticsConverter;
+use parquet::arrow::arrow_reader::{
+ ArrowReaderBuilder, ArrowReaderOptions, ParquetRecordBatchReaderBuilder,
+};
+use parquet::arrow::ArrowWriter;
+use parquet::file::properties::{EnabledStatistics, WriterProperties};
+
+use super::make_test_file_rg;
+
+#[derive(Debug, Default, Clone)]
+struct Int64Case {
+ /// Number of nulls in the column
+ null_values: usize,
+ /// Non null values in the range `[no_null_values_start,
+ /// no_null_values_end]`, one value for each row
+ no_null_values_start: i64,
+ no_null_values_end: i64,
+ /// Number of rows per row group
+ row_per_group: usize,
+ /// if specified, overrides default statistics settings
+ enable_stats: Option<EnabledStatistics>,
+ /// If specified, the number of values in each page
+ data_page_row_count_limit: Option<usize>,
+}
+
+impl Int64Case {
+ /// Return a record batch with i64 with Null values
+ /// The first no_null_values_end - no_null_values_start values
+ /// are non-null with the specified range, the rest are null
+ fn make_int64_batches_with_null(&self) -> RecordBatch {
+ let schema = Arc::new(Schema::new(vec![Field::new("i64", DataType::Int64, true)]));
+
+ let v64: Vec<i64> =
+ (self.no_null_values_start as _..self.no_null_values_end as _).collect();
+
+ RecordBatch::try_new(
+ schema,
+ vec![make_array(
+ Int64Array::from_iter(
+ v64.into_iter()
+ .map(Some)
+ .chain(std::iter::repeat(None).take(self.null_values)),
+ )
+ .to_data(),
+ )],
+ )
+ .unwrap()
+ }
+
+ // Create a parquet file with the specified settings
+ pub fn build(&self) -> ParquetRecordBatchReaderBuilder<File> {
+ let batches = vec![self.make_int64_batches_with_null()];
+ build_parquet_file(
+ self.row_per_group,
+ self.enable_stats,
+ self.data_page_row_count_limit,
+ batches,
+ )
+ }
+}
+
+fn build_parquet_file(
+ row_per_group: usize,
+ enable_stats: Option<EnabledStatistics>,
+ data_page_row_count_limit: Option<usize>,
+ batches: Vec<RecordBatch>,
+) -> ParquetRecordBatchReaderBuilder<File> {
+ let mut output_file = tempfile::Builder::new()
+ .prefix("parquert_statistics_test")
+ .suffix(".parquet")
+ .tempfile()
+ .expect("tempfile creation");
+
+ let mut builder = WriterProperties::builder().set_max_row_group_size(row_per_group);
+ if let Some(enable_stats) = enable_stats {
+ builder = builder.set_statistics_enabled(enable_stats);
+ }
+ if let Some(data_page_row_count_limit) = data_page_row_count_limit {
+ builder = builder.set_data_page_row_count_limit(data_page_row_count_limit);
+ }
+ let props = builder.build();
+
+ let schema = batches[0].schema();
+
+ let mut writer = ArrowWriter::try_new(&mut output_file, schema, Some(props)).unwrap();
+
+ // if we have a datapage limit send the batches in one at a time to give
+ // the writer a chance to be split into multiple pages
+ if data_page_row_count_limit.is_some() {
+ for batch in &batches {
+ for i in 0..batch.num_rows() {
+ writer.write(&batch.slice(i, 1)).expect("writing batch");
+ }
+ }
+ } else {
+ for batch in &batches {
+ writer.write(batch).expect("writing batch");
+ }
+ }
+
+ let _file_meta = writer.close().unwrap();
+
+ let file = output_file.reopen().unwrap();
+ let options = ArrowReaderOptions::new().with_page_index(true);
+ ArrowReaderBuilder::try_new_with_options(file, options).unwrap()
+}
+
+/// Defines what data to create in a parquet file
+#[derive(Debug, Clone, Copy)]
+struct TestReader {
+ /// What data to create in the parquet file
+ scenario: Scenario,
+ /// Number of rows per row group
+ row_per_group: usize,
+}
+
+impl TestReader {
+ /// Create a parquet file with the specified data, and return a
+ /// ParquetRecordBatchReaderBuilder opened to that file.
+ async fn build(self) -> ParquetRecordBatchReaderBuilder<File> {
+ let TestReader {
+ scenario,
+ row_per_group,
+ } = self;
+ let file = make_test_file_rg(scenario, row_per_group).await;
+
+ // open the file & get the reader
+ let file = file.reopen().unwrap();
+ let options = ArrowReaderOptions::new().with_page_index(true);
+ ArrowReaderBuilder::try_new_with_options(file, options).unwrap()
+ }
+}
+
+/// Which statistics should we check?
+#[derive(Clone, Debug, Copy)]
+enum Check {
+ /// Extract and check row group statistics
+ RowGroup,
+ /// Extract and check data page statistics
+ DataPage,
+ /// Extract and check both row group and data page statistics.
+ ///
+ /// Note if a row group contains a single data page,
+ /// the statistics for row groups and data pages are the same.
+ Both,
+}
+
+impl Check {
+ fn row_group(&self) -> bool {
+ match self {
+ Self::RowGroup | Self::Both => true,
+ Self::DataPage => false,
+ }
+ }
+
+ fn data_page(&self) -> bool {
+ match self {
+ Self::DataPage | Self::Both => true,
+ Self::RowGroup => false,
+ }
+ }
+}
+
+/// Defines a test case for statistics extraction
+struct Test<'a> {
+ /// The parquet file reader
+ reader: &'a ParquetRecordBatchReaderBuilder<File>,
+ expected_min: ArrayRef,
+ expected_max: ArrayRef,
+ expected_null_counts: UInt64Array,
+ expected_row_counts: Option<UInt64Array>,
+ /// Which column to extract statistics from
+ column_name: &'static str,
+ /// What statistics should be checked?
+ check: Check,
+}
+
+impl<'a> Test<'a> {
+ fn run(self) {
+ let converter = StatisticsConverter::try_new(
+ self.column_name,
+ self.reader.schema(),
+ self.reader.parquet_schema(),
+ )
+ .unwrap();
+
+ self.run_checks(converter);
+ }
+
+ fn run_with_schema(self, schema: &Schema) {
+ let converter =
+ StatisticsConverter::try_new(self.column_name, schema, self.reader.parquet_schema())
+ .unwrap();
+
+ self.run_checks(converter);
+ }
+
+ fn run_checks(self, converter: StatisticsConverter) {
+ let Self {
+ reader,
+ expected_min,
+ expected_max,
+ expected_null_counts,
+ expected_row_counts,
+ column_name,
+ check,
+ } = self;
+
+ let row_groups = reader.metadata().row_groups();
+
+ if check.data_page() {
+ let column_page_index = reader
+ .metadata()
+ .column_index()
+ .expect("File should have column page indices");
+
+ let column_offset_index = reader
+ .metadata()
+ .offset_index()
+ .expect("File should have column offset indices");
+
+ let row_group_indices: Vec<_> = (0..row_groups.len()).collect();
+
+ let min = converter
+ .data_page_mins(column_page_index, column_offset_index, &row_group_indices)
+ .unwrap();
+ assert_eq!(
+ &min, &expected_min,
+ "{column_name}: Mismatch with expected data page minimums"
+ );
+
+ let max = converter
+ .data_page_maxes(column_page_index, column_offset_index, &row_group_indices)
+ .unwrap();
+ assert_eq!(
+ &max, &expected_max,
+ "{column_name}: Mismatch with expected data page maximum"
+ );
+
+ let null_counts = converter
+ .data_page_null_counts(column_page_index, column_offset_index, &row_group_indices)
+ .unwrap();
+
+ assert_eq!(
+ &null_counts, &expected_null_counts,
+ "{column_name}: Mismatch with expected data page null counts. \
+ Actual: {null_counts:?}. Expected: {expected_null_counts:?}"
+ );
+
+ let row_counts = converter
+ .data_page_row_counts(column_offset_index, row_groups, &row_group_indices)
+ .unwrap();
+ assert_eq!(
+ row_counts, expected_row_counts,
+ "{column_name}: Mismatch with expected row counts. \
+ Actual: {row_counts:?}. Expected: {expected_row_counts:?}"
+ );
+ }
+
+ if check.row_group() {
+ let min = converter.row_group_mins(row_groups).unwrap();
+ assert_eq!(
+ &min, &expected_min,
+ "{column_name}: Mismatch with expected minimums"
+ );
+
+ let max = converter.row_group_maxes(row_groups).unwrap();
+ assert_eq!(
+ &max, &expected_max,
+ "{column_name}: Mismatch with expected maximum"
+ );
+
+ let null_counts = converter.row_group_null_counts(row_groups).unwrap();
+ assert_eq!(
+ &null_counts, &expected_null_counts,
+ "{column_name}: Mismatch with expected null counts. \
+ Actual: {null_counts:?}. Expected: {expected_null_counts:?}"
+ );
+
+ let row_counts = converter
+ .row_group_row_counts(reader.metadata().row_groups().iter())
+ .unwrap();
+ assert_eq!(
+ row_counts, expected_row_counts,
+ "{column_name}: Mismatch with expected row counts. \
+ Actual: {row_counts:?}. Expected: {expected_row_counts:?}"
+ );
+ }
+ }
+
+ /// Run the test and expect a column not found error
+ fn run_col_not_found(self) {
+ let Self {
+ reader,
+ expected_min: _,
+ expected_max: _,
+ expected_null_counts: _,
+ expected_row_counts: _,
+ column_name,
+ ..
+ } = self;
+
+ let converter =
+ StatisticsConverter::try_new(column_name, reader.schema(), reader.parquet_schema());
+
+ assert!(converter.is_err());
+ }
+}
+
+// TESTS
+//
+// Remaining cases
+// f64::NAN
+// - Using truncated statistics ("exact min value" and "exact max value" https://docs.rs/parquet/latest/parquet/file/statistics/enum.Statistics.html#method.max_is_exact)
+
+#[tokio::test]
+async fn test_one_row_group_without_null() {
+ let reader = Int64Case {
+ null_values: 0,
+ no_null_values_start: 4,
+ no_null_values_end: 7,
+ row_per_group: 20,
+ ..Default::default()
+ }
+ .build();
+
+ Test {
+ reader: &reader,
+ // min is 4
+ expected_min: Arc::new(Int64Array::from(vec![4])),
+ // max is 6
+ expected_max: Arc::new(Int64Array::from(vec![6])),
+ // no nulls
+ expected_null_counts: UInt64Array::from(vec![0]),
+ // 3 rows
+ expected_row_counts: Some(UInt64Array::from(vec![3])),
+ column_name: "i64",
+ check: Check::Both,
+ }
+ .run()
+}
+
+#[tokio::test]
+async fn test_one_row_group_with_null_and_negative() {
+ let reader = Int64Case {
+ null_values: 2,
+ no_null_values_start: -1,
+ no_null_values_end: 5,
+ row_per_group: 20,
+ ..Default::default()
+ }
+ .build();
+
+ Test {
+ reader: &reader,
+ // min is -1
+ expected_min: Arc::new(Int64Array::from(vec![-1])),
+ // max is 4
+ expected_max: Arc::new(Int64Array::from(vec![4])),
+ // 2 nulls
+ expected_null_counts: UInt64Array::from(vec![2]),
+ // 8 rows
+ expected_row_counts: Some(UInt64Array::from(vec![8])),
+ column_name: "i64",
+ check: Check::Both,
+ }
+ .run()
+}
+
+#[tokio::test]
+async fn test_two_row_group_with_null() {
+ let reader = Int64Case {
+ null_values: 2,
+ no_null_values_start: 4,
+ no_null_values_end: 17,
+ row_per_group: 10,
+ ..Default::default()
+ }
+ .build();
+
+ Test {
+ reader: &reader,
+ // mins are [4, 14]
+ expected_min: Arc::new(Int64Array::from(vec![4, 14])),
+ // maxes are [13, 16]
+ expected_max: Arc::new(Int64Array::from(vec![13, 16])),
+ // nulls are [0, 2]
+ expected_null_counts: UInt64Array::from(vec![0, 2]),
+ // row counts are [10, 5]
+ expected_row_counts: Some(UInt64Array::from(vec![10, 5])),
+ column_name: "i64",
+ check: Check::Both,
+ }
+ .run()
+}
+
+#[tokio::test]
+async fn test_two_row_groups_with_all_nulls_in_one() {
+ let reader = Int64Case {
+ null_values: 4,
+ no_null_values_start: -2,
+ no_null_values_end: 2,
+ row_per_group: 5,
+ ..Default::default()
+ }
+ .build();
+
+ Test {
+ reader: &reader,
+ // mins are [-2, null]
+ expected_min: Arc::new(Int64Array::from(vec![Some(-2), None])),
+ // maxes are [1, null]
+ expected_max: Arc::new(Int64Array::from(vec![Some(1), None])),
+ // nulls are [1, 3]
+ expected_null_counts: UInt64Array::from(vec![1, 3]),
+ // row counts are [5, 3]
+ expected_row_counts: Some(UInt64Array::from(vec![5, 3])),
+ column_name: "i64",
+ check: Check::Both,
+ }
+ .run()
+}
+
+#[tokio::test]
+async fn test_multiple_data_pages_nulls_and_negatives() {
+ let reader = Int64Case {
+ null_values: 3,
+ no_null_values_start: -1,
+ no_null_values_end: 10,
+ row_per_group: 20,
+ // limit page row count to 4
+ data_page_row_count_limit: Some(4),
+ enable_stats: Some(EnabledStatistics::Page),
+ }
+ .build();
+
+ // Data layout looks like this:
+ //
+ // page 0: [-1, 0, 1, 2]
+ // page 1: [3, 4, 5, 6]
+ // page 2: [7, 8, 9, null]
+ // page 3: [null, null]
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(Int64Array::from(vec![Some(-1), Some(3), Some(7), None])),
+ expected_max: Arc::new(Int64Array::from(vec![Some(2), Some(6), Some(9), None])),
+ expected_null_counts: UInt64Array::from(vec![0, 0, 1, 2]),
+ expected_row_counts: Some(UInt64Array::from(vec![4, 4, 4, 2])),
+ column_name: "i64",
+ check: Check::DataPage,
+ }
+ .run()
+}
+
+#[tokio::test]
+async fn test_data_page_stats_with_all_null_page() {
+ for data_type in &[
+ DataType::Boolean,
+ DataType::UInt64,
+ DataType::UInt32,
+ DataType::UInt16,
+ DataType::UInt8,
+ DataType::Int64,
+ DataType::Int32,
+ DataType::Int16,
+ DataType::Int8,
+ DataType::Float16,
+ DataType::Float32,
+ DataType::Float64,
+ DataType::Date32,
+ DataType::Date64,
+ DataType::Time32(TimeUnit::Millisecond),
+ DataType::Time32(TimeUnit::Second),
+ DataType::Time64(TimeUnit::Microsecond),
+ DataType::Time64(TimeUnit::Nanosecond),
+ DataType::Timestamp(TimeUnit::Second, None),
+ DataType::Timestamp(TimeUnit::Millisecond, None),
+ DataType::Timestamp(TimeUnit::Microsecond, None),
+ DataType::Timestamp(TimeUnit::Nanosecond, None),
+ DataType::Binary,
+ DataType::LargeBinary,
+ DataType::FixedSizeBinary(3),
+ DataType::Utf8,
+ DataType::LargeUtf8,
+ DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
+ DataType::Decimal128(8, 2), // as INT32
+ DataType::Decimal128(10, 2), // as INT64
+ DataType::Decimal128(20, 2), // as FIXED_LEN_BYTE_ARRAY
+ DataType::Decimal256(8, 2), // as INT32
+ DataType::Decimal256(10, 2), // as INT64
+ DataType::Decimal256(20, 2), // as FIXED_LEN_BYTE_ARRAY
+ ] {
+ let batch = RecordBatch::try_from_iter(vec![("col", new_null_array(data_type, 4))])
+ .expect("record batch creation");
+
+ let reader = build_parquet_file(4, Some(EnabledStatistics::Page), Some(4), vec![batch]);
+
+ let expected_data_type = match data_type {
+ DataType::Dictionary(_, value_type) => value_type.as_ref(),
+ _ => data_type,
+ };
+
+ // There is one data page with 4 nulls
+ // The statistics should be present but null
+ Test {
+ reader: &reader,
+ expected_min: new_null_array(expected_data_type, 1),
+ expected_max: new_null_array(expected_data_type, 1),
+ expected_null_counts: UInt64Array::from(vec![4]),
+ expected_row_counts: Some(UInt64Array::from(vec![4])),
+ column_name: "col",
+ check: Check::DataPage,
+ }
+ .run()
+ }
+}
+
+/////////////// MORE GENERAL TESTS //////////////////////
+// . Many columns in a file
+// . Differnet data types
+// . Different row group sizes
+
+// Four different integer types
+#[tokio::test]
+async fn test_int_64() {
+ // This creates a parquet files of 4 columns named "i8", "i16", "i32", "i64"
+ let reader = TestReader {
+ scenario: Scenario::Int,
+ row_per_group: 5,
+ }
+ .build()
+ .await;
+
+ // since each row has only one data page, the statistics are the same
+ Test {
+ reader: &reader,
+ // mins are [-5, -4, 0, 5]
+ expected_min: Arc::new(Int64Array::from(vec![-5, -4, 0, 5])),
+ // maxes are [-1, 0, 4, 9]
+ expected_max: Arc::new(Int64Array::from(vec![-1, 0, 4, 9])),
+ // nulls are [0, 0, 0, 0]
+ expected_null_counts: UInt64Array::from(vec![0, 0, 0, 0]),
+ // row counts are [5, 5, 5, 5]
+ expected_row_counts: Some(UInt64Array::from(vec![5, 5, 5, 5])),
+ column_name: "i64",
+ check: Check::Both,
+ }
+ .run();
+}
+
+#[tokio::test]
+async fn test_int_32() {
+ // This creates a parquet files of 4 columns named "i8", "i16", "i32", "i64"
+ let reader = TestReader {
+ scenario: Scenario::Int,
+ row_per_group: 5,
+ }
+ .build()
+ .await;
+
+ Test {
+ reader: &reader,
+ // mins are [-5, -4, 0, 5]
+ expected_min: Arc::new(Int32Array::from(vec![-5, -4, 0, 5])),
+ // maxes are [-1, 0, 4, 9]
+ expected_max: Arc::new(Int32Array::from(vec![-1, 0, 4, 9])),
+ // nulls are [0, 0, 0, 0]
+ expected_null_counts: UInt64Array::from(vec![0, 0, 0, 0]),
+ // row counts are [5, 5, 5, 5]
+ expected_row_counts: Some(UInt64Array::from(vec![5, 5, 5, 5])),
+ column_name: "i32",
+ check: Check::Both,
+ }
+ .run();
+}
+
+#[tokio::test]
+async fn test_int_16() {
+ // This creates a parquet files of 4 columns named "i8", "i16", "i32", "i64"
+ let reader = TestReader {
+ scenario: Scenario::Int,
+ row_per_group: 5,
+ }
+ .build()
+ .await;
+
+ Test {
+ reader: &reader,
+ // mins are [-5, -4, 0, 5]
+ expected_min: Arc::new(Int16Array::from(vec![-5, -4, 0, 5])), // panic here because the actual data is Int32Array
+ // maxes are [-1, 0, 4, 9]
+ expected_max: Arc::new(Int16Array::from(vec![-1, 0, 4, 9])),
+ // nulls are [0, 0, 0, 0]
+ expected_null_counts: UInt64Array::from(vec![0, 0, 0, 0]),
+ // row counts are [5, 5, 5, 5]
+ expected_row_counts: Some(UInt64Array::from(vec![5, 5, 5, 5])),
+ column_name: "i16",
+ check: Check::Both,
+ }
+ .run();
+}
+
+#[tokio::test]
+async fn test_int_8() {
+ // This creates a parquet files of 4 columns named "i8", "i16", "i32", "i64"
+ let reader = TestReader {
+ scenario: Scenario::Int,
+ row_per_group: 5,
+ }
+ .build()
+ .await;
+
+ Test {
+ reader: &reader,
+ // mins are [-5, -4, 0, 5]
+ expected_min: Arc::new(Int8Array::from(vec![-5, -4, 0, 5])), // panic here because the actual data is Int32Array
+ // maxes are [-1, 0, 4, 9]
+ expected_max: Arc::new(Int8Array::from(vec![-1, 0, 4, 9])),
+ // nulls are [0, 0, 0, 0]
+ expected_null_counts: UInt64Array::from(vec![0, 0, 0, 0]),
+ // row counts are [5, 5, 5, 5]
+ expected_row_counts: Some(UInt64Array::from(vec![5, 5, 5, 5])),
+ column_name: "i8",
+ check: Check::Both,
+ }
+ .run();
+}
+
+#[tokio::test]
+async fn test_float_16() {
+ // This creates a parquet files of 1 column named f
+ let reader = TestReader {
+ scenario: Scenario::Float16,
+ row_per_group: 5,
+ }
+ .build()
+ .await;
+
+ Test {
+ reader: &reader,
+ // mins are [-5, -4, 0, 5]
+ expected_min: Arc::new(Float16Array::from(vec![
+ f16::from_f32(-5.),
+ f16::from_f32(-4.),
+ f16::from_f32(-0.),
+ f16::from_f32(5.),
+ ])),
+ // maxes are [-1, 0, 4, 9]
+ expected_max: Arc::new(Float16Array::from(vec![
+ f16::from_f32(-1.),
+ f16::from_f32(0.),
+ f16::from_f32(4.),
+ f16::from_f32(9.),
+ ])),
+ // nulls are [0, 0, 0, 0]
+ expected_null_counts: UInt64Array::from(vec![0, 0, 0, 0]),
+ // row counts are [5, 5, 5, 5]
+ expected_row_counts: Some(UInt64Array::from(vec![5, 5, 5, 5])),
+ column_name: "f",
+ check: Check::Both,
+ }
+ .run();
+}
+
+#[tokio::test]
+async fn test_float_32() {
+ // This creates a parquet files of 1 column named f
+ let reader = TestReader {
+ scenario: Scenario::Float32,
+ row_per_group: 5,
+ }
+ .build()
+ .await;
+
+ Test {
+ reader: &reader,
+ // mins are [-5, -4, 0, 5]
+ expected_min: Arc::new(Float32Array::from(vec![-5., -4., -0., 5.0])),
+ // maxes are [-1, 0, 4, 9]
+ expected_max: Arc::new(Float32Array::from(vec![-1., 0., 4., 9.])),
+ // nulls are [0, 0, 0, 0]
+ expected_null_counts: UInt64Array::from(vec![0, 0, 0, 0]),
+ // row counts are [5, 5, 5, 5]
+ expected_row_counts: Some(UInt64Array::from(vec![5, 5, 5, 5])),
+ column_name: "f",
+ check: Check::Both,
+ }
+ .run();
+}
+
+#[tokio::test]
+async fn test_float_64() {
+ // This creates a parquet files of 1 column named f
+ let reader = TestReader {
+ scenario: Scenario::Float64,
+ row_per_group: 5,
+ }
+ .build()
+ .await;
+
+ Test {
+ reader: &reader,
+ // mins are [-5, -4, 0, 5]
+ expected_min: Arc::new(Float64Array::from(vec![-5., -4., -0., 5.0])),
+ // maxes are [-1, 0, 4, 9]
+ expected_max: Arc::new(Float64Array::from(vec![-1., 0., 4., 9.])),
+ // nulls are [0, 0, 0, 0]
+ expected_null_counts: UInt64Array::from(vec![0, 0, 0, 0]),
+ // row counts are [5, 5, 5, 5]
+ expected_row_counts: Some(UInt64Array::from(vec![5, 5, 5, 5])),
+ column_name: "f",
+ check: Check::Both,
+ }
+ .run();
+}
+
+// timestamp
+#[tokio::test]
+async fn test_timestamp() {
+ // This creates a parquet files of 9 columns named "nanos", "nanos_timezoned", "micros", "micros_timezoned", "millis", "millis_timezoned", "seconds", "seconds_timezoned", "names"
+ // "nanos" --> TimestampNanosecondArray
+ // "nanos_timezoned" --> TimestampNanosecondArray
+ // "micros" --> TimestampMicrosecondArray
+ // "micros_timezoned" --> TimestampMicrosecondArray
+ // "millis" --> TimestampMillisecondArray
+ // "millis_timezoned" --> TimestampMillisecondArray
+ // "seconds" --> TimestampSecondArray
+ // "seconds_timezoned" --> TimestampSecondArray
+ // "names" --> StringArray
+ //
+ // The file is created by 4 record batches, each has 5 rows.
+ // Since the row group size is set to 5, those 4 batches will go into 4 row groups
+ // This creates a parquet files of 4 columns named "nanos", "nanos_timezoned", "micros", "micros_timezoned", "millis", "millis_timezoned", "seconds", "seconds_timezoned"
+ let reader = TestReader {
+ scenario: Scenario::Timestamps,
+ row_per_group: 5,
+ }
+ .build()
+ .await;
+
+ let tz = "Pacific/Efate";
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(TimestampNanosecondArray::from(vec![
+ TimestampNanosecondType::parse("2020-01-01T01:01:01"),
+ TimestampNanosecondType::parse("2020-01-01T01:01:11"),
+ TimestampNanosecondType::parse("2020-01-01T01:11:01"),
+ TimestampNanosecondType::parse("2020-01-11T01:01:01"),
+ ])),
+ expected_max: Arc::new(TimestampNanosecondArray::from(vec![
+ TimestampNanosecondType::parse("2020-01-02T01:01:01"),
+ TimestampNanosecondType::parse("2020-01-02T01:01:11"),
+ TimestampNanosecondType::parse("2020-01-02T01:11:01"),
+ TimestampNanosecondType::parse("2020-01-12T01:01:01"),
+ ])),
+ // nulls are [1, 1, 1, 1]
+ expected_null_counts: UInt64Array::from(vec![1, 1, 1, 1]),
+ // row counts are [5, 5, 5, 5]
+ expected_row_counts: Some(UInt64Array::from(vec![5, 5, 5, 5])),
+ column_name: "nanos",
+ check: Check::Both,
+ }
+ .run();
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(
+ TimestampNanosecondArray::from(vec![
+ TimestampNanosecondType::parse("2020-01-01T01:01:01"),
+ TimestampNanosecondType::parse("2020-01-01T01:01:11"),
+ TimestampNanosecondType::parse("2020-01-01T01:11:01"),
+ TimestampNanosecondType::parse("2020-01-11T01:01:01"),
+ ])
+ .with_timezone(tz),
+ ),
+ expected_max: Arc::new(
+ TimestampNanosecondArray::from(vec![
+ TimestampNanosecondType::parse("2020-01-02T01:01:01"),
+ TimestampNanosecondType::parse("2020-01-02T01:01:11"),
+ TimestampNanosecondType::parse("2020-01-02T01:11:01"),
+ TimestampNanosecondType::parse("2020-01-12T01:01:01"),
+ ])
+ .with_timezone(tz),
+ ),
+ // nulls are [1, 1, 1, 1]
+ expected_null_counts: UInt64Array::from(vec![1, 1, 1, 1]),
+ // row counts are [5, 5, 5, 5]
+ expected_row_counts: Some(UInt64Array::from(vec![5, 5, 5, 5])),
+ column_name: "nanos_timezoned",
+ check: Check::Both,
+ }
+ .run();
+
+ // micros
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(TimestampMicrosecondArray::from(vec![
+ TimestampMicrosecondType::parse("2020-01-01T01:01:01"),
+ TimestampMicrosecondType::parse("2020-01-01T01:01:11"),
+ TimestampMicrosecondType::parse("2020-01-01T01:11:01"),
+ TimestampMicrosecondType::parse("2020-01-11T01:01:01"),
+ ])),
+ expected_max: Arc::new(TimestampMicrosecondArray::from(vec![
+ TimestampMicrosecondType::parse("2020-01-02T01:01:01"),
+ TimestampMicrosecondType::parse("2020-01-02T01:01:11"),
+ TimestampMicrosecondType::parse("2020-01-02T01:11:01"),
+ TimestampMicrosecondType::parse("2020-01-12T01:01:01"),
+ ])),
+ expected_null_counts: UInt64Array::from(vec![1, 1, 1, 1]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 5, 5, 5])),
+ column_name: "micros",
+ check: Check::Both,
+ }
+ .run();
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(
+ TimestampMicrosecondArray::from(vec![
+ TimestampMicrosecondType::parse("2020-01-01T01:01:01"),
+ TimestampMicrosecondType::parse("2020-01-01T01:01:11"),
+ TimestampMicrosecondType::parse("2020-01-01T01:11:01"),
+ TimestampMicrosecondType::parse("2020-01-11T01:01:01"),
+ ])
+ .with_timezone(tz),
+ ),
+ expected_max: Arc::new(
+ TimestampMicrosecondArray::from(vec![
+ TimestampMicrosecondType::parse("2020-01-02T01:01:01"),
+ TimestampMicrosecondType::parse("2020-01-02T01:01:11"),
+ TimestampMicrosecondType::parse("2020-01-02T01:11:01"),
+ TimestampMicrosecondType::parse("2020-01-12T01:01:01"),
+ ])
+ .with_timezone(tz),
+ ),
+ // nulls are [1, 1, 1, 1]
+ expected_null_counts: UInt64Array::from(vec![1, 1, 1, 1]),
+ // row counts are [5, 5, 5, 5]
+ expected_row_counts: Some(UInt64Array::from(vec![5, 5, 5, 5])),
+ column_name: "micros_timezoned",
+ check: Check::Both,
+ }
+ .run();
+
+ // millis
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(TimestampMillisecondArray::from(vec![
+ TimestampMillisecondType::parse("2020-01-01T01:01:01"),
+ TimestampMillisecondType::parse("2020-01-01T01:01:11"),
+ TimestampMillisecondType::parse("2020-01-01T01:11:01"),
+ TimestampMillisecondType::parse("2020-01-11T01:01:01"),
+ ])),
+ expected_max: Arc::new(TimestampMillisecondArray::from(vec![
+ TimestampMillisecondType::parse("2020-01-02T01:01:01"),
+ TimestampMillisecondType::parse("2020-01-02T01:01:11"),
+ TimestampMillisecondType::parse("2020-01-02T01:11:01"),
+ TimestampMillisecondType::parse("2020-01-12T01:01:01"),
+ ])),
+ expected_null_counts: UInt64Array::from(vec![1, 1, 1, 1]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 5, 5, 5])),
+ column_name: "millis",
+ check: Check::Both,
+ }
+ .run();
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(
+ TimestampMillisecondArray::from(vec![
+ TimestampMillisecondType::parse("2020-01-01T01:01:01"),
+ TimestampMillisecondType::parse("2020-01-01T01:01:11"),
+ TimestampMillisecondType::parse("2020-01-01T01:11:01"),
+ TimestampMillisecondType::parse("2020-01-11T01:01:01"),
+ ])
+ .with_timezone(tz),
+ ),
+ expected_max: Arc::new(
+ TimestampMillisecondArray::from(vec![
+ TimestampMillisecondType::parse("2020-01-02T01:01:01"),
+ TimestampMillisecondType::parse("2020-01-02T01:01:11"),
+ TimestampMillisecondType::parse("2020-01-02T01:11:01"),
+ TimestampMillisecondType::parse("2020-01-12T01:01:01"),
+ ])
+ .with_timezone(tz),
+ ),
+ // nulls are [1, 1, 1, 1]
+ expected_null_counts: UInt64Array::from(vec![1, 1, 1, 1]),
+ // row counts are [5, 5, 5, 5]
+ expected_row_counts: Some(UInt64Array::from(vec![5, 5, 5, 5])),
+ column_name: "millis_timezoned",
+ check: Check::Both,
+ }
+ .run();
+
+ // seconds
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(TimestampSecondArray::from(vec![
+ TimestampSecondType::parse("2020-01-01T01:01:01"),
+ TimestampSecondType::parse("2020-01-01T01:01:11"),
+ TimestampSecondType::parse("2020-01-01T01:11:01"),
+ TimestampSecondType::parse("2020-01-11T01:01:01"),
+ ])),
+ expected_max: Arc::new(TimestampSecondArray::from(vec![
+ TimestampSecondType::parse("2020-01-02T01:01:01"),
+ TimestampSecondType::parse("2020-01-02T01:01:11"),
+ TimestampSecondType::parse("2020-01-02T01:11:01"),
+ TimestampSecondType::parse("2020-01-12T01:01:01"),
+ ])),
+ expected_null_counts: UInt64Array::from(vec![1, 1, 1, 1]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 5, 5, 5])),
+ column_name: "seconds",
+ check: Check::Both,
+ }
+ .run();
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(
+ TimestampSecondArray::from(vec![
+ TimestampSecondType::parse("2020-01-01T01:01:01"),
+ TimestampSecondType::parse("2020-01-01T01:01:11"),
+ TimestampSecondType::parse("2020-01-01T01:11:01"),
+ TimestampSecondType::parse("2020-01-11T01:01:01"),
+ ])
+ .with_timezone(tz),
+ ),
+ expected_max: Arc::new(
+ TimestampSecondArray::from(vec![
+ TimestampSecondType::parse("2020-01-02T01:01:01"),
+ TimestampSecondType::parse("2020-01-02T01:01:11"),
+ TimestampSecondType::parse("2020-01-02T01:11:01"),
+ TimestampSecondType::parse("2020-01-12T01:01:01"),
+ ])
+ .with_timezone(tz),
+ ),
+ // nulls are [1, 1, 1, 1]
+ expected_null_counts: UInt64Array::from(vec![1, 1, 1, 1]),
+ // row counts are [5, 5, 5, 5]
+ expected_row_counts: Some(UInt64Array::from(vec![5, 5, 5, 5])),
+ column_name: "seconds_timezoned",
+ check: Check::Both,
+ }
+ .run();
+}
+
+// timestamp with different row group sizes
+#[tokio::test]
+async fn test_timestamp_diff_rg_sizes() {
+ // This creates a parquet files of 9 columns named "nanos", "nanos_timezoned", "micros", "micros_timezoned", "millis", "millis_timezoned", "seconds", "seconds_timezoned", "names"
+ // "nanos" --> TimestampNanosecondArray
+ // "nanos_timezoned" --> TimestampNanosecondArray
+ // "micros" --> TimestampMicrosecondArray
+ // "micros_timezoned" --> TimestampMicrosecondArray
+ // "millis" --> TimestampMillisecondArray
+ // "millis_timezoned" --> TimestampMillisecondArray
+ // "seconds" --> TimestampSecondArray
+ // "seconds_timezoned" --> TimestampSecondArray
+ // "names" --> StringArray
+ //
+ // The file is created by 4 record batches (each has a null row), each has 5 rows but then will be split into 3 row groups with size 8, 8, 4
+ let reader = TestReader {
+ scenario: Scenario::Timestamps,
+ row_per_group: 8, // note that the row group size is 8
+ }
+ .build()
+ .await;
+
+ let tz = "Pacific/Efate";
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(TimestampNanosecondArray::from(vec![
+ TimestampNanosecondType::parse("2020-01-01T01:01:01"),
+ TimestampNanosecondType::parse("2020-01-01T01:11:01"),
+ TimestampNanosecondType::parse("2020-01-11T01:02:01"),
+ ])),
+ expected_max: Arc::new(TimestampNanosecondArray::from(vec![
+ TimestampNanosecondType::parse("2020-01-02T01:01:01"),
+ TimestampNanosecondType::parse("2020-01-11T01:01:01"),
+ TimestampNanosecondType::parse("2020-01-12T01:01:01"),
+ ])),
+ // nulls are [1, 2, 1]
+ expected_null_counts: UInt64Array::from(vec![1, 2, 1]),
+ // row counts are [8, 8, 4]
+ expected_row_counts: Some(UInt64Array::from(vec![8, 8, 4])),
+ column_name: "nanos",
+ check: Check::Both,
+ }
+ .run();
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(
+ TimestampNanosecondArray::from(vec![
+ TimestampNanosecondType::parse("2020-01-01T01:01:01"),
+ TimestampNanosecondType::parse("2020-01-01T01:11:01"),
+ TimestampNanosecondType::parse("2020-01-11T01:02:01"),
+ ])
+ .with_timezone(tz),
+ ),
+ expected_max: Arc::new(
+ TimestampNanosecondArray::from(vec![
+ TimestampNanosecondType::parse("2020-01-02T01:01:01"),
+ TimestampNanosecondType::parse("2020-01-11T01:01:01"),
+ TimestampNanosecondType::parse("2020-01-12T01:01:01"),
+ ])
+ .with_timezone(tz),
+ ),
+ // nulls are [1, 2, 1]
+ expected_null_counts: UInt64Array::from(vec![1, 2, 1]),
+ // row counts are [8, 8, 4]
+ expected_row_counts: Some(UInt64Array::from(vec![8, 8, 4])),
+ column_name: "nanos_timezoned",
+ check: Check::Both,
+ }
+ .run();
+
+ // micros
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(TimestampMicrosecondArray::from(vec![
+ TimestampMicrosecondType::parse("2020-01-01T01:01:01"),
+ TimestampMicrosecondType::parse("2020-01-01T01:11:01"),
+ TimestampMicrosecondType::parse("2020-01-11T01:02:01"),
+ ])),
+ expected_max: Arc::new(TimestampMicrosecondArray::from(vec![
+ TimestampMicrosecondType::parse("2020-01-02T01:01:01"),
+ TimestampMicrosecondType::parse("2020-01-11T01:01:01"),
+ TimestampMicrosecondType::parse("2020-01-12T01:01:01"),
+ ])),
+ expected_null_counts: UInt64Array::from(vec![1, 2, 1]),
+ expected_row_counts: Some(UInt64Array::from(vec![8, 8, 4])),
+ column_name: "micros",
+ check: Check::Both,
+ }
+ .run();
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(
+ TimestampMicrosecondArray::from(vec![
+ TimestampMicrosecondType::parse("2020-01-01T01:01:01"),
+ TimestampMicrosecondType::parse("2020-01-01T01:11:01"),
+ TimestampMicrosecondType::parse("2020-01-11T01:02:01"),
+ ])
+ .with_timezone(tz),
+ ),
+ expected_max: Arc::new(
+ TimestampMicrosecondArray::from(vec![
+ TimestampMicrosecondType::parse("2020-01-02T01:01:01"),
+ TimestampMicrosecondType::parse("2020-01-11T01:01:01"),
+ TimestampMicrosecondType::parse("2020-01-12T01:01:01"),
+ ])
+ .with_timezone(tz),
+ ),
+ // nulls are [1, 2, 1]
+ expected_null_counts: UInt64Array::from(vec![1, 2, 1]),
+ // row counts are [8, 8, 4]
+ expected_row_counts: Some(UInt64Array::from(vec![8, 8, 4])),
+ column_name: "micros_timezoned",
+ check: Check::Both,
+ }
+ .run();
+
+ // millis
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(TimestampMillisecondArray::from(vec![
+ TimestampMillisecondType::parse("2020-01-01T01:01:01"),
+ TimestampMillisecondType::parse("2020-01-01T01:11:01"),
+ TimestampMillisecondType::parse("2020-01-11T01:02:01"),
+ ])),
+ expected_max: Arc::new(TimestampMillisecondArray::from(vec![
+ TimestampMillisecondType::parse("2020-01-02T01:01:01"),
+ TimestampMillisecondType::parse("2020-01-11T01:01:01"),
+ TimestampMillisecondType::parse("2020-01-12T01:01:01"),
+ ])),
+ expected_null_counts: UInt64Array::from(vec![1, 2, 1]),
+ expected_row_counts: Some(UInt64Array::from(vec![8, 8, 4])),
+ column_name: "millis",
+ check: Check::Both,
+ }
+ .run();
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(
+ TimestampMillisecondArray::from(vec![
+ TimestampMillisecondType::parse("2020-01-01T01:01:01"),
+ TimestampMillisecondType::parse("2020-01-01T01:11:01"),
+ TimestampMillisecondType::parse("2020-01-11T01:02:01"),
+ ])
+ .with_timezone(tz),
+ ),
+ expected_max: Arc::new(
+ TimestampMillisecondArray::from(vec![
+ TimestampMillisecondType::parse("2020-01-02T01:01:01"),
+ TimestampMillisecondType::parse("2020-01-11T01:01:01"),
+ TimestampMillisecondType::parse("2020-01-12T01:01:01"),
+ ])
+ .with_timezone(tz),
+ ),
+ // nulls are [1, 2, 1]
+ expected_null_counts: UInt64Array::from(vec![1, 2, 1]),
+ // row counts are [8, 8, 4]
+ expected_row_counts: Some(UInt64Array::from(vec![8, 8, 4])),
+ column_name: "millis_timezoned",
+ check: Check::Both,
+ }
+ .run();
+
+ // seconds
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(TimestampSecondArray::from(vec![
+ TimestampSecondType::parse("2020-01-01T01:01:01"),
+ TimestampSecondType::parse("2020-01-01T01:11:01"),
+ TimestampSecondType::parse("2020-01-11T01:02:01"),
+ ])),
+ expected_max: Arc::new(TimestampSecondArray::from(vec![
+ TimestampSecondType::parse("2020-01-02T01:01:01"),
+ TimestampSecondType::parse("2020-01-11T01:01:01"),
+ TimestampSecondType::parse("2020-01-12T01:01:01"),
+ ])),
+ expected_null_counts: UInt64Array::from(vec![1, 2, 1]),
+ expected_row_counts: Some(UInt64Array::from(vec![8, 8, 4])),
+ column_name: "seconds",
+ check: Check::Both,
+ }
+ .run();
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(
+ TimestampSecondArray::from(vec![
+ TimestampSecondType::parse("2020-01-01T01:01:01"),
+ TimestampSecondType::parse("2020-01-01T01:11:01"),
+ TimestampSecondType::parse("2020-01-11T01:02:01"),
+ ])
+ .with_timezone(tz),
+ ),
+ expected_max: Arc::new(
+ TimestampSecondArray::from(vec![
+ TimestampSecondType::parse("2020-01-02T01:01:01"),
+ TimestampSecondType::parse("2020-01-11T01:01:01"),
+ TimestampSecondType::parse("2020-01-12T01:01:01"),
+ ])
+ .with_timezone(tz),
+ ),
+ // nulls are [1, 2, 1]
+ expected_null_counts: UInt64Array::from(vec![1, 2, 1]),
+ // row counts are [8, 8, 4]
+ expected_row_counts: Some(UInt64Array::from(vec![8, 8, 4])),
+ column_name: "seconds_timezoned",
+ check: Check::Both,
+ }
+ .run();
+}
+
+// date with different row group sizes
+#[tokio::test]
+async fn test_dates_32_diff_rg_sizes() {
+ // This creates a parquet files of 3 columns named "date32", "date64", "names"
+ // "date32" --> Date32Array
+ // "date64" --> Date64Array
+ // "names" --> StringArray
+ //
+ // The file is created by 4 record batches (each has a null row), each has 5 rows but then will be split into 2 row groups with size 13, 7
+ let reader = TestReader {
+ scenario: Scenario::Dates,
+ row_per_group: 13,
+ }
+ .build()
+ .await;
+
+ Test {
+ reader: &reader,
+ // mins are [2020-01-01, 2020-10-30]
+ expected_min: Arc::new(Date32Array::from(vec![
+ Date32Type::parse("2020-01-01"),
+ Date32Type::parse("2020-10-30"),
+ ])),
+ // maxes are [2020-10-29, 2029-11-12]
+ expected_max: Arc::new(Date32Array::from(vec![
+ Date32Type::parse("2020-10-29"),
+ Date32Type::parse("2029-11-12"),
+ ])),
+ // nulls are [2, 2]
+ expected_null_counts: UInt64Array::from(vec![2, 2]),
+ // row counts are [13, 7]
+ expected_row_counts: Some(UInt64Array::from(vec![13, 7])),
+ column_name: "date32",
+ check: Check::Both,
+ }
+ .run();
+}
+
+#[tokio::test]
+async fn test_time32_second_diff_rg_sizes() {
+ let reader = TestReader {
+ scenario: Scenario::Time32Second,
+ row_per_group: 4,
+ }
+ .build()
+ .await;
+
+ // Test for Time32Second column
+ Test {
+ reader: &reader,
+ // Assuming specific minimum and maximum values for demonstration
+ expected_min: Arc::new(Time32SecondArray::from(vec![18506, 18510, 18514, 18518])),
+ expected_max: Arc::new(Time32SecondArray::from(vec![18509, 18513, 18517, 18521])),
+ expected_null_counts: UInt64Array::from(vec![0, 0, 0, 0]), // Assuming 1 null per row group for simplicity
+ expected_row_counts: Some(UInt64Array::from(vec![4, 4, 4, 4])),
+ column_name: "second",
+ check: Check::Both,
+ }
+ .run();
+}
+
+#[tokio::test]
+async fn test_time32_millisecond_diff_rg_sizes() {
+ let reader = TestReader {
+ scenario: Scenario::Time32Millisecond,
+ row_per_group: 4,
+ }
+ .build()
+ .await;
+
+ // Test for Time32Millisecond column
+ Test {
+ reader: &reader,
+ // Assuming specific minimum and maximum values for demonstration
+ expected_min: Arc::new(Time32MillisecondArray::from(vec![
+ 3600000, 3600004, 3600008, 3600012,
+ ])),
+ expected_max: Arc::new(Time32MillisecondArray::from(vec![
+ 3600003, 3600007, 3600011, 3600015,
+ ])),
+ expected_null_counts: UInt64Array::from(vec![0, 0, 0, 0]), // Assuming 1 null per row group for simplicity
+ expected_row_counts: Some(UInt64Array::from(vec![4, 4, 4, 4])),
+ column_name: "millisecond",
+ check: Check::Both,
+ }
+ .run();
+}
+
+#[tokio::test]
+async fn test_time64_microsecond_diff_rg_sizes() {
+ let reader = TestReader {
+ scenario: Scenario::Time64Microsecond,
+ row_per_group: 4,
+ }
+ .build()
+ .await;
+
+ // Test for Time64MicroSecond column
+ Test {
+ reader: &reader,
+ // Assuming specific minimum and maximum values for demonstration
+ expected_min: Arc::new(Time64MicrosecondArray::from(vec![
+ 1234567890123,
+ 1234567890127,
+ 1234567890131,
+ 1234567890135,
+ ])),
+ expected_max: Arc::new(Time64MicrosecondArray::from(vec![
+ 1234567890126,
+ 1234567890130,
+ 1234567890134,
+ 1234567890138,
+ ])),
+ expected_null_counts: UInt64Array::from(vec![0, 0, 0, 0]), // Assuming 1 null per row group for simplicity
+ expected_row_counts: Some(UInt64Array::from(vec![4, 4, 4, 4])),
+ column_name: "microsecond",
+ check: Check::Both,
+ }
+ .run();
+}
+
+#[tokio::test]
+async fn test_time64_nanosecond_diff_rg_sizes() {
+ let reader = TestReader {
+ scenario: Scenario::Time64Nanosecond,
+ row_per_group: 4,
+ }
+ .build()
+ .await;
+
+ // Test for Time32Second column
+ Test {
+ reader: &reader,
+ // Assuming specific minimum and maximum values for demonstration
+ expected_min: Arc::new(Time64NanosecondArray::from(vec![
+ 987654321012345,
+ 987654321012349,
+ 987654321012353,
+ 987654321012357,
+ ])),
+ expected_max: Arc::new(Time64NanosecondArray::from(vec![
+ 987654321012348,
+ 987654321012352,
+ 987654321012356,
+ 987654321012360,
+ ])),
+ expected_null_counts: UInt64Array::from(vec![0, 0, 0, 0]), // Assuming 1 null per row group for simplicity
+ expected_row_counts: Some(UInt64Array::from(vec![4, 4, 4, 4])),
+ column_name: "nanosecond",
+ check: Check::Both,
+ }
+ .run();
+}
+
+#[tokio::test]
+async fn test_dates_64_diff_rg_sizes() {
+ // The file is created by 4 record batches (each has a null row), each has 5 rows but then will be split into 2 row groups with size 13, 7
+ let reader = TestReader {
+ scenario: Scenario::Dates,
+ row_per_group: 13,
+ }
+ .build()
+ .await;
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(Date64Array::from(vec![
+ Date64Type::parse("2020-01-01"),
+ Date64Type::parse("2020-10-30"),
+ ])),
+ expected_max: Arc::new(Date64Array::from(vec![
+ Date64Type::parse("2020-10-29"),
+ Date64Type::parse("2029-11-12"),
+ ])),
+ expected_null_counts: UInt64Array::from(vec![2, 2]),
+ expected_row_counts: Some(UInt64Array::from(vec![13, 7])),
+ column_name: "date64",
+ check: Check::Both,
+ }
+ .run();
+}
+
+#[tokio::test]
+async fn test_uint() {
+ // This creates a parquet files of 4 columns named "u8", "u16", "u32", "u64"
+ // "u8" --> UInt8Array
+ // "u16" --> UInt16Array
+ // "u32" --> UInt32Array
+ // "u64" --> UInt64Array
+
+ // The file is created by 4 record batches (each has a null row), each has 5 rows but then will be split into 5 row groups with size 4
+ let reader = TestReader {
+ scenario: Scenario::UInt,
+ row_per_group: 4,
+ }
+ .build()
+ .await;
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(UInt8Array::from(vec![0, 1, 4, 7, 251])),
+ expected_max: Arc::new(UInt8Array::from(vec![3, 4, 6, 250, 254])),
+ expected_null_counts: UInt64Array::from(vec![0, 0, 0, 0, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![4, 4, 4, 4, 4])),
+ column_name: "u8",
+ check: Check::Both,
+ }
+ .run();
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(UInt16Array::from(vec![0, 1, 4, 7, 251])),
+ expected_max: Arc::new(UInt16Array::from(vec![3, 4, 6, 250, 254])),
+ expected_null_counts: UInt64Array::from(vec![0, 0, 0, 0, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![4, 4, 4, 4, 4])),
+ column_name: "u16",
+ check: Check::Both,
+ }
+ .run();
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(UInt32Array::from(vec![0, 1, 4, 7, 251])),
+ expected_max: Arc::new(UInt32Array::from(vec![3, 4, 6, 250, 254])),
+ expected_null_counts: UInt64Array::from(vec![0, 0, 0, 0, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![4, 4, 4, 4, 4])),
+ column_name: "u32",
+ check: Check::Both,
+ }
+ .run();
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(UInt64Array::from(vec![0, 1, 4, 7, 251])),
+ expected_max: Arc::new(UInt64Array::from(vec![3, 4, 6, 250, 254])),
+ expected_null_counts: UInt64Array::from(vec![0, 0, 0, 0, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![4, 4, 4, 4, 4])),
+ column_name: "u64",
+ check: Check::Both,
+ }
+ .run();
+}
+
+#[tokio::test]
+async fn test_int32_range() {
+ // This creates a parquet file of 1 column "i"
+ // file has 2 record batches, each has 2 rows. They will be saved into one row group
+ let reader = TestReader {
+ scenario: Scenario::Int32Range,
+ row_per_group: 5,
+ }
+ .build()
+ .await;
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(Int32Array::from(vec![0])),
+ expected_max: Arc::new(Int32Array::from(vec![300000])),
+ expected_null_counts: UInt64Array::from(vec![0]),
+ expected_row_counts: Some(UInt64Array::from(vec![4])),
+ column_name: "i",
+ check: Check::Both,
+ }
+ .run();
+}
+
+#[tokio::test]
+async fn test_uint32_range() {
+ // This creates a parquet file of 1 column "u"
+ // file has 2 record batches, each has 2 rows. They will be saved into one row group
+ let reader = TestReader {
+ scenario: Scenario::UInt32Range,
+ row_per_group: 5,
+ }
+ .build()
+ .await;
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(UInt32Array::from(vec![0])),
+ expected_max: Arc::new(UInt32Array::from(vec![300000])),
+ expected_null_counts: UInt64Array::from(vec![0]),
+ expected_row_counts: Some(UInt64Array::from(vec![4])),
+ column_name: "u",
+ check: Check::Both,
+ }
+ .run();
+}
+
+#[tokio::test]
+async fn test_numeric_limits_unsigned() {
+ // file has 7 rows, 2 row groups: one with 5 rows, one with 2 rows.
+ let reader = TestReader {
+ scenario: Scenario::NumericLimits,
+ row_per_group: 5,
+ }
+ .build()
+ .await;
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(UInt8Array::from(vec![u8::MIN, 100])),
+ expected_max: Arc::new(UInt8Array::from(vec![100, u8::MAX])),
+ expected_null_counts: UInt64Array::from(vec![0, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 2])),
+ column_name: "u8",
+ check: Check::Both,
+ }
+ .run();
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(UInt16Array::from(vec![u16::MIN, 100])),
+ expected_max: Arc::new(UInt16Array::from(vec![100, u16::MAX])),
+ expected_null_counts: UInt64Array::from(vec![0, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 2])),
+ column_name: "u16",
+ check: Check::Both,
+ }
+ .run();
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(UInt32Array::from(vec![u32::MIN, 100])),
+ expected_max: Arc::new(UInt32Array::from(vec![100, u32::MAX])),
+ expected_null_counts: UInt64Array::from(vec![0, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 2])),
+ column_name: "u32",
+ check: Check::Both,
+ }
+ .run();
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(UInt64Array::from(vec![u64::MIN, 100])),
+ expected_max: Arc::new(UInt64Array::from(vec![100, u64::MAX])),
+ expected_null_counts: UInt64Array::from(vec![0, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 2])),
+ column_name: "u64",
+ check: Check::Both,
+ }
+ .run();
+}
+
+#[tokio::test]
+async fn test_numeric_limits_signed() {
+ // file has 7 rows, 2 row groups: one with 5 rows, one with 2 rows.
+ let reader = TestReader {
+ scenario: Scenario::NumericLimits,
+ row_per_group: 5,
+ }
+ .build()
+ .await;
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(Int8Array::from(vec![i8::MIN, -100])),
+ expected_max: Arc::new(Int8Array::from(vec![100, i8::MAX])),
+ expected_null_counts: UInt64Array::from(vec![0, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 2])),
+ column_name: "i8",
+ check: Check::Both,
+ }
+ .run();
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(Int16Array::from(vec![i16::MIN, -100])),
+ expected_max: Arc::new(Int16Array::from(vec![100, i16::MAX])),
+ expected_null_counts: UInt64Array::from(vec![0, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 2])),
+ column_name: "i16",
+ check: Check::Both,
+ }
+ .run();
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(Int32Array::from(vec![i32::MIN, -100])),
+ expected_max: Arc::new(Int32Array::from(vec![100, i32::MAX])),
+ expected_null_counts: UInt64Array::from(vec![0, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 2])),
+ column_name: "i32",
+ check: Check::Both,
+ }
+ .run();
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(Int64Array::from(vec![i64::MIN, -100])),
+ expected_max: Arc::new(Int64Array::from(vec![100, i64::MAX])),
+ expected_null_counts: UInt64Array::from(vec![0, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 2])),
+ column_name: "i64",
+ check: Check::Both,
+ }
+ .run();
+}
+
+#[tokio::test]
+async fn test_numeric_limits_float() {
+ // file has 7 rows, 2 row groups: one with 5 rows, one with 2 rows.
+ let reader = TestReader {
+ scenario: Scenario::NumericLimits,
+ row_per_group: 5,
+ }
+ .build()
+ .await;
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(Float32Array::from(vec![f32::MIN, -100.0])),
+ expected_max: Arc::new(Float32Array::from(vec![100.0, f32::MAX])),
+ expected_null_counts: UInt64Array::from(vec![0, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 2])),
+ column_name: "f32",
+ check: Check::Both,
+ }
+ .run();
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(Float64Array::from(vec![f64::MIN, -100.0])),
+ expected_max: Arc::new(Float64Array::from(vec![100.0, f64::MAX])),
+ expected_null_counts: UInt64Array::from(vec![0, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 2])),
+ column_name: "f64",
+ check: Check::Both,
+ }
+ .run();
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(Float32Array::from(vec![-1.0, -100.0])),
+ expected_max: Arc::new(Float32Array::from(vec![100.0, -100.0])),
+ expected_null_counts: UInt64Array::from(vec![0, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 2])),
+ column_name: "f32_nan",
+ check: Check::Both,
+ }
+ .run();
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(Float64Array::from(vec![-1.0, -100.0])),
+ expected_max: Arc::new(Float64Array::from(vec![100.0, -100.0])),
+ expected_null_counts: UInt64Array::from(vec![0, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 2])),
+ column_name: "f64_nan",
+ check: Check::Both,
+ }
+ .run();
+}
+
+#[tokio::test]
+async fn test_float64() {
+ // This creates a parquet file of 1 column "f"
+ // file has 4 record batches, each has 5 rows. They will be saved into 4 row groups
+ let reader = TestReader {
+ scenario: Scenario::Float64,
+ row_per_group: 5,
+ }
+ .build()
+ .await;
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(Float64Array::from(vec![-5.0, -4.0, -0.0, 5.0])),
+ expected_max: Arc::new(Float64Array::from(vec![-1.0, 0.0, 4.0, 9.0])),
+ expected_null_counts: UInt64Array::from(vec![0, 0, 0, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 5, 5, 5])),
+ column_name: "f",
+ check: Check::Both,
+ }
+ .run();
+}
+
+#[tokio::test]
+async fn test_float16() {
+ // This creates a parquet file of 1 column "f"
+ // file has 4 record batches, each has 5 rows. They will be saved into 4 row groups
+ let reader = TestReader {
+ scenario: Scenario::Float16,
+ row_per_group: 5,
+ }
+ .build()
+ .await;
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(Float16Array::from(
+ vec![-5.0, -4.0, -0.0, 5.0]
+ .into_iter()
+ .map(f16::from_f32)
+ .collect::<Vec<_>>(),
+ )),
+ expected_max: Arc::new(Float16Array::from(
+ vec![-1.0, 0.0, 4.0, 9.0]
+ .into_iter()
+ .map(f16::from_f32)
+ .collect::<Vec<_>>(),
+ )),
+ expected_null_counts: UInt64Array::from(vec![0, 0, 0, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 5, 5, 5])),
+ column_name: "f",
+ check: Check::Both,
+ }
+ .run();
+}
+
+#[tokio::test]
+async fn test_decimal() {
+ // This creates a parquet file of 1 column "decimal_col" with decimal data type and precicion 9, scale 2
+ // file has 3 record batches, each has 5 rows. They will be saved into 3 row groups
+ let reader = TestReader {
+ scenario: Scenario::Decimal,
+ row_per_group: 5,
+ }
+ .build()
+ .await;
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(
+ Decimal128Array::from(vec![100, -500, 2000])
+ .with_precision_and_scale(9, 2)
+ .unwrap(),
+ ),
+ expected_max: Arc::new(
+ Decimal128Array::from(vec![600, 600, 6000])
+ .with_precision_and_scale(9, 2)
+ .unwrap(),
+ ),
+ expected_null_counts: UInt64Array::from(vec![0, 0, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 5, 5])),
+ column_name: "decimal_col",
+ check: Check::Both,
+ }
+ .run();
+}
+#[tokio::test]
+async fn test_decimal_256() {
+ // This creates a parquet file of 1 column "decimal256_col" with decimal data type and precicion 9, scale 2
+ // file has 3 record batches, each has 5 rows. They will be saved into 3 row groups
+ let reader = TestReader {
+ scenario: Scenario::Decimal256,
+ row_per_group: 5,
+ }
+ .build()
+ .await;
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(
+ Decimal256Array::from(vec![i256::from(100), i256::from(-500), i256::from(2000)])
+ .with_precision_and_scale(9, 2)
+ .unwrap(),
+ ),
+ expected_max: Arc::new(
+ Decimal256Array::from(vec![i256::from(600), i256::from(600), i256::from(6000)])
+ .with_precision_and_scale(9, 2)
+ .unwrap(),
+ ),
+ expected_null_counts: UInt64Array::from(vec![0, 0, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 5, 5])),
+ column_name: "decimal256_col",
+ check: Check::Both,
+ }
+ .run();
+}
+#[tokio::test]
+async fn test_dictionary() {
+ let reader = TestReader {
+ scenario: Scenario::Dictionary,
+ row_per_group: 5,
+ }
+ .build()
+ .await;
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(StringArray::from(vec!["abc", "aaa"])),
+ expected_max: Arc::new(StringArray::from(vec!["def", "fffff"])),
+ expected_null_counts: UInt64Array::from(vec![1, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 2])),
+ column_name: "string_dict_i8",
+ check: Check::Both,
+ }
+ .run();
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(StringArray::from(vec!["abc", "aaa"])),
+ expected_max: Arc::new(StringArray::from(vec!["def", "fffff"])),
+ expected_null_counts: UInt64Array::from(vec![1, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 2])),
+ column_name: "string_dict_i32",
+ check: Check::Both,
+ }
+ .run();
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(Int64Array::from(vec![-100, 0])),
+ expected_max: Arc::new(Int64Array::from(vec![0, 100])),
+ expected_null_counts: UInt64Array::from(vec![1, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 2])),
+ column_name: "int_dict_i8",
+ check: Check::Both,
+ }
+ .run();
+}
+
+#[tokio::test]
+async fn test_byte() {
+ // This creates a parquet file of 5 columns
+ // "name"
+ // "service_string"
+ // "service_binary"
+ // "service_fixedsize"
+ // "service_large_binary"
+
+ // file has 3 record batches, each has 5 rows. They will be saved into 3 row groups
+ let reader = TestReader {
+ scenario: Scenario::ByteArray,
+ row_per_group: 5,
+ }
+ .build()
+ .await;
+
+ // column "name"
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(StringArray::from(vec![
+ "all frontends",
+ "mixed",
+ "all backends",
+ ])),
+ expected_max: Arc::new(StringArray::from(vec![
+ "all frontends",
+ "mixed",
+ "all backends",
+ ])),
+ expected_null_counts: UInt64Array::from(vec![0, 0, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 5, 5])),
+ column_name: "name",
+ check: Check::Both,
+ }
+ .run();
+
+ // column "service_string"
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(StringArray::from(vec![
+ "frontend five",
+ "backend one",
+ "backend eight",
+ ])),
+ expected_max: Arc::new(StringArray::from(vec![
+ "frontend two",
+ "frontend six",
+ "backend six",
+ ])),
+ expected_null_counts: UInt64Array::from(vec![0, 0, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 5, 5])),
+ column_name: "service_string",
+ check: Check::Both,
+ }
+ .run();
+
+ // column "service_binary"
+
+ let expected_service_binary_min_values: Vec<&[u8]> =
+ vec![b"frontend five", b"backend one", b"backend eight"];
+
+ let expected_service_binary_max_values: Vec<&[u8]> =
+ vec![b"frontend two", b"frontend six", b"backend six"];
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(BinaryArray::from(expected_service_binary_min_values)),
+ expected_max: Arc::new(BinaryArray::from(expected_service_binary_max_values)),
+ expected_null_counts: UInt64Array::from(vec![0, 0, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 5, 5])),
+ column_name: "service_binary",
+ check: Check::Both,
+ }
+ .run();
+
+ // column "service_fixedsize"
+ // b"fe1", b"be1", b"be4"
+ let min_input = vec![vec![102, 101, 49], vec![98, 101, 49], vec![98, 101, 52]];
+ // b"fe5", b"fe6", b"be8"
+ let max_input = vec![vec![102, 101, 55], vec![102, 101, 54], vec![98, 101, 56]];
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(FixedSizeBinaryArray::try_from_iter(min_input.into_iter()).unwrap()),
+ expected_max: Arc::new(FixedSizeBinaryArray::try_from_iter(max_input.into_iter()).unwrap()),
+ expected_null_counts: UInt64Array::from(vec![0, 0, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 5, 5])),
+ column_name: "service_fixedsize",
+ check: Check::Both,
+ }
+ .run();
+
+ let expected_service_large_binary_min_values: Vec<&[u8]> =
+ vec![b"frontend five", b"backend one", b"backend eight"];
+
+ let expected_service_large_binary_max_values: Vec<&[u8]> =
+ vec![b"frontend two", b"frontend six", b"backend six"];
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(LargeBinaryArray::from(
+ expected_service_large_binary_min_values,
+ )),
+ expected_max: Arc::new(LargeBinaryArray::from(
+ expected_service_large_binary_max_values,
+ )),
+ expected_null_counts: UInt64Array::from(vec![0, 0, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 5, 5])),
+ column_name: "service_large_binary",
+ check: Check::Both,
+ }
+ .run();
+}
+
+// PeriodsInColumnNames
+#[tokio::test]
+async fn test_period_in_column_names() {
+ // This creates a parquet file of 2 columns "name" and "service.name"
+ // file has 3 record batches, each has 5 rows. They will be saved into 3 row groups
+ let reader = TestReader {
+ scenario: Scenario::PeriodsInColumnNames,
+ row_per_group: 5,
+ }
+ .build()
+ .await;
+
+ // column "name"
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(StringArray::from(vec![
+ "HTTP GET / DISPATCH",
+ "HTTP PUT / DISPATCH",
+ "HTTP GET / DISPATCH",
+ ])),
+ expected_max: Arc::new(StringArray::from(vec![
+ "HTTP GET / DISPATCH",
+ "HTTP PUT / DISPATCH",
+ "HTTP GET / DISPATCH",
+ ])),
+ expected_null_counts: UInt64Array::from(vec![0, 0, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 5, 5])),
+ column_name: "name",
+ check: Check::Both,
+ }
+ .run();
+
+ // column "service.name"
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(StringArray::from(vec!["frontend", "backend", "backend"])),
+ expected_max: Arc::new(StringArray::from(vec!["frontend", "frontend", "backend"])),
+ expected_null_counts: UInt64Array::from(vec![0, 0, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 5, 5])),
+ column_name: "service.name",
+ check: Check::Both,
+ }
+ .run();
+}
+
+// Boolean
+#[tokio::test]
+async fn test_boolean() {
+ // This creates a parquet files of 1 column named "bool"
+ // The file is created by 2 record batches each has 5 rows --> 2 row groups
+ let reader = TestReader {
+ scenario: Scenario::Boolean,
+ row_per_group: 5,
+ }
+ .build()
+ .await;
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(BooleanArray::from(vec![false, false])),
+ expected_max: Arc::new(BooleanArray::from(vec![true, false])),
+ expected_null_counts: UInt64Array::from(vec![1, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 5])),
+ column_name: "bool",
+ check: Check::Both,
+ }
+ .run();
+}
+
+// struct array
+// BUG
+// https://github.com/apache/datafusion/issues/10609
+// Note that: since I have not worked on struct array before, there may be a bug in the test code rather than the real bug in the code
+#[ignore]
+#[tokio::test]
+async fn test_struct() {
+ // This creates a parquet files of 1 column named "struct"
+ // The file is created by 1 record batch with 3 rows in the struct array
+ let reader = TestReader {
+ scenario: Scenario::StructArray,
+ row_per_group: 5,
+ }
+ .build()
+ .await;
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(struct_array(vec![(Some(1), Some(6.0), Some(12.0))])),
+ expected_max: Arc::new(struct_array(vec![(Some(2), Some(8.5), Some(14.0))])),
+ expected_null_counts: UInt64Array::from(vec![0]),
+ expected_row_counts: Some(UInt64Array::from(vec![3])),
+ column_name: "struct",
+ check: Check::RowGroup,
+ }
+ .run();
+}
+
+// UTF8
+#[tokio::test]
+async fn test_utf8() {
+ let reader = TestReader {
+ scenario: Scenario::UTF8,
+ row_per_group: 5,
+ }
+ .build()
+ .await;
+
+ // test for utf8
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(StringArray::from(vec!["a", "e"])),
+ expected_max: Arc::new(StringArray::from(vec!["d", "i"])),
+ expected_null_counts: UInt64Array::from(vec![1, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 5])),
+ column_name: "utf8",
+ check: Check::Both,
+ }
+ .run();
+
+ // test for large_utf8
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(LargeStringArray::from(vec!["a", "e"])),
+ expected_max: Arc::new(LargeStringArray::from(vec!["d", "i"])),
+ expected_null_counts: UInt64Array::from(vec![1, 0]),
+ expected_row_counts: Some(UInt64Array::from(vec![5, 5])),
+ column_name: "large_utf8",
+ check: Check::Both,
+ }
+ .run();
+}
+
+////// Files with missing statistics ///////
+
+#[tokio::test]
+async fn test_missing_statistics() {
+ let reader = Int64Case {
+ null_values: 0,
+ no_null_values_start: 4,
+ no_null_values_end: 7,
+ row_per_group: 5,
+ enable_stats: Some(EnabledStatistics::None),
+ ..Default::default()
+ }
+ .build();
+
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(Int64Array::from(vec![None])),
+ expected_max: Arc::new(Int64Array::from(vec![None])),
+ expected_null_counts: UInt64Array::from(vec![None]),
+ expected_row_counts: Some(UInt64Array::from(vec![3])), // still has row count statistics
+ column_name: "i64",
+ check: Check::Both,
+ }
+ .run();
+}
+
+/////// NEGATIVE TESTS ///////
+// column not found
+#[tokio::test]
+async fn test_column_not_found() {
+ let reader = TestReader {
+ scenario: Scenario::Dates,
+ row_per_group: 5,
+ }
+ .build()
+ .await;
+ Test {
+ reader: &reader,
+ expected_min: Arc::new(Int64Array::from(vec![18262, 18565])),
+ expected_max: Arc::new(Int64Array::from(vec![18564, 21865])),
+ expected_null_counts: UInt64Array::from(vec![2, 2]),
+ expected_row_counts: Some(UInt64Array::from(vec![13, 7])),
+ column_name: "not_a_column",
+ check: Check::Both,
+ }
+ .run_col_not_found();
+}
+
+#[tokio::test]
+async fn test_column_non_existent() {
+ // Create a schema with an additional column
+ // that will not have a matching parquet index
+ let schema = Arc::new(Schema::new(vec![
+ Field::new("i8", DataType::Int8, true),
+ Field::new("i16", DataType::Int16, true),
+ Field::new("i32", DataType::Int32, true),
+ Field::new("i64", DataType::Int64, true),
+ Field::new("i_do_not_exist", DataType::Int64, true),
+ ]));
+
+ let reader = TestReader {
+ scenario: Scenario::Int,
+ row_per_group: 5,
+ }
+ .build()
+ .await;
+
+ Test {
+ reader: &reader,
+ // mins are [-5, -4, 0, 5]
+ expected_min: Arc::new(Int64Array::from(vec![None, None, None, None])),
+ // maxes are [-1, 0, 4, 9]
+ expected_max: Arc::new(Int64Array::from(vec![None, None, None, None])),
+ // nulls are [0, 0, 0, 0]
+ expected_null_counts: UInt64Array::from(vec![None, None, None, None]),
+ // row counts are [5, 5, 5, 5]
+ expected_row_counts: None,
+ column_name: "i_do_not_exist",
+ check: Check::Both,
+ }
+ .run_with_schema(&schema);
+}
|
Add function that converts from parquet statistics `ParquetStatistics` to arrow arrays `ArrayRef`
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
<!--
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
(This section helps Arrow developers understand the context and *why* for this feature, in addition to the *what*)
-->
**Describe the solution you'd like**
<!--
A clear and concise description of what you want to happen.
-->
Add util function to convert from `ParquetStatistics` to `ArrayRef`
**Describe alternatives you've considered**
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
arrow-datafusion has a util trait `PruningStatistics` that converts `RowGroupPruningStatistics` into `ArrayRef` used to prune the blocks.
~https://github.com/apache/arrow-datafusion/blob/main/datafusion/core/src/physical_plan/file_format/parquet/row_groups.rs#L229~
https://github.com/apache/arrow-datafusion/blob/b8f90fe9366a7406afbf5bb3f3afe5854adcf26a/datafusion/core/src/datasource/physical_plan/parquet/row_groups.rs#L103-L228
But the util function like `get_min_max_values` will convert the `statistics`into datafusion's `ScalarValue` and convert it back into `ArrayRef` which seems very redundant because it could be done without datafusion.
So I suggest that arrow-rs could support this trait like [arrow2 did](https://github.com/jorgecarleitao/arrow2/blob/main/src/io/parquet/read/statistics/mod.rs#LL445C1-L445C1)
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
|
This would also help us in IOx (see https://github.com/influxdata/influxdb_iox/issues/7470, per @crepererum )
It would also be aweome to get a similar treatment for Data pages (the so called "page index" values)
Maybe we could add something to the `parquet` with the `arrow` featre: https://docs.rs/parquet/41.0.0/parquet/arrow/index.html
That could read the parquet statistics as an ArrayRef
@tustvold notes that the translation from parquet data model to arrow data model is quite tricky -- and he may have time to do this in a week or two
Note we have started refactoring the code in DataFusion into a format that could reasonable be ported upstream (see https://github.com/apache/arrow-datafusion/pull/8294)
@sundy-li I wonder if there is code that handles this feature? I didn't see any obvious PRs
https://github.com/apache/arrow-rs/pulls?q=is%3Apr+statistics+is%3Aclosed
(I still harbor goals of getting this feature into arrow-rs)
Just wondering if there's anything left to do to address this issue please? If so, I'm happy to pick this up if that's ok.
> Just wondering if there's anything left to do to address this issue please? If so, I'm happy to pick this up if that's ok.
That would be amazing -- thank you very much @opensourcegeek
What I think would be idea is an an API in `parquet::arrow` that looks like this:
```rust
/// statistics extracted from `Statistics` as Arrow `ArrayRef`s
///
/// # Note:
/// If the corresponding `Statistics` is not present, or has no information for
/// a column, a NULL is present in the corresponding array entry
pub struct ArrowStatistics {
/// min values
min: ArrayRef,
/// max values
max: ArrayRef,
/// Row counts (UInt64Array)
row_count: ArrayRef,
/// Null Counts (UInt64Array)
null_count: ArrayRef,
}
// (TODO accessors for min/max/row_count/null_count)
/// Extract `ArrowStatistics` from the parquet [`Statistics`]
pub fn parquet_stats_to_arrow(
arrow_datatype: &DataType,
statistics: impl IntoIterator<Item = Option<&Statistics>>
) -> Result<ArrowStatisics> {
todo!()
}
```
(This is similar to the existing API [parquet](https://docs.rs/parquet/latest/parquet/index.html)::[arrow](https://docs.rs/parquet/latest/parquet/arrow/index.html)::[parquet_to_arrow_schema](https://docs.rs/parquet/latest/parquet/arrow/fn.parquet_to_arrow_schema.html#))
Note it is this [`Statistics`](https://docs.rs/parquet/latest/parquet/file/statistics/enum.Statistics.html)
There is a version of this code here in DataFusion that could perhaps be` adapted: https://github.com/apache/datafusion/blob/accce9732e26723cab2ffc521edbf5a3fe7460b3/datafusion/core/src/datasource/physical_plan/parquet/statistics.rs#L179-L186
## Testing
I suggest you add a new top level test binary in https://github.com/apache/arrow-rs/tree/master/parquet/tests called `statistics.rs`
The tests should look like:
```
let record_batch = make_batch_with_relevant_datatype();
// write batch/batches to file
// open file / extract stats from metadata
// compare stats
```
I can help writing these tests
I personally suggest:
1. Make a PR with the basic API and a few basic types (like Int/UInt and maybe String) and figure out the test pattern (I can definitely help here)
2. Then we can fill out support for the rest of the types in a follow on PR
cc @tustvold in case you have other ideas
Thanks @alamb - I'll take a stab tomorrow and see how I get on. I'm new to Parquet so please bear with me.
I had a chance to go through the code on a high level, thanks @alamb for the pointers, it helped me to get started. What will call this new function please? Just trying to understand the whole flow if that's ok. Thanks
> I had a chance to go through the code on a high level, thanks @alamb for the pointers, it helped me to get started. What will call this new function please? Just trying to understand the whole flow if that's ok. Thanks
The major usecase I have initially is to implement the [PruningStatistics API](https://docs.rs/datafusion/latest/datafusion/physical_optimizer/pruning/trait.PruningStatistics.html) in DataFusion which supports pruning(skipping) Row Groups based on a range anaylsis of min/max values, documented [here](https://docs.rs/datafusion/latest/datafusion/physical_optimizer/pruning/struct.PruningPredicate.html#introduction)
So for example, given a filter in a query such as `a = 5`, DataFusion would use the min and max values of `a` in each row group to determine if there were any rows in that row group that could match
Does that make sense?
That makes sense - thanks @alamb
```rust
pub fn parquet_stats_to_arrow(
arrow_datatype: &DataType,
statistics: impl IntoIterator<Item = Option<&Statistics>>
) -> Result<ArrowStatisics> {
todo!()
}
```
To implement the above function, I'm just trying to suss out the details now. Below are the questions (probably very basic - apologies) using your `a = 5` example,
- `arrow_datatype`, this will be `a`s arrow data type => Int64 or the likes?
- `impl IntoIterator<Item = Option<&Statistics>>`, will this be Parquet Statistics of all columns in 'current' row group? So I'd have to fish out `a`? Not sure if I've interpreted correctly, to be able to fish statistics out for `a` I'd need to know I'm fishing out for `a`. So I'm wondering if it is already Parquet Statistics for `a` only, if that's the case why it's `impl IntoIterator` and not just `Option<&Statistics>`?
- `Result<ArrowStatistics>`, once I get a handle on `a`'s Parquet [statistic](https://docs.rs/parquet/latest/parquet/file/statistics/enum.Statistics.html), I think I'd need to convert each of the [ValueStatistic](https://docs.rs/parquet/latest/parquet/file/statistics/struct.ValueStatistics.html) to [ArrayRef](https://docs.rs/arrow/latest/arrow/array/type.ArrayRef.html) based on `a`'s type? I couldn't find `row_count()` in `ValueStatistics` though.
Sorry, just trying to get an understanding of all the moving parts.
> arrow_datatype, this will be as arrow data type => Int64 or the likes?
I was thinking https://docs.rs/arrow/latest/arrow/datatypes/enum.DataType.html
> impl IntoIterator<Item = Option<&Statistics>>, will this be Parquet Statistics of all columns in 'current' row group
I think it would be [Statistics](https://docs.rs/parquet/latest/parquet/file/statistics/enum.Statistics.html), where each [Statistics](https://docs.rs/parquet/latest/parquet/file/statistics/enum.Statistics.html) represents the values for a single row group.
> if that's the case why it's impl IntoIterator and not just Option<&Statistics>?
The idea is to be able to create (efficiently) statistics for multiple row groups at a time -- since each arrow Array has significant overhead, they only make sense when they store multiple values
> Sorry, just trying to get an understanding of all the moving parts.
Yeah, I agree this is a complex issue....
Thanks @alamb - I'll take a closer look tonight
I think I get the context now, after going through the `RowGroupPruningStatistics` code in datafusion (relevant code below for future reference) - thanks for that pointer @alamb.
```rust
fn column(&self, name: &str) -> Option<(&ColumnChunkMetaData, &FieldRef)> {
let (idx, field) = parquet_column(self.parquet_schema, self.arrow_schema, name)?;
Some((self.row_group_metadata.column(idx), field))
}
fn min_values(&self, column: &Column) -> Option<ArrayRef> {
let (column, field) = self.column(&column.name)?;
// here we already have mapped the statistics relevant just for the column
min_statistics(field.data_type(), std::iter::once(column.statistics())).ok()
}
```
I was thinking that ParquetStatistics iterator that is getting passed into the function, was for _all_ columns in a row group. That's where I got a bit confused. I'll continue with it, documenting this as it was a light bulb moment for me and may help someone looking into this in the future.
Sorry I am a bit late to the party here, correctly interpreting the statistics requires more than just [Statistics](https://docs.rs/parquet/latest/parquet/file/statistics/enum.Statistics.html), as there is additional information that specifies things like sort order, truncation, logical types, etc... It is very likely the existing logic in DF is incorrect, which is fine, but we shouldn't commit to an API here that prevents us doing this correctly.
Additionally the API needs to be able to also handle the [Page Index](https://docs.rs/parquet/latest/parquet/file/page_index/index/struct.PageIndex.html) which exposes slightly different information from what is encoded in the file metadata.
I don't mean to discourage you, but this is one of the most arcane and subtle areas of parquet and I wonder if it might be worth starting out with something a little simpler as a first contribution? I'd recommend any of the issues marked "good first issue". As it stands this ticket needs extensive research and design work from someone with a good deal of knowledge about parquet, before even getting started on what will likely be pretty complex code. There are still ongoing discussions on parquet-format about correctly interpreting statistics, the standard under-specified a number of key things :sweat_smile:.
In any event I think the discussion on this ticket so far has been helpful.
I was purposely trying to avoid a general purpose "correctly interpret all the possible statistics in parquet" type ticket for precisely the reasons @tustvold mentions about the scope being unclear
If we wait for a complete well understood API I fear it is such a big barrier we will never start.
I personally believe the functionality spelled out on this ticket (for which we have an existing example of use) would be beneficial to create.
However, that being said, maybe it would be better to start by implementing it in DataFusion where the usecase is clear and we don't have to commit to a long term API, and once it looks good we can decide if we should port it upstream
I will endeavour to pick this ticket up as a matter of priority once I have finished the current non arrow related work that is eating all my available time
Understood @tustvold - I was looking for something in the parquet sort of area to work on after doing a "good first issue" and landed on this one.
@tustvold / @alamb - I'm happy to leave this alone or if you think it's worth doing what's been proposed in this ticket in DataFusion, I can do that too. I'm easy, thanks both for your feedback.
Given @tustvold 's concerns I think we should not do it in this repo
If you wanted to work in the DataFusion repo to start vectorizing this code (and writing tests for that) I think it is valuable but it may be tricky and require non trivial research
Filed https://github.com/apache/datafusion/issues/10453 for the work in DataFusion and I think I may have recruited @NGA-TRAN to help with that
Here is a proposed API for DataFusion: https://github.com/apache/datafusion/issues/10453#issuecomment-2117733259
I helped out with some of the implementation details in the Data Fusion implementation so I think I'm familiar enough with what's involved to port that work over here unless @tustvold was still planning to pick it up?
Thank you @efredine 🙏 -- I don't think @tustvold was planning to pick this up (though he can correct me if I a wrong)
I recommend:
1. put the statistics code in its own module (perhaps `statistics.rs` in https://github.com/apache/arrow-rs/tree/master/parquet/src/arrow/arrow_reader?)
2. Put the tests from arrow_statistics.rs in their own "integration" test in https://github.com/apache/arrow-rs/tree/master/parquet/tests (perhaps `statistics.rs)
Thank you so much 🙏
I haven't started on this yet and can't get to it until tomorrow at the earliest, so if anyone else feels inclined to pick it up please go ahead. I'll update the ticket once I have started.
ok - starting work on this now
|
2024-07-11T22:06:19Z
|
52.1
|
effccc13a9ef6e650049a160734d5ededb2a5383
|
apache/arrow-rs
| 6,041
|
apache__arrow-rs-6041
|
[
"6038"
] |
66390ff8ec15bb6ed585f353f67a19574da4375a
|
diff --git a/arrow-flight/Cargo.toml b/arrow-flight/Cargo.toml
index 60ba3ae827de..eaa1dd7e394d 100644
--- a/arrow-flight/Cargo.toml
+++ b/arrow-flight/Cargo.toml
@@ -44,11 +44,11 @@ bytes = { version = "1", default-features = false }
futures = { version = "0.3", default-features = false, features = ["alloc"] }
once_cell = { version = "1", optional = true }
paste = { version = "1.0" }
-prost = { version = "0.12.3", default-features = false, features = ["prost-derive"] }
+prost = { version = "0.13.1", default-features = false, features = ["prost-derive"] }
# For Timestamp type
-prost-types = { version = "0.12.3", default-features = false }
+prost-types = { version = "0.13.1", default-features = false }
tokio = { version = "1.0", default-features = false, features = ["macros", "rt", "rt-multi-thread"] }
-tonic = { version = "0.11.0", default-features = false, features = ["transport", "codegen", "prost"] }
+tonic = { version = "0.12.0", default-features = false, features = ["transport", "codegen", "prost"] }
# CLI-related dependencies
anyhow = { version = "1.0", optional = true }
@@ -70,8 +70,9 @@ cli = ["anyhow", "arrow-cast/prettyprint", "clap", "tracing-log", "tracing-subsc
[dev-dependencies]
arrow-cast = { workspace = true, features = ["prettyprint"] }
assert_cmd = "2.0.8"
-http = "0.2.9"
-http-body = "0.4.5"
+http = "1.1.0"
+http-body = "1.0.0"
+hyper-util = "0.1"
pin-project-lite = "0.2"
tempfile = "3.3"
tokio-stream = { version = "0.1", features = ["net"] }
diff --git a/arrow-flight/examples/flight_sql_server.rs b/arrow-flight/examples/flight_sql_server.rs
index 031628eaa833..d5168debc433 100644
--- a/arrow-flight/examples/flight_sql_server.rs
+++ b/arrow-flight/examples/flight_sql_server.rs
@@ -783,7 +783,8 @@ impl ProstMessageExt for FetchResults {
#[cfg(test)]
mod tests {
use super::*;
- use futures::TryStreamExt;
+ use futures::{TryFutureExt, TryStreamExt};
+ use hyper_util::rt::TokioIo;
use std::fs;
use std::future::Future;
use std::net::SocketAddr;
@@ -843,7 +844,8 @@ mod tests {
.serve_with_incoming(stream);
let request_future = async {
- let connector = service_fn(move |_| UnixStream::connect(path.clone()));
+ let connector =
+ service_fn(move |_| UnixStream::connect(path.clone()).map_ok(TokioIo::new));
let channel = Endpoint::try_from("http://example.com")
.unwrap()
.connect_with_connector(connector)
diff --git a/arrow-flight/gen/Cargo.toml b/arrow-flight/gen/Cargo.toml
index 7264a527ca8d..a12c683776b4 100644
--- a/arrow-flight/gen/Cargo.toml
+++ b/arrow-flight/gen/Cargo.toml
@@ -33,5 +33,5 @@ publish = false
# Pin specific version of the tonic-build dependencies to avoid auto-generated
# (and checked in) arrow.flight.protocol.rs from changing
proc-macro2 = { version = "=1.0.86", default-features = false }
-prost-build = { version = "=0.12.6", default-features = false }
-tonic-build = { version = "=0.11.0", default-features = false, features = ["transport", "prost"] }
+prost-build = { version = "=0.13.1", default-features = false }
+tonic-build = { version = "=0.12.0", default-features = false, features = ["transport", "prost"] }
diff --git a/arrow-flight/src/arrow.flight.protocol.rs b/arrow-flight/src/arrow.flight.protocol.rs
index bc314de9d19f..8c7292894eab 100644
--- a/arrow-flight/src/arrow.flight.protocol.rs
+++ b/arrow-flight/src/arrow.flight.protocol.rs
@@ -38,7 +38,7 @@ pub struct BasicAuth {
pub password: ::prost::alloc::string::String,
}
#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, ::prost::Message)]
pub struct Empty {}
///
/// Describes an available action, including both the name used for execution
@@ -103,7 +103,7 @@ pub struct Result {
///
/// The result should be stored in Result.body.
#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, ::prost::Message)]
pub struct CancelFlightInfoResult {
#[prost(enumeration = "CancelStatus", tag = "1")]
pub status: i32,
@@ -1053,19 +1053,17 @@ pub mod flight_service_server {
/// can expose a set of actions that are available.
#[derive(Debug)]
pub struct FlightServiceServer<T: FlightService> {
- inner: _Inner<T>,
+ inner: Arc<T>,
accept_compression_encodings: EnabledCompressionEncodings,
send_compression_encodings: EnabledCompressionEncodings,
max_decoding_message_size: Option<usize>,
max_encoding_message_size: Option<usize>,
}
- struct _Inner<T>(Arc<T>);
impl<T: FlightService> FlightServiceServer<T> {
pub fn new(inner: T) -> Self {
Self::from_arc(Arc::new(inner))
}
pub fn from_arc(inner: Arc<T>) -> Self {
- let inner = _Inner(inner);
Self {
inner,
accept_compression_encodings: Default::default(),
@@ -1128,7 +1126,6 @@ pub mod flight_service_server {
Poll::Ready(Ok(()))
}
fn call(&mut self, req: http::Request<B>) -> Self::Future {
- let inner = self.inner.clone();
match req.uri().path() {
"/arrow.flight.protocol.FlightService/Handshake" => {
#[allow(non_camel_case_types)]
@@ -1162,7 +1159,6 @@ pub mod flight_service_server {
let max_encoding_message_size = self.max_encoding_message_size;
let inner = self.inner.clone();
let fut = async move {
- let inner = inner.0;
let method = HandshakeSvc(inner);
let codec = tonic::codec::ProstCodec::default();
let mut grpc = tonic::server::Grpc::new(codec)
@@ -1209,7 +1205,6 @@ pub mod flight_service_server {
let max_encoding_message_size = self.max_encoding_message_size;
let inner = self.inner.clone();
let fut = async move {
- let inner = inner.0;
let method = ListFlightsSvc(inner);
let codec = tonic::codec::ProstCodec::default();
let mut grpc = tonic::server::Grpc::new(codec)
@@ -1255,7 +1250,6 @@ pub mod flight_service_server {
let max_encoding_message_size = self.max_encoding_message_size;
let inner = self.inner.clone();
let fut = async move {
- let inner = inner.0;
let method = GetFlightInfoSvc(inner);
let codec = tonic::codec::ProstCodec::default();
let mut grpc = tonic::server::Grpc::new(codec)
@@ -1302,7 +1296,6 @@ pub mod flight_service_server {
let max_encoding_message_size = self.max_encoding_message_size;
let inner = self.inner.clone();
let fut = async move {
- let inner = inner.0;
let method = PollFlightInfoSvc(inner);
let codec = tonic::codec::ProstCodec::default();
let mut grpc = tonic::server::Grpc::new(codec)
@@ -1348,7 +1341,6 @@ pub mod flight_service_server {
let max_encoding_message_size = self.max_encoding_message_size;
let inner = self.inner.clone();
let fut = async move {
- let inner = inner.0;
let method = GetSchemaSvc(inner);
let codec = tonic::codec::ProstCodec::default();
let mut grpc = tonic::server::Grpc::new(codec)
@@ -1395,7 +1387,6 @@ pub mod flight_service_server {
let max_encoding_message_size = self.max_encoding_message_size;
let inner = self.inner.clone();
let fut = async move {
- let inner = inner.0;
let method = DoGetSvc(inner);
let codec = tonic::codec::ProstCodec::default();
let mut grpc = tonic::server::Grpc::new(codec)
@@ -1442,7 +1433,6 @@ pub mod flight_service_server {
let max_encoding_message_size = self.max_encoding_message_size;
let inner = self.inner.clone();
let fut = async move {
- let inner = inner.0;
let method = DoPutSvc(inner);
let codec = tonic::codec::ProstCodec::default();
let mut grpc = tonic::server::Grpc::new(codec)
@@ -1489,7 +1479,6 @@ pub mod flight_service_server {
let max_encoding_message_size = self.max_encoding_message_size;
let inner = self.inner.clone();
let fut = async move {
- let inner = inner.0;
let method = DoExchangeSvc(inner);
let codec = tonic::codec::ProstCodec::default();
let mut grpc = tonic::server::Grpc::new(codec)
@@ -1536,7 +1525,6 @@ pub mod flight_service_server {
let max_encoding_message_size = self.max_encoding_message_size;
let inner = self.inner.clone();
let fut = async move {
- let inner = inner.0;
let method = DoActionSvc(inner);
let codec = tonic::codec::ProstCodec::default();
let mut grpc = tonic::server::Grpc::new(codec)
@@ -1583,7 +1571,6 @@ pub mod flight_service_server {
let max_encoding_message_size = self.max_encoding_message_size;
let inner = self.inner.clone();
let fut = async move {
- let inner = inner.0;
let method = ListActionsSvc(inner);
let codec = tonic::codec::ProstCodec::default();
let mut grpc = tonic::server::Grpc::new(codec)
@@ -1605,8 +1592,11 @@ pub mod flight_service_server {
Ok(
http::Response::builder()
.status(200)
- .header("grpc-status", "12")
- .header("content-type", "application/grpc")
+ .header("grpc-status", tonic::Code::Unimplemented as i32)
+ .header(
+ http::header::CONTENT_TYPE,
+ tonic::metadata::GRPC_CONTENT_TYPE,
+ )
.body(empty_body())
.unwrap(),
)
@@ -1627,16 +1617,6 @@ pub mod flight_service_server {
}
}
}
- impl<T: FlightService> Clone for _Inner<T> {
- fn clone(&self) -> Self {
- Self(Arc::clone(&self.0))
- }
- }
- impl<T: std::fmt::Debug> std::fmt::Debug for _Inner<T> {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(f, "{:?}", self.0)
- }
- }
impl<T: FlightService> tonic::server::NamedService for FlightServiceServer<T> {
const NAME: &'static str = "arrow.flight.protocol.FlightService";
}
diff --git a/arrow-flight/src/sql/arrow.flight.protocol.sql.rs b/arrow-flight/src/sql/arrow.flight.protocol.sql.rs
index c1f0fac0f6ba..5e6f198df75c 100644
--- a/arrow-flight/src/sql/arrow.flight.protocol.sql.rs
+++ b/arrow-flight/src/sql/arrow.flight.protocol.sql.rs
@@ -101,7 +101,7 @@ pub struct CommandGetSqlInfo {
/// >
/// The returned data should be ordered by data_type and then by type_name.
#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, ::prost::Message)]
pub struct CommandGetXdbcTypeInfo {
///
/// Specifies the data type to search for the info.
@@ -121,7 +121,7 @@ pub struct CommandGetXdbcTypeInfo {
/// >
/// The returned data should be ordered by catalog_name.
#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, ::prost::Message)]
pub struct CommandGetCatalogs {}
///
/// Represents a request to retrieve the list of database schemas on a Flight SQL enabled backend.
@@ -232,7 +232,7 @@ pub struct CommandGetTables {
/// >
/// The returned data should be ordered by table_type.
#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, ::prost::Message)]
pub struct CommandGetTableTypes {}
///
/// Represents a request to retrieve the primary keys of a table on a Flight SQL enabled backend.
@@ -511,7 +511,7 @@ pub struct ActionClosePreparedStatementRequest {
/// Request message for the "BeginTransaction" action.
/// Begins a transaction.
#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, ::prost::Message)]
pub struct ActionBeginTransactionRequest {}
///
/// Request message for the "BeginSavepoint" action.
@@ -802,7 +802,7 @@ pub struct CommandPreparedStatementUpdate {
/// CommandPreparedStatementUpdate was in the request, containing
/// results from the update.
#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, ::prost::Message)]
pub struct DoPutUpdateResult {
/// The number of records updated. A return value of -1 represents
/// an unknown updated record count.
@@ -862,7 +862,7 @@ pub struct ActionCancelQueryRequest {
/// This command is deprecated since 13.0.0. Use the "CancelFlightInfo"
/// action with DoAction instead.
#[allow(clippy::derive_partial_eq_without_eq)]
-#[derive(Clone, PartialEq, ::prost::Message)]
+#[derive(Clone, Copy, PartialEq, ::prost::Message)]
pub struct ActionCancelQueryResult {
#[prost(enumeration = "action_cancel_query_result::CancelResult", tag = "1")]
pub result: i32,
|
diff --git a/arrow-flight/tests/common/trailers_layer.rs b/arrow-flight/tests/common/trailers_layer.rs
index b2ab74f7d925..0ccb7df86c74 100644
--- a/arrow-flight/tests/common/trailers_layer.rs
+++ b/arrow-flight/tests/common/trailers_layer.rs
@@ -21,7 +21,7 @@ use std::task::{Context, Poll};
use futures::ready;
use http::{HeaderValue, Request, Response};
-use http_body::SizeHint;
+use http_body::{Frame, SizeHint};
use pin_project_lite::pin_project;
use tower::{Layer, Service};
@@ -99,31 +99,19 @@ impl<B: http_body::Body> http_body::Body for WrappedBody<B> {
type Data = B::Data;
type Error = B::Error;
- fn poll_data(
- mut self: Pin<&mut Self>,
+ fn poll_frame(
+ self: Pin<&mut Self>,
cx: &mut Context<'_>,
- ) -> Poll<Option<Result<Self::Data, Self::Error>>> {
- self.as_mut().project().inner.poll_data(cx)
- }
-
- fn poll_trailers(
- mut self: Pin<&mut Self>,
- cx: &mut Context<'_>,
- ) -> Poll<Result<Option<http::header::HeaderMap>, Self::Error>> {
- let result: Result<Option<http::header::HeaderMap>, Self::Error> =
- ready!(self.as_mut().project().inner.poll_trailers(cx));
-
- let mut trailers = http::header::HeaderMap::new();
- trailers.insert("test-trailer", HeaderValue::from_static("trailer_val"));
+ ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
+ let mut result = ready!(self.project().inner.poll_frame(cx));
- match result {
- Ok(Some(mut existing)) => {
- existing.extend(trailers.iter().map(|(k, v)| (k.clone(), v.clone())));
- Poll::Ready(Ok(Some(existing)))
+ if let Some(Ok(frame)) = &mut result {
+ if let Some(trailers) = frame.trailers_mut() {
+ trailers.insert("test-trailer", HeaderValue::from_static("trailer_val"));
}
- Ok(None) => Poll::Ready(Ok(Some(trailers))),
- Err(e) => Poll::Ready(Err(e)),
}
+
+ Poll::Ready(result)
}
fn is_end_stream(&self) -> bool {
diff --git a/arrow-integration-testing/Cargo.toml b/arrow-integration-testing/Cargo.toml
index 032b99f4fbbb..7be56d919852 100644
--- a/arrow-integration-testing/Cargo.toml
+++ b/arrow-integration-testing/Cargo.toml
@@ -42,11 +42,11 @@ async-trait = { version = "0.1.41", default-features = false }
clap = { version = "4", default-features = false, features = ["std", "derive", "help", "error-context", "usage"] }
futures = { version = "0.3", default-features = false }
hex = { version = "0.4", default-features = false, features = ["std"] }
-prost = { version = "0.12", default-features = false }
+prost = { version = "0.13", default-features = false }
serde = { version = "1.0", default-features = false, features = ["rc", "derive"] }
serde_json = { version = "1.0", default-features = false, features = ["std"] }
tokio = { version = "1.0", default-features = false }
-tonic = { version = "0.11", default-features = false }
+tonic = { version = "0.12", default-features = false }
tracing-subscriber = { version = "0.3.1", default-features = false, features = ["fmt"], optional = true }
num = { version = "0.4", default-features = false, features = ["std"] }
flate2 = { version = "1", default-features = false, features = ["rust_backend"] }
|
Update prost requirement from 0.12.3 to 0.13.1
Updates the requirements on [prost](https://github.com/tokio-rs/prost) to permit the latest version.
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a href="https://github.com/tokio-rs/prost/blob/master/CHANGELOG.md">prost's changelog</a>.</em></p>
<blockquote>
<h1>Prost version 0.13.1</h1>
<p><em>PROST!</em> is a <a href="https://developers.google.com/protocol-buffers/">Protocol Buffers</a> implementation for the <a href="https://www.rust-lang.org/">Rust Language</a>. <code>prost</code> generates simple, idiomatic Rust code from <code>proto2</code> and <code>proto3</code> files.</p>
<h2>Bug fixes</h2>
<ul>
<li>Enum variant named Error causes ambiguous item (<a href="https://redirect.github.com/tokio-rs/prost/issues/1098">#1098</a>)</li>
</ul>
<h1>PROST version 0.13.0</h1>
<p><strong>note</strong>: this version was yanked in favor of 0.13.1</p>
<p><em>PROST!</em> is a <a href="https://developers.google.com/protocol-buffers/">Protocol Buffers</a> implementation for the <a href="https://www.rust-lang.org/">Rust Language</a>. <code>prost</code> generates simple, idiomatic Rust code from <code>proto2</code> and <code>proto3</code> files.</p>
<p>This major update brings new features and fixes:</p>
<h2>Breaking changes</h2>
<ul>
<li>
<p>derive Copy trait for messages where possible (<a href="https://redirect.github.com/tokio-rs/prost/issues/950">#950</a>)</p>
<p><code>prost-build</code> will automatically derive <code>trait Copy</code> for some messages. If you manually implement <code>Copy</code> you should remove your implementation.</p>
</li>
<li>
<p>Change generated functions signatures to remove type parameters (<a href="https://redirect.github.com/tokio-rs/prost/issues/1045">#1045</a>)</p>
<p>The function signature of <code>trait Message</code> is changed to use <code>impl Buf</code> instead of a named generic type. If you implement <code>trait Message</code>, you should change the function signature.</p>
</li>
<li>
<p>Lightweight error value in TryFrom<!-- raw HTML omitted --> for enums (<a href="https://redirect.github.com/tokio-rs/prost/issues/1010">#1010</a>)</p>
<p>When a <code>impl TryFrom<i32></code> is generated by <code>prost</code> derive macros, it will now return the error type <code>UnknownEnumValue</code> instead of <code>DecodeError</code>. The new error can be used to retreive the integer value that failed to convert.</p>
</li>
</ul>
<h2>Features</h2>
<ul>
<li>
<p>fix: Only touch include file if contents is changed (<a href="https://redirect.github.com/tokio-rs/prost/issues/1058">#1058</a>)</p>
<p>Most generated files are untouched when the contents doesn't change. Use the same mechanism for include file as well.</p>
</li>
</ul>
<h2>Dependencies</h2>
<ul>
<li>update env_logger requirement from 0.10 to 0.11 (<a href="https://redirect.github.com/tokio-rs/prost/issues/1074">#1074</a>)</li>
<li>update criterion requirement from 0.4 to 0.5 (<a href="https://redirect.github.com/tokio-rs/prost/issues/1071">#1071</a>)</li>
<li>Remove unused libz-sys (<a href="https://redirect.github.com/tokio-rs/prost/issues/1077">#1077</a>)</li>
<li>build(deps): update itertools requirement from >=0.10, <!-- raw HTML omitted -->=0.10, <=0.13 (<a href="https://redirect.github.com/tokio-rs/prost/issues/1070">#1070</a>)</li>
</ul>
<h2>Documentation</h2>
<ul>
<li>better checking of tag duplicates, avoid discarding invalid variant errs (<a href="https://redirect.github.com/tokio-rs/prost/issues/951">#951</a>)</li>
<li>docs: Fix broken link warnings (<a href="https://redirect.github.com/tokio-rs/prost/issues/1056">#1056</a>)</li>
<li>Add missing LICENSE symlink (<a href="https://redirect.github.com/tokio-rs/prost/issues/1086">#1086</a>)</li>
</ul>
<h2>Internal</h2>
<ul>
<li>workspace package metadata (<a href="https://redirect.github.com/tokio-rs/prost/issues/1036">#1036</a>)</li>
<li>fix: Build error due to merge conflict (<a href="https://redirect.github.com/tokio-rs/prost/issues/1068">#1068</a>)</li>
<li>build: Fix release scripts (<a href="https://redirect.github.com/tokio-rs/prost/issues/1055">#1055</a>)</li>
<li>chore: Add ci to check MSRV (<a href="https://redirect.github.com/tokio-rs/prost/issues/1057">#1057</a>)</li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a href="https://github.com/tokio-rs/prost/commit/f19104a3d4345f4635bbc5fd54cb5089572e2660"><code>f19104a</code></a> chore: prepare 0.13.1 release (<a href="https://redirect.github.com/tokio-rs/prost/issues/1099">#1099</a>)</li>
<li><a href="https://github.com/tokio-rs/prost/commit/26463f437e1a3445c9d3119cf9cf0f64f5b23dfa"><code>26463f4</code></a> fix: Enum variant named <code>Error</code> causes ambiguous item (<a href="https://redirect.github.com/tokio-rs/prost/issues/1098">#1098</a>)</li>
<li><a href="https://github.com/tokio-rs/prost/commit/23f71749696d5836afa143cbbb860fa8943e0640"><code>23f7174</code></a> chore: Release version 0.13.0 (<a href="https://redirect.github.com/tokio-rs/prost/issues/1093">#1093</a>)</li>
<li><a href="https://github.com/tokio-rs/prost/commit/7a1424cf8c71c0c276970d1b8f1ef17c424d818d"><code>7a1424c</code></a> build: Fix prepare-release.sh (<a href="https://redirect.github.com/tokio-rs/prost/issues/1094">#1094</a>)</li>
<li><a href="https://github.com/tokio-rs/prost/commit/7790799b0dfc65f70cfde0a26e8f29f77510744a"><code>7790799</code></a> build(deps): update itertools requirement from >=0.10, <=0.12 to >=0.10, <=0....</li>
<li><a href="https://github.com/tokio-rs/prost/commit/4a0cc17102700d1215c791f1ee4b8df22481a19f"><code>4a0cc17</code></a> Add missing LICENSE symlink (<a href="https://redirect.github.com/tokio-rs/prost/issues/1086">#1086</a>)</li>
<li><a href="https://github.com/tokio-rs/prost/commit/ae33a5ea97ff2df8a508b6f80fa5b88c4bc0c0a6"><code>ae33a5e</code></a> ci: Set rust version of clippy job to a fixed version (<a href="https://redirect.github.com/tokio-rs/prost/issues/1090">#1090</a>)</li>
<li><a href="https://github.com/tokio-rs/prost/commit/ba776540834b0cecbbaa6ca98bd79d9682cd7e92"><code>ba77654</code></a> fix: Only touch include file if contents is changed (<a href="https://redirect.github.com/tokio-rs/prost/issues/1058">#1058</a>)</li>
<li><a href="https://github.com/tokio-rs/prost/commit/e7049d3eb20cf33bb1ac60bff19cc3a7bd48f6f2"><code>e7049d3</code></a> workspace package metadata (<a href="https://redirect.github.com/tokio-rs/prost/issues/1036">#1036</a>)</li>
<li><a href="https://github.com/tokio-rs/prost/commit/ef4930c140c639eaaa0362662d90e55a31977eb3"><code>ef4930c</code></a> docs: Fix broken link warnings (<a href="https://redirect.github.com/tokio-rs/prost/issues/1056">#1056</a>)</li>
<li>Additional commits viewable in <a href="https://github.com/tokio-rs/prost/compare/v0.12.3...v0.13.1">compare view</a></li>
</ul>
</details>
<br />
Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.
[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)
---
<details>
<summary>Dependabot commands and options</summary>
<br />
You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
</details>
|
This should be treated as a breaking change.
|
2024-07-11T06:23:13Z
|
52.1
|
effccc13a9ef6e650049a160734d5ededb2a5383
|
apache/arrow-rs
| 6,039
|
apache__arrow-rs-6039
|
[
"6033"
] |
e70c16d67d866ab7e4a75ef584c6fdc7b91e687c
|
diff --git a/arrow-array/src/array/dictionary_array.rs b/arrow-array/src/array/dictionary_array.rs
index 045917a1bfb8..d6c5dd4c3e13 100644
--- a/arrow-array/src/array/dictionary_array.rs
+++ b/arrow-array/src/array/dictionary_array.rs
@@ -1025,13 +1025,13 @@ mod tests {
let value_data = ArrayData::builder(DataType::Int8)
.len(8)
.add_buffer(Buffer::from(
- &[10_i8, 11, 12, 13, 14, 15, 16, 17].to_byte_slice(),
+ [10_i8, 11, 12, 13, 14, 15, 16, 17].to_byte_slice(),
))
.build()
.unwrap();
// Construct a buffer for value offsets, for the nested array:
- let keys = Buffer::from(&[2_i16, 3, 4].to_byte_slice());
+ let keys = Buffer::from([2_i16, 3, 4].to_byte_slice());
// Construct a dictionary array from the above two
let key_type = DataType::Int16;
diff --git a/arrow-array/src/array/fixed_size_list_array.rs b/arrow-array/src/array/fixed_size_list_array.rs
index 6f3a76908723..0d57d9a690aa 100644
--- a/arrow-array/src/array/fixed_size_list_array.rs
+++ b/arrow-array/src/array/fixed_size_list_array.rs
@@ -674,7 +674,7 @@ mod tests {
assert_eq!(err.to_string(), "Invalid argument error: Found unmasked nulls for non-nullable FixedSizeListArray field \"item\"");
// Valid as nulls in child masked by parent
- let nulls = NullBuffer::new(BooleanBuffer::new(vec![0b0000101].into(), 0, 3));
+ let nulls = NullBuffer::new(BooleanBuffer::new(Buffer::from([0b0000101]), 0, 3));
FixedSizeListArray::new(field, 2, values.clone(), Some(nulls));
let field = Arc::new(Field::new("item", DataType::Int64, true));
diff --git a/arrow-array/src/array/map_array.rs b/arrow-array/src/array/map_array.rs
index ed22ba1d8a37..bddf202bdede 100644
--- a/arrow-array/src/array/map_array.rs
+++ b/arrow-array/src/array/map_array.rs
@@ -448,20 +448,20 @@ mod tests {
// Construct key and values
let keys_data = ArrayData::builder(DataType::Int32)
.len(8)
- .add_buffer(Buffer::from(&[0, 1, 2, 3, 4, 5, 6, 7].to_byte_slice()))
+ .add_buffer(Buffer::from([0, 1, 2, 3, 4, 5, 6, 7].to_byte_slice()))
.build()
.unwrap();
let values_data = ArrayData::builder(DataType::UInt32)
.len(8)
.add_buffer(Buffer::from(
- &[0u32, 10, 20, 30, 40, 50, 60, 70].to_byte_slice(),
+ [0u32, 10, 20, 30, 40, 50, 60, 70].to_byte_slice(),
))
.build()
.unwrap();
// Construct a buffer for value offsets, for the nested array:
// [[0, 1, 2], [3, 4, 5], [6, 7]]
- let entry_offsets = Buffer::from(&[0, 3, 6, 8].to_byte_slice());
+ let entry_offsets = Buffer::from([0, 3, 6, 8].to_byte_slice());
let keys = Arc::new(Field::new("keys", DataType::Int32, false));
let values = Arc::new(Field::new("values", DataType::UInt32, false));
@@ -493,13 +493,13 @@ mod tests {
// Construct key and values
let key_data = ArrayData::builder(DataType::Int32)
.len(8)
- .add_buffer(Buffer::from(&[0, 1, 2, 3, 4, 5, 6, 7].to_byte_slice()))
+ .add_buffer(Buffer::from([0, 1, 2, 3, 4, 5, 6, 7].to_byte_slice()))
.build()
.unwrap();
let value_data = ArrayData::builder(DataType::UInt32)
.len(8)
.add_buffer(Buffer::from(
- &[0u32, 10, 20, 0, 40, 0, 60, 70].to_byte_slice(),
+ [0u32, 10, 20, 0, 40, 0, 60, 70].to_byte_slice(),
))
.null_bit_buffer(Some(Buffer::from(&[0b11010110])))
.build()
@@ -507,7 +507,7 @@ mod tests {
// Construct a buffer for value offsets, for the nested array:
// [[0, 1, 2], [3, 4, 5], [6, 7]]
- let entry_offsets = Buffer::from(&[0, 3, 6, 8].to_byte_slice());
+ let entry_offsets = Buffer::from([0, 3, 6, 8].to_byte_slice());
let keys_field = Arc::new(Field::new("keys", DataType::Int32, false));
let values_field = Arc::new(Field::new("values", DataType::UInt32, true));
@@ -617,18 +617,18 @@ mod tests {
// Construct key and values
let keys_data = ArrayData::builder(DataType::Int32)
.len(5)
- .add_buffer(Buffer::from(&[3, 4, 5, 6, 7].to_byte_slice()))
+ .add_buffer(Buffer::from([3, 4, 5, 6, 7].to_byte_slice()))
.build()
.unwrap();
let values_data = ArrayData::builder(DataType::UInt32)
.len(5)
- .add_buffer(Buffer::from(&[30u32, 40, 50, 60, 70].to_byte_slice()))
+ .add_buffer(Buffer::from([30u32, 40, 50, 60, 70].to_byte_slice()))
.build()
.unwrap();
// Construct a buffer for value offsets, for the nested array:
// [[3, 4, 5], [6, 7]]
- let entry_offsets = Buffer::from(&[0, 3, 5].to_byte_slice());
+ let entry_offsets = Buffer::from([0, 3, 5].to_byte_slice());
let keys = Arc::new(Field::new("keys", DataType::Int32, false));
let values = Arc::new(Field::new("values", DataType::UInt32, false));
diff --git a/arrow-array/src/array/struct_array.rs b/arrow-array/src/array/struct_array.rs
index ae292944e37b..44a7f38c32ce 100644
--- a/arrow-array/src/array/struct_array.rs
+++ b/arrow-array/src/array/struct_array.rs
@@ -549,7 +549,7 @@ mod tests {
let expected_string_data = ArrayData::builder(DataType::Utf8)
.len(4)
.null_bit_buffer(Some(Buffer::from(&[9_u8])))
- .add_buffer(Buffer::from(&[0, 3, 3, 3, 7].to_byte_slice()))
+ .add_buffer(Buffer::from([0, 3, 3, 3, 7].to_byte_slice()))
.add_buffer(Buffer::from(b"joemark"))
.build()
.unwrap();
@@ -557,7 +557,7 @@ mod tests {
let expected_int_data = ArrayData::builder(DataType::Int32)
.len(4)
.null_bit_buffer(Some(Buffer::from(&[11_u8])))
- .add_buffer(Buffer::from(&[1, 2, 0, 4].to_byte_slice()))
+ .add_buffer(Buffer::from([1, 2, 0, 4].to_byte_slice()))
.build()
.unwrap();
diff --git a/arrow-buffer/src/buffer/immutable.rs b/arrow-buffer/src/buffer/immutable.rs
index 2c743842fb05..52e201ca15a2 100644
--- a/arrow-buffer/src/buffer/immutable.rs
+++ b/arrow-buffer/src/buffer/immutable.rs
@@ -543,7 +543,7 @@ mod tests {
#[test]
fn test_access_concurrently() {
- let buffer = Buffer::from(vec![1, 2, 3, 4, 5]);
+ let buffer = Buffer::from([1, 2, 3, 4, 5]);
let buffer2 = buffer.clone();
assert_eq!([1, 2, 3, 4, 5], buffer.as_slice());
diff --git a/arrow-buffer/src/util/bit_chunk_iterator.rs b/arrow-buffer/src/util/bit_chunk_iterator.rs
index 9e4fb8268dff..4404509085f3 100644
--- a/arrow-buffer/src/util/bit_chunk_iterator.rs
+++ b/arrow-buffer/src/util/bit_chunk_iterator.rs
@@ -456,7 +456,7 @@ mod tests {
const ALLOC_SIZE: usize = 4 * 1024;
let input = vec![0xFF_u8; ALLOC_SIZE];
- let buffer: Buffer = Buffer::from(input);
+ let buffer: Buffer = Buffer::from_vec(input);
let bitchunks = buffer.bit_chunks(57, ALLOC_SIZE * 8 - 57);
diff --git a/arrow-cast/src/base64.rs b/arrow-cast/src/base64.rs
index 50c7423626ed..534b21878c56 100644
--- a/arrow-cast/src/base64.rs
+++ b/arrow-cast/src/base64.rs
@@ -20,7 +20,7 @@
//! [`StringArray`]: arrow_array::StringArray
use arrow_array::{Array, GenericBinaryArray, GenericStringArray, OffsetSizeTrait};
-use arrow_buffer::OffsetBuffer;
+use arrow_buffer::{Buffer, OffsetBuffer};
use arrow_schema::ArrowError;
use base64::encoded_len;
use base64::engine::Config;
@@ -50,7 +50,9 @@ pub fn b64_encode<E: Engine, O: OffsetSizeTrait>(
assert_eq!(offset, buffer_len);
// Safety: Base64 is valid UTF-8
- unsafe { GenericStringArray::new_unchecked(offsets, buffer.into(), array.nulls().cloned()) }
+ unsafe {
+ GenericStringArray::new_unchecked(offsets, Buffer::from_vec(buffer), array.nulls().cloned())
+ }
}
/// Base64 decode each element of `array` with the provided [`Engine`]
@@ -79,7 +81,7 @@ pub fn b64_decode<E: Engine, O: OffsetSizeTrait>(
Ok(GenericBinaryArray::new(
offsets,
- buffer.into(),
+ Buffer::from_vec(buffer),
array.nulls().cloned(),
))
}
diff --git a/arrow-data/src/data.rs b/arrow-data/src/data.rs
index b6ff4518e0a2..d6d6b90b6592 100644
--- a/arrow-data/src/data.rs
+++ b/arrow-data/src/data.rs
@@ -1959,7 +1959,7 @@ mod tests {
.len(20)
.offset(5)
.add_buffer(b1)
- .null_bit_buffer(Some(Buffer::from(vec![
+ .null_bit_buffer(Some(Buffer::from([
0b01011111, 0b10110101, 0b01100011, 0b00011110,
])))
.build()
@@ -2164,7 +2164,7 @@ mod tests {
#[test]
fn test_count_nulls() {
- let buffer = Buffer::from(vec![0b00010110, 0b10011111]);
+ let buffer = Buffer::from([0b00010110, 0b10011111]);
let buffer = NullBuffer::new(BooleanBuffer::new(buffer, 0, 16));
let count = count_nulls(Some(&buffer), 0, 16);
assert_eq!(count, 7);
diff --git a/arrow-flight/src/utils.rs b/arrow-flight/src/utils.rs
index c1e2d61fc5a9..37d7ff9e7293 100644
--- a/arrow-flight/src/utils.rs
+++ b/arrow-flight/src/utils.rs
@@ -94,7 +94,7 @@ pub fn flight_data_to_arrow_batch(
})
.map(|batch| {
reader::read_record_batch(
- &Buffer::from(&data.data_body),
+ &Buffer::from(data.data_body.as_ref()),
batch,
schema,
dictionaries_by_id,
diff --git a/arrow-ipc/src/compression.rs b/arrow-ipc/src/compression.rs
index 0d8b7b4c1bd4..47ea7785cbec 100644
--- a/arrow-ipc/src/compression.rs
+++ b/arrow-ipc/src/compression.rs
@@ -103,8 +103,8 @@ impl CompressionCodec {
} else if let Ok(decompressed_length) = usize::try_from(decompressed_length) {
// decompress data using the codec
let input_data = &input[(LENGTH_OF_PREFIX_DATA as usize)..];
- self.decompress(input_data, decompressed_length as _)?
- .into()
+ let v = self.decompress(input_data, decompressed_length as _)?;
+ Buffer::from_vec(v)
} else {
return Err(ArrowError::IpcError(format!(
"Invalid uncompressed length: {decompressed_length}"
diff --git a/arrow-json/src/reader/mod.rs b/arrow-json/src/reader/mod.rs
index 3e1c5d2fc896..97d9c8962618 100644
--- a/arrow-json/src/reader/mod.rs
+++ b/arrow-json/src/reader/mod.rs
@@ -1850,7 +1850,7 @@ mod tests {
let c = ArrayDataBuilder::new(c_field.data_type().clone())
.len(7)
.add_child_data(d.to_data())
- .null_bit_buffer(Some(Buffer::from(vec![0b00111011])))
+ .null_bit_buffer(Some(Buffer::from([0b00111011])))
.build()
.unwrap();
let b = BooleanArray::from(vec![
@@ -1866,14 +1866,14 @@ mod tests {
.len(7)
.add_child_data(b.to_data())
.add_child_data(c.clone())
- .null_bit_buffer(Some(Buffer::from(vec![0b00111111])))
+ .null_bit_buffer(Some(Buffer::from([0b00111111])))
.build()
.unwrap();
let a_list = ArrayDataBuilder::new(a_field.data_type().clone())
.len(6)
.add_buffer(Buffer::from_slice_ref([0i32, 2, 3, 6, 6, 6, 7]))
.add_child_data(a)
- .null_bit_buffer(Some(Buffer::from(vec![0b00110111])))
+ .null_bit_buffer(Some(Buffer::from([0b00110111])))
.build()
.unwrap();
let expected = make_array(a_list);
diff --git a/arrow-json/src/writer.rs b/arrow-json/src/writer.rs
index ef4141d7ab2a..86d2e88d99f0 100644
--- a/arrow-json/src/writer.rs
+++ b/arrow-json/src/writer.rs
@@ -927,12 +927,12 @@ mod tests {
let a_values = StringArray::from(vec!["a", "a1", "b", "c", "d", "e"]);
// list column rows: ["a", "a1"], ["b"], ["c"], ["d"], ["e"]
- let a_value_offsets = Buffer::from(&[0, 2, 3, 4, 5, 6].to_byte_slice());
+ let a_value_offsets = Buffer::from([0, 2, 3, 4, 5, 6].to_byte_slice());
let a_list_data = ArrayData::builder(field_c1.data_type().clone())
.len(5)
.add_buffer(a_value_offsets)
.add_child_data(a_values.into_data())
- .null_bit_buffer(Some(Buffer::from(vec![0b00011111])))
+ .null_bit_buffer(Some(Buffer::from([0b00011111])))
.build()
.unwrap();
let a = ListArray::from(a_list_data);
@@ -976,17 +976,17 @@ mod tests {
// list column rows: [[1, 2], [3]], [], [[4, 5, 6]]
let a_values = Int32Array::from(vec![1, 2, 3, 4, 5, 6]);
- let a_value_offsets = Buffer::from(&[0, 2, 3, 6].to_byte_slice());
+ let a_value_offsets = Buffer::from([0, 2, 3, 6].to_byte_slice());
// Construct a list array from the above two
let a_list_data = ArrayData::builder(list_inner_type.data_type().clone())
.len(3)
.add_buffer(a_value_offsets)
- .null_bit_buffer(Some(Buffer::from(vec![0b00000111])))
+ .null_bit_buffer(Some(Buffer::from([0b00000111])))
.add_child_data(a_values.into_data())
.build()
.unwrap();
- let c1_value_offsets = Buffer::from(&[0, 2, 2, 3].to_byte_slice());
+ let c1_value_offsets = Buffer::from([0, 2, 2, 3].to_byte_slice());
let c1_list_data = ArrayData::builder(field_c1.data_type().clone())
.len(3)
.add_buffer(c1_value_offsets)
@@ -1058,12 +1058,12 @@ mod tests {
// [{"c11": 1, "c12": {"c121": "e"}}, {"c12": {"c121": "f"}}],
// null,
// [{"c11": 5, "c12": {"c121": "g"}}]
- let c1_value_offsets = Buffer::from(&[0, 2, 2, 3].to_byte_slice());
+ let c1_value_offsets = Buffer::from([0, 2, 2, 3].to_byte_slice());
let c1_list_data = ArrayData::builder(field_c1.data_type().clone())
.len(3)
.add_buffer(c1_value_offsets)
.add_child_data(struct_values.into_data())
- .null_bit_buffer(Some(Buffer::from(vec![0b00000101])))
+ .null_bit_buffer(Some(Buffer::from([0b00000101])))
.build()
.unwrap();
let c1 = ListArray::from(c1_list_data);
@@ -1225,7 +1225,7 @@ mod tests {
);
// [{"foo": 10}, null, {}, {"bar": 20, "baz": 30, "qux": 40}, {"quux": 50}, {}]
- let entry_offsets = Buffer::from(&[0, 1, 1, 1, 4, 5, 5].to_byte_slice());
+ let entry_offsets = Buffer::from([0, 1, 1, 1, 4, 5, 5].to_byte_slice());
let valid_buffer = Buffer::from([0b00111101]);
let map_data = ArrayData::builder(map_data_type.clone())
@@ -1408,7 +1408,7 @@ mod tests {
);
// [{"list":[{"int32":1,"utf8":"a"},{"int32":null,"utf8":"b"}]},{"list":null},{"list":[{int32":5,"utf8":null}]},{"list":null}]
- let entry_offsets = Buffer::from(&[0, 2, 2, 3, 3].to_byte_slice());
+ let entry_offsets = Buffer::from([0, 2, 2, 3, 3].to_byte_slice());
let data = ArrayData::builder(field.data_type().clone())
.len(4)
.add_buffer(entry_offsets)
diff --git a/arrow-select/src/dictionary.rs b/arrow-select/src/dictionary.rs
index d0b6fcfc3ac9..2a532600b6cc 100644
--- a/arrow-select/src/dictionary.rs
+++ b/arrow-select/src/dictionary.rs
@@ -297,7 +297,7 @@ mod tests {
#[test]
fn test_merge_nulls() {
- let buffer = Buffer::from("helloworldbingohelloworld");
+ let buffer = Buffer::from(b"helloworldbingohelloworld");
let offsets = OffsetBuffer::from_lengths([5, 5, 5, 5, 5]);
let nulls = NullBuffer::from(vec![true, false, true, true, true]);
let values = StringArray::new(offsets, buffer, Some(nulls));
diff --git a/arrow-string/src/substring.rs b/arrow-string/src/substring.rs
index f5fe811032fb..fc2f6c8ada08 100644
--- a/arrow-string/src/substring.rs
+++ b/arrow-string/src/substring.rs
@@ -732,7 +732,7 @@ mod tests {
}
fn generic_string_with_non_zero_offset<O: OffsetSizeTrait>() {
- let values = "hellotherearrow";
+ let values = b"hellotherearrow";
let offsets = &[
O::zero(),
O::from_usize(5).unwrap(),
@@ -867,7 +867,7 @@ mod tests {
let data = ArrayData::builder(GenericStringArray::<O>::DATA_TYPE)
.len(2)
.add_buffer(Buffer::from_slice_ref(offsets))
- .add_buffer(Buffer::from(values))
+ .add_buffer(Buffer::from(values.as_bytes()))
.null_bit_buffer(Some(Buffer::from(bitmap)))
.offset(1)
.build()
diff --git a/arrow/examples/builders.rs b/arrow/examples/builders.rs
index ad6b879642ab..5c8cd51c55a0 100644
--- a/arrow/examples/builders.rs
+++ b/arrow/examples/builders.rs
@@ -88,13 +88,13 @@ fn main() {
// buffer.
let value_data = ArrayData::builder(DataType::Int32)
.len(8)
- .add_buffer(Buffer::from(&[0, 1, 2, 3, 4, 5, 6, 7].to_byte_slice()))
+ .add_buffer(Buffer::from([0, 1, 2, 3, 4, 5, 6, 7].to_byte_slice()))
.build()
.unwrap();
// Construct a buffer for value offsets, for the nested array:
// [[0, 1, 2], [3, 4, 5], [6, 7]]
- let value_offsets = Buffer::from(&[0, 3, 6, 8].to_byte_slice());
+ let value_offsets = Buffer::from([0, 3, 6, 8].to_byte_slice());
// Construct a list array from the above two
let list_data_type = DataType::List(Arc::new(Field::new("item", DataType::Int32, false)));
diff --git a/arrow/examples/tensor_builder.rs b/arrow/examples/tensor_builder.rs
index 90ad1b4868f7..45440533da27 100644
--- a/arrow/examples/tensor_builder.rs
+++ b/arrow/examples/tensor_builder.rs
@@ -57,7 +57,7 @@ fn main() -> Result<()> {
// In order to build a tensor from an array the function to_byte_slice add the
// required padding to the elements in the array.
- let buf = Buffer::from(&[0, 1, 2, 3, 4, 5, 6, 7, 9, 10].to_byte_slice());
+ let buf = Buffer::from([0, 1, 2, 3, 4, 5, 6, 7, 9, 10].to_byte_slice());
let tensor = Int32Tensor::try_new(buf, Some(vec![2, 5]), None, None)?;
println!("\nInt32 Tensor");
println!("{tensor:?}");
diff --git a/parquet/src/arrow/array_reader/byte_view_array.rs b/parquet/src/arrow/array_reader/byte_view_array.rs
index d1a0313dc1e8..5845e2c08cec 100644
--- a/parquet/src/arrow/array_reader/byte_view_array.rs
+++ b/parquet/src/arrow/array_reader/byte_view_array.rs
@@ -28,6 +28,7 @@ use crate::encodings::decoding::{Decoder, DeltaBitPackDecoder};
use crate::errors::{ParquetError, Result};
use crate::schema::types::ColumnDescPtr;
use arrow_array::{builder::make_view, ArrayRef};
+use arrow_buffer::Buffer;
use arrow_data::ByteView;
use arrow_schema::DataType as ArrowType;
use bytes::Bytes;
@@ -666,7 +667,7 @@ impl ByteViewArrayDecoderDelta {
v
};
- let actual_block_id = output.append_block(array_buffer.into());
+ let actual_block_id = output.append_block(Buffer::from_vec(array_buffer));
assert_eq!(actual_block_id, buffer_id);
Ok(read)
}
diff --git a/parquet/src/arrow/array_reader/list_array.rs b/parquet/src/arrow/array_reader/list_array.rs
index 7c66c5c23112..e1752f30cea8 100644
--- a/parquet/src/arrow/array_reader/list_array.rs
+++ b/parquet/src/arrow/array_reader/list_array.rs
@@ -213,7 +213,7 @@ impl<OffsetSize: OffsetSizeTrait> ArrayReader for ListArrayReader<OffsetSize> {
return Err(general_err!("Failed to reconstruct list from level data"));
}
- let value_offsets = Buffer::from(&list_offsets.to_byte_slice());
+ let value_offsets = Buffer::from(list_offsets.to_byte_slice());
let mut data_builder = ArrayData::builder(self.get_data_type().clone())
.len(list_offsets.len() - 1)
diff --git a/parquet/src/arrow/arrow_writer/levels.rs b/parquet/src/arrow/arrow_writer/levels.rs
index c50e612b2473..3e828bbddd17 100644
--- a/parquet/src/arrow/arrow_writer/levels.rs
+++ b/parquet/src/arrow/arrow_writer/levels.rs
@@ -1050,7 +1050,7 @@ mod tests {
let a_list_data = ArrayData::builder(a_list_type.clone())
.len(5)
.add_buffer(a_value_offsets)
- .null_bit_buffer(Some(Buffer::from(vec![0b00011011])))
+ .null_bit_buffer(Some(Buffer::from([0b00011011])))
.add_child_data(a_values.to_data())
.build()
.unwrap();
@@ -1116,7 +1116,7 @@ mod tests {
// Construct a buffer for value offsets, for the nested array:
// [[1], [2, 3], null, [4, 5, 6], [7, 8, 9, 10]]
- let g_value_offsets = arrow::buffer::Buffer::from(&[0, 1, 3, 3, 6, 10].to_byte_slice());
+ let g_value_offsets = arrow::buffer::Buffer::from([0, 1, 3, 3, 6, 10].to_byte_slice());
// Construct a list array from the above two
let g_list_data = ArrayData::builder(struct_field_g.data_type().clone())
diff --git a/parquet/src/arrow/arrow_writer/mod.rs b/parquet/src/arrow/arrow_writer/mod.rs
index f83e56c7abe6..cf46f3b64a57 100644
--- a/parquet/src/arrow/arrow_writer/mod.rs
+++ b/parquet/src/arrow/arrow_writer/mod.rs
@@ -1206,7 +1206,7 @@ mod tests {
// Construct a buffer for value offsets, for the nested array:
// [[1], [2, 3], null, [4, 5, 6], [7, 8, 9, 10]]
- let a_value_offsets = arrow::buffer::Buffer::from(&[0, 1, 3, 3, 6, 10].to_byte_slice());
+ let a_value_offsets = arrow::buffer::Buffer::from([0, 1, 3, 3, 6, 10].to_byte_slice());
// Construct a list array from the above two
let a_list_data = ArrayData::builder(DataType::List(Arc::new(Field::new(
@@ -1217,7 +1217,7 @@ mod tests {
.len(5)
.add_buffer(a_value_offsets)
.add_child_data(a_values.into_data())
- .null_bit_buffer(Some(Buffer::from(vec![0b00011011])))
+ .null_bit_buffer(Some(Buffer::from([0b00011011])))
.build()
.unwrap();
let a = ListArray::from(a_list_data);
@@ -1246,7 +1246,7 @@ mod tests {
// Construct a buffer for value offsets, for the nested array:
// [[1], [2, 3], [], [4, 5, 6], [7, 8, 9, 10]]
- let a_value_offsets = arrow::buffer::Buffer::from(&[0, 1, 3, 3, 6, 10].to_byte_slice());
+ let a_value_offsets = arrow::buffer::Buffer::from([0, 1, 3, 3, 6, 10].to_byte_slice());
// Construct a list array from the above two
let a_list_data = ArrayData::builder(DataType::List(Arc::new(Field::new(
@@ -1405,7 +1405,7 @@ mod tests {
// Construct a buffer for value offsets, for the nested array:
// [[1], [2, 3], [], [4, 5, 6], [7, 8, 9, 10]]
- let g_value_offsets = arrow::buffer::Buffer::from(&[0, 1, 3, 3, 6, 10].to_byte_slice());
+ let g_value_offsets = arrow::buffer::Buffer::from([0, 1, 3, 3, 6, 10].to_byte_slice());
// Construct a list array from the above two
let g_list_data = ArrayData::builder(struct_field_g.data_type().clone())
@@ -1420,7 +1420,7 @@ mod tests {
.len(5)
.add_buffer(g_value_offsets)
.add_child_data(g_value.to_data())
- .null_bit_buffer(Some(Buffer::from(vec![0b00011011])))
+ .null_bit_buffer(Some(Buffer::from([0b00011011])))
.build()
.unwrap();
let h = ListArray::from(h_list_data);
@@ -1525,14 +1525,14 @@ mod tests {
let c = Int32Array::from(vec![Some(1), None, Some(3), None, None, Some(6)]);
let b_data = ArrayDataBuilder::new(field_b.data_type().clone())
.len(6)
- .null_bit_buffer(Some(Buffer::from(vec![0b00100111])))
+ .null_bit_buffer(Some(Buffer::from([0b00100111])))
.add_child_data(c.into_data())
.build()
.unwrap();
let b = StructArray::from(b_data);
let a_data = ArrayDataBuilder::new(field_a.data_type().clone())
.len(6)
- .null_bit_buffer(Some(Buffer::from(vec![0b00101111])))
+ .null_bit_buffer(Some(Buffer::from([0b00101111])))
.add_child_data(b.into_data())
.build()
.unwrap();
@@ -1595,7 +1595,7 @@ mod tests {
let c = Int32Array::from(vec![1, 2, 3, 4, 5, 6]);
let b_data = ArrayDataBuilder::new(type_b)
.len(6)
- .null_bit_buffer(Some(Buffer::from(vec![0b00100111])))
+ .null_bit_buffer(Some(Buffer::from([0b00100111])))
.add_child_data(c.into_data())
.build()
.unwrap();
@@ -2280,7 +2280,7 @@ mod tests {
// Build [[], null, [null, null]]
let a_values = NullArray::new(2);
- let a_value_offsets = arrow::buffer::Buffer::from(&[0, 0, 0, 2].to_byte_slice());
+ let a_value_offsets = arrow::buffer::Buffer::from([0, 0, 0, 2].to_byte_slice());
let a_list_data = ArrayData::builder(DataType::List(Arc::new(Field::new(
"item",
DataType::Null,
@@ -2288,7 +2288,7 @@ mod tests {
))))
.len(3)
.add_buffer(a_value_offsets)
- .null_bit_buffer(Some(Buffer::from(vec![0b00000101])))
+ .null_bit_buffer(Some(Buffer::from([0b00000101])))
.add_child_data(a_values.into_data())
.build()
.unwrap();
@@ -2310,7 +2310,7 @@ mod tests {
#[test]
fn list_single_column() {
let a_values = Int32Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
- let a_value_offsets = arrow::buffer::Buffer::from(&[0, 1, 3, 3, 6, 10].to_byte_slice());
+ let a_value_offsets = arrow::buffer::Buffer::from([0, 1, 3, 3, 6, 10].to_byte_slice());
let a_list_data = ArrayData::builder(DataType::List(Arc::new(Field::new(
"item",
DataType::Int32,
@@ -2318,7 +2318,7 @@ mod tests {
))))
.len(5)
.add_buffer(a_value_offsets)
- .null_bit_buffer(Some(Buffer::from(vec![0b00011011])))
+ .null_bit_buffer(Some(Buffer::from([0b00011011])))
.add_child_data(a_values.into_data())
.build()
.unwrap();
@@ -2334,7 +2334,7 @@ mod tests {
#[test]
fn large_list_single_column() {
let a_values = Int32Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
- let a_value_offsets = arrow::buffer::Buffer::from(&[0i64, 1, 3, 3, 6, 10].to_byte_slice());
+ let a_value_offsets = arrow::buffer::Buffer::from([0i64, 1, 3, 3, 6, 10].to_byte_slice());
let a_list_data = ArrayData::builder(DataType::LargeList(Arc::new(Field::new(
"large_item",
DataType::Int32,
@@ -2343,7 +2343,7 @@ mod tests {
.len(5)
.add_buffer(a_value_offsets)
.add_child_data(a_values.into_data())
- .null_bit_buffer(Some(Buffer::from(vec![0b00011011])))
+ .null_bit_buffer(Some(Buffer::from([0b00011011])))
.build()
.unwrap();
|
diff --git a/arrow-integration-test/src/lib.rs b/arrow-integration-test/src/lib.rs
index 66fa9f3320e0..d1486fd5a153 100644
--- a/arrow-integration-test/src/lib.rs
+++ b/arrow-integration-test/src/lib.rs
@@ -696,7 +696,7 @@ pub fn array_from_json(
let list_data = ArrayData::builder(field.data_type().clone())
.len(json_col.count)
.offset(0)
- .add_buffer(Buffer::from(&offsets.to_byte_slice()))
+ .add_buffer(Buffer::from(offsets.to_byte_slice()))
.add_child_data(child_array.into_data())
.null_bit_buffer(Some(null_buf))
.build()
@@ -720,7 +720,7 @@ pub fn array_from_json(
let list_data = ArrayData::builder(field.data_type().clone())
.len(json_col.count)
.offset(0)
- .add_buffer(Buffer::from(&offsets.to_byte_slice()))
+ .add_buffer(Buffer::from(offsets.to_byte_slice()))
.add_child_data(child_array.into_data())
.null_bit_buffer(Some(null_buf))
.build()
@@ -839,7 +839,7 @@ pub fn array_from_json(
.collect();
let array_data = ArrayData::builder(field.data_type().clone())
.len(json_col.count)
- .add_buffer(Buffer::from(&offsets.to_byte_slice()))
+ .add_buffer(Buffer::from(offsets.to_byte_slice()))
.add_child_data(child_array.into_data())
.null_bit_buffer(Some(null_buf))
.build()
diff --git a/arrow-integration-testing/src/flight_client_scenarios/integration_test.rs b/arrow-integration-testing/src/flight_client_scenarios/integration_test.rs
index ec88ce36a4d2..1a6c4e28a76b 100644
--- a/arrow-integration-testing/src/flight_client_scenarios/integration_test.rs
+++ b/arrow-integration-testing/src/flight_client_scenarios/integration_test.rs
@@ -262,7 +262,7 @@ async fn receive_batch_flight_data(
while message.header_type() == ipc::MessageHeader::DictionaryBatch {
reader::read_dictionary(
- &Buffer::from(&data.data_body),
+ &Buffer::from(data.data_body.as_ref()),
message
.header_as_dictionary_batch()
.expect("Error parsing dictionary"),
diff --git a/arrow-integration-testing/src/flight_server_scenarios/integration_test.rs b/arrow-integration-testing/src/flight_server_scenarios/integration_test.rs
index a03c1cd1a31a..76eb9d880199 100644
--- a/arrow-integration-testing/src/flight_server_scenarios/integration_test.rs
+++ b/arrow-integration-testing/src/flight_server_scenarios/integration_test.rs
@@ -364,7 +364,7 @@ async fn save_uploaded_chunks(
let batch = record_batch_from_message(
message,
- &Buffer::from(data.data_body),
+ &Buffer::from(data.data_body.as_ref()),
schema_ref.clone(),
&dictionaries_by_id,
)
@@ -375,7 +375,7 @@ async fn save_uploaded_chunks(
ipc::MessageHeader::DictionaryBatch => {
dictionary_from_message(
message,
- &Buffer::from(data.data_body),
+ &Buffer::from(data.data_body.as_ref()),
schema_ref.clone(),
&mut dictionaries_by_id,
)
diff --git a/arrow/tests/array_equal.rs b/arrow/tests/array_equal.rs
index 15011c547284..7ed4dae1ed08 100644
--- a/arrow/tests/array_equal.rs
+++ b/arrow/tests/array_equal.rs
@@ -445,7 +445,7 @@ fn test_empty_offsets_list_equal() {
.len(0)
.add_buffer(Buffer::from([0i32, 2, 3, 4, 6, 7, 8].to_byte_slice()))
.add_child_data(Int32Array::from(vec![1, 2, -1, -2, 3, 4, -3, -4]).into_data())
- .null_bit_buffer(Some(Buffer::from(vec![0b00001001])))
+ .null_bit_buffer(Some(Buffer::from([0b00001001])))
.build()
.unwrap()
.into();
@@ -483,7 +483,7 @@ fn test_list_null() {
.len(6)
.add_buffer(Buffer::from([0i32, 2, 3, 4, 6, 7, 8].to_byte_slice()))
.add_child_data(c_values.into_data())
- .null_bit_buffer(Some(Buffer::from(vec![0b00001001])))
+ .null_bit_buffer(Some(Buffer::from([0b00001001])))
.build()
.unwrap()
.into();
@@ -506,7 +506,7 @@ fn test_list_null() {
.len(6)
.add_buffer(Buffer::from([0i32, 2, 3, 4, 6, 7, 8].to_byte_slice()))
.add_child_data(d_values.into_data())
- .null_bit_buffer(Some(Buffer::from(vec![0b00001001])))
+ .null_bit_buffer(Some(Buffer::from([0b00001001])))
.build()
.unwrap()
.into();
@@ -807,7 +807,7 @@ fn test_struct_equal_null() {
Field::new("f1", DataType::Utf8, true),
Field::new("f2", DataType::Int32, true),
])))
- .null_bit_buffer(Some(Buffer::from(vec![0b00001011])))
+ .null_bit_buffer(Some(Buffer::from([0b00001011])))
.len(5)
.add_child_data(strings.to_data())
.add_child_data(ints.to_data())
@@ -819,7 +819,7 @@ fn test_struct_equal_null() {
Field::new("f1", DataType::Utf8, true),
Field::new("f2", DataType::Int32, true),
])))
- .null_bit_buffer(Some(Buffer::from(vec![0b00001011])))
+ .null_bit_buffer(Some(Buffer::from([0b00001011])))
.len(5)
.add_child_data(strings.to_data())
.add_child_data(ints_non_null.to_data())
@@ -835,7 +835,7 @@ fn test_struct_equal_null() {
Field::new("f1", DataType::Utf8, true),
Field::new("f2", DataType::Int32, true),
])))
- .null_bit_buffer(Some(Buffer::from(vec![0b00001011])))
+ .null_bit_buffer(Some(Buffer::from([0b00001011])))
.len(5)
.add_child_data(strings.to_data())
.add_child_data(c_ints_non_null.to_data())
@@ -849,7 +849,7 @@ fn test_struct_equal_null() {
let a = ArrayData::builder(DataType::Struct(
vec![Field::new("f3", a.data_type().clone(), true)].into(),
))
- .null_bit_buffer(Some(Buffer::from(vec![0b00011110])))
+ .null_bit_buffer(Some(Buffer::from([0b00011110])))
.len(5)
.add_child_data(a.to_data())
.build()
@@ -868,7 +868,7 @@ fn test_struct_equal_null() {
Field::new("f1", DataType::Utf8, true),
Field::new("f2", DataType::Int32, true),
])))
- .null_bit_buffer(Some(Buffer::from(vec![0b00001011])))
+ .null_bit_buffer(Some(Buffer::from([0b00001011])))
.len(5)
.add_child_data(strings.to_data())
.add_child_data(ints_non_null.to_data())
@@ -878,7 +878,7 @@ fn test_struct_equal_null() {
let b = ArrayData::builder(DataType::Struct(
vec![Field::new("f3", b.data_type().clone(), true)].into(),
))
- .null_bit_buffer(Some(Buffer::from(vec![0b00011110])))
+ .null_bit_buffer(Some(Buffer::from([0b00011110])))
.len(5)
.add_child_data(b)
.build()
@@ -909,7 +909,7 @@ fn test_struct_equal_null_variable_size() {
let a = ArrayData::builder(DataType::Struct(
vec![Field::new("f1", DataType::Utf8, true)].into(),
))
- .null_bit_buffer(Some(Buffer::from(vec![0b00001010])))
+ .null_bit_buffer(Some(Buffer::from([0b00001010])))
.len(5)
.add_child_data(strings1.to_data())
.build()
@@ -919,7 +919,7 @@ fn test_struct_equal_null_variable_size() {
let b = ArrayData::builder(DataType::Struct(
vec![Field::new("f1", DataType::Utf8, true)].into(),
))
- .null_bit_buffer(Some(Buffer::from(vec![0b00001010])))
+ .null_bit_buffer(Some(Buffer::from([0b00001010])))
.len(5)
.add_child_data(strings2.to_data())
.build()
@@ -939,7 +939,7 @@ fn test_struct_equal_null_variable_size() {
let c = ArrayData::builder(DataType::Struct(
vec![Field::new("f1", DataType::Utf8, true)].into(),
))
- .null_bit_buffer(Some(Buffer::from(vec![0b00001011])))
+ .null_bit_buffer(Some(Buffer::from([0b00001011])))
.len(5)
.add_child_data(strings3.to_data())
.build()
diff --git a/arrow/tests/array_validation.rs b/arrow/tests/array_validation.rs
index 41def9051d44..1321f10f9438 100644
--- a/arrow/tests/array_validation.rs
+++ b/arrow/tests/array_validation.rs
@@ -63,7 +63,7 @@ fn test_fixed_width_overflow() {
#[should_panic(expected = "null_bit_buffer size too small. got 1 needed 2")]
fn test_bitmap_too_small() {
let buffer = make_i32_buffer(9);
- let null_bit_buffer = Buffer::from(vec![0b11111111]);
+ let null_bit_buffer = Buffer::from([0b11111111]);
ArrayData::try_new(
DataType::Int32,
|
Remove `From` impls that copy data into `arrow_buffer::Buffer`
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
@XiangpengHao found this on https://github.com/apache/arrow-rs/pull/6031 and I am breaking it into its own ticket
```rust
let block_id = output.append_block(self.buf.clone().into());
```
> I thought the into() will convert the Bytes into array_buffer::Buffer() without copying the data.
However, `self.buf` is `bytes::Bytes`, not `arrow_buffer::Bytes` (they confusingly having the same name). The consequence is that the code above will use this From impl
https://github.com/apache/arrow-rs/blob/3ce8e842afed03340e5caaac90ebebc267ad174a/arrow-buffer/src/buffer/immutable.rs#L361-L370
Which results in a copy of data
To avoid the copy, the code is changed to
```rust
// Here we convert `bytes::Bytes` into `arrow_buffer::Bytes`, which is zero copy
// Then we convert `arrow_buffer::Bytes` into `arrow_buffer:Buffer`, which is also zero copy
let bytes = arrow_buffer::Buffer::from_bytes(self.data.clone().into());
let block_id = output.append_block(bytes);
```
**Describe the solution you'd like**
We should do something to prevent future very subtle mistakes (and possibly remove other instances of such mistakes in arrow-rs)
**Describe alternatives you've considered**
One thing we could do is to remove any `From` impls for Buffer that copy data and instead use an explicit function name. This would make it more explicit when copying was occuring, providing more control and making mistakes such as fixed in https://github.com/apache/arrow-rs/pull/6031 less likely
Something like this, for example
```rust
impl Buffer {
/// Creating a `Buffer` instance by copying the memory from a `AsRef<[u8]>` into a newly
/// allocated memory region.
pub fn new_from_slice<T: AsRef<[u8]>>(data: T) -> Self {
...
}
```
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
|
1000% this, the current hacks of using `Buffer::from_vec`, etc... are counter-intuitive and surprising.
I had hoped that we would get specialization and be able to fix it this way, but sadly it looks like that is stuck in limbo. As such a breaking change to remove the blanket impl makes sense to me.
Take
> Take
🤔 we should probably bring the take workflow into this repo from datafusion: https://github.com/apache/datafusion/blob/main/.github/workflows/take.yml
|
2024-07-10T15:15:30Z
|
52.1
|
effccc13a9ef6e650049a160734d5ededb2a5383
|
apache/arrow-rs
| 5,971
|
apache__arrow-rs-5971
|
[
"5487"
] |
0a4d8a14b58e45ef92e31541f0b51a5b25de5f10
|
diff --git a/arrow-flight/src/encode.rs b/arrow-flight/src/encode.rs
index f59c29e68173..e7722fd7f0a8 100644
--- a/arrow-flight/src/encode.rs
+++ b/arrow-flight/src/encode.rs
@@ -304,7 +304,11 @@ impl FlightDataEncoder {
// The first message is the schema message, and all
// batches have the same schema
let send_dictionaries = self.dictionary_handling == DictionaryHandling::Resend;
- let schema = Arc::new(prepare_schema_for_flight(schema, send_dictionaries));
+ let schema = Arc::new(prepare_schema_for_flight(
+ schema,
+ &mut self.encoder.dictionary_tracker,
+ send_dictionaries,
+ ));
let mut schema_flight_data = self.encoder.encode_schema(&schema);
// attach any metadata requested
@@ -438,24 +442,28 @@ pub enum DictionaryHandling {
Resend,
}
-fn prepare_field_for_flight(field: &FieldRef, send_dictionaries: bool) -> Field {
+fn prepare_field_for_flight(
+ field: &FieldRef,
+ dictionary_tracker: &mut DictionaryTracker,
+ send_dictionaries: bool,
+) -> Field {
match field.data_type() {
DataType::List(inner) => Field::new_list(
field.name(),
- prepare_field_for_flight(inner, send_dictionaries),
+ prepare_field_for_flight(inner, dictionary_tracker, send_dictionaries),
field.is_nullable(),
)
.with_metadata(field.metadata().clone()),
DataType::LargeList(inner) => Field::new_list(
field.name(),
- prepare_field_for_flight(inner, send_dictionaries),
+ prepare_field_for_flight(inner, dictionary_tracker, send_dictionaries),
field.is_nullable(),
)
.with_metadata(field.metadata().clone()),
DataType::Struct(fields) => {
let new_fields: Vec<Field> = fields
.iter()
- .map(|f| prepare_field_for_flight(f, send_dictionaries))
+ .map(|f| prepare_field_for_flight(f, dictionary_tracker, send_dictionaries))
.collect();
Field::new_struct(field.name(), new_fields, field.is_nullable())
.with_metadata(field.metadata().clone())
@@ -463,17 +471,37 @@ fn prepare_field_for_flight(field: &FieldRef, send_dictionaries: bool) -> Field
DataType::Union(fields, mode) => {
let (type_ids, new_fields): (Vec<i8>, Vec<Field>) = fields
.iter()
- .map(|(type_id, f)| (type_id, prepare_field_for_flight(f, send_dictionaries)))
+ .map(|(type_id, f)| {
+ (
+ type_id,
+ prepare_field_for_flight(f, dictionary_tracker, send_dictionaries),
+ )
+ })
.unzip();
Field::new_union(field.name(), type_ids, new_fields, *mode)
}
- DataType::Dictionary(_, value_type) if !send_dictionaries => Field::new(
- field.name(),
- value_type.as_ref().clone(),
- field.is_nullable(),
- )
- .with_metadata(field.metadata().clone()),
+ DataType::Dictionary(_, value_type) => {
+ if !send_dictionaries {
+ Field::new(
+ field.name(),
+ value_type.as_ref().clone(),
+ field.is_nullable(),
+ )
+ .with_metadata(field.metadata().clone())
+ } else {
+ let dict_id = dictionary_tracker.set_dict_id(field.as_ref());
+
+ Field::new_dict(
+ field.name(),
+ field.data_type().clone(),
+ field.is_nullable(),
+ dict_id,
+ field.dict_is_ordered().unwrap_or_default(),
+ )
+ .with_metadata(field.metadata().clone())
+ }
+ }
_ => field.as_ref().clone(),
}
}
@@ -483,18 +511,38 @@ fn prepare_field_for_flight(field: &FieldRef, send_dictionaries: bool) -> Field
/// Convert dictionary types to underlying types
///
/// See hydrate_dictionary for more information
-fn prepare_schema_for_flight(schema: &Schema, send_dictionaries: bool) -> Schema {
+fn prepare_schema_for_flight(
+ schema: &Schema,
+ dictionary_tracker: &mut DictionaryTracker,
+ send_dictionaries: bool,
+) -> Schema {
let fields: Fields = schema
.fields()
.iter()
.map(|field| match field.data_type() {
- DataType::Dictionary(_, value_type) if !send_dictionaries => Field::new(
- field.name(),
- value_type.as_ref().clone(),
- field.is_nullable(),
- )
- .with_metadata(field.metadata().clone()),
- tpe if tpe.is_nested() => prepare_field_for_flight(field, send_dictionaries),
+ DataType::Dictionary(_, value_type) => {
+ if !send_dictionaries {
+ Field::new(
+ field.name(),
+ value_type.as_ref().clone(),
+ field.is_nullable(),
+ )
+ .with_metadata(field.metadata().clone())
+ } else {
+ let dict_id = dictionary_tracker.set_dict_id(field.as_ref());
+ Field::new_dict(
+ field.name(),
+ field.data_type().clone(),
+ field.is_nullable(),
+ dict_id,
+ field.dict_is_ordered().unwrap_or_default(),
+ )
+ .with_metadata(field.metadata().clone())
+ }
+ }
+ tpe if tpe.is_nested() => {
+ prepare_field_for_flight(field, dictionary_tracker, send_dictionaries)
+ }
_ => field.as_ref().clone(),
})
.collect();
@@ -548,10 +596,14 @@ struct FlightIpcEncoder {
impl FlightIpcEncoder {
fn new(options: IpcWriteOptions, error_on_replacement: bool) -> Self {
+ let preserve_dict_id = options.preserve_dict_id();
Self {
options,
data_gen: IpcDataGenerator::default(),
- dictionary_tracker: DictionaryTracker::new(error_on_replacement),
+ dictionary_tracker: DictionaryTracker::new_with_preserve_dict_id(
+ error_on_replacement,
+ preserve_dict_id,
+ ),
}
}
@@ -619,7 +671,10 @@ fn hydrate_dictionary(array: &ArrayRef, data_type: &DataType) -> Result<ArrayRef
#[cfg(test)]
mod tests {
- use arrow_array::builder::StringDictionaryBuilder;
+ use crate::decode::{DecodedPayload, FlightDataDecoder};
+ use arrow_array::builder::{
+ GenericByteDictionaryBuilder, ListBuilder, StringDictionaryBuilder, StructBuilder,
+ };
use arrow_array::*;
use arrow_array::{cast::downcast_array, types::*};
use arrow_buffer::ScalarBuffer;
@@ -628,8 +683,6 @@ mod tests {
use arrow_schema::{UnionFields, UnionMode};
use std::collections::HashMap;
- use crate::decode::{DecodedPayload, FlightDataDecoder};
-
use super::*;
#[test]
@@ -708,9 +761,52 @@ mod tests {
}
}
+ #[tokio::test]
+ async fn test_dictionary_resend() {
+ let arr1: DictionaryArray<UInt16Type> = vec!["a", "a", "b"].into_iter().collect();
+ let arr2: DictionaryArray<UInt16Type> = vec!["c", "c", "d"].into_iter().collect();
+
+ let schema = Arc::new(Schema::new(vec![Field::new_dictionary(
+ "dict",
+ DataType::UInt16,
+ DataType::Utf8,
+ false,
+ )]));
+ let batch1 = RecordBatch::try_new(schema.clone(), vec![Arc::new(arr1)]).unwrap();
+ let batch2 = RecordBatch::try_new(schema, vec![Arc::new(arr2)]).unwrap();
+
+ verify_flight_round_trip(vec![batch1, batch2]).await;
+ }
+
+ #[tokio::test]
+ async fn test_multiple_dictionaries_resend() {
+ // Create a schema with two dictionary fields that have the same dict ID
+ let schema = Arc::new(Schema::new(vec![
+ Field::new_dictionary("dict_1", DataType::UInt16, DataType::Utf8, false),
+ Field::new_dictionary("dict_2", DataType::UInt16, DataType::Utf8, false),
+ ]));
+
+ let arr_one_1: Arc<DictionaryArray<UInt16Type>> =
+ Arc::new(vec!["a", "a", "b"].into_iter().collect());
+ let arr_one_2: Arc<DictionaryArray<UInt16Type>> =
+ Arc::new(vec!["c", "c", "d"].into_iter().collect());
+ let arr_two_1: Arc<DictionaryArray<UInt16Type>> =
+ Arc::new(vec!["b", "a", "c"].into_iter().collect());
+ let arr_two_2: Arc<DictionaryArray<UInt16Type>> =
+ Arc::new(vec!["k", "d", "e"].into_iter().collect());
+ let batch1 =
+ RecordBatch::try_new(schema.clone(), vec![arr_one_1.clone(), arr_one_2.clone()])
+ .unwrap();
+ let batch2 =
+ RecordBatch::try_new(schema.clone(), vec![arr_two_1.clone(), arr_two_2.clone()])
+ .unwrap();
+
+ verify_flight_round_trip(vec![batch1, batch2]).await;
+ }
+
#[tokio::test]
async fn test_dictionary_list_hydration() {
- let mut builder = builder::ListBuilder::new(StringDictionaryBuilder::<UInt16Type>::new());
+ let mut builder = ListBuilder::new(StringDictionaryBuilder::<UInt16Type>::new());
builder.append_value(vec![Some("a"), None, Some("b")]);
@@ -766,6 +862,30 @@ mod tests {
}
}
+ #[tokio::test]
+ async fn test_dictionary_list_resend() {
+ let mut builder = ListBuilder::new(StringDictionaryBuilder::<UInt16Type>::new());
+
+ builder.append_value(vec![Some("a"), None, Some("b")]);
+
+ let arr1 = builder.finish();
+
+ builder.append_value(vec![Some("c"), None, Some("d")]);
+
+ let arr2 = builder.finish();
+
+ let schema = Arc::new(Schema::new(vec![Field::new_list(
+ "dict_list",
+ Field::new_dictionary("item", DataType::UInt16, DataType::Utf8, true),
+ true,
+ )]));
+
+ let batch1 = RecordBatch::try_new(schema.clone(), vec![Arc::new(arr1)]).unwrap();
+ let batch2 = RecordBatch::try_new(schema.clone(), vec![Arc::new(arr2)]).unwrap();
+
+ verify_flight_round_trip(vec![batch1, batch2]).await;
+ }
+
#[tokio::test]
async fn test_dictionary_struct_hydration() {
let struct_fields = vec![Field::new_list(
@@ -774,26 +894,38 @@ mod tests {
true,
)];
- let mut builder = builder::ListBuilder::new(StringDictionaryBuilder::<UInt16Type>::new());
+ let mut struct_builder = StructBuilder::new(
+ struct_fields.clone(),
+ vec![Box::new(builder::ListBuilder::new(
+ StringDictionaryBuilder::<UInt16Type>::new(),
+ ))],
+ );
- builder.append_value(vec![Some("a"), None, Some("b")]);
+ struct_builder
+ .field_builder::<ListBuilder<GenericByteDictionaryBuilder<UInt16Type,GenericStringType<i32>>>>(0)
+ .unwrap()
+ .append_value(vec![Some("a"), None, Some("b")]);
- let arr1 = Arc::new(builder.finish());
- let arr1 = StructArray::new(struct_fields.clone().into(), vec![arr1], None);
+ struct_builder.append(true);
- builder.append_value(vec![Some("c"), None, Some("d")]);
+ let arr1 = struct_builder.finish();
- let arr2 = Arc::new(builder.finish());
- let arr2 = StructArray::new(struct_fields.clone().into(), vec![arr2], None);
+ struct_builder
+ .field_builder::<ListBuilder<GenericByteDictionaryBuilder<UInt16Type,GenericStringType<i32>>>>(0)
+ .unwrap()
+ .append_value(vec![Some("c"), None, Some("d")]);
+ struct_builder.append(true);
+
+ let arr2 = struct_builder.finish();
let schema = Arc::new(Schema::new(vec![Field::new_struct(
"struct",
- struct_fields.clone(),
+ struct_fields,
true,
)]));
let batch1 = RecordBatch::try_new(schema.clone(), vec![Arc::new(arr1)]).unwrap();
- let batch2 = RecordBatch::try_new(schema.clone(), vec![Arc::new(arr2)]).unwrap();
+ let batch2 = RecordBatch::try_new(schema, vec![Arc::new(arr2)]).unwrap();
let stream = futures::stream::iter(vec![Ok(batch1), Ok(batch2)]);
@@ -838,6 +970,43 @@ mod tests {
}
}
+ #[tokio::test]
+ async fn test_dictionary_struct_resend() {
+ let struct_fields = vec![Field::new_list(
+ "dict_list",
+ Field::new_dictionary("item", DataType::UInt16, DataType::Utf8, true),
+ true,
+ )];
+
+ let mut struct_builder = StructBuilder::new(
+ struct_fields.clone(),
+ vec![Box::new(builder::ListBuilder::new(
+ StringDictionaryBuilder::<UInt16Type>::new(),
+ ))],
+ );
+
+ struct_builder.field_builder::<ListBuilder<GenericByteDictionaryBuilder<UInt16Type,GenericStringType<i32>>>>(0).unwrap().append_value(vec![Some("a"), None, Some("b")]);
+ struct_builder.append(true);
+
+ let arr1 = struct_builder.finish();
+
+ struct_builder.field_builder::<ListBuilder<GenericByteDictionaryBuilder<UInt16Type,GenericStringType<i32>>>>(0).unwrap().append_value(vec![Some("c"), None, Some("d")]);
+ struct_builder.append(true);
+
+ let arr2 = struct_builder.finish();
+
+ let schema = Arc::new(Schema::new(vec![Field::new_struct(
+ "struct",
+ struct_fields,
+ true,
+ )]));
+
+ let batch1 = RecordBatch::try_new(schema.clone(), vec![Arc::new(arr1)]).unwrap();
+ let batch2 = RecordBatch::try_new(schema, vec![Arc::new(arr2)]).unwrap();
+
+ verify_flight_round_trip(vec![batch1, batch2]).await;
+ }
+
#[tokio::test]
async fn test_dictionary_union_hydration() {
let struct_fields = vec![Field::new_list(
@@ -1004,42 +1173,124 @@ mod tests {
}
#[tokio::test]
- async fn test_send_dictionaries() {
- let schema = Arc::new(Schema::new(vec![Field::new_dictionary(
- "dict",
- DataType::UInt16,
- DataType::Utf8,
- false,
+ async fn test_dictionary_union_resend() {
+ let struct_fields = vec![Field::new_list(
+ "dict_list",
+ Field::new_dictionary("item", DataType::UInt16, DataType::Utf8, true),
+ true,
+ )];
+
+ let union_fields = [
+ (
+ 0,
+ Arc::new(Field::new_list(
+ "dict_list",
+ Field::new_dictionary("item", DataType::UInt16, DataType::Utf8, true),
+ true,
+ )),
+ ),
+ (
+ 1,
+ Arc::new(Field::new_struct("struct", struct_fields.clone(), true)),
+ ),
+ (2, Arc::new(Field::new("string", DataType::Utf8, true))),
+ ]
+ .into_iter()
+ .collect::<UnionFields>();
+
+ let struct_fields = vec![Field::new_list(
+ "dict_list",
+ Field::new_dictionary("item", DataType::UInt16, DataType::Utf8, true),
+ true,
+ )];
+
+ let mut builder = builder::ListBuilder::new(StringDictionaryBuilder::<UInt16Type>::new());
+
+ builder.append_value(vec![Some("a"), None, Some("b")]);
+
+ let arr1 = builder.finish();
+
+ let type_id_buffer = [0].into_iter().collect::<ScalarBuffer<i8>>();
+ let arr1 = UnionArray::try_new(
+ union_fields.clone(),
+ type_id_buffer,
+ None,
+ vec![
+ Arc::new(arr1) as Arc<dyn Array>,
+ new_null_array(union_fields.iter().nth(1).unwrap().1.data_type(), 1),
+ new_null_array(union_fields.iter().nth(2).unwrap().1.data_type(), 1),
+ ],
+ )
+ .unwrap();
+
+ builder.append_value(vec![Some("c"), None, Some("d")]);
+
+ let arr2 = Arc::new(builder.finish());
+ let arr2 = StructArray::new(struct_fields.clone().into(), vec![arr2], None);
+
+ let type_id_buffer = [1].into_iter().collect::<ScalarBuffer<i8>>();
+ let arr2 = UnionArray::try_new(
+ union_fields.clone(),
+ type_id_buffer,
+ None,
+ vec![
+ new_null_array(union_fields.iter().next().unwrap().1.data_type(), 1),
+ Arc::new(arr2),
+ new_null_array(union_fields.iter().nth(2).unwrap().1.data_type(), 1),
+ ],
+ )
+ .unwrap();
+
+ let type_id_buffer = [2].into_iter().collect::<ScalarBuffer<i8>>();
+ let arr3 = UnionArray::try_new(
+ union_fields.clone(),
+ type_id_buffer,
+ None,
+ vec![
+ new_null_array(union_fields.iter().next().unwrap().1.data_type(), 1),
+ new_null_array(union_fields.iter().nth(1).unwrap().1.data_type(), 1),
+ Arc::new(StringArray::from(vec!["e"])),
+ ],
+ )
+ .unwrap();
+
+ let (type_ids, union_fields): (Vec<_>, Vec<_>) = union_fields
+ .iter()
+ .map(|(type_id, field_ref)| (type_id, (*Arc::clone(field_ref)).clone()))
+ .unzip();
+ let schema = Arc::new(Schema::new(vec![Field::new_union(
+ "union",
+ type_ids.clone(),
+ union_fields.clone(),
+ UnionMode::Sparse,
)]));
- let arr_one: Arc<DictionaryArray<UInt16Type>> =
- Arc::new(vec!["a", "a", "b"].into_iter().collect());
- let arr_two: Arc<DictionaryArray<UInt16Type>> =
- Arc::new(vec!["b", "a", "c"].into_iter().collect());
- let batch_one = RecordBatch::try_new(schema.clone(), vec![arr_one.clone()]).unwrap();
- let batch_two = RecordBatch::try_new(schema.clone(), vec![arr_two.clone()]).unwrap();
+ let batch1 = RecordBatch::try_new(schema.clone(), vec![Arc::new(arr1)]).unwrap();
+ let batch2 = RecordBatch::try_new(schema.clone(), vec![Arc::new(arr2)]).unwrap();
+ let batch3 = RecordBatch::try_new(schema.clone(), vec![Arc::new(arr3)]).unwrap();
+
+ verify_flight_round_trip(vec![batch1, batch2, batch3]).await;
+ }
+
+ async fn verify_flight_round_trip(mut batches: Vec<RecordBatch>) {
+ let expected_schema = batches.first().unwrap().schema();
let encoder = FlightDataEncoderBuilder::default()
+ .with_options(IpcWriteOptions::default().with_preserve_dict_id(false))
.with_dictionary_handling(DictionaryHandling::Resend)
- .build(futures::stream::iter(vec![Ok(batch_one), Ok(batch_two)]));
+ .build(futures::stream::iter(batches.clone().into_iter().map(Ok)));
+
+ let mut expected_batches = batches.drain(..);
let mut decoder = FlightDataDecoder::new(encoder);
- let mut expected_array = arr_one;
while let Some(decoded) = decoder.next().await {
let decoded = decoded.unwrap();
match decoded.payload {
DecodedPayload::None => {}
- DecodedPayload::Schema(s) => assert_eq!(s, schema),
+ DecodedPayload::Schema(s) => assert_eq!(s, expected_schema),
DecodedPayload::RecordBatch(b) => {
- assert_eq!(b.schema(), schema);
-
- let actual_array = Arc::new(downcast_array::<DictionaryArray<UInt16Type>>(
- b.column_by_name("dict").unwrap(),
- ));
-
- assert_eq!(actual_array, expected_array);
-
- expected_array = arr_two.clone();
+ let expected_batch = expected_batches.next().unwrap();
+ assert_eq!(b, expected_batch);
}
}
}
@@ -1051,7 +1302,9 @@ mod tests {
HashMap::from([("some_key".to_owned(), "some_value".to_owned())]),
);
- let got = prepare_schema_for_flight(&schema, false);
+ let mut dictionary_tracker = DictionaryTracker::new_with_preserve_dict_id(false, true);
+
+ let got = prepare_schema_for_flight(&schema, &mut dictionary_tracker, false);
assert!(got.metadata().contains_key("some_key"));
}
@@ -1072,7 +1325,7 @@ mod tests {
options: &IpcWriteOptions,
) -> (Vec<FlightData>, FlightData) {
let data_gen = IpcDataGenerator::default();
- let mut dictionary_tracker = DictionaryTracker::new(false);
+ let mut dictionary_tracker = DictionaryTracker::new_with_preserve_dict_id(false, true);
let (encoded_dictionaries, encoded_batch) = data_gen
.encoded_batch(batch, &mut dictionary_tracker, options)
diff --git a/arrow-flight/src/utils.rs b/arrow-flight/src/utils.rs
index 32716a52eb0d..c1e2d61fc5a9 100644
--- a/arrow-flight/src/utils.rs
+++ b/arrow-flight/src/utils.rs
@@ -39,7 +39,8 @@ pub fn flight_data_from_arrow_batch(
options: &IpcWriteOptions,
) -> (Vec<FlightData>, FlightData) {
let data_gen = writer::IpcDataGenerator::default();
- let mut dictionary_tracker = writer::DictionaryTracker::new(false);
+ let mut dictionary_tracker =
+ writer::DictionaryTracker::new_with_preserve_dict_id(false, options.preserve_dict_id());
let (encoded_dictionaries, encoded_batch) = data_gen
.encoded_batch(batch, &mut dictionary_tracker, options)
@@ -149,7 +150,8 @@ pub fn batches_to_flight_data(
let mut flight_data = vec![];
let data_gen = writer::IpcDataGenerator::default();
- let mut dictionary_tracker = writer::DictionaryTracker::new(false);
+ let mut dictionary_tracker =
+ writer::DictionaryTracker::new_with_preserve_dict_id(false, options.preserve_dict_id());
for batch in batches.iter() {
let (encoded_dictionaries, encoded_batch) =
diff --git a/arrow-ipc/src/reader.rs b/arrow-ipc/src/reader.rs
index 3423d06b6fca..1f83200d65f8 100644
--- a/arrow-ipc/src/reader.rs
+++ b/arrow-ipc/src/reader.rs
@@ -617,7 +617,7 @@ fn read_dictionary_impl(
let id = batch.id();
let fields_using_this_dictionary = schema.fields_with_dict_id(id);
let first_field = fields_using_this_dictionary.first().ok_or_else(|| {
- ArrowError::InvalidArgumentError("dictionary id not found in schema".to_string())
+ ArrowError::InvalidArgumentError(format!("dictionary id {id} not found in schema"))
})?;
// As the dictionary batch does not contain the type of the
@@ -643,7 +643,7 @@ fn read_dictionary_impl(
_ => None,
}
.ok_or_else(|| {
- ArrowError::InvalidArgumentError("dictionary id not found in schema".to_string())
+ ArrowError::InvalidArgumentError(format!("dictionary id {id} not found in schema"))
})?;
// We don't currently record the isOrdered field. This could be general
@@ -1812,7 +1812,7 @@ mod tests {
"values",
DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Utf8)),
true,
- 1,
+ 2,
false,
));
let entry_struct = StructArray::from(vec![
@@ -2082,7 +2082,7 @@ mod tests {
.unwrap();
let gen = IpcDataGenerator {};
- let mut dict_tracker = DictionaryTracker::new(false);
+ let mut dict_tracker = DictionaryTracker::new_with_preserve_dict_id(false, true);
let (_, encoded) = gen
.encoded_batch(&batch, &mut dict_tracker, &Default::default())
.unwrap();
@@ -2119,7 +2119,7 @@ mod tests {
.unwrap();
let gen = IpcDataGenerator {};
- let mut dict_tracker = DictionaryTracker::new(false);
+ let mut dict_tracker = DictionaryTracker::new_with_preserve_dict_id(false, true);
let (_, encoded) = gen
.encoded_batch(&batch, &mut dict_tracker, &Default::default())
.unwrap();
diff --git a/arrow-ipc/src/writer.rs b/arrow-ipc/src/writer.rs
index f74a86e013cd..c0782195999d 100644
--- a/arrow-ipc/src/writer.rs
+++ b/arrow-ipc/src/writer.rs
@@ -59,6 +59,11 @@ pub struct IpcWriteOptions {
/// Compression, if desired. Will result in a runtime error
/// if the corresponding feature is not enabled
batch_compression_type: Option<crate::CompressionType>,
+ /// Flag indicating whether the writer should preserver the dictionary IDs defined in the
+ /// schema or generate unique dictionary IDs internally during encoding.
+ ///
+ /// Defaults to `true`
+ preserve_dict_id: bool,
}
impl IpcWriteOptions {
@@ -81,7 +86,7 @@ impl IpcWriteOptions {
}
Ok(self)
}
- /// Try create IpcWriteOptions, checking for incompatible settings
+ /// Try to create IpcWriteOptions, checking for incompatible settings
pub fn try_new(
alignment: usize,
write_legacy_ipc_format: bool,
@@ -106,6 +111,7 @@ impl IpcWriteOptions {
write_legacy_ipc_format,
metadata_version,
batch_compression_type: None,
+ preserve_dict_id: true,
}),
crate::MetadataVersion::V5 => {
if write_legacy_ipc_format {
@@ -118,6 +124,7 @@ impl IpcWriteOptions {
write_legacy_ipc_format,
metadata_version,
batch_compression_type: None,
+ preserve_dict_id: true,
})
}
}
@@ -126,6 +133,22 @@ impl IpcWriteOptions {
))),
}
}
+
+ pub fn preserve_dict_id(&self) -> bool {
+ self.preserve_dict_id
+ }
+
+ /// Set whether the IPC writer should preserve the dictionary IDs in the schema
+ /// or auto-assign unique dictionary IDs during encoding (defaults to true)
+ ///
+ /// If this option is true, the application must handle assigning ids
+ /// to the dictionary batches in order to encode them correctly
+ ///
+ /// The default will change to `false` in future releases
+ pub fn with_preserve_dict_id(mut self, preserve_dict_id: bool) -> Self {
+ self.preserve_dict_id = preserve_dict_id;
+ self
+ }
}
impl Default for IpcWriteOptions {
@@ -135,6 +158,7 @@ impl Default for IpcWriteOptions {
write_legacy_ipc_format: false,
metadata_version: crate::MetadataVersion::V5,
batch_compression_type: None,
+ preserve_dict_id: true,
}
}
}
@@ -163,7 +187,7 @@ impl Default for IpcWriteOptions {
///
/// // encode the batch into zero or more encoded dictionaries
/// // and the data for the actual array.
-/// let data_gen = IpcDataGenerator {};
+/// let data_gen = IpcDataGenerator::default();
/// let (encoded_dictionaries, encoded_message) = data_gen
/// .encoded_batch(&batch, &mut dictionary_tracker, &options)
/// .unwrap();
@@ -198,12 +222,13 @@ impl IpcDataGenerator {
}
}
- fn _encode_dictionaries(
+ fn _encode_dictionaries<I: Iterator<Item = i64>>(
&self,
column: &ArrayRef,
encoded_dictionaries: &mut Vec<EncodedData>,
dictionary_tracker: &mut DictionaryTracker,
write_options: &IpcWriteOptions,
+ dict_id: &mut I,
) -> Result<(), ArrowError> {
match column.data_type() {
DataType::Struct(fields) => {
@@ -215,6 +240,7 @@ impl IpcDataGenerator {
encoded_dictionaries,
dictionary_tracker,
write_options,
+ dict_id,
)?;
}
}
@@ -235,6 +261,7 @@ impl IpcDataGenerator {
encoded_dictionaries,
dictionary_tracker,
write_options,
+ dict_id,
)?;
}
DataType::List(field) => {
@@ -245,6 +272,7 @@ impl IpcDataGenerator {
encoded_dictionaries,
dictionary_tracker,
write_options,
+ dict_id,
)?;
}
DataType::LargeList(field) => {
@@ -255,6 +283,7 @@ impl IpcDataGenerator {
encoded_dictionaries,
dictionary_tracker,
write_options,
+ dict_id,
)?;
}
DataType::FixedSizeList(field, _) => {
@@ -268,6 +297,7 @@ impl IpcDataGenerator {
encoded_dictionaries,
dictionary_tracker,
write_options,
+ dict_id,
)?;
}
DataType::Map(field, _) => {
@@ -285,6 +315,7 @@ impl IpcDataGenerator {
encoded_dictionaries,
dictionary_tracker,
write_options,
+ dict_id,
)?;
// values
@@ -294,6 +325,7 @@ impl IpcDataGenerator {
encoded_dictionaries,
dictionary_tracker,
write_options,
+ dict_id,
)?;
}
DataType::Union(fields, _) => {
@@ -306,6 +338,7 @@ impl IpcDataGenerator {
encoded_dictionaries,
dictionary_tracker,
write_options,
+ dict_id,
)?;
}
}
@@ -315,19 +348,24 @@ impl IpcDataGenerator {
Ok(())
}
- fn encode_dictionaries(
+ fn encode_dictionaries<I: Iterator<Item = i64>>(
&self,
field: &Field,
column: &ArrayRef,
encoded_dictionaries: &mut Vec<EncodedData>,
dictionary_tracker: &mut DictionaryTracker,
write_options: &IpcWriteOptions,
+ dict_id_seq: &mut I,
) -> Result<(), ArrowError> {
match column.data_type() {
DataType::Dictionary(_key_type, _value_type) => {
- let dict_id = field
- .dict_id()
- .expect("All Dictionary types have `dict_id`");
+ let dict_id = dict_id_seq
+ .next()
+ .or_else(|| field.dict_id())
+ .ok_or_else(|| {
+ ArrowError::IpcError(format!("no dict id for field {}", field.name()))
+ })?;
+
let dict_data = column.to_data();
let dict_values = &dict_data.child_data()[0];
@@ -338,6 +376,7 @@ impl IpcDataGenerator {
encoded_dictionaries,
dictionary_tracker,
write_options,
+ dict_id_seq,
)?;
let emit = dictionary_tracker.insert(dict_id, column)?;
@@ -355,6 +394,7 @@ impl IpcDataGenerator {
encoded_dictionaries,
dictionary_tracker,
write_options,
+ dict_id_seq,
)?,
}
@@ -373,6 +413,8 @@ impl IpcDataGenerator {
let schema = batch.schema();
let mut encoded_dictionaries = Vec::with_capacity(schema.all_fields().len());
+ let mut dict_id = dictionary_tracker.dict_ids.clone().into_iter();
+
for (i, field) in schema.fields().iter().enumerate() {
let column = batch.column(i);
self.encode_dictionaries(
@@ -381,6 +423,7 @@ impl IpcDataGenerator {
&mut encoded_dictionaries,
dictionary_tracker,
write_options,
+ &mut dict_id,
)?;
}
@@ -671,20 +714,73 @@ fn into_zero_offset_run_array<R: RunEndIndexType>(
/// isn't allowed in the `FileWriter`.
pub struct DictionaryTracker {
written: HashMap<i64, ArrayData>,
+ dict_ids: Vec<i64>,
error_on_replacement: bool,
+ preserve_dict_id: bool,
}
impl DictionaryTracker {
- /// Create a new [`DictionaryTracker`]. If `error_on_replacement`
+ /// Create a new [`DictionaryTracker`].
+ ///
+ /// If `error_on_replacement`
/// is true, an error will be generated if an update to an
/// existing dictionary is attempted.
+ ///
+ /// If `preserve_dict_id` is true, the dictionary ID defined in the schema
+ /// is used, otherwise a unique dictionary ID will be assigned by incrementing
+ /// the last seen dictionary ID (or using `0` if no other dictionary IDs have been
+ /// seen)
pub fn new(error_on_replacement: bool) -> Self {
Self {
written: HashMap::new(),
+ dict_ids: Vec::new(),
error_on_replacement,
+ preserve_dict_id: true,
}
}
+ /// Create a new [`DictionaryTracker`].
+ ///
+ /// If `error_on_replacement`
+ /// is true, an error will be generated if an update to an
+ /// existing dictionary is attempted.
+ pub fn new_with_preserve_dict_id(error_on_replacement: bool, preserve_dict_id: bool) -> Self {
+ Self {
+ written: HashMap::new(),
+ dict_ids: Vec::new(),
+ error_on_replacement,
+ preserve_dict_id,
+ }
+ }
+
+ /// Set the dictionary ID for `field`.
+ ///
+ /// If `preserve_dict_id` is true, this will return the `dict_id` in `field` (or panic if `field` does
+ /// not have a `dict_id` defined).
+ ///
+ /// If `preserve_dict_id` is false, this will return the value of the last `dict_id` assigned incremented by 1
+ /// or 0 in the case where no dictionary IDs have yet been assigned
+ pub fn set_dict_id(&mut self, field: &Field) -> i64 {
+ let next = if self.preserve_dict_id {
+ field.dict_id().expect("no dict_id in field")
+ } else {
+ self.dict_ids
+ .last()
+ .copied()
+ .map(|i| i + 1)
+ .unwrap_or_default()
+ };
+
+ self.dict_ids.push(next);
+ next
+ }
+
+ /// Return the sequence of dictionary IDs in the order they should be observed while
+ /// traversing the schema
+ pub fn dict_id(&mut self) -> &[i64] {
+ &self.dict_ids
+ }
+
/// Keep track of the dictionary with the given ID and values. Behavior:
///
/// * If this ID has been written already and has the same data, return `Ok(false)` to indicate
@@ -771,6 +867,7 @@ impl<W: Write> FileWriter<W> {
// write the schema, set the written bytes to the schema + header
let encoded_message = data_gen.schema_to_bytes(schema, &write_options);
let (meta, data) = write_message(&mut writer, encoded_message, &write_options)?;
+ let preserve_dict_id = write_options.preserve_dict_id;
Ok(Self {
writer,
write_options,
@@ -779,7 +876,10 @@ impl<W: Write> FileWriter<W> {
dictionary_blocks: vec![],
record_blocks: vec![],
finished: false,
- dictionary_tracker: DictionaryTracker::new(true),
+ dictionary_tracker: DictionaryTracker::new_with_preserve_dict_id(
+ true,
+ preserve_dict_id,
+ ),
custom_metadata: HashMap::new(),
data_gen,
})
@@ -936,11 +1036,15 @@ impl<W: Write> StreamWriter<W> {
// write the schema, set the written bytes to the schema
let encoded_message = data_gen.schema_to_bytes(schema, &write_options);
write_message(&mut writer, encoded_message, &write_options)?;
+ let preserve_dict_id = write_options.preserve_dict_id;
Ok(Self {
writer,
write_options,
finished: false,
- dictionary_tracker: DictionaryTracker::new(false),
+ dictionary_tracker: DictionaryTracker::new_with_preserve_dict_id(
+ false,
+ preserve_dict_id,
+ ),
data_gen,
})
}
@@ -1817,11 +1921,12 @@ mod tests {
let batch = RecordBatch::try_new(schema, vec![Arc::new(union)]).unwrap();
let gen = IpcDataGenerator {};
- let mut dict_tracker = DictionaryTracker::new(false);
+ let mut dict_tracker = DictionaryTracker::new_with_preserve_dict_id(false, true);
gen.encoded_batch(&batch, &mut dict_tracker, &Default::default())
.unwrap();
- // Dictionary with id 2 should have been written to the dict tracker
+ // The encoder will assign dict IDs itself to ensure uniqueness and ignore the dict ID in the schema
+ // so we expect the dict will be keyed to 0
assert!(dict_tracker.written.contains_key(&2));
}
@@ -1852,11 +1957,10 @@ mod tests {
let batch = RecordBatch::try_new(schema, vec![struct_array]).unwrap();
let gen = IpcDataGenerator {};
- let mut dict_tracker = DictionaryTracker::new(false);
+ let mut dict_tracker = DictionaryTracker::new_with_preserve_dict_id(false, true);
gen.encoded_batch(&batch, &mut dict_tracker, &Default::default())
.unwrap();
- // Dictionary with id 2 should have been written to the dict tracker
assert!(dict_tracker.written.contains_key(&2));
}
|
diff --git a/arrow-integration-testing/src/flight_client_scenarios/integration_test.rs b/arrow-integration-testing/src/flight_client_scenarios/integration_test.rs
index c6b5a72ca6e2..ec88ce36a4d2 100644
--- a/arrow-integration-testing/src/flight_client_scenarios/integration_test.rs
+++ b/arrow-integration-testing/src/flight_client_scenarios/integration_test.rs
@@ -123,7 +123,7 @@ async fn send_batch(
options: &writer::IpcWriteOptions,
) -> Result {
let data_gen = writer::IpcDataGenerator::default();
- let mut dictionary_tracker = writer::DictionaryTracker::new(false);
+ let mut dictionary_tracker = writer::DictionaryTracker::new_with_preserve_dict_id(false, true);
let (encoded_dictionaries, encoded_batch) = data_gen
.encoded_batch(batch, &mut dictionary_tracker, options)
diff --git a/arrow-integration-testing/src/flight_server_scenarios/integration_test.rs b/arrow-integration-testing/src/flight_server_scenarios/integration_test.rs
index 25203ecb7697..a03c1cd1a31a 100644
--- a/arrow-integration-testing/src/flight_server_scenarios/integration_test.rs
+++ b/arrow-integration-testing/src/flight_server_scenarios/integration_test.rs
@@ -119,7 +119,8 @@ impl FlightService for FlightServiceImpl {
.enumerate()
.flat_map(|(counter, batch)| {
let data_gen = writer::IpcDataGenerator::default();
- let mut dictionary_tracker = writer::DictionaryTracker::new(false);
+ let mut dictionary_tracker =
+ writer::DictionaryTracker::new_with_preserve_dict_id(false, true);
let (encoded_dictionaries, encoded_batch) = data_gen
.encoded_batch(batch, &mut dictionary_tracker, &options)
|
Improve documentation around handling of dictionary arrays in arrow flight
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
<!--
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
(This section helps Arrow developers understand the context and *why* for this feature, in addition to the *what*)
-->
Documentation around handling of dictionary arrays in arrow flight is confusing.
**Describe the solution you'd like**
<!--
A clear and concise description of what you want to happen.
-->
Improve doc comments so it is more clear how it works and what the different options mean concretely
**Describe alternatives you've considered**
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
Leave people confused and let them figure it out through trial and error like I did :)
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
|
Related slack thread: https://the-asf.slack.com/archives/C01QUFS30TD/p1709986070881859?thread_ts=1709815827.985999&cid=C01QUFS30TD
`label_issue.py` automatically added labels {'arrow'} from #5488
`label_issue.py` automatically added labels {'arrow-flight'} from #5488
|
2024-06-27T19:16:52Z
|
52.0
|
0a4d8a14b58e45ef92e31541f0b51a5b25de5f10
|
apache/arrow-rs
| 5,862
|
apache__arrow-rs-5862
|
[
"4897"
] |
a20116ec36f8c0c959aa9e6c547dc7e5625ebb1b
|
diff --git a/arrow-data/src/transform/mod.rs b/arrow-data/src/transform/mod.rs
index b0d9475afcd6..1e43bf488cbe 100644
--- a/arrow-data/src/transform/mod.rs
+++ b/arrow-data/src/transform/mod.rs
@@ -385,7 +385,10 @@ impl<'a> MutableArrayData<'a> {
array_capacity = *capacity;
new_buffers(data_type, *capacity)
}
- (DataType::List(_) | DataType::LargeList(_), Capacities::List(capacity, _)) => {
+ (
+ DataType::List(_) | DataType::LargeList(_) | DataType::FixedSizeList(_, _),
+ Capacities::List(capacity, _),
+ ) => {
array_capacity = *capacity;
new_buffers(data_type, *capacity)
}
@@ -501,12 +504,23 @@ impl<'a> MutableArrayData<'a> {
MutableArrayData::new(value_child, use_nulls, array_capacity),
]
}
- DataType::FixedSizeList(_, _) => {
+ DataType::FixedSizeList(_, size) => {
let children = arrays
.iter()
.map(|array| &array.child_data()[0])
.collect::<Vec<_>>();
- vec![MutableArrayData::new(children, use_nulls, array_capacity)]
+ let capacities =
+ if let Capacities::List(capacity, ref child_capacities) = capacities {
+ child_capacities
+ .clone()
+ .map(|c| *c)
+ .unwrap_or(Capacities::Array(capacity * *size as usize))
+ } else {
+ Capacities::Array(array_capacity * *size as usize)
+ };
+ vec![MutableArrayData::with_capacities(
+ children, use_nulls, capacities,
+ )]
}
DataType::Union(fields, _) => (0..fields.len())
.map(|i| {
diff --git a/arrow-select/src/concat.rs b/arrow-select/src/concat.rs
index f98e85475a25..5732d721b340 100644
--- a/arrow-select/src/concat.rs
+++ b/arrow-select/src/concat.rs
@@ -54,6 +54,34 @@ fn binary_capacity<T: ByteArrayType>(arrays: &[&dyn Array]) -> Capacities {
Capacities::Binary(item_capacity, Some(bytes_capacity))
}
+fn fixed_size_list_capacity(arrays: &[&dyn Array], data_type: &DataType) -> Capacities {
+ if let DataType::FixedSizeList(f, _) = data_type {
+ let item_capacity = arrays.iter().map(|a| a.len()).sum();
+ let child_data_type = f.data_type();
+ match child_data_type {
+ // These types should match the types that `get_capacity`
+ // has special handling for.
+ DataType::Utf8
+ | DataType::LargeUtf8
+ | DataType::Binary
+ | DataType::LargeBinary
+ | DataType::FixedSizeList(_, _) => {
+ let values: Vec<&dyn arrow_array::Array> = arrays
+ .iter()
+ .map(|a| a.as_fixed_size_list().values().as_ref())
+ .collect();
+ Capacities::List(
+ item_capacity,
+ Some(Box::new(get_capacity(&values, child_data_type))),
+ )
+ }
+ _ => Capacities::Array(item_capacity),
+ }
+ } else {
+ unreachable!("illegal data type for fixed size list")
+ }
+}
+
fn concat_dictionaries<K: ArrowDictionaryKeyType>(
arrays: &[&dyn Array],
) -> Result<ArrayRef, ArrowError> {
@@ -107,6 +135,17 @@ macro_rules! dict_helper {
};
}
+fn get_capacity(arrays: &[&dyn Array], data_type: &DataType) -> Capacities {
+ match data_type {
+ DataType::Utf8 => binary_capacity::<Utf8Type>(arrays),
+ DataType::LargeUtf8 => binary_capacity::<LargeUtf8Type>(arrays),
+ DataType::Binary => binary_capacity::<BinaryType>(arrays),
+ DataType::LargeBinary => binary_capacity::<LargeBinaryType>(arrays),
+ DataType::FixedSizeList(_, _) => fixed_size_list_capacity(arrays, data_type),
+ _ => Capacities::Array(arrays.iter().map(|a| a.len()).sum()),
+ }
+}
+
/// Concatenate multiple [Array] of the same type into a single [ArrayRef].
pub fn concat(arrays: &[&dyn Array]) -> Result<ArrayRef, ArrowError> {
if arrays.is_empty() {
@@ -124,20 +163,15 @@ pub fn concat(arrays: &[&dyn Array]) -> Result<ArrayRef, ArrowError> {
"It is not possible to concatenate arrays of different data types.".to_string(),
));
}
-
- let capacity = match d {
- DataType::Utf8 => binary_capacity::<Utf8Type>(arrays),
- DataType::LargeUtf8 => binary_capacity::<LargeUtf8Type>(arrays),
- DataType::Binary => binary_capacity::<BinaryType>(arrays),
- DataType::LargeBinary => binary_capacity::<LargeBinaryType>(arrays),
- DataType::Dictionary(k, _) => downcast_integer! {
+ if let DataType::Dictionary(k, _) = d {
+ downcast_integer! {
k.as_ref() => (dict_helper, arrays),
_ => unreachable!("illegal dictionary key type {k}")
- },
- _ => Capacities::Array(arrays.iter().map(|a| a.len()).sum()),
- };
-
- concat_fallback(arrays, capacity)
+ };
+ } else {
+ let capacity = get_capacity(arrays, d);
+ concat_fallback(arrays, capacity)
+ }
}
/// Concatenates arrays using MutableArrayData
@@ -373,6 +407,37 @@ mod tests {
assert_eq!(array_result.as_ref(), &array_expected as &dyn Array);
}
+ #[test]
+ fn test_concat_primitive_fixed_size_list_arrays() {
+ let list1 = vec![
+ Some(vec![Some(-1), None]),
+ None,
+ Some(vec![Some(10), Some(20)]),
+ ];
+ let list1_array =
+ FixedSizeListArray::from_iter_primitive::<Int64Type, _, _>(list1.clone(), 2);
+
+ let list2 = vec![
+ None,
+ Some(vec![Some(100), None]),
+ Some(vec![Some(102), Some(103)]),
+ ];
+ let list2_array =
+ FixedSizeListArray::from_iter_primitive::<Int64Type, _, _>(list2.clone(), 2);
+
+ let list3 = vec![Some(vec![Some(1000), Some(1001)])];
+ let list3_array =
+ FixedSizeListArray::from_iter_primitive::<Int64Type, _, _>(list3.clone(), 2);
+
+ let array_result = concat(&[&list1_array, &list2_array, &list3_array]).unwrap();
+
+ let expected = list1.into_iter().chain(list2).chain(list3);
+ let array_expected =
+ FixedSizeListArray::from_iter_primitive::<Int64Type, _, _>(expected, 2);
+
+ assert_eq!(array_result.as_ref(), &array_expected as &dyn Array);
+ }
+
#[test]
fn test_concat_struct_arrays() {
let field = Arc::new(Field::new("field", DataType::Int64, true));
diff --git a/arrow/benches/concatenate_kernel.rs b/arrow/benches/concatenate_kernel.rs
index 2f5b654394e4..0c553f8b3f3c 100644
--- a/arrow/benches/concatenate_kernel.rs
+++ b/arrow/benches/concatenate_kernel.rs
@@ -17,6 +17,8 @@
#[macro_use]
extern crate criterion;
+use std::sync::Arc;
+
use criterion::Criterion;
extern crate arrow;
@@ -82,6 +84,24 @@ fn add_benchmark(c: &mut Criterion) {
c.bench_function("concat str nulls 1024", |b| {
b.iter(|| bench_concat(&v1, &v2))
});
+
+ let v1 = FixedSizeListArray::try_new(
+ Arc::new(Field::new("item", DataType::Int32, true)),
+ 1024,
+ Arc::new(create_primitive_array::<Int32Type>(1024 * 1024, 0.0)),
+ None,
+ )
+ .unwrap();
+ let v2 = FixedSizeListArray::try_new(
+ Arc::new(Field::new("item", DataType::Int32, true)),
+ 1024,
+ Arc::new(create_primitive_array::<Int32Type>(1024 * 1024, 0.0)),
+ None,
+ )
+ .unwrap();
+ c.bench_function("concat fixed size lists", |b| {
+ b.iter(|| bench_concat(&v1, &v2))
+ });
}
criterion_group!(benches, add_benchmark);
|
diff --git a/arrow/tests/array_transform.rs b/arrow/tests/array_transform.rs
index 42e4da7c4b4e..08f23c200d52 100644
--- a/arrow/tests/array_transform.rs
+++ b/arrow/tests/array_transform.rs
@@ -17,9 +17,9 @@
use arrow::array::{
Array, ArrayRef, BooleanArray, Decimal128Array, DictionaryArray, FixedSizeBinaryArray,
- Int16Array, Int32Array, Int64Array, Int64Builder, ListArray, ListBuilder, MapBuilder,
- NullArray, StringArray, StringBuilder, StringDictionaryBuilder, StructArray, UInt8Array,
- UnionArray,
+ FixedSizeListBuilder, Int16Array, Int32Array, Int64Array, Int64Builder, ListArray, ListBuilder,
+ MapBuilder, NullArray, StringArray, StringBuilder, StringDictionaryBuilder, StructArray,
+ UInt16Array, UInt16Builder, UInt8Array, UnionArray,
};
use arrow::datatypes::Int16Type;
use arrow_array::StringViewArray;
@@ -1074,43 +1074,42 @@ fn test_mixed_types() {
MutableArrayData::new(vec![&a, &b], false, 4);
}
-/*
-// this is an old test used on a meanwhile removed dead code
-// that is still useful when `MutableArrayData` supports fixed-size lists.
#[test]
-fn test_fixed_size_list_append() -> Result<()> {
- let int_builder = UInt16Builder::new(64);
+fn test_fixed_size_list_append() {
+ let int_builder = UInt16Builder::with_capacity(64);
let mut builder = FixedSizeListBuilder::<UInt16Builder>::new(int_builder, 2);
- builder.values().append_slice(&[1, 2])?;
- builder.append(true)?;
- builder.values().append_slice(&[3, 4])?;
- builder.append(false)?;
- builder.values().append_slice(&[5, 6])?;
- builder.append(true)?;
-
- let a_builder = UInt16Builder::new(64);
+ builder.values().append_slice(&[1, 2]);
+ builder.append(true);
+ builder.values().append_slice(&[3, 4]);
+ builder.append(false);
+ builder.values().append_slice(&[5, 6]);
+ builder.append(true);
+ let a = builder.finish().into_data();
+
+ let a_builder = UInt16Builder::with_capacity(64);
let mut a_builder = FixedSizeListBuilder::<UInt16Builder>::new(a_builder, 2);
- a_builder.values().append_slice(&[7, 8])?;
- a_builder.append(true)?;
- a_builder.values().append_slice(&[9, 10])?;
- a_builder.append(true)?;
- a_builder.values().append_slice(&[11, 12])?;
- a_builder.append(false)?;
- a_builder.values().append_slice(&[13, 14])?;
- a_builder.append(true)?;
- a_builder.values().append_null()?;
- a_builder.values().append_null()?;
- a_builder.append(true)?;
- let a = a_builder.finish();
+ a_builder.values().append_slice(&[7, 8]);
+ a_builder.append(true);
+ a_builder.values().append_slice(&[9, 10]);
+ a_builder.append(true);
+ a_builder.values().append_slice(&[11, 12]);
+ a_builder.append(false);
+ a_builder.values().append_slice(&[13, 14]);
+ a_builder.append(true);
+ a_builder.values().append_null();
+ a_builder.values().append_null();
+ a_builder.append(true);
+ let b = a_builder.finish().into_data();
+
+ let mut mutable = MutableArrayData::new(vec![&a, &b], false, 10);
+ mutable.extend(0, 0, a.len());
+ mutable.extend(1, 0, b.len());
// append array
- builder.append_data(&[
- a.data(),
- a.slice(1, 3).data(),
- a.slice(2, 1).data(),
- a.slice(5, 0).data(),
- ])?;
- let finished = builder.finish();
+ mutable.extend(1, 1, 4);
+ mutable.extend(1, 2, 3);
+
+ let finished = mutable.freeze();
let expected_int_array = UInt16Array::from(vec![
Some(1),
@@ -1141,23 +1140,14 @@ fn test_fixed_size_list_append() -> Result<()> {
Some(11),
Some(12),
]);
- let expected_list_data = ArrayData::new(
- DataType::FixedSizeList(
- Arc::new(Field::new("item", DataType::UInt16, true)),
- 2,
- ),
+ let expected_fixed_size_list_data = ArrayData::try_new(
+ DataType::FixedSizeList(Arc::new(Field::new("item", DataType::UInt16, true)), 2),
12,
- None,
- None,
+ Some(Buffer::from(&[0b11011101, 0b101])),
0,
vec![],
- vec![expected_int_array.data()],
- );
- let expected_list =
- FixedSizeListArray::from(Arc::new(expected_list_data) as ArrayData);
- assert_eq!(&expected_list.values(), &finished.values());
- assert_eq!(expected_list.len(), finished.len());
-
- Ok(())
+ vec![expected_int_array.to_data()],
+ )
+ .unwrap();
+ assert_eq!(finished, expected_fixed_size_list_data);
}
-*/
|
concat should preallocate for FixedSizeList
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
Right now, concat only pre-allocates for string, binary, dictionary and primitive arrays (IIUC):
https://github.com/apache/arrow-rs/blob/208da03979b2903c3182c20ef382b2895756380a/arrow-select/src/concat.rs#L129-L139
We use `FixedSizeList<{FloatType}>` as a storage type for tensor arrays, and not pre-allocating can get very expensive in plans. https://github.com/lancedb/lance/issues/1360
**Describe the solution you'd like**
Should provide capacities for fixed size list array. We likely need to add an entry to this enum:
https://github.com/apache/arrow-rs/blob/b46ea46aa65149fac763671b0adcb9c4e406ec11/arrow-data/src/transform/mod.rs#L323-L344
**Describe alternatives you've considered**
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
|
2024-06-10T15:57:58Z
|
52.0
|
0a4d8a14b58e45ef92e31541f0b51a5b25de5f10
|
|
apache/arrow-rs
| 5,773
|
apache__arrow-rs-5773
|
[
"5254"
] |
30767a687b48d0dbd2e030eef327826c39095123
|
diff --git a/parquet_derive/src/parquet_field.rs b/parquet_derive/src/parquet_field.rs
index 3ab85a8972f5..9fff76c42d1d 100644
--- a/parquet_derive/src/parquet_field.rs
+++ b/parquet_derive/src/parquet_field.rs
@@ -136,7 +136,7 @@ impl Field {
Type::Option(_) => unimplemented!("Unsupported nesting encountered"),
Type::Reference(_, ref second_type)
| Type::Vec(ref second_type)
- | Type::Array(ref second_type)
+ | Type::Array(ref second_type, _)
| Type::Slice(ref second_type) => match **second_type {
Type::TypePath(_) => Some(self.optional_definition_levels()),
_ => unimplemented!("Unsupported nesting encountered"),
@@ -144,11 +144,11 @@ impl Field {
},
Type::Reference(_, ref first_type)
| Type::Vec(ref first_type)
- | Type::Array(ref first_type)
+ | Type::Array(ref first_type, _)
| Type::Slice(ref first_type) => match **first_type {
Type::TypePath(_) => None,
Type::Vec(ref second_type)
- | Type::Array(ref second_type)
+ | Type::Array(ref second_type, _)
| Type::Slice(ref second_type) => match **second_type {
Type::TypePath(_) => None,
Type::Reference(_, ref third_type) => match **third_type {
@@ -161,7 +161,7 @@ impl Field {
match **second_type {
Type::TypePath(_) => Some(self.optional_definition_levels()),
Type::Vec(ref third_type)
- | Type::Array(ref third_type)
+ | Type::Array(ref third_type, _)
| Type::Slice(ref third_type) => match **third_type {
Type::TypePath(_) => Some(self.optional_definition_levels()),
Type::Reference(_, ref fourth_type) => match **fourth_type {
@@ -316,25 +316,23 @@ impl Field {
let logical_type = self.ty.logical_type();
let repetition = self.ty.repetition();
let converted_type = self.ty.converted_type();
+ let length = self.ty.length();
+
+ let mut builder = quote! {
+ ParquetType::primitive_type_builder(#field_name, #physical_type)
+ .with_logical_type(#logical_type)
+ .with_repetition(#repetition)
+ };
if let Some(converted_type) = converted_type {
- quote! {
- fields.push(ParquetType::primitive_type_builder(#field_name, #physical_type)
- .with_logical_type(#logical_type)
- .with_repetition(#repetition)
- .with_converted_type(#converted_type)
- .build().unwrap().into()
- )
- }
- } else {
- quote! {
- fields.push(ParquetType::primitive_type_builder(#field_name, #physical_type)
- .with_logical_type(#logical_type)
- .with_repetition(#repetition)
- .build().unwrap().into()
- )
- }
+ builder = quote! { #builder.with_converted_type(#converted_type) };
+ }
+
+ if let Some(length) = length {
+ builder = quote! { #builder.with_length(#length) };
}
+
+ quote! { fields.push(#builder.build().unwrap().into()) }
}
fn option_into_vals(&self) -> proc_macro2::TokenStream {
@@ -394,7 +392,7 @@ impl Field {
quote! { rec.#field_name.signed_duration_since(::chrono::NaiveDate::from_ymd(1970, 1, 1)).num_days() as i32 }
}
Some(ThirdPartyType::Uuid) => {
- quote! { (&rec.#field_name.to_string()[..]).into() }
+ quote! { rec.#field_name.as_bytes().to_vec().into() }
}
_ => {
if self.is_a_byte_buf {
@@ -430,7 +428,7 @@ impl Field {
}
}
Some(ThirdPartyType::Uuid) => {
- quote! { ::uuid::Uuid::parse_str(vals[i].data().convert()).unwrap() }
+ quote! { ::uuid::Uuid::from_bytes(vals[i].data().try_into().unwrap()) }
}
_ => match &self.ty {
Type::TypePath(_) => match self.ty.last_part().as_str() {
@@ -469,7 +467,7 @@ impl Field {
#[allow(clippy::large_enum_variant)]
#[derive(Debug, PartialEq)]
enum Type {
- Array(Box<Type>),
+ Array(Box<Type>, syn::Expr),
Option(Box<Type>),
Slice(Box<Type>),
Vec(Box<Type>),
@@ -542,7 +540,7 @@ impl Type {
Type::TypePath(_) => parent_ty.unwrap_or(ty),
Type::Option(ref first_type)
| Type::Vec(ref first_type)
- | Type::Array(ref first_type)
+ | Type::Array(ref first_type, _)
| Type::Slice(ref first_type)
| Type::Reference(_, ref first_type) => {
Type::leaf_type_recursive_helper(first_type, Some(ty))
@@ -560,7 +558,7 @@ impl Type {
Type::TypePath(ref type_) => type_,
Type::Option(ref first_type)
| Type::Vec(ref first_type)
- | Type::Array(ref first_type)
+ | Type::Array(ref first_type, _)
| Type::Slice(ref first_type)
| Type::Reference(_, ref first_type) => match **first_type {
Type::TypePath(ref type_) => type_,
@@ -607,7 +605,7 @@ impl Type {
let leaf_type = self.leaf_type_recursive();
match leaf_type {
- Type::Array(ref first_type) => {
+ Type::Array(ref first_type, _length) => {
if let Type::TypePath(_) = **first_type {
if last_part == "u8" {
return BasicType::FIXED_LEN_BYTE_ARRAY;
@@ -638,17 +636,38 @@ impl Type {
}
"f32" => BasicType::FLOAT,
"f64" => BasicType::DOUBLE,
- "String" | "str" | "Uuid" => BasicType::BYTE_ARRAY,
+ "String" | "str" => BasicType::BYTE_ARRAY,
+ "Uuid" => BasicType::FIXED_LEN_BYTE_ARRAY,
f => unimplemented!("{} currently is not supported", f),
}
}
+ fn length(&self) -> Option<syn::Expr> {
+ let last_part = self.last_part();
+ let leaf_type = self.leaf_type_recursive();
+
+ // `[u8; N]` => Some(N)
+ if let Type::Array(ref first_type, length) = leaf_type {
+ if let Type::TypePath(_) = **first_type {
+ if last_part == "u8" {
+ return Some(length.clone());
+ }
+ }
+ }
+
+ match last_part.trim() {
+ // Uuid => [u8; 16] => Some(16)
+ "Uuid" => Some(syn::parse_quote!(16)),
+ _ => None,
+ }
+ }
+
fn logical_type(&self) -> proc_macro2::TokenStream {
let last_part = self.last_part();
let leaf_type = self.leaf_type_recursive();
match leaf_type {
- Type::Array(ref first_type) => {
+ Type::Array(ref first_type, _length) => {
if let Type::TypePath(_) = **first_type {
if last_part == "u8" {
return quote! { None };
@@ -789,7 +808,7 @@ impl Type {
fn from_type_array(f: &syn::Field, ta: &syn::TypeArray) -> Self {
let inner_type = Type::from_type(f, ta.elem.as_ref());
- Type::Array(Box::new(inner_type))
+ Type::Array(Box::new(inner_type), ta.len.clone())
}
fn from_type_slice(f: &syn::Field, ts: &syn::TypeSlice) -> Self {
@@ -1091,6 +1110,7 @@ mod test {
a_fix_byte_buf: [u8; 10],
a_complex_option: ::std::option::Option<&Vec<u8>>,
a_complex_vec: &::std::vec::Vec<&Option<u8>>,
+ a_uuid: ::uuid::Uuid,
}
};
@@ -1110,7 +1130,42 @@ mod test {
BasicType::BYTE_ARRAY,
BasicType::FIXED_LEN_BYTE_ARRAY,
BasicType::BYTE_ARRAY,
- BasicType::INT32
+ BasicType::INT32,
+ BasicType::FIXED_LEN_BYTE_ARRAY,
+ ]
+ )
+ }
+
+ #[test]
+ fn test_type_length() {
+ let snippet: proc_macro2::TokenStream = quote! {
+ struct LotsOfInnerTypes {
+ a_buf: ::std::vec::Vec<u8>,
+ a_number: i32,
+ a_verbose_option: ::std::option::Option<bool>,
+ a_silly_string: String,
+ a_fix_byte_buf: [u8; 10],
+ a_complex_option: ::std::option::Option<&Vec<u8>>,
+ a_complex_vec: &::std::vec::Vec<&Option<u8>>,
+ a_uuid: ::uuid::Uuid,
+ }
+ };
+
+ let fields = extract_fields(snippet);
+ let converted_fields: Vec<_> = fields.iter().map(Type::from).collect();
+ let lengths: Vec<_> = converted_fields.iter().map(|ty| ty.length()).collect();
+
+ assert_eq!(
+ lengths,
+ vec![
+ None,
+ None,
+ None,
+ None,
+ Some(syn::parse_quote!(10)),
+ None,
+ None,
+ Some(syn::parse_quote!(16)),
]
)
}
@@ -1328,8 +1383,8 @@ mod test {
let when = Field::from(&fields[0]);
assert_eq!(when.writer_snippet().to_string(),(quote!{
{
- let vals : Vec<_> = records.iter().map(|rec| (&rec.unique_id.to_string()[..]).into() ).collect();
- if let ColumnWriter::ByteArrayColumnWriter(ref mut typed) = column_writer.untyped() {
+ let vals : Vec<_> = records.iter().map(|rec| rec.unique_id.as_bytes().to_vec().into() ).collect();
+ if let ColumnWriter::FixedLenByteArrayColumnWriter(ref mut typed) = column_writer.untyped() {
typed.write_batch(&vals[..], None, None) ?;
} else {
panic!("Schema and struct disagree on type for {}" , stringify!{ unique_id })
@@ -1349,7 +1404,7 @@ mod test {
}
}).collect();
- if let ColumnWriter::ByteArrayColumnWriter(ref mut typed) = column_writer.untyped() {
+ if let ColumnWriter::FixedLenByteArrayColumnWriter(ref mut typed) = column_writer.untyped() {
typed.write_batch(&vals[..], Some(&definition_levels[..]), None) ?;
} else {
panic!("Schema and struct disagree on type for {}" , stringify!{ maybe_unique_id })
@@ -1371,13 +1426,13 @@ mod test {
assert_eq!(when.reader_snippet().to_string(),(quote!{
{
let mut vals = Vec::new();
- if let ColumnReader::ByteArrayColumnReader(mut typed) = column_reader {
+ if let ColumnReader::FixedLenByteArrayColumnReader(mut typed) = column_reader {
typed.read_records(num_records, None, None, &mut vals)?;
} else {
panic!("Schema and struct disagree on type for {}", stringify!{ unique_id });
}
for (i, r) in &mut records[..num_records].iter_mut().enumerate() {
- r.unique_id = ::uuid::Uuid::parse_str(vals[i].data().convert()).unwrap();
+ r.unique_id = ::uuid::Uuid::from_bytes(vals[i].data().try_into().unwrap());
}
}
}).to_string());
|
diff --git a/parquet_derive_test/Cargo.toml b/parquet_derive_test/Cargo.toml
index a5d2e76d4503..a3a4b58fea95 100644
--- a/parquet_derive_test/Cargo.toml
+++ b/parquet_derive_test/Cargo.toml
@@ -32,3 +32,4 @@ rust-version = { workspace = true }
parquet = { workspace = true }
parquet_derive = { path = "../parquet_derive", default-features = false }
chrono = { workspace = true }
+uuid = { version = "1", features = ["v4"] }
diff --git a/parquet_derive_test/src/lib.rs b/parquet_derive_test/src/lib.rs
index 25734813a8d8..3743c6b55c7c 100644
--- a/parquet_derive_test/src/lib.rs
+++ b/parquet_derive_test/src/lib.rs
@@ -42,6 +42,7 @@ struct ACompleteRecord<'a> {
pub borrowed_maybe_a_string: &'a Option<String>,
pub borrowed_maybe_a_str: &'a Option<&'a str>,
pub now: chrono::NaiveDateTime,
+ pub uuid: uuid::Uuid,
pub byte_vec: Vec<u8>,
pub maybe_byte_vec: Option<Vec<u8>>,
pub borrowed_byte_vec: &'a [u8],
@@ -61,6 +62,7 @@ struct APartiallyCompleteRecord {
pub double: f64,
pub now: chrono::NaiveDateTime,
pub date: chrono::NaiveDate,
+ pub uuid: uuid::Uuid,
pub byte_vec: Vec<u8>,
}
@@ -105,6 +107,7 @@ mod tests {
OPTIONAL BINARY borrowed_maybe_a_string (STRING);
OPTIONAL BINARY borrowed_maybe_a_str (STRING);
REQUIRED INT64 now (TIMESTAMP_MILLIS);
+ REQUIRED FIXED_LEN_BYTE_ARRAY (16) uuid (UUID);
REQUIRED BINARY byte_vec;
OPTIONAL BINARY maybe_byte_vec;
REQUIRED BINARY borrowed_byte_vec;
@@ -144,6 +147,7 @@ mod tests {
borrowed_maybe_a_string: &maybe_a_string,
borrowed_maybe_a_str: &maybe_a_str,
now: chrono::Utc::now().naive_local(),
+ uuid: uuid::Uuid::new_v4(),
byte_vec: vec![0x65, 0x66, 0x67],
maybe_byte_vec: Some(vec![0x88, 0x89, 0x90]),
borrowed_byte_vec: &borrowed_byte_vec,
@@ -179,6 +183,7 @@ mod tests {
double: std::f64::NAN,
now: chrono::Utc::now().naive_local(),
date: chrono::naive::NaiveDate::from_ymd_opt(2015, 3, 14).unwrap(),
+ uuid: uuid::Uuid::new_v4(),
byte_vec: vec![0x65, 0x66, 0x67],
}];
|
parquet_derive: UUID should not be a ByteArray
**Describe the bug**
<!--
A clear and concise description of what the bug is.
-->
`ParquetRecordWriter` is marking UUID as a `ByteArray` which causes a panic.
```
General("Cannot annotate Uuid from BYTE_ARRAY for field 'session_id'")
```
**To Reproduce**
<!--
Steps to reproduce the behavior:
-->
```
#[derive(parquet_derive::ParquetRecordWriter)]
struct RequestData {
session_id: uuid::Uuid,
}
fn main() {
let data: &[RequestData] = &[];
let _schema = data.schema();
}
```
**Expected behavior**
<!--
A clear and concise description of what you expected to happen.
-->
UUID should be typed as a `FixedLenByteArray` with length 16.
**Additional context**
<!--
Add any other context about the problem here.
-->
https://github.com/apache/arrow-rs/blob/3cd6da0a6b97056f3717d3491c84ec6d734aa262/parquet_derive/src/parquet_field.rs#L641
|
2024-05-16T08:39:17Z
|
51.0
|
30767a687b48d0dbd2e030eef327826c39095123
|
|
apache/arrow-rs
| 5,769
|
apache__arrow-rs-5769
|
[
"5654"
] |
30767a687b48d0dbd2e030eef327826c39095123
|
diff --git a/arrow-arith/src/numeric.rs b/arrow-arith/src/numeric.rs
index b2c87bba5143..17b794762b9f 100644
--- a/arrow-arith/src/numeric.rs
+++ b/arrow-arith/src/numeric.rs
@@ -25,7 +25,7 @@ use arrow_array::cast::AsArray;
use arrow_array::timezone::Tz;
use arrow_array::types::*;
use arrow_array::*;
-use arrow_buffer::ArrowNativeType;
+use arrow_buffer::{ArrowNativeType, IntervalDayTime, IntervalMonthDayNano};
use arrow_schema::{ArrowError, DataType, IntervalUnit, TimeUnit};
use crate::arity::{binary, try_binary};
@@ -343,12 +343,12 @@ trait TimestampOp: ArrowTimestampType {
type Duration: ArrowPrimitiveType<Native = i64>;
fn add_year_month(timestamp: i64, delta: i32, tz: Tz) -> Option<i64>;
- fn add_day_time(timestamp: i64, delta: i64, tz: Tz) -> Option<i64>;
- fn add_month_day_nano(timestamp: i64, delta: i128, tz: Tz) -> Option<i64>;
+ fn add_day_time(timestamp: i64, delta: IntervalDayTime, tz: Tz) -> Option<i64>;
+ fn add_month_day_nano(timestamp: i64, delta: IntervalMonthDayNano, tz: Tz) -> Option<i64>;
fn sub_year_month(timestamp: i64, delta: i32, tz: Tz) -> Option<i64>;
- fn sub_day_time(timestamp: i64, delta: i64, tz: Tz) -> Option<i64>;
- fn sub_month_day_nano(timestamp: i64, delta: i128, tz: Tz) -> Option<i64>;
+ fn sub_day_time(timestamp: i64, delta: IntervalDayTime, tz: Tz) -> Option<i64>;
+ fn sub_month_day_nano(timestamp: i64, delta: IntervalMonthDayNano, tz: Tz) -> Option<i64>;
}
macro_rules! timestamp {
@@ -360,11 +360,11 @@ macro_rules! timestamp {
Self::add_year_months(left, right, tz)
}
- fn add_day_time(left: i64, right: i64, tz: Tz) -> Option<i64> {
+ fn add_day_time(left: i64, right: IntervalDayTime, tz: Tz) -> Option<i64> {
Self::add_day_time(left, right, tz)
}
- fn add_month_day_nano(left: i64, right: i128, tz: Tz) -> Option<i64> {
+ fn add_month_day_nano(left: i64, right: IntervalMonthDayNano, tz: Tz) -> Option<i64> {
Self::add_month_day_nano(left, right, tz)
}
@@ -372,11 +372,11 @@ macro_rules! timestamp {
Self::subtract_year_months(left, right, tz)
}
- fn sub_day_time(left: i64, right: i64, tz: Tz) -> Option<i64> {
+ fn sub_day_time(left: i64, right: IntervalDayTime, tz: Tz) -> Option<i64> {
Self::subtract_day_time(left, right, tz)
}
- fn sub_month_day_nano(left: i64, right: i128, tz: Tz) -> Option<i64> {
+ fn sub_month_day_nano(left: i64, right: IntervalMonthDayNano, tz: Tz) -> Option<i64> {
Self::subtract_month_day_nano(left, right, tz)
}
}
@@ -506,12 +506,12 @@ fn timestamp_op<T: TimestampOp>(
/// Note: these should be fallible (#4456)
trait DateOp: ArrowTemporalType {
fn add_year_month(timestamp: Self::Native, delta: i32) -> Self::Native;
- fn add_day_time(timestamp: Self::Native, delta: i64) -> Self::Native;
- fn add_month_day_nano(timestamp: Self::Native, delta: i128) -> Self::Native;
+ fn add_day_time(timestamp: Self::Native, delta: IntervalDayTime) -> Self::Native;
+ fn add_month_day_nano(timestamp: Self::Native, delta: IntervalMonthDayNano) -> Self::Native;
fn sub_year_month(timestamp: Self::Native, delta: i32) -> Self::Native;
- fn sub_day_time(timestamp: Self::Native, delta: i64) -> Self::Native;
- fn sub_month_day_nano(timestamp: Self::Native, delta: i128) -> Self::Native;
+ fn sub_day_time(timestamp: Self::Native, delta: IntervalDayTime) -> Self::Native;
+ fn sub_month_day_nano(timestamp: Self::Native, delta: IntervalMonthDayNano) -> Self::Native;
}
macro_rules! date {
@@ -521,11 +521,11 @@ macro_rules! date {
Self::add_year_months(left, right)
}
- fn add_day_time(left: Self::Native, right: i64) -> Self::Native {
+ fn add_day_time(left: Self::Native, right: IntervalDayTime) -> Self::Native {
Self::add_day_time(left, right)
}
- fn add_month_day_nano(left: Self::Native, right: i128) -> Self::Native {
+ fn add_month_day_nano(left: Self::Native, right: IntervalMonthDayNano) -> Self::Native {
Self::add_month_day_nano(left, right)
}
@@ -533,11 +533,11 @@ macro_rules! date {
Self::subtract_year_months(left, right)
}
- fn sub_day_time(left: Self::Native, right: i64) -> Self::Native {
+ fn sub_day_time(left: Self::Native, right: IntervalDayTime) -> Self::Native {
Self::subtract_day_time(left, right)
}
- fn sub_month_day_nano(left: Self::Native, right: i128) -> Self::Native {
+ fn sub_month_day_nano(left: Self::Native, right: IntervalMonthDayNano) -> Self::Native {
Self::subtract_month_day_nano(left, right)
}
}
@@ -1346,13 +1346,10 @@ mod tests {
IntervalMonthDayNanoType::make_value(35, -19, 41899000000000000)
])
);
- let a = IntervalMonthDayNanoArray::from(vec![i64::MAX as i128]);
- let b = IntervalMonthDayNanoArray::from(vec![1]);
+ let a = IntervalMonthDayNanoArray::from(vec![IntervalMonthDayNano::MAX]);
+ let b = IntervalMonthDayNanoArray::from(vec![IntervalMonthDayNano::ONE]);
let err = add(&a, &b).unwrap_err().to_string();
- assert_eq!(
- err,
- "Compute error: Overflow happened on: 9223372036854775807 + 1"
- );
+ assert_eq!(err, "Compute error: Overflow happened on: 2147483647 + 1");
}
fn test_duration_impl<T: ArrowPrimitiveType<Native = i64>>() {
diff --git a/arrow-array/src/arithmetic.rs b/arrow-array/src/arithmetic.rs
index 590536190309..72989ad7d5ef 100644
--- a/arrow-array/src/arithmetic.rs
+++ b/arrow-array/src/arithmetic.rs
@@ -15,7 +15,7 @@
// specific language governing permissions and limitations
// under the License.
-use arrow_buffer::{i256, ArrowNativeType};
+use arrow_buffer::{i256, ArrowNativeType, IntervalDayTime, IntervalMonthDayNano};
use arrow_schema::ArrowError;
use half::f16;
use num::complex::ComplexFloat;
@@ -139,7 +139,10 @@ pub trait ArrowNativeTypeOp: ArrowNativeType {
macro_rules! native_type_op {
($t:tt) => {
- native_type_op!($t, 0, 1, $t::MIN, $t::MAX);
+ native_type_op!($t, 0, 1);
+ };
+ ($t:tt, $zero:expr, $one: expr) => {
+ native_type_op!($t, $zero, $one, $t::MIN, $t::MAX);
};
($t:tt, $zero:expr, $one: expr, $min: expr, $max: expr) => {
impl ArrowNativeTypeOp for $t {
@@ -284,6 +287,13 @@ native_type_op!(u32);
native_type_op!(u64);
native_type_op!(i256, i256::ZERO, i256::ONE, i256::MIN, i256::MAX);
+native_type_op!(IntervalDayTime, IntervalDayTime::ZERO, IntervalDayTime::ONE);
+native_type_op!(
+ IntervalMonthDayNano,
+ IntervalMonthDayNano::ZERO,
+ IntervalMonthDayNano::ONE
+);
+
macro_rules! native_type_float_op {
($t:tt, $zero:expr, $one:expr, $min:expr, $max:expr) => {
impl ArrowNativeTypeOp for $t {
diff --git a/arrow-array/src/array/dictionary_array.rs b/arrow-array/src/array/dictionary_array.rs
index 763e340b792b..045917a1bfb8 100644
--- a/arrow-array/src/array/dictionary_array.rs
+++ b/arrow-array/src/array/dictionary_array.rs
@@ -946,7 +946,7 @@ where
/// return Ok(d.with_values(r));
/// }
/// downcast_primitive_array! {
-/// a => Ok(Arc::new(a.iter().map(|x| x.map(|x| x.to_string())).collect::<StringArray>())),
+/// a => Ok(Arc::new(a.iter().map(|x| x.map(|x| format!("{x:?}"))).collect::<StringArray>())),
/// d => Err(ArrowError::InvalidArgumentError(format!("{d:?} not supported")))
/// }
/// }
diff --git a/arrow-array/src/array/primitive_array.rs b/arrow-array/src/array/primitive_array.rs
index 924cab1ac839..919a1010116b 100644
--- a/arrow-array/src/array/primitive_array.rs
+++ b/arrow-array/src/array/primitive_array.rs
@@ -1502,6 +1502,7 @@ mod tests {
use crate::builder::{Decimal128Builder, Decimal256Builder};
use crate::cast::downcast_array;
use crate::BooleanArray;
+ use arrow_buffer::{IntervalDayTime, IntervalMonthDayNano};
use arrow_schema::TimeUnit;
#[test]
@@ -1624,33 +1625,46 @@ mod tests {
assert_eq!(-5, arr.value(2));
assert_eq!(-5, arr.values()[2]);
- // a day_time interval contains days and milliseconds, but we do not yet have accessors for the values
- let arr = IntervalDayTimeArray::from(vec![Some(1), None, Some(-5)]);
+ let v0 = IntervalDayTime {
+ days: 34,
+ milliseconds: 1,
+ };
+ let v2 = IntervalDayTime {
+ days: -2,
+ milliseconds: -5,
+ };
+
+ let arr = IntervalDayTimeArray::from(vec![Some(v0), None, Some(v2)]);
+
assert_eq!(3, arr.len());
assert_eq!(0, arr.offset());
assert_eq!(1, arr.null_count());
- assert_eq!(1, arr.value(0));
- assert_eq!(1, arr.values()[0]);
+ assert_eq!(v0, arr.value(0));
+ assert_eq!(v0, arr.values()[0]);
assert!(arr.is_null(1));
- assert_eq!(-5, arr.value(2));
- assert_eq!(-5, arr.values()[2]);
+ assert_eq!(v2, arr.value(2));
+ assert_eq!(v2, arr.values()[2]);
- // a month_day_nano interval contains months, days and nanoseconds,
- // but we do not yet have accessors for the values.
- // TODO: implement month, day, and nanos access method for month_day_nano.
- let arr = IntervalMonthDayNanoArray::from(vec![
- Some(100000000000000000000),
- None,
- Some(-500000000000000000000),
- ]);
+ let v0 = IntervalMonthDayNano {
+ months: 2,
+ days: 34,
+ nanoseconds: -1,
+ };
+ let v2 = IntervalMonthDayNano {
+ months: -3,
+ days: -2,
+ nanoseconds: 4,
+ };
+
+ let arr = IntervalMonthDayNanoArray::from(vec![Some(v0), None, Some(v2)]);
assert_eq!(3, arr.len());
assert_eq!(0, arr.offset());
assert_eq!(1, arr.null_count());
- assert_eq!(100000000000000000000, arr.value(0));
- assert_eq!(100000000000000000000, arr.values()[0]);
+ assert_eq!(v0, arr.value(0));
+ assert_eq!(v0, arr.values()[0]);
assert!(arr.is_null(1));
- assert_eq!(-500000000000000000000, arr.value(2));
- assert_eq!(-500000000000000000000, arr.values()[2]);
+ assert_eq!(v2, arr.value(2));
+ assert_eq!(v2, arr.values()[2]);
}
#[test]
@@ -2460,7 +2474,7 @@ mod tests {
expected = "PrimitiveArray expected data type Interval(MonthDayNano) got Interval(DayTime)"
)]
fn test_invalid_interval_type() {
- let array = IntervalDayTimeArray::from(vec![1, 2, 3]);
+ let array = IntervalDayTimeArray::from(vec![IntervalDayTime::ZERO]);
let _ = IntervalMonthDayNanoArray::from(array.into_data());
}
diff --git a/arrow-array/src/types.rs b/arrow-array/src/types.rs
index 038b2a291f58..198a11cb6974 100644
--- a/arrow-array/src/types.rs
+++ b/arrow-array/src/types.rs
@@ -23,7 +23,7 @@ use crate::delta::{
use crate::temporal_conversions::as_datetime_with_timezone;
use crate::timezone::Tz;
use crate::{ArrowNativeTypeOp, OffsetSizeTrait};
-use arrow_buffer::{i256, Buffer, OffsetBuffer};
+use arrow_buffer::{i256, Buffer, IntervalDayTime, IntervalMonthDayNano, OffsetBuffer};
use arrow_data::decimal::{validate_decimal256_precision, validate_decimal_precision};
use arrow_data::{validate_binary_view, validate_string_view};
use arrow_schema::{
@@ -220,7 +220,7 @@ make_type!(
);
make_type!(
IntervalDayTimeType,
- i64,
+ IntervalDayTime,
DataType::Interval(IntervalUnit::DayTime),
r#"A “calendar” interval type in days and milliseconds.
@@ -247,7 +247,7 @@ which can lead to surprising results. Please see the description of ordering on
);
make_type!(
IntervalMonthDayNanoType,
- i128,
+ IntervalMonthDayNano,
DataType::Interval(IntervalUnit::MonthDayNano),
r#"A “calendar” interval type in months, days, and nanoseconds.
@@ -264,11 +264,11 @@ Each field is independent (e.g. there is no constraint that the quantity of
nanoseconds represents less than a day's worth of time).
```text
-┌──────────────────────────────┬─────────────┬──────────────┐
-│ Nanos │ Days │ Months │
-│ (64 bits) │ (32 bits) │ (32 bits) │
-└──────────────────────────────┴─────────────┴──────────────┘
- 0 63 95 127 bit offset
+┌───────────────┬─────────────┬─────────────────────────────┐
+│ Months │ Days │ Nanos │
+│ (32 bits) │ (32 bits) │ (64 bits) │
+└───────────────┴─────────────┴─────────────────────────────┘
+ 0 32 64 128 bit offset
```
Please see the [Arrow Spec](https://github.com/apache/arrow/blob/081b4022fe6f659d8765efc82b3f4787c5039e3c/format/Schema.fbs#L409-L415) for more details
@@ -917,25 +917,8 @@ impl IntervalDayTimeType {
/// * `days` - The number of days (+/-) represented in this interval
/// * `millis` - The number of milliseconds (+/-) represented in this interval
#[inline]
- pub fn make_value(
- days: i32,
- millis: i32,
- ) -> <IntervalDayTimeType as ArrowPrimitiveType>::Native {
- /*
- https://github.com/apache/arrow/blob/02c8598d264c839a5b5cf3109bfd406f3b8a6ba5/cpp/src/arrow/type.h#L1433
- struct DayMilliseconds {
- int32_t days = 0;
- int32_t milliseconds = 0;
- ...
- }
- 64 56 48 40 32 24 16 8 0
- +-------+-------+-------+-------+-------+-------+-------+-------+
- | days | milliseconds |
- +-------+-------+-------+-------+-------+-------+-------+-------+
- */
- let m = millis as u64 & u32::MAX as u64;
- let d = (days as u64 & u32::MAX as u64) << 32;
- (m | d) as <IntervalDayTimeType as ArrowPrimitiveType>::Native
+ pub fn make_value(days: i32, milliseconds: i32) -> IntervalDayTime {
+ IntervalDayTime { days, milliseconds }
}
/// Turns a IntervalDayTimeType into a tuple of (days, milliseconds)
@@ -944,10 +927,8 @@ impl IntervalDayTimeType {
///
/// * `i` - The IntervalDayTimeType to convert
#[inline]
- pub fn to_parts(i: <IntervalDayTimeType as ArrowPrimitiveType>::Native) -> (i32, i32) {
- let days = (i >> 32) as i32;
- let ms = i as i32;
- (days, ms)
+ pub fn to_parts(i: IntervalDayTime) -> (i32, i32) {
+ (i.days, i.milliseconds)
}
}
@@ -960,27 +941,12 @@ impl IntervalMonthDayNanoType {
/// * `days` - The number of days (+/-) represented in this interval
/// * `nanos` - The number of nanoseconds (+/-) represented in this interval
#[inline]
- pub fn make_value(
- months: i32,
- days: i32,
- nanos: i64,
- ) -> <IntervalMonthDayNanoType as ArrowPrimitiveType>::Native {
- /*
- https://github.com/apache/arrow/blob/02c8598d264c839a5b5cf3109bfd406f3b8a6ba5/cpp/src/arrow/type.h#L1475
- struct MonthDayNanos {
- int32_t months;
- int32_t days;
- int64_t nanoseconds;
+ pub fn make_value(months: i32, days: i32, nanoseconds: i64) -> IntervalMonthDayNano {
+ IntervalMonthDayNano {
+ months,
+ days,
+ nanoseconds,
}
- 128 112 96 80 64 48 32 16 0
- +-------+-------+-------+-------+-------+-------+-------+-------+
- | months | days | nanos |
- +-------+-------+-------+-------+-------+-------+-------+-------+
- */
- let m = (months as u128 & u32::MAX as u128) << 96;
- let d = (days as u128 & u32::MAX as u128) << 64;
- let n = nanos as u128 & u64::MAX as u128;
- (m | d | n) as <IntervalMonthDayNanoType as ArrowPrimitiveType>::Native
}
/// Turns a IntervalMonthDayNanoType into a tuple of (months, days, nanos)
@@ -989,13 +955,8 @@ impl IntervalMonthDayNanoType {
///
/// * `i` - The IntervalMonthDayNanoType to convert
#[inline]
- pub fn to_parts(
- i: <IntervalMonthDayNanoType as ArrowPrimitiveType>::Native,
- ) -> (i32, i32, i64) {
- let months = (i >> 96) as i32;
- let days = (i >> 64) as i32;
- let nanos = i as i64;
- (months, days, nanos)
+ pub fn to_parts(i: IntervalMonthDayNano) -> (i32, i32, i64) {
+ (i.months, i.days, i.nanoseconds)
}
}
diff --git a/arrow-buffer/src/arith.rs b/arrow-buffer/src/arith.rs
new file mode 100644
index 000000000000..ca693c3607dc
--- /dev/null
+++ b/arrow-buffer/src/arith.rs
@@ -0,0 +1,63 @@
+// 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.
+
+/// Derives `std::ops::$op` for `$ty` calling `$wrapping` or `$checked` variants
+/// based on if debug_assertions enabled
+macro_rules! derive_arith {
+ ($ty:ty, $t:ident, $op:ident, $wrapping:ident, $checked:ident) => {
+ impl std::ops::$t for $ty {
+ type Output = $ty;
+
+ #[cfg(debug_assertions)]
+ fn $op(self, rhs: Self) -> Self::Output {
+ self.$checked(rhs)
+ .expect(concat!(stringify!($ty), " overflow"))
+ }
+
+ #[cfg(not(debug_assertions))]
+ fn $op(self, rhs: Self) -> Self::Output {
+ self.$wrapping(rhs)
+ }
+ }
+
+ impl<'a> std::ops::$t<$ty> for &'a $ty {
+ type Output = $ty;
+
+ fn $op(self, rhs: $ty) -> Self::Output {
+ (*self).$op(rhs)
+ }
+ }
+
+ impl<'a> std::ops::$t<&'a $ty> for $ty {
+ type Output = $ty;
+
+ fn $op(self, rhs: &'a $ty) -> Self::Output {
+ self.$op(*rhs)
+ }
+ }
+
+ impl<'a, 'b> std::ops::$t<&'b $ty> for &'a $ty {
+ type Output = $ty;
+
+ fn $op(self, rhs: &'b $ty) -> Self::Output {
+ (*self).$op(*rhs)
+ }
+ }
+ };
+}
+
+pub(crate) use derive_arith;
diff --git a/arrow-buffer/src/bigint/mod.rs b/arrow-buffer/src/bigint/mod.rs
index a8aaff13cd27..bbe65b073aa6 100644
--- a/arrow-buffer/src/bigint/mod.rs
+++ b/arrow-buffer/src/bigint/mod.rs
@@ -15,6 +15,7 @@
// specific language governing permissions and limitations
// under the License.
+use crate::arith::derive_arith;
use crate::bigint::div::div_rem;
use num::cast::AsPrimitive;
use num::{BigInt, FromPrimitive, ToPrimitive};
@@ -638,55 +639,13 @@ fn mulx(a: u128, b: u128) -> (u128, u128) {
(low, high)
}
-macro_rules! derive_op {
- ($t:ident, $op:ident, $wrapping:ident, $checked:ident) => {
- impl std::ops::$t for i256 {
- type Output = i256;
+derive_arith!(i256, Add, add, wrapping_add, checked_add);
+derive_arith!(i256, Sub, sub, wrapping_sub, checked_sub);
+derive_arith!(i256, Mul, mul, wrapping_mul, checked_mul);
+derive_arith!(i256, Div, div, wrapping_div, checked_div);
+derive_arith!(i256, Rem, rem, wrapping_rem, checked_rem);
- #[cfg(debug_assertions)]
- fn $op(self, rhs: Self) -> Self::Output {
- self.$checked(rhs).expect("i256 overflow")
- }
-
- #[cfg(not(debug_assertions))]
- fn $op(self, rhs: Self) -> Self::Output {
- self.$wrapping(rhs)
- }
- }
-
- impl<'a> std::ops::$t<i256> for &'a i256 {
- type Output = i256;
-
- fn $op(self, rhs: i256) -> Self::Output {
- (*self).$op(rhs)
- }
- }
-
- impl<'a> std::ops::$t<&'a i256> for i256 {
- type Output = i256;
-
- fn $op(self, rhs: &'a i256) -> Self::Output {
- self.$op(*rhs)
- }
- }
-
- impl<'a, 'b> std::ops::$t<&'b i256> for &'a i256 {
- type Output = i256;
-
- fn $op(self, rhs: &'b i256) -> Self::Output {
- (*self).$op(*rhs)
- }
- }
- };
-}
-
-derive_op!(Add, add, wrapping_add, checked_add);
-derive_op!(Sub, sub, wrapping_sub, checked_sub);
-derive_op!(Mul, mul, wrapping_mul, checked_mul);
-derive_op!(Div, div, wrapping_div, checked_div);
-derive_op!(Rem, rem, wrapping_rem, checked_rem);
-
-impl std::ops::Neg for i256 {
+impl Neg for i256 {
type Output = i256;
#[cfg(debug_assertions)]
diff --git a/arrow-buffer/src/interval.rs b/arrow-buffer/src/interval.rs
new file mode 100644
index 000000000000..7e8043e9a724
--- /dev/null
+++ b/arrow-buffer/src/interval.rs
@@ -0,0 +1,424 @@
+// 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.
+
+use crate::arith::derive_arith;
+use std::ops::Neg;
+
+/// Value of an IntervalMonthDayNano array
+#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
+#[repr(C)]
+pub struct IntervalMonthDayNano {
+ pub months: i32,
+ pub days: i32,
+ pub nanoseconds: i64,
+}
+
+impl IntervalMonthDayNano {
+ /// The additive identity i.e. `0`.
+ pub const ZERO: Self = Self::new(0, 0, 0);
+
+ /// The multiplicative identity, i.e. `1`.
+ pub const ONE: Self = Self::new(1, 1, 1);
+
+ /// The multiplicative inverse, i.e. `-1`.
+ pub const MINUS_ONE: Self = Self::new(-1, -1, -1);
+
+ /// The maximum value that can be represented
+ pub const MAX: Self = Self::new(i32::MAX, i32::MAX, i64::MAX);
+
+ /// The minimum value that can be represented
+ pub const MIN: Self = Self::new(i32::MIN, i32::MIN, i64::MIN);
+
+ /// Create a new [`IntervalMonthDayNano`]
+ #[inline]
+ pub const fn new(months: i32, days: i32, nanoseconds: i64) -> Self {
+ Self {
+ months,
+ days,
+ nanoseconds,
+ }
+ }
+
+ /// Computes the absolute value
+ #[inline]
+ pub fn wrapping_abs(self) -> Self {
+ Self {
+ months: self.months.wrapping_abs(),
+ days: self.days.wrapping_abs(),
+ nanoseconds: self.nanoseconds.wrapping_abs(),
+ }
+ }
+
+ /// Computes the absolute value
+ #[inline]
+ pub fn checked_abs(self) -> Option<Self> {
+ Some(Self {
+ months: self.months.checked_abs()?,
+ days: self.days.checked_abs()?,
+ nanoseconds: self.nanoseconds.checked_abs()?,
+ })
+ }
+
+ /// Negates the value
+ #[inline]
+ pub fn wrapping_neg(self) -> Self {
+ Self {
+ months: self.months.wrapping_neg(),
+ days: self.days.wrapping_neg(),
+ nanoseconds: self.nanoseconds.wrapping_neg(),
+ }
+ }
+
+ /// Negates the value
+ #[inline]
+ pub fn checked_neg(self) -> Option<Self> {
+ Some(Self {
+ months: self.months.checked_neg()?,
+ days: self.days.checked_neg()?,
+ nanoseconds: self.nanoseconds.checked_neg()?,
+ })
+ }
+
+ /// Performs wrapping addition
+ #[inline]
+ pub fn wrapping_add(self, other: Self) -> Self {
+ Self {
+ months: self.months.wrapping_add(other.months),
+ days: self.days.wrapping_add(other.days),
+ nanoseconds: self.nanoseconds.wrapping_add(other.nanoseconds),
+ }
+ }
+
+ /// Performs checked addition
+ #[inline]
+ pub fn checked_add(self, other: Self) -> Option<Self> {
+ Some(Self {
+ months: self.months.checked_add(other.months)?,
+ days: self.days.checked_add(other.days)?,
+ nanoseconds: self.nanoseconds.checked_add(other.nanoseconds)?,
+ })
+ }
+
+ /// Performs wrapping subtraction
+ #[inline]
+ pub fn wrapping_sub(self, other: Self) -> Self {
+ Self {
+ months: self.months.wrapping_sub(other.months),
+ days: self.days.wrapping_sub(other.days),
+ nanoseconds: self.nanoseconds.wrapping_sub(other.nanoseconds),
+ }
+ }
+
+ /// Performs checked subtraction
+ #[inline]
+ pub fn checked_sub(self, other: Self) -> Option<Self> {
+ Some(Self {
+ months: self.months.checked_sub(other.months)?,
+ days: self.days.checked_sub(other.days)?,
+ nanoseconds: self.nanoseconds.checked_sub(other.nanoseconds)?,
+ })
+ }
+
+ /// Performs wrapping multiplication
+ #[inline]
+ pub fn wrapping_mul(self, other: Self) -> Self {
+ Self {
+ months: self.months.wrapping_mul(other.months),
+ days: self.days.wrapping_mul(other.days),
+ nanoseconds: self.nanoseconds.wrapping_mul(other.nanoseconds),
+ }
+ }
+
+ /// Performs checked multiplication
+ pub fn checked_mul(self, other: Self) -> Option<Self> {
+ Some(Self {
+ months: self.months.checked_mul(other.months)?,
+ days: self.days.checked_mul(other.days)?,
+ nanoseconds: self.nanoseconds.checked_mul(other.nanoseconds)?,
+ })
+ }
+
+ /// Performs wrapping division
+ #[inline]
+ pub fn wrapping_div(self, other: Self) -> Self {
+ Self {
+ months: self.months.wrapping_div(other.months),
+ days: self.days.wrapping_div(other.days),
+ nanoseconds: self.nanoseconds.wrapping_div(other.nanoseconds),
+ }
+ }
+
+ /// Performs checked division
+ pub fn checked_div(self, other: Self) -> Option<Self> {
+ Some(Self {
+ months: self.months.checked_div(other.months)?,
+ days: self.days.checked_div(other.days)?,
+ nanoseconds: self.nanoseconds.checked_div(other.nanoseconds)?,
+ })
+ }
+
+ /// Performs wrapping remainder
+ #[inline]
+ pub fn wrapping_rem(self, other: Self) -> Self {
+ Self {
+ months: self.months.wrapping_rem(other.months),
+ days: self.days.wrapping_rem(other.days),
+ nanoseconds: self.nanoseconds.wrapping_rem(other.nanoseconds),
+ }
+ }
+
+ /// Performs checked remainder
+ pub fn checked_rem(self, other: Self) -> Option<Self> {
+ Some(Self {
+ months: self.months.checked_rem(other.months)?,
+ days: self.days.checked_rem(other.days)?,
+ nanoseconds: self.nanoseconds.checked_rem(other.nanoseconds)?,
+ })
+ }
+
+ /// Performs wrapping exponentiation
+ #[inline]
+ pub fn wrapping_pow(self, exp: u32) -> Self {
+ Self {
+ months: self.months.wrapping_pow(exp),
+ days: self.days.wrapping_pow(exp),
+ nanoseconds: self.nanoseconds.wrapping_pow(exp),
+ }
+ }
+
+ /// Performs checked exponentiation
+ #[inline]
+ pub fn checked_pow(self, exp: u32) -> Option<Self> {
+ Some(Self {
+ months: self.months.checked_pow(exp)?,
+ days: self.days.checked_pow(exp)?,
+ nanoseconds: self.nanoseconds.checked_pow(exp)?,
+ })
+ }
+}
+
+impl Neg for IntervalMonthDayNano {
+ type Output = Self;
+
+ #[cfg(debug_assertions)]
+ fn neg(self) -> Self::Output {
+ self.checked_neg().expect("IntervalMonthDayNano overflow")
+ }
+
+ #[cfg(not(debug_assertions))]
+ fn neg(self) -> Self::Output {
+ self.wrapping_neg()
+ }
+}
+
+derive_arith!(IntervalMonthDayNano, Add, add, wrapping_add, checked_add);
+derive_arith!(IntervalMonthDayNano, Sub, sub, wrapping_sub, checked_sub);
+derive_arith!(IntervalMonthDayNano, Mul, mul, wrapping_mul, checked_mul);
+derive_arith!(IntervalMonthDayNano, Div, div, wrapping_div, checked_div);
+derive_arith!(IntervalMonthDayNano, Rem, rem, wrapping_rem, checked_rem);
+
+/// Value of an IntervalDayTime array
+#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
+#[repr(C)]
+pub struct IntervalDayTime {
+ pub days: i32,
+ pub milliseconds: i32,
+}
+
+impl IntervalDayTime {
+ /// The additive identity i.e. `0`.
+ pub const ZERO: Self = Self::new(0, 0);
+
+ /// The multiplicative identity, i.e. `1`.
+ pub const ONE: Self = Self::new(1, 1);
+
+ /// The multiplicative inverse, i.e. `-1`.
+ pub const MINUS_ONE: Self = Self::new(-1, -1);
+
+ /// The maximum value that can be represented
+ pub const MAX: Self = Self::new(i32::MAX, i32::MAX);
+
+ /// The minimum value that can be represented
+ pub const MIN: Self = Self::new(i32::MIN, i32::MIN);
+
+ /// Create a new [`IntervalDayTime`]
+ #[inline]
+ pub const fn new(days: i32, milliseconds: i32) -> Self {
+ Self { days, milliseconds }
+ }
+
+ /// Computes the absolute value
+ #[inline]
+ pub fn wrapping_abs(self) -> Self {
+ Self {
+ days: self.days.wrapping_abs(),
+ milliseconds: self.milliseconds.wrapping_abs(),
+ }
+ }
+
+ /// Computes the absolute value
+ #[inline]
+ pub fn checked_abs(self) -> Option<Self> {
+ Some(Self {
+ days: self.days.checked_abs()?,
+ milliseconds: self.milliseconds.checked_abs()?,
+ })
+ }
+
+ /// Negates the value
+ #[inline]
+ pub fn wrapping_neg(self) -> Self {
+ Self {
+ days: self.days.wrapping_neg(),
+ milliseconds: self.milliseconds.wrapping_neg(),
+ }
+ }
+
+ /// Negates the value
+ #[inline]
+ pub fn checked_neg(self) -> Option<Self> {
+ Some(Self {
+ days: self.days.checked_neg()?,
+ milliseconds: self.milliseconds.checked_neg()?,
+ })
+ }
+
+ /// Performs wrapping addition
+ #[inline]
+ pub fn wrapping_add(self, other: Self) -> Self {
+ Self {
+ days: self.days.wrapping_add(other.days),
+ milliseconds: self.milliseconds.wrapping_add(other.milliseconds),
+ }
+ }
+
+ /// Performs checked addition
+ #[inline]
+ pub fn checked_add(self, other: Self) -> Option<Self> {
+ Some(Self {
+ days: self.days.checked_add(other.days)?,
+ milliseconds: self.milliseconds.checked_add(other.milliseconds)?,
+ })
+ }
+
+ /// Performs wrapping subtraction
+ #[inline]
+ pub fn wrapping_sub(self, other: Self) -> Self {
+ Self {
+ days: self.days.wrapping_sub(other.days),
+ milliseconds: self.milliseconds.wrapping_sub(other.milliseconds),
+ }
+ }
+
+ /// Performs checked subtraction
+ #[inline]
+ pub fn checked_sub(self, other: Self) -> Option<Self> {
+ Some(Self {
+ days: self.days.checked_sub(other.days)?,
+ milliseconds: self.milliseconds.checked_sub(other.milliseconds)?,
+ })
+ }
+
+ /// Performs wrapping multiplication
+ #[inline]
+ pub fn wrapping_mul(self, other: Self) -> Self {
+ Self {
+ days: self.days.wrapping_mul(other.days),
+ milliseconds: self.milliseconds.wrapping_mul(other.milliseconds),
+ }
+ }
+
+ /// Performs checked multiplication
+ pub fn checked_mul(self, other: Self) -> Option<Self> {
+ Some(Self {
+ days: self.days.checked_mul(other.days)?,
+ milliseconds: self.milliseconds.checked_mul(other.milliseconds)?,
+ })
+ }
+
+ /// Performs wrapping division
+ #[inline]
+ pub fn wrapping_div(self, other: Self) -> Self {
+ Self {
+ days: self.days.wrapping_div(other.days),
+ milliseconds: self.milliseconds.wrapping_div(other.milliseconds),
+ }
+ }
+
+ /// Performs checked division
+ pub fn checked_div(self, other: Self) -> Option<Self> {
+ Some(Self {
+ days: self.days.checked_div(other.days)?,
+ milliseconds: self.milliseconds.checked_div(other.milliseconds)?,
+ })
+ }
+
+ /// Performs wrapping remainder
+ #[inline]
+ pub fn wrapping_rem(self, other: Self) -> Self {
+ Self {
+ days: self.days.wrapping_rem(other.days),
+ milliseconds: self.milliseconds.wrapping_rem(other.milliseconds),
+ }
+ }
+
+ /// Performs checked remainder
+ pub fn checked_rem(self, other: Self) -> Option<Self> {
+ Some(Self {
+ days: self.days.checked_rem(other.days)?,
+ milliseconds: self.milliseconds.checked_rem(other.milliseconds)?,
+ })
+ }
+
+ /// Performs wrapping exponentiation
+ #[inline]
+ pub fn wrapping_pow(self, exp: u32) -> Self {
+ Self {
+ days: self.days.wrapping_pow(exp),
+ milliseconds: self.milliseconds.wrapping_pow(exp),
+ }
+ }
+
+ /// Performs checked exponentiation
+ #[inline]
+ pub fn checked_pow(self, exp: u32) -> Option<Self> {
+ Some(Self {
+ days: self.days.checked_pow(exp)?,
+ milliseconds: self.milliseconds.checked_pow(exp)?,
+ })
+ }
+}
+
+impl Neg for IntervalDayTime {
+ type Output = Self;
+
+ #[cfg(debug_assertions)]
+ fn neg(self) -> Self::Output {
+ self.checked_neg().expect("IntervalDayMillisecond overflow")
+ }
+
+ #[cfg(not(debug_assertions))]
+ fn neg(self) -> Self::Output {
+ self.wrapping_neg()
+ }
+}
+
+derive_arith!(IntervalDayTime, Add, add, wrapping_add, checked_add);
+derive_arith!(IntervalDayTime, Sub, sub, wrapping_sub, checked_sub);
+derive_arith!(IntervalDayTime, Mul, mul, wrapping_mul, checked_mul);
+derive_arith!(IntervalDayTime, Div, div, wrapping_div, checked_div);
+derive_arith!(IntervalDayTime, Rem, rem, wrapping_rem, checked_rem);
diff --git a/arrow-buffer/src/lib.rs b/arrow-buffer/src/lib.rs
index 612897af9bed..a7bf93ed0c16 100644
--- a/arrow-buffer/src/lib.rs
+++ b/arrow-buffer/src/lib.rs
@@ -28,10 +28,17 @@ pub mod builder;
pub use builder::*;
mod bigint;
-mod bytes;
-mod native;
pub use bigint::i256;
+mod bytes;
+
+mod native;
pub use native::*;
+
mod util;
pub use util::*;
+
+mod interval;
+pub use interval::*;
+
+mod arith;
diff --git a/arrow-buffer/src/native.rs b/arrow-buffer/src/native.rs
index de665d4e3874..e05c1311ff3c 100644
--- a/arrow-buffer/src/native.rs
+++ b/arrow-buffer/src/native.rs
@@ -15,7 +15,7 @@
// specific language governing permissions and limitations
// under the License.
-use crate::i256;
+use crate::{i256, IntervalDayTime, IntervalMonthDayNano};
use half::f16;
mod private {
@@ -239,6 +239,60 @@ impl ArrowNativeType for i256 {
}
}
+impl private::Sealed for IntervalMonthDayNano {}
+impl ArrowNativeType for IntervalMonthDayNano {
+ fn from_usize(_: usize) -> Option<Self> {
+ None
+ }
+
+ fn as_usize(self) -> usize {
+ ((self.months as u64) | ((self.days as u64) << 32)) as usize
+ }
+
+ fn usize_as(i: usize) -> Self {
+ Self::new(i as _, ((i as u64) >> 32) as _, 0)
+ }
+
+ fn to_usize(self) -> Option<usize> {
+ None
+ }
+
+ fn to_isize(self) -> Option<isize> {
+ None
+ }
+
+ fn to_i64(self) -> Option<i64> {
+ None
+ }
+}
+
+impl private::Sealed for IntervalDayTime {}
+impl ArrowNativeType for IntervalDayTime {
+ fn from_usize(_: usize) -> Option<Self> {
+ None
+ }
+
+ fn as_usize(self) -> usize {
+ ((self.days as u64) | ((self.milliseconds as u64) << 32)) as usize
+ }
+
+ fn usize_as(i: usize) -> Self {
+ Self::new(i as _, ((i as u64) >> 32) as _)
+ }
+
+ fn to_usize(self) -> Option<usize> {
+ None
+ }
+
+ fn to_isize(self) -> Option<isize> {
+ None
+ }
+
+ fn to_i64(self) -> Option<i64> {
+ None
+ }
+}
+
/// Allows conversion from supported Arrow types to a byte slice.
pub trait ToByteSlice {
/// Converts this instance into a byte slice
@@ -282,4 +336,18 @@ mod tests {
assert!(a.to_usize().is_none());
assert_eq!(a.to_isize().unwrap(), -1);
}
+
+ #[test]
+ fn test_interval_usize() {
+ assert_eq!(IntervalDayTime::new(1, 0).as_usize(), 1);
+ assert_eq!(IntervalMonthDayNano::new(1, 0, 0).as_usize(), 1);
+
+ let a = IntervalDayTime::new(23, 53);
+ let b = IntervalDayTime::usize_as(a.as_usize());
+ assert_eq!(a, b);
+
+ let a = IntervalMonthDayNano::new(23, 53, 0);
+ let b = IntervalMonthDayNano::usize_as(a.as_usize());
+ assert_eq!(a, b);
+ }
}
diff --git a/arrow-cast/src/cast/mod.rs b/arrow-cast/src/cast/mod.rs
index 171267f80543..294d7a6e4d31 100644
--- a/arrow-cast/src/cast/mod.rs
+++ b/arrow-cast/src/cast/mod.rs
@@ -46,7 +46,7 @@ use crate::cast::dictionary::*;
use crate::cast::list::*;
use crate::cast::string::*;
-use arrow_buffer::ScalarBuffer;
+use arrow_buffer::{IntervalMonthDayNano, ScalarBuffer};
use arrow_data::ByteView;
use chrono::{NaiveTime, Offset, TimeZone, Utc};
use std::cmp::Ordering;
@@ -275,11 +275,6 @@ pub fn can_cast_types(from_type: &DataType, to_type: &DataType) -> bool {
DayTime => false,
MonthDayNano => false,
},
- (Int64, Interval(to_type)) => match to_type {
- YearMonth => false,
- DayTime => true,
- MonthDayNano => false,
- },
(Duration(_), Interval(MonthDayNano)) => true,
(Interval(MonthDayNano), Duration(_)) => true,
(Interval(YearMonth), Interval(MonthDayNano)) => true,
@@ -392,9 +387,9 @@ fn cast_month_day_nano_to_duration<D: ArrowTemporalType<Native = i64>>(
};
if cast_options.safe {
- let iter = array
- .iter()
- .map(|v| v.and_then(|v| (v >> 64 == 0).then_some((v as i64) / scale)));
+ let iter = array.iter().map(|v| {
+ v.and_then(|v| (v.days == 0 && v.months == 0).then_some(v.nanoseconds / scale))
+ });
Ok(Arc::new(unsafe {
PrimitiveArray::<D>::from_trusted_len_iter(iter)
}))
@@ -402,8 +397,8 @@ fn cast_month_day_nano_to_duration<D: ArrowTemporalType<Native = i64>>(
let vec = array
.iter()
.map(|v| {
- v.map(|v| match v >> 64 {
- 0 => Ok((v as i64) / scale),
+ v.map(|v| match v.days == 0 && v.months == 0 {
+ true => Ok((v.nanoseconds) / scale),
_ => Err(ArrowError::ComputeError(
"Cannot convert interval containing non-zero months or days to duration"
.to_string(),
@@ -442,9 +437,12 @@ fn cast_duration_to_interval<D: ArrowTemporalType<Native = i64>>(
};
if cast_options.safe {
- let iter = array
- .iter()
- .map(|v| v.and_then(|v| v.checked_mul(scale).map(|v| v as i128)));
+ let iter = array.iter().map(|v| {
+ v.and_then(|v| {
+ v.checked_mul(scale)
+ .map(|v| IntervalMonthDayNano::new(0, 0, v))
+ })
+ });
Ok(Arc::new(unsafe {
PrimitiveArray::<IntervalMonthDayNanoType>::from_trusted_len_iter(iter)
}))
@@ -454,7 +452,7 @@ fn cast_duration_to_interval<D: ArrowTemporalType<Native = i64>>(
.map(|v| {
v.map(|v| {
if let Ok(v) = v.mul_checked(scale) {
- Ok(v as i128)
+ Ok(IntervalMonthDayNano::new(0, 0, v))
} else {
Err(ArrowError::ComputeError(format!(
"Cannot cast to {:?}. Overflowing on {:?}",
@@ -1959,18 +1957,9 @@ pub fn cast_with_options(
(Interval(IntervalUnit::DayTime), Interval(IntervalUnit::MonthDayNano)) => {
cast_interval_day_time_to_interval_month_day_nano(array, cast_options)
}
- (Interval(IntervalUnit::YearMonth), Int64) => {
- cast_numeric_arrays::<IntervalYearMonthType, Int64Type>(array, cast_options)
- }
- (Interval(IntervalUnit::DayTime), Int64) => {
- cast_reinterpret_arrays::<IntervalDayTimeType, Int64Type>(array)
- }
(Int32, Interval(IntervalUnit::YearMonth)) => {
cast_reinterpret_arrays::<Int32Type, IntervalYearMonthType>(array)
}
- (Int64, Interval(IntervalUnit::DayTime)) => {
- cast_reinterpret_arrays::<Int64Type, IntervalDayTimeType>(array)
- }
(_, _) => Err(ArrowError::CastError(format!(
"Casting from {from_type:?} to {to_type:?} not supported",
))),
@@ -2335,7 +2324,7 @@ where
#[cfg(test)]
mod tests {
- use arrow_buffer::{Buffer, NullBuffer};
+ use arrow_buffer::{Buffer, IntervalDayTime, NullBuffer};
use chrono::NaiveDate;
use half::f16;
@@ -5059,25 +5048,6 @@ mod tests {
}
}
- #[test]
- fn test_cast_interval_to_i64() {
- let base = vec![5, 6, 7, 8];
-
- let interval_arrays = vec![
- Arc::new(IntervalDayTimeArray::from(base.clone())) as ArrayRef,
- Arc::new(IntervalYearMonthArray::from(
- base.iter().map(|x| *x as i32).collect::<Vec<i32>>(),
- )) as ArrayRef,
- ];
-
- for arr in interval_arrays {
- assert!(can_cast_types(arr.data_type(), &DataType::Int64));
- let result = cast(&arr, &DataType::Int64).unwrap();
- let result = result.as_primitive::<Int64Type>();
- assert_eq!(base.as_slice(), result.values());
- }
- }
-
#[test]
fn test_cast_to_strings() {
let a = Int32Array::from(vec![1, 2, 3]);
@@ -8379,7 +8349,10 @@ mod tests {
casted_array.data_type(),
&DataType::Interval(IntervalUnit::MonthDayNano)
);
- assert_eq!(casted_array.value(0), 1234567000000000);
+ assert_eq!(
+ casted_array.value(0),
+ IntervalMonthDayNano::new(0, 0, 1234567000000000)
+ );
let array = vec![i64::MAX];
let casted_array = cast_from_duration_to_interval::<DurationSecondType>(
@@ -8409,7 +8382,10 @@ mod tests {
casted_array.data_type(),
&DataType::Interval(IntervalUnit::MonthDayNano)
);
- assert_eq!(casted_array.value(0), 1234567000000);
+ assert_eq!(
+ casted_array.value(0),
+ IntervalMonthDayNano::new(0, 0, 1234567000000)
+ );
let array = vec![i64::MAX];
let casted_array = cast_from_duration_to_interval::<DurationMillisecondType>(
@@ -8439,7 +8415,10 @@ mod tests {
casted_array.data_type(),
&DataType::Interval(IntervalUnit::MonthDayNano)
);
- assert_eq!(casted_array.value(0), 1234567000);
+ assert_eq!(
+ casted_array.value(0),
+ IntervalMonthDayNano::new(0, 0, 1234567000)
+ );
let array = vec![i64::MAX];
let casted_array = cast_from_duration_to_interval::<DurationMicrosecondType>(
@@ -8469,7 +8448,10 @@ mod tests {
casted_array.data_type(),
&DataType::Interval(IntervalUnit::MonthDayNano)
);
- assert_eq!(casted_array.value(0), 1234567);
+ assert_eq!(
+ casted_array.value(0),
+ IntervalMonthDayNano::new(0, 0, 1234567)
+ );
let array = vec![i64::MAX];
let casted_array = cast_from_duration_to_interval::<DurationNanosecondType>(
@@ -8480,7 +8462,10 @@ mod tests {
},
)
.unwrap();
- assert_eq!(casted_array.value(0), 9223372036854775807);
+ assert_eq!(
+ casted_array.value(0),
+ IntervalMonthDayNano::new(0, 0, i64::MAX)
+ );
}
/// helper function to test casting from interval to duration
@@ -8505,14 +8490,15 @@ mod tests {
safe: false,
format_options: FormatOptions::default(),
};
+ let v = IntervalMonthDayNano::new(0, 0, 1234567);
// from interval month day nano to duration second
- let array = vec![1234567].into();
+ let array = vec![v].into();
let casted_array: DurationSecondArray =
cast_from_interval_to_duration(&array, &nullable).unwrap();
assert_eq!(casted_array.value(0), 0);
- let array = vec![i128::MAX].into();
+ let array = vec![IntervalMonthDayNano::MAX].into();
let casted_array: DurationSecondArray =
cast_from_interval_to_duration(&array, &nullable).unwrap();
assert!(!casted_array.is_valid(0));
@@ -8521,12 +8507,12 @@ mod tests {
assert!(res.is_err());
// from interval month day nano to duration millisecond
- let array = vec![1234567].into();
+ let array = vec![v].into();
let casted_array: DurationMillisecondArray =
cast_from_interval_to_duration(&array, &nullable).unwrap();
assert_eq!(casted_array.value(0), 1);
- let array = vec![i128::MAX].into();
+ let array = vec![IntervalMonthDayNano::MAX].into();
let casted_array: DurationMillisecondArray =
cast_from_interval_to_duration(&array, &nullable).unwrap();
assert!(!casted_array.is_valid(0));
@@ -8535,12 +8521,12 @@ mod tests {
assert!(res.is_err());
// from interval month day nano to duration microsecond
- let array = vec![1234567].into();
+ let array = vec![v].into();
let casted_array: DurationMicrosecondArray =
cast_from_interval_to_duration(&array, &nullable).unwrap();
assert_eq!(casted_array.value(0), 1234);
- let array = vec![i128::MAX].into();
+ let array = vec![IntervalMonthDayNano::MAX].into();
let casted_array =
cast_from_interval_to_duration::<DurationMicrosecondType>(&array, &nullable).unwrap();
assert!(!casted_array.is_valid(0));
@@ -8550,12 +8536,12 @@ mod tests {
assert!(casted_array.is_err());
// from interval month day nano to duration nanosecond
- let array = vec![1234567].into();
+ let array = vec![v].into();
let casted_array: DurationNanosecondArray =
cast_from_interval_to_duration(&array, &nullable).unwrap();
assert_eq!(casted_array.value(0), 1234567);
- let array = vec![i128::MAX].into();
+ let array = vec![IntervalMonthDayNano::MAX].into();
let casted_array: DurationNanosecondArray =
cast_from_interval_to_duration(&array, &nullable).unwrap();
assert!(!casted_array.is_valid(0));
@@ -8618,12 +8604,15 @@ mod tests {
casted_array.data_type(),
&DataType::Interval(IntervalUnit::MonthDayNano)
);
- assert_eq!(casted_array.value(0), 97812474910747780469848774134464512);
+ assert_eq!(
+ casted_array.value(0),
+ IntervalMonthDayNano::new(1234567, 0, 0)
+ );
}
/// helper function to test casting from interval day time to interval month day nano
fn cast_from_interval_day_time_to_interval_month_day_nano(
- array: Vec<i64>,
+ array: Vec<IntervalDayTime>,
cast_options: &CastOptions,
) -> Result<PrimitiveArray<IntervalMonthDayNanoType>, ArrowError> {
let array = PrimitiveArray::<IntervalDayTimeType>::from(array);
@@ -8641,7 +8630,7 @@ mod tests {
#[test]
fn test_cast_from_interval_day_time_to_interval_month_day_nano() {
// from interval day time to interval month day nano
- let array = vec![123];
+ let array = vec![IntervalDayTime::new(123, 0)];
let casted_array =
cast_from_interval_day_time_to_interval_month_day_nano(array, &CastOptions::default())
.unwrap();
@@ -8649,7 +8638,7 @@ mod tests {
casted_array.data_type(),
&DataType::Interval(IntervalUnit::MonthDayNano)
);
- assert_eq!(casted_array.value(0), 123000000);
+ assert_eq!(casted_array.value(0), IntervalMonthDayNano::new(0, 123, 0));
}
#[test]
diff --git a/arrow-cast/src/display.rs b/arrow-cast/src/display.rs
index a5f69b660944..edde288e9c35 100644
--- a/arrow-cast/src/display.rs
+++ b/arrow-cast/src/display.rs
@@ -660,19 +660,16 @@ impl<'a> DisplayIndex for &'a PrimitiveArray<IntervalYearMonthType> {
impl<'a> DisplayIndex for &'a PrimitiveArray<IntervalDayTimeType> {
fn write(&self, idx: usize, f: &mut dyn Write) -> FormatResult {
- let value: u64 = self.value(idx) as u64;
+ let value = self.value(idx);
- let days_parts: i32 = ((value & 0xFFFFFFFF00000000) >> 32) as i32;
- let milliseconds_part: i32 = (value & 0xFFFFFFFF) as i32;
-
- let secs = milliseconds_part / 1_000;
+ let secs = value.milliseconds / 1_000;
let mins = secs / 60;
let hours = mins / 60;
let secs = secs - (mins * 60);
let mins = mins - (hours * 60);
- let milliseconds = milliseconds_part % 1_000;
+ let milliseconds = value.milliseconds % 1_000;
let secs_sign = if secs < 0 || milliseconds < 0 {
"-"
@@ -683,7 +680,7 @@ impl<'a> DisplayIndex for &'a PrimitiveArray<IntervalDayTimeType> {
write!(
f,
"0 years 0 mons {} days {} hours {} mins {}{}.{:03} secs",
- days_parts,
+ value.days,
hours,
mins,
secs_sign,
@@ -696,28 +693,24 @@ impl<'a> DisplayIndex for &'a PrimitiveArray<IntervalDayTimeType> {
impl<'a> DisplayIndex for &'a PrimitiveArray<IntervalMonthDayNanoType> {
fn write(&self, idx: usize, f: &mut dyn Write) -> FormatResult {
- let value: u128 = self.value(idx) as u128;
-
- let months_part: i32 = ((value & 0xFFFFFFFF000000000000000000000000) >> 96) as i32;
- let days_part: i32 = ((value & 0xFFFFFFFF0000000000000000) >> 64) as i32;
- let nanoseconds_part: i64 = (value & 0xFFFFFFFFFFFFFFFF) as i64;
+ let value = self.value(idx);
- let secs = nanoseconds_part / 1_000_000_000;
+ let secs = value.nanoseconds / 1_000_000_000;
let mins = secs / 60;
let hours = mins / 60;
let secs = secs - (mins * 60);
let mins = mins - (hours * 60);
- let nanoseconds = nanoseconds_part % 1_000_000_000;
+ let nanoseconds = value.nanoseconds % 1_000_000_000;
let secs_sign = if secs < 0 || nanoseconds < 0 { "-" } else { "" };
write!(
f,
"0 years {} mons {} days {} hours {} mins {}{}.{:09} secs",
- months_part,
- days_part,
+ value.months,
+ value.days,
hours,
mins,
secs_sign,
diff --git a/arrow-cast/src/pretty.rs b/arrow-cast/src/pretty.rs
index 00bba928114f..49fb359b9d42 100644
--- a/arrow-cast/src/pretty.rs
+++ b/arrow-cast/src/pretty.rs
@@ -142,7 +142,7 @@ mod tests {
use arrow_array::builder::*;
use arrow_array::types::*;
use arrow_array::*;
- use arrow_buffer::ScalarBuffer;
+ use arrow_buffer::{IntervalDayTime, IntervalMonthDayNano, ScalarBuffer};
use arrow_schema::*;
use crate::display::array_value_to_string;
@@ -963,12 +963,12 @@ mod tests {
#[test]
fn test_pretty_format_interval_day_time() {
let arr = Arc::new(arrow_array::IntervalDayTimeArray::from(vec![
- Some(-600000),
- Some(4294966295),
- Some(4294967295),
- Some(1),
- Some(10),
- Some(100),
+ Some(IntervalDayTime::new(-1, -600_000)),
+ Some(IntervalDayTime::new(0, -1001)),
+ Some(IntervalDayTime::new(0, -1)),
+ Some(IntervalDayTime::new(0, 1)),
+ Some(IntervalDayTime::new(0, 10)),
+ Some(IntervalDayTime::new(0, 100)),
]));
let schema = Arc::new(Schema::new(vec![Field::new(
@@ -1002,19 +1002,19 @@ mod tests {
#[test]
fn test_pretty_format_interval_month_day_nano_array() {
let arr = Arc::new(arrow_array::IntervalMonthDayNanoArray::from(vec![
- Some(-600000000000),
- Some(18446744072709551615),
- Some(18446744073709551615),
- Some(1),
- Some(10),
- Some(100),
- Some(1_000),
- Some(10_000),
- Some(100_000),
- Some(1_000_000),
- Some(10_000_000),
- Some(100_000_000),
- Some(1_000_000_000),
+ Some(IntervalMonthDayNano::new(-1, -1, -600_000_000_000)),
+ Some(IntervalMonthDayNano::new(0, 0, -1_000_000_001)),
+ Some(IntervalMonthDayNano::new(0, 0, -1)),
+ Some(IntervalMonthDayNano::new(0, 0, 1)),
+ Some(IntervalMonthDayNano::new(0, 0, 10)),
+ Some(IntervalMonthDayNano::new(0, 0, 100)),
+ Some(IntervalMonthDayNano::new(0, 0, 1_000)),
+ Some(IntervalMonthDayNano::new(0, 0, 10_000)),
+ Some(IntervalMonthDayNano::new(0, 0, 100_000)),
+ Some(IntervalMonthDayNano::new(0, 0, 1_000_000)),
+ Some(IntervalMonthDayNano::new(0, 0, 10_000_000)),
+ Some(IntervalMonthDayNano::new(0, 0, 100_000_000)),
+ Some(IntervalMonthDayNano::new(0, 0, 1_000_000_000)),
]));
let schema = Arc::new(Schema::new(vec![Field::new(
diff --git a/arrow-data/src/data.rs b/arrow-data/src/data.rs
index d092fd049d77..5ee966394882 100644
--- a/arrow-data/src/data.rs
+++ b/arrow-data/src/data.rs
@@ -20,7 +20,9 @@
use crate::bit_iterator::BitSliceIterator;
use arrow_buffer::buffer::{BooleanBuffer, NullBuffer};
-use arrow_buffer::{bit_util, i256, ArrowNativeType, Buffer, MutableBuffer};
+use arrow_buffer::{
+ bit_util, i256, ArrowNativeType, Buffer, IntervalDayTime, IntervalMonthDayNano, MutableBuffer,
+};
use arrow_schema::{ArrowError, DataType, UnionMode};
use std::ops::Range;
use std::sync::Arc;
@@ -1568,8 +1570,10 @@ pub fn layout(data_type: &DataType) -> DataTypeLayout {
DataType::Time32(_) => DataTypeLayout::new_fixed_width::<i32>(),
DataType::Time64(_) => DataTypeLayout::new_fixed_width::<i64>(),
DataType::Interval(YearMonth) => DataTypeLayout::new_fixed_width::<i32>(),
- DataType::Interval(DayTime) => DataTypeLayout::new_fixed_width::<i64>(),
- DataType::Interval(MonthDayNano) => DataTypeLayout::new_fixed_width::<i128>(),
+ DataType::Interval(DayTime) => DataTypeLayout::new_fixed_width::<IntervalDayTime>(),
+ DataType::Interval(MonthDayNano) => {
+ DataTypeLayout::new_fixed_width::<IntervalMonthDayNano>()
+ }
DataType::Duration(_) => DataTypeLayout::new_fixed_width::<i64>(),
DataType::Decimal128(_, _) => DataTypeLayout::new_fixed_width::<i128>(),
DataType::Decimal256(_, _) => DataTypeLayout::new_fixed_width::<i256>(),
diff --git a/arrow-ord/src/comparison.rs b/arrow-ord/src/comparison.rs
index 4f56883eaebe..4197b610e7ac 100644
--- a/arrow-ord/src/comparison.rs
+++ b/arrow-ord/src/comparison.rs
@@ -119,7 +119,7 @@ mod tests {
ListBuilder, PrimitiveDictionaryBuilder, StringBuilder, StringDictionaryBuilder,
};
use arrow_array::types::*;
- use arrow_buffer::{i256, ArrowNativeType, Buffer};
+ use arrow_buffer::{i256, ArrowNativeType, Buffer, IntervalDayTime, IntervalMonthDayNano};
use arrow_data::ArrayData;
use arrow_schema::{DataType, Field};
use half::f16;
@@ -856,26 +856,48 @@ mod tests {
#[test]
fn test_interval_array() {
- let a = IntervalDayTimeArray::from(vec![Some(0), Some(6), Some(834), None, Some(3), None]);
- let b =
- IntervalDayTimeArray::from(vec![Some(70), Some(6), Some(833), Some(6), Some(3), None]);
+ let a = IntervalDayTimeArray::from(vec![
+ Some(IntervalDayTime::new(0, 1)),
+ Some(IntervalDayTime::new(0, 6)),
+ Some(IntervalDayTime::new(4, 834)),
+ None,
+ Some(IntervalDayTime::new(2, 3)),
+ None
+ ]);
+ let b = IntervalDayTimeArray::from(vec![
+ Some(IntervalDayTime::new(0, 4)),
+ Some(IntervalDayTime::new(0, 6)),
+ Some(IntervalDayTime::new(0, 834)),
+ None,
+ Some(IntervalDayTime::new(2, 3)),
+ None
+ ]);
let res = crate::cmp::eq(&a, &b).unwrap();
assert_eq!(
&res,
&BooleanArray::from(vec![Some(false), Some(true), Some(false), None, Some(true), None])
);
- let a =
- IntervalMonthDayNanoArray::from(vec![Some(0), Some(6), Some(834), None, Some(3), None]);
- let b = IntervalMonthDayNanoArray::from(
- vec![Some(86), Some(5), Some(8), Some(6), Some(3), None],
- );
+ let a = IntervalMonthDayNanoArray::from(vec![
+ Some(IntervalMonthDayNano::new(0, 0, 6)),
+ Some(IntervalMonthDayNano::new(2, 0, 0)),
+ Some(IntervalMonthDayNano::new(2, -5, 0)),
+ None,
+ Some(IntervalMonthDayNano::new(0, 0, 2)),
+ Some(IntervalMonthDayNano::new(5, 0, -23)),
+ ]);
+ let b = IntervalMonthDayNanoArray::from(vec![
+ Some(IntervalMonthDayNano::new(0, 0, 6)),
+ Some(IntervalMonthDayNano::new(2, 3, 0)),
+ Some(IntervalMonthDayNano::new(5, -5, 0)),
+ None,
+ Some(IntervalMonthDayNano::new(-1, 0, 2)),
+ None,
+ ]);
let res = crate::cmp::lt(&a, &b).unwrap();
assert_eq!(
&res,
- &BooleanArray::from(
- vec![Some(true), Some(false), Some(false), None, Some(false), None]
- )
+ &BooleanArray::from(vec![Some(false), Some(true), Some(true), None, Some(false), None])
);
let a =
@@ -1421,10 +1443,22 @@ mod tests {
#[test]
fn test_interval_dyn_scalar() {
- let array = IntervalDayTimeArray::from(vec![Some(1), None, Some(8), None, Some(10)]);
+ let array = IntervalDayTimeArray::from(vec![
+ Some(IntervalDayTime::new(1, 0)),
+ None,
+ Some(IntervalDayTime::new(8, 0)),
+ None,
+ Some(IntervalDayTime::new(10, 0)),
+ ]);
test_primitive_dyn_scalar(array);
- let array = IntervalMonthDayNanoArray::from(vec![Some(1), None, Some(8), None, Some(10)]);
+ let array = IntervalMonthDayNanoArray::from(vec![
+ Some(IntervalMonthDayNano::new(1, 0, 0)),
+ None,
+ Some(IntervalMonthDayNano::new(8, 0, 0)),
+ None,
+ Some(IntervalMonthDayNano::new(10, 0, 0)),
+ ]);
test_primitive_dyn_scalar(array);
let array = IntervalYearMonthArray::from(vec![Some(1), None, Some(8), None, Some(10)]);
@@ -2054,11 +2088,16 @@ mod tests {
#[test]
fn test_eq_dyn_neq_dyn_dictionary_interval_array() {
- let values = IntervalDayTimeArray::from(vec![1, 6, 10, 2, 3, 5]);
+ let values = IntervalDayTimeArray::from(vec![
+ Some(IntervalDayTime::new(0, 1)),
+ Some(IntervalDayTime::new(0, 1)),
+ Some(IntervalDayTime::new(0, 6)),
+ Some(IntervalDayTime::new(4, 10)),
+ ]);
let values = Arc::new(values) as ArrayRef;
let keys1 = UInt64Array::from_iter_values([1_u64, 0, 3]);
- let keys2 = UInt64Array::from_iter_values([2_u64, 0, 3]);
+ let keys2 = UInt64Array::from_iter_values([2_u64, 1, 3]);
let dict_array1 = DictionaryArray::new(keys1, values.clone());
let dict_array2 = DictionaryArray::new(keys2, values.clone());
diff --git a/arrow-ord/src/ord.rs b/arrow-ord/src/ord.rs
index e793038de929..8f21cd7c498d 100644
--- a/arrow-ord/src/ord.rs
+++ b/arrow-ord/src/ord.rs
@@ -131,7 +131,7 @@ pub fn build_compare(left: &dyn Array, right: &dyn Array) -> Result<DynComparato
#[cfg(test)]
pub mod tests {
use super::*;
- use arrow_buffer::{i256, OffsetBuffer};
+ use arrow_buffer::{i256, IntervalDayTime, OffsetBuffer};
use half::f16;
use std::sync::Arc;
@@ -396,21 +396,25 @@ pub mod tests {
#[test]
fn test_interval_dict() {
- let values = IntervalDayTimeArray::from(vec![1, 0, 2, 5]);
+ let v1 = IntervalDayTime::new(0, 1);
+ let v2 = IntervalDayTime::new(0, 2);
+ let v3 = IntervalDayTime::new(12, 2);
+
+ let values = IntervalDayTimeArray::from(vec![Some(v1), Some(v2), None, Some(v3)]);
let keys = Int8Array::from_iter_values([0, 0, 1, 3]);
let array1 = DictionaryArray::new(keys, Arc::new(values));
- let values = IntervalDayTimeArray::from(vec![2, 3, 4, 5]);
+ let values = IntervalDayTimeArray::from(vec![Some(v3), Some(v2), None, Some(v1)]);
let keys = Int8Array::from_iter_values([0, 1, 1, 3]);
let array2 = DictionaryArray::new(keys, Arc::new(values));
let cmp = build_compare(&array1, &array2).unwrap();
- assert_eq!(Ordering::Less, cmp(0, 0));
- assert_eq!(Ordering::Less, cmp(0, 3));
- assert_eq!(Ordering::Equal, cmp(3, 3));
- assert_eq!(Ordering::Greater, cmp(3, 1));
- assert_eq!(Ordering::Greater, cmp(3, 2));
+ assert_eq!(Ordering::Less, cmp(0, 0)); // v1 vs v3
+ assert_eq!(Ordering::Equal, cmp(0, 3)); // v1 vs v1
+ assert_eq!(Ordering::Greater, cmp(3, 3)); // v3 vs v1
+ assert_eq!(Ordering::Greater, cmp(3, 1)); // v3 vs v2
+ assert_eq!(Ordering::Greater, cmp(3, 2)); // v3 vs v2
}
#[test]
diff --git a/arrow-row/src/fixed.rs b/arrow-row/src/fixed.rs
index 831105bd5f15..0f3c3d0912f6 100644
--- a/arrow-row/src/fixed.rs
+++ b/arrow-row/src/fixed.rs
@@ -19,7 +19,9 @@ use crate::array::PrimitiveArray;
use crate::null_sentinel;
use arrow_array::builder::BufferBuilder;
use arrow_array::{ArrowPrimitiveType, BooleanArray, FixedSizeBinaryArray};
-use arrow_buffer::{bit_util, i256, ArrowNativeType, Buffer, MutableBuffer};
+use arrow_buffer::{
+ bit_util, i256, ArrowNativeType, Buffer, IntervalDayTime, IntervalMonthDayNano, MutableBuffer,
+};
use arrow_data::{ArrayData, ArrayDataBuilder};
use arrow_schema::{DataType, SortOptions};
use half::f16;
@@ -163,6 +165,44 @@ impl FixedLengthEncoding for f64 {
}
}
+impl FixedLengthEncoding for IntervalDayTime {
+ type Encoded = [u8; 8];
+
+ fn encode(self) -> Self::Encoded {
+ let mut out = [0_u8; 8];
+ out[..4].copy_from_slice(&self.days.encode());
+ out[4..].copy_from_slice(&self.milliseconds.encode());
+ out
+ }
+
+ fn decode(encoded: Self::Encoded) -> Self {
+ Self {
+ days: i32::decode(encoded[..4].try_into().unwrap()),
+ milliseconds: i32::decode(encoded[4..].try_into().unwrap()),
+ }
+ }
+}
+
+impl FixedLengthEncoding for IntervalMonthDayNano {
+ type Encoded = [u8; 16];
+
+ fn encode(self) -> Self::Encoded {
+ let mut out = [0_u8; 16];
+ out[..4].copy_from_slice(&self.months.encode());
+ out[4..8].copy_from_slice(&self.days.encode());
+ out[8..].copy_from_slice(&self.nanoseconds.encode());
+ out
+ }
+
+ fn decode(encoded: Self::Encoded) -> Self {
+ Self {
+ months: i32::decode(encoded[..4].try_into().unwrap()),
+ days: i32::decode(encoded[4..8].try_into().unwrap()),
+ nanoseconds: i64::decode(encoded[8..].try_into().unwrap()),
+ }
+ }
+}
+
/// Returns the total encoded length (including null byte) for a value of type `T::Native`
pub const fn encoded_len<T>(_col: &PrimitiveArray<T>) -> usize
where
diff --git a/arrow-select/src/take.rs b/arrow-select/src/take.rs
index a4dd2470ab6d..b8d59142db7d 100644
--- a/arrow-select/src/take.rs
+++ b/arrow-select/src/take.rs
@@ -845,6 +845,7 @@ pub fn take_record_batch(
mod tests {
use super::*;
use arrow_array::builder::*;
+ use arrow_buffer::{IntervalDayTime, IntervalMonthDayNano};
use arrow_schema::{Field, Fields, TimeUnit};
fn test_take_decimal_arrays(
@@ -1158,20 +1159,26 @@ mod tests {
.unwrap();
// interval_day_time
+ let v1 = IntervalDayTime::new(0, 0);
+ let v2 = IntervalDayTime::new(2, 0);
+ let v3 = IntervalDayTime::new(-15, 0);
test_take_primitive_arrays::<IntervalDayTimeType>(
- vec![Some(0), None, Some(2), Some(-15), None],
+ vec![Some(v1), None, Some(v2), Some(v3), None],
&index,
None,
- vec![Some(-15), None, None, Some(-15), Some(2)],
+ vec![Some(v3), None, None, Some(v3), Some(v2)],
)
.unwrap();
// interval_month_day_nano
+ let v1 = IntervalMonthDayNano::new(0, 0, 0);
+ let v2 = IntervalMonthDayNano::new(2, 0, 0);
+ let v3 = IntervalMonthDayNano::new(-15, 0, 0);
test_take_primitive_arrays::<IntervalMonthDayNanoType>(
- vec![Some(0), None, Some(2), Some(-15), None],
+ vec![Some(v1), None, Some(v2), Some(v3), None],
&index,
None,
- vec![Some(-15), None, None, Some(-15), Some(2)],
+ vec![Some(v3), None, None, Some(v3), Some(v2)],
)
.unwrap();
diff --git a/arrow/benches/comparison_kernels.rs b/arrow/benches/comparison_kernels.rs
index a272144b52e0..f330e1386cc4 100644
--- a/arrow/benches/comparison_kernels.rs
+++ b/arrow/benches/comparison_kernels.rs
@@ -22,9 +22,9 @@ use criterion::Criterion;
extern crate arrow;
use arrow::compute::kernels::cmp::*;
-use arrow::datatypes::IntervalMonthDayNanoType;
use arrow::util::bench_util::*;
use arrow::{array::*, datatypes::Float32Type, datatypes::Int32Type};
+use arrow_buffer::IntervalMonthDayNano;
use arrow_string::like::*;
use arrow_string::regexp::regexp_is_match_utf8_scalar;
@@ -59,10 +59,8 @@ fn add_benchmark(c: &mut Criterion) {
let arr_a = create_primitive_array_with_seed::<Float32Type>(SIZE, 0.0, 42);
let arr_b = create_primitive_array_with_seed::<Float32Type>(SIZE, 0.0, 43);
- let arr_month_day_nano_a =
- create_primitive_array_with_seed::<IntervalMonthDayNanoType>(SIZE, 0.0, 43);
- let arr_month_day_nano_b =
- create_primitive_array_with_seed::<IntervalMonthDayNanoType>(SIZE, 0.0, 43);
+ let arr_month_day_nano_a = create_month_day_nano_array_with_seed(SIZE, 0.0, 43);
+ let arr_month_day_nano_b = create_month_day_nano_array_with_seed(SIZE, 0.0, 43);
let arr_string = create_string_array::<i32>(SIZE, 0.0);
let scalar = Float32Array::from(vec![1.0]);
@@ -134,7 +132,7 @@ fn add_benchmark(c: &mut Criterion) {
c.bench_function("eq MonthDayNano", |b| {
b.iter(|| eq(&arr_month_day_nano_a, &arr_month_day_nano_b))
});
- let scalar = IntervalMonthDayNanoArray::new_scalar(123);
+ let scalar = IntervalMonthDayNanoArray::new_scalar(IntervalMonthDayNano::new(123, 0, 0));
c.bench_function("eq scalar MonthDayNano", |b| {
b.iter(|| eq(&arr_month_day_nano_b, &scalar).unwrap())
diff --git a/arrow/src/util/bench_util.rs b/arrow/src/util/bench_util.rs
index 140c5bc9259d..9fae8e6bab38 100644
--- a/arrow/src/util/bench_util.rs
+++ b/arrow/src/util/bench_util.rs
@@ -20,7 +20,7 @@
use crate::array::*;
use crate::datatypes::*;
use crate::util::test_util::seedable_rng;
-use arrow_buffer::Buffer;
+use arrow_buffer::{Buffer, IntervalMonthDayNano};
use rand::distributions::uniform::SampleUniform;
use rand::thread_rng;
use rand::Rng;
@@ -72,6 +72,24 @@ where
.collect()
}
+pub fn create_month_day_nano_array_with_seed(
+ size: usize,
+ null_density: f32,
+ seed: u64,
+) -> IntervalMonthDayNanoArray {
+ let mut rng = StdRng::seed_from_u64(seed);
+
+ (0..size)
+ .map(|_| {
+ if rng.gen::<f32>() < null_density {
+ None
+ } else {
+ Some(IntervalMonthDayNano::new(rng.gen(), rng.gen(), rng.gen()))
+ }
+ })
+ .collect()
+}
+
/// Creates an random (but fixed-seeded) array of a given size and null density
pub fn create_boolean_array(size: usize, null_density: f32, true_density: f32) -> BooleanArray
where
diff --git a/parquet/src/arrow/array_reader/fixed_len_byte_array.rs b/parquet/src/arrow/array_reader/fixed_len_byte_array.rs
index a0d25d403c1b..a9159bb47125 100644
--- a/parquet/src/arrow/array_reader/fixed_len_byte_array.rs
+++ b/parquet/src/arrow/array_reader/fixed_len_byte_array.rs
@@ -30,7 +30,7 @@ use arrow_array::{
ArrayRef, Decimal128Array, Decimal256Array, FixedSizeBinaryArray, Float16Array,
IntervalDayTimeArray, IntervalYearMonthArray,
};
-use arrow_buffer::{i256, Buffer};
+use arrow_buffer::{i256, Buffer, IntervalDayTime};
use arrow_data::ArrayDataBuilder;
use arrow_schema::{DataType as ArrowType, IntervalUnit};
use bytes::Bytes;
@@ -195,7 +195,14 @@ impl ArrayReader for FixedLenByteArrayReader {
IntervalUnit::DayTime => Arc::new(
binary
.iter()
- .map(|o| o.map(|b| i64::from_le_bytes(b[4..12].try_into().unwrap())))
+ .map(|o| {
+ o.map(|b| {
+ IntervalDayTime::new(
+ i32::from_le_bytes(b[4..8].try_into().unwrap()),
+ i32::from_le_bytes(b[8..12].try_into().unwrap()),
+ )
+ })
+ })
.collect::<IntervalDayTimeArray>(),
) as ArrayRef,
IntervalUnit::MonthDayNano => {
diff --git a/parquet/src/arrow/arrow_reader/mod.rs b/parquet/src/arrow/arrow_reader/mod.rs
index a30bf168619f..db75c54bf5d0 100644
--- a/parquet/src/arrow/arrow_reader/mod.rs
+++ b/parquet/src/arrow/arrow_reader/mod.rs
@@ -750,7 +750,7 @@ mod tests {
Decimal128Type, Decimal256Type, DecimalType, Float16Type, Float32Type, Float64Type,
};
use arrow_array::*;
- use arrow_buffer::{i256, ArrowNativeType, Buffer};
+ use arrow_buffer::{i256, ArrowNativeType, Buffer, IntervalDayTime};
use arrow_data::ArrayDataBuilder;
use arrow_schema::{ArrowError, DataType as ArrowDataType, Field, Fields, Schema};
use arrow_select::concat::concat_batches;
@@ -1060,8 +1060,12 @@ mod tests {
Arc::new(
vals.iter()
.map(|x| {
- x.as_ref()
- .map(|b| i64::from_le_bytes(b.as_ref()[4..12].try_into().unwrap()))
+ x.as_ref().map(|b| IntervalDayTime {
+ days: i32::from_le_bytes(b.as_ref()[4..8].try_into().unwrap()),
+ milliseconds: i32::from_le_bytes(
+ b.as_ref()[8..12].try_into().unwrap(),
+ ),
+ })
})
.collect::<IntervalDayTimeArray>(),
)
diff --git a/parquet/src/arrow/arrow_writer/mod.rs b/parquet/src/arrow/arrow_writer/mod.rs
index bf4b88ac52d4..60feda69e841 100644
--- a/parquet/src/arrow/arrow_writer/mod.rs
+++ b/parquet/src/arrow/arrow_writer/mod.rs
@@ -942,11 +942,11 @@ fn get_interval_dt_array_slice(
) -> Vec<FixedLenByteArray> {
let mut values = Vec::with_capacity(indices.len());
for i in indices {
- let mut prefix = vec![0; 4];
- let mut value = array.value(*i).to_le_bytes().to_vec();
- prefix.append(&mut value);
- debug_assert_eq!(prefix.len(), 12);
- values.push(FixedLenByteArray::from(ByteArray::from(prefix)));
+ let mut out = [0; 12];
+ let value = array.value(*i);
+ out[4..8].copy_from_slice(&value.days.to_le_bytes());
+ out[8..12].copy_from_slice(&value.milliseconds.to_le_bytes());
+ values.push(FixedLenByteArray::from(ByteArray::from(out.to_vec())));
}
values
}
@@ -1016,7 +1016,7 @@ mod tests {
use arrow::error::Result as ArrowResult;
use arrow::util::pretty::pretty_format_batches;
use arrow::{array::*, buffer::Buffer};
- use arrow_buffer::NullBuffer;
+ use arrow_buffer::{IntervalDayTime, IntervalMonthDayNano, NullBuffer};
use arrow_schema::Fields;
use crate::basic::Encoding;
@@ -2057,7 +2057,12 @@ mod tests {
#[test]
fn interval_day_time_single_column() {
- required_and_optional::<IntervalDayTimeArray, _>(0..SMALL_SIZE as i64);
+ required_and_optional::<IntervalDayTimeArray, _>(vec![
+ IntervalDayTime::new(0, 1),
+ IntervalDayTime::new(0, 3),
+ IntervalDayTime::new(3, -2),
+ IntervalDayTime::new(-200, 4),
+ ]);
}
#[test]
@@ -2065,7 +2070,12 @@ mod tests {
expected = "Attempting to write an Arrow interval type MonthDayNano to parquet that is not yet implemented"
)]
fn interval_month_day_nano_single_column() {
- required_and_optional::<IntervalMonthDayNanoArray, _>(0..SMALL_SIZE as i128);
+ required_and_optional::<IntervalMonthDayNanoArray, _>(vec![
+ IntervalMonthDayNano::new(0, 1, 5),
+ IntervalMonthDayNano::new(0, 3, 2),
+ IntervalMonthDayNano::new(3, -2, -5),
+ IntervalMonthDayNano::new(-200, 4, -1),
+ ]);
}
#[test]
|
diff --git a/arrow-integration-test/src/lib.rs b/arrow-integration-test/src/lib.rs
index 30f0ccfbe12d..66fa9f3320e0 100644
--- a/arrow-integration-test/src/lib.rs
+++ b/arrow-integration-test/src/lib.rs
@@ -21,7 +21,7 @@
//!
//! This is not a canonical format, but provides a human-readable way of verifying language implementations
-use arrow_buffer::ScalarBuffer;
+use arrow_buffer::{IntervalDayTime, IntervalMonthDayNano, ScalarBuffer};
use hex::decode;
use num::BigInt;
use num::Signed;
@@ -32,7 +32,6 @@ use std::sync::Arc;
use arrow::array::*;
use arrow::buffer::{Buffer, MutableBuffer};
-use arrow::compute;
use arrow::datatypes::*;
use arrow::error::{ArrowError, Result};
use arrow::util::bit_util;
@@ -349,10 +348,7 @@ pub fn array_from_json(
}
Ok(Arc::new(b.finish()))
}
- DataType::Int32
- | DataType::Date32
- | DataType::Time32(_)
- | DataType::Interval(IntervalUnit::YearMonth) => {
+ DataType::Int32 | DataType::Date32 | DataType::Time32(_) => {
let mut b = Int32Builder::with_capacity(json_col.count);
for (is_valid, value) in json_col
.validity
@@ -367,14 +363,29 @@ pub fn array_from_json(
};
}
let array = Arc::new(b.finish()) as ArrayRef;
- compute::cast(&array, field.data_type())
+ arrow::compute::cast(&array, field.data_type())
+ }
+ DataType::Interval(IntervalUnit::YearMonth) => {
+ let mut b = IntervalYearMonthBuilder::with_capacity(json_col.count);
+ for (is_valid, value) in json_col
+ .validity
+ .as_ref()
+ .unwrap()
+ .iter()
+ .zip(json_col.data.unwrap())
+ {
+ match is_valid {
+ 1 => b.append_value(value.as_i64().unwrap() as i32),
+ _ => b.append_null(),
+ };
+ }
+ Ok(Arc::new(b.finish()))
}
DataType::Int64
| DataType::Date64
| DataType::Time64(_)
| DataType::Timestamp(_, _)
- | DataType::Duration(_)
- | DataType::Interval(IntervalUnit::DayTime) => {
+ | DataType::Duration(_) => {
let mut b = Int64Builder::with_capacity(json_col.count);
for (is_valid, value) in json_col
.validity
@@ -387,6 +398,25 @@ pub fn array_from_json(
1 => b.append_value(match value {
Value::Number(n) => n.as_i64().unwrap(),
Value::String(s) => s.parse().expect("Unable to parse string as i64"),
+ _ => panic!("Unable to parse {value:?} as number"),
+ }),
+ _ => b.append_null(),
+ };
+ }
+ let array = Arc::new(b.finish()) as ArrayRef;
+ arrow::compute::cast(&array, field.data_type())
+ }
+ DataType::Interval(IntervalUnit::DayTime) => {
+ let mut b = IntervalDayTimeBuilder::with_capacity(json_col.count);
+ for (is_valid, value) in json_col
+ .validity
+ .as_ref()
+ .unwrap()
+ .iter()
+ .zip(json_col.data.unwrap())
+ {
+ match is_valid {
+ 1 => b.append_value(match value {
Value::Object(ref map)
if map.contains_key("days") && map.contains_key("milliseconds") =>
{
@@ -397,13 +427,9 @@ pub fn array_from_json(
match (days, milliseconds) {
(Value::Number(d), Value::Number(m)) => {
- let mut bytes = [0_u8; 8];
- let m = (m.as_i64().unwrap() as i32).to_le_bytes();
- let d = (d.as_i64().unwrap() as i32).to_le_bytes();
-
- let c = [d, m].concat();
- bytes.copy_from_slice(c.as_slice());
- i64::from_le_bytes(bytes)
+ let days = d.as_i64().unwrap() as _;
+ let millis = m.as_i64().unwrap() as _;
+ IntervalDayTime::new(days, millis)
}
_ => {
panic!("Unable to parse {value:?} as interval daytime")
@@ -418,8 +444,7 @@ pub fn array_from_json(
_ => b.append_null(),
};
}
- let array = Arc::new(b.finish()) as ArrayRef;
- compute::cast(&array, field.data_type())
+ Ok(Arc::new(b.finish()))
}
DataType::UInt8 => {
let mut b = UInt8Builder::with_capacity(json_col.count);
@@ -523,11 +548,7 @@ pub fn array_from_json(
let months = months.as_i64().unwrap() as i32;
let days = days.as_i64().unwrap() as i32;
let nanoseconds = nanoseconds.as_i64().unwrap();
- let months_days_ns: i128 =
- ((nanoseconds as i128) & 0xFFFFFFFFFFFFFFFF) << 64
- | ((days as i128) & 0xFFFFFFFF) << 32
- | ((months as i128) & 0xFFFFFFFF);
- months_days_ns
+ IntervalMonthDayNano::new(months, days, nanoseconds)
}
(_, _, _) => {
panic!("Unable to parse {v:?} as MonthDayNano")
diff --git a/arrow/tests/array_cast.rs b/arrow/tests/array_cast.rs
index 2d3167c928d0..0fd89cc2bff4 100644
--- a/arrow/tests/array_cast.rs
+++ b/arrow/tests/array_cast.rs
@@ -32,7 +32,7 @@ use arrow_array::{
TimestampMicrosecondArray, TimestampMillisecondArray, TimestampNanosecondArray,
TimestampSecondArray, UInt16Array, UInt32Array, UInt64Array, UInt8Array, UnionArray,
};
-use arrow_buffer::{i256, Buffer};
+use arrow_buffer::{i256, Buffer, IntervalDayTime, IntervalMonthDayNano};
use arrow_cast::pretty::pretty_format_columns;
use arrow_cast::{can_cast_types, cast};
use arrow_data::ArrayData;
@@ -249,8 +249,14 @@ fn get_arrays_of_all_types() -> Vec<ArrayRef> {
Arc::new(Time64MicrosecondArray::from(vec![1000, 2000])),
Arc::new(Time64NanosecondArray::from(vec![1000, 2000])),
Arc::new(IntervalYearMonthArray::from(vec![1000, 2000])),
- Arc::new(IntervalDayTimeArray::from(vec![1000, 2000])),
- Arc::new(IntervalMonthDayNanoArray::from(vec![1000, 2000])),
+ Arc::new(IntervalDayTimeArray::from(vec![
+ IntervalDayTime::new(0, 1000),
+ IntervalDayTime::new(0, 2000),
+ ])),
+ Arc::new(IntervalMonthDayNanoArray::from(vec![
+ IntervalMonthDayNano::new(0, 0, 1000),
+ IntervalMonthDayNano::new(0, 0, 1000),
+ ])),
Arc::new(DurationSecondArray::from(vec![1000, 2000])),
Arc::new(DurationMillisecondArray::from(vec![1000, 2000])),
Arc::new(DurationMicrosecondArray::from(vec![1000, 2000])),
|
Rust Interval definition incorrect
It seems the Rust `INTERVAL` definition is incorrect. Please see https://github.com/duckdb/duckdb-wasm/issues/1696#issuecomment-2047021075 for more details on the bug and where it occurs in the code.
Particularly this definition: https://github.com/apache/arrow-rs/blob/36a6e515f99866eae5332dfc887c6cb5f8135064/arrow-array/src/types.rs#L265-L269
|
@pitrou do you know if the integration tests cover the interval types?
@avantgardnerio as the author of https://github.com/apache/arrow-rs/pull/2235 which appears to have switched these round, perhaps you could weigh in here
> @avantgardnerio as the author of #2235 which appears to have switched these round, perhaps you could weigh in here
Honestly, I don't recall the reasoning. I know at the time I was working with JDBC interop, so I assume it was to make that work.
I agree we should do whatever arrow-cpp does, as that seems to be the reference implementation, to the extent that there is one.
> @pitrou do you know if the integration tests cover the interval types?
Yes, they do.
https://github.com/apache/arrow/blob/7003e90c113cec58a620deddf56af71eb305af2a/dev/archery/archery/integration/datagen.py#L1653-L1669
One way to avoid this leading to subtle downstream breakage might be to do something along the lines of https://github.com/apache/arrow-rs/issues/3125
Typing down some things that @tustvold told me today:
1. we think the tests ensure the data round trips but does not actually ensure both ends interpret them in the same way (aka they don't cover this particular bug)
2. He plans to work on this ticket, likely next week(ish)
3. In order to avoid subtle breaking changes (due to the same type i128 being interpreted differently by different versions) he plans to do something like https://github.com/apache/arrow-rs/issues/3125
@tustvold reports is that it is unlikely that this will be done this week due to other higher priorities
It turns out the reason we didn't detect this with our integration tests, is that they were actually using different, correct, logic for constructing the expected values from the JSON data - https://github.com/apache/arrow-rs/pull/5765
@alamb and I had a good discussion about the pros/cons of switching to a structured representation (#3125), vs simply flipping the order (#5656). The broad points were:
* There are extremely few, if any, operations that are well defined for the integral representation of compound types
* Switching to a structured type would allow us to keep the sort order the same
* Switching to a structured type would make it easy to find code that is making incorrect layout assumptions
* Arrow-cpp uses a structured type - https://github.com/apache/arrow/blob/433ceef8a292932b31ddb3127f95eeb85ae41df5/cpp/src/arrow/type.h#L1731
As such the decision was that a custom struct should be used where operations, such as arithmetic, on the integral representation have no semantic meaning. Specifically this means types such as timestamps, decimals, and even IntervalYearMonth should remain using integral types as their native representation, as operations on the integral representation are well-defined. However, types like IntervalMonthDayNano or ByteView (#5736) should switch to a non-integral representation.
|
2024-05-15T18:17:11Z
|
51.0
|
30767a687b48d0dbd2e030eef327826c39095123
|
apache/arrow-rs
| 5,717
|
apache__arrow-rs-5717
|
[
"5716"
] |
a126d5097b71273428fba68d1c430f3d4beee684
|
diff --git a/parquet_derive/src/parquet_field.rs b/parquet_derive/src/parquet_field.rs
index 9fff76c42d1d..f99ea3e0356c 100644
--- a/parquet_derive/src/parquet_field.rs
+++ b/parquet_derive/src/parquet_field.rs
@@ -239,7 +239,8 @@ impl Field {
/// because this parsing logic is not sophisticated enough for definition
/// levels beyond 2.
///
- /// `Option` types and references not supported
+ /// `Option` types and references not supported, but the column itself can be nullable
+ /// (i.e., def_level==1), as long as the values are all valid.
pub fn reader_snippet(&self) -> proc_macro2::TokenStream {
let ident = &self.ident;
let column_reader = self.ty.column_reader();
@@ -248,7 +249,13 @@ impl Field {
let write_batch_expr = quote! {
let mut vals = Vec::new();
if let #column_reader(mut typed) = column_reader {
- typed.read_records(num_records, None, None, &mut vals)?;
+ let mut definition_levels = Vec::new();
+ let (total_num, valid_num, decoded_num) = typed.read_records(
+ num_records, Some(&mut definition_levels), None, &mut vals)?;
+ if valid_num != decoded_num {
+ panic!("Support only valid records, found {} null records in column type {}",
+ decoded_num - valid_num, stringify!{#ident});
+ }
} else {
panic!("Schema and struct disagree on type for {}", stringify!{#ident});
}
@@ -876,15 +883,21 @@ mod test {
snippet,
(quote! {
{
- let mut vals = Vec::new();
- if let ColumnReader::Int64ColumnReader(mut typed) = column_reader {
- typed.read_records(num_records, None, None, &mut vals)?;
- } else {
- panic!("Schema and struct disagree on type for {}", stringify!{ counter });
- }
- for (i, r) in &mut records[..num_records].iter_mut().enumerate() {
- r.counter = vals[i] as usize;
- }
+ let mut vals = Vec::new();
+ if let ColumnReader::Int64ColumnReader(mut typed) = column_reader {
+ let mut definition_levels = Vec::new();
+ let (total_num, valid_num, decoded_num) = typed.read_records(
+ num_records, Some(&mut definition_levels), None, &mut vals)?;
+ if valid_num != decoded_num {
+ panic!("Support only valid records, found {} null records in column type {}",
+ decoded_num - valid_num, stringify!{counter});
+ }
+ } else {
+ panic!("Schema and struct disagree on type for {}", stringify!{counter});
+ }
+ for (i, r) in &mut records[..num_records].iter_mut().enumerate() {
+ r.counter = vals[i] as usize;
+ }
}
})
.to_string()
@@ -1291,7 +1304,13 @@ mod test {
{
let mut vals = Vec::new();
if let ColumnReader::Int64ColumnReader(mut typed) = column_reader {
- typed.read_records(num_records, None, None, &mut vals)?;
+ let mut definition_levels = Vec::new();
+ let (total_num, valid_num, decoded_num) = typed.read_records(
+ num_records, Some(&mut definition_levels), None, &mut vals)?;
+ if valid_num != decoded_num {
+ panic!("Support only valid records, found {} null records in column type {}",
+ decoded_num - valid_num, stringify!{henceforth});
+ }
} else {
panic!("Schema and struct disagree on type for {}", stringify!{ henceforth });
}
@@ -1359,7 +1378,13 @@ mod test {
{
let mut vals = Vec::new();
if let ColumnReader::Int32ColumnReader(mut typed) = column_reader {
- typed.read_records(num_records, None, None, &mut vals)?;
+ let mut definition_levels = Vec::new();
+ let (total_num, valid_num, decoded_num) = typed.read_records(
+ num_records, Some(&mut definition_levels), None, &mut vals)?;
+ if valid_num != decoded_num {
+ panic!("Support only valid records, found {} null records in column type {}",
+ decoded_num - valid_num, stringify!{henceforth});
+ }
} else {
panic!("Schema and struct disagree on type for {}", stringify!{ henceforth });
}
@@ -1427,7 +1452,13 @@ mod test {
{
let mut vals = Vec::new();
if let ColumnReader::FixedLenByteArrayColumnReader(mut typed) = column_reader {
- typed.read_records(num_records, None, None, &mut vals)?;
+ let mut definition_levels = Vec::new();
+ let (total_num, valid_num, decoded_num) = typed.read_records(
+ num_records, Some(&mut definition_levels), None, &mut vals)?;
+ if valid_num != decoded_num {
+ panic!("Support only valid records, found {} null records in column type {}",
+ decoded_num - valid_num, stringify!{unique_id});
+ }
} else {
panic!("Schema and struct disagree on type for {}", stringify!{ unique_id });
}
|
diff --git a/parquet_derive_test/src/lib.rs b/parquet_derive_test/src/lib.rs
index 3743c6b55c7c..e168ad5b980a 100644
--- a/parquet_derive_test/src/lib.rs
+++ b/parquet_derive_test/src/lib.rs
@@ -66,6 +66,25 @@ struct APartiallyCompleteRecord {
pub byte_vec: Vec<u8>,
}
+// This struct has OPTIONAL columns
+// If these fields are guaranteed to be valid
+// we can load this struct into APartiallyCompleteRecord
+#[derive(PartialEq, ParquetRecordWriter, Debug)]
+struct APartiallyOptionalRecord {
+ pub bool: bool,
+ pub string: String,
+ pub maybe_i16: Option<i16>,
+ pub maybe_i32: Option<i32>,
+ pub maybe_u64: Option<u64>,
+ pub isize: isize,
+ pub float: f32,
+ pub double: f64,
+ pub now: chrono::NaiveDateTime,
+ pub date: chrono::NaiveDate,
+ pub uuid: uuid::Uuid,
+ pub byte_vec: Vec<u8>,
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -218,6 +237,47 @@ mod tests {
assert_eq!(drs[0], out[0]);
}
+ #[test]
+ fn test_parquet_derive_read_optional_but_valid_column() {
+ let file = get_temp_file("test_parquet_derive_read_optional", &[]);
+ let drs: Vec<APartiallyOptionalRecord> = vec![APartiallyOptionalRecord {
+ bool: true,
+ string: "a string".into(),
+ maybe_i16: Some(-45),
+ maybe_i32: Some(456),
+ maybe_u64: Some(4563424),
+ isize: -365,
+ float: 3.5,
+ double: std::f64::NAN,
+ now: chrono::Utc::now().naive_local(),
+ date: chrono::naive::NaiveDate::from_ymd_opt(2015, 3, 14).unwrap(),
+ uuid: uuid::Uuid::new_v4(),
+ byte_vec: vec![0x65, 0x66, 0x67],
+ }];
+
+ let generated_schema = drs.as_slice().schema().unwrap();
+
+ let props = Default::default();
+ let mut writer =
+ SerializedFileWriter::new(file.try_clone().unwrap(), generated_schema, props).unwrap();
+
+ let mut row_group = writer.next_row_group().unwrap();
+ drs.as_slice().write_to_row_group(&mut row_group).unwrap();
+ row_group.close().unwrap();
+ writer.close().unwrap();
+
+ use parquet::file::{reader::FileReader, serialized_reader::SerializedFileReader};
+ let reader = SerializedFileReader::new(file).unwrap();
+ let mut out: Vec<APartiallyCompleteRecord> = Vec::new();
+
+ let mut row_group = reader.get_row_group(0).unwrap();
+ out.read_from_row_group(&mut *row_group, 1).unwrap();
+
+ assert_eq!(drs[0].maybe_i16.unwrap(), out[0].i16);
+ assert_eq!(drs[0].maybe_i32.unwrap(), out[0].i32);
+ assert_eq!(drs[0].maybe_u64.unwrap(), out[0].u64);
+ }
+
/// Returns file handle for a temp file in 'target' directory with a provided content
pub fn get_temp_file(file_name: &str, content: &[u8]) -> fs::File {
// build tmp path to a file in "target/debug/testdata"
|
[parquet_derive] support OPTIONAL (def_level = 1) columns by default
## Problem Description
<!--
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
(This section helps Arrow developers understand the context and *why* for this feature, in addition to the *what*)
-->
I'm working on parquet files written by `pyarrow` (embedded in `pandas`). I came across `parquet_derive` and it avoids boilerplates in my project.
The problem is, it doesn't work on the parquet files that is written by `pandas` with default setup, it throws error information:
```text
Parquet error: must specify definition levels
```
After digging into this, I found that the problem is the parquet file generated by `pyarrow` has def_level=1, i.e., every column, even without a null value, is OPTIONAL.
<img width="677" alt="image" src="https://github.com/apache/arrow-rs/assets/27212391/b6b4cc96-8c53-4d41-9c66-4f802476dd7a">
However, the macro generate code that does not allow definition level, thus it fails to parsing columns with OPTIONAL value, even there is no actual NULL values:
```rust
typed.read_records(num_records, None, None, &mut vals)?;
```
The API it calls is: https://docs.rs/parquet/latest/parquet/column/reader/struct.GenericColumnReader.html#method.read_records .
## My Solution
The solution is straight-forward. I have fixed the problem locally, I'm willing to contribute a pull request, but I don't know if this solution is reasonable in the scope of the whole `arrow` project.
Basically, I think we need to provide definition level in `read_record`:
```rust
typed.read_records(num_records, None /*should use a Some(&mut Vec<i16>)*/, None, &mut vals)?;
```
In one word, with this solution, `parquet_derive` can now handle:
1. (already supported) parquet file with all columns REQUIRED
2. **(new introduced) parquet file with OPTIONAL columns but are always guaranteed to be valid**.
### Pros
- This solution does not break current features
- This solution makes parquet_derive more general in handling parquet files.
It can pass the tests in `parquet_derive_tests`. I also add checks against the parsed records and valid records, to avoid abusing it for columns with NULLs.
### Cons
- It will be slightly slower since it allocates an extra `Vec<i16>` for each column when invoking `read_from_row_group`.
I don't think it is a big deal, though, compared to the inconvenience of not supporting OPTIONAL columns. Moreover, we can make use of the max_def_levels (for REQUIRED column, it is 0) to skip creating the Vec.
|
What happens if you specify the field as `Option` to match the schema?
> What happens if you specify the field as `Option` to match the schema?
I have tried, it does not work, because:
1. the OPTIONAL, REQUIRED, REPEATED tags are generated automatically in the macro.
2. even I workaround 1 by enforce the field to be OPTIONAL, the actual parsing code, i.e.:
```rust
typed.read_records(num_records, None, None, &mut vals)?;
```
is not dynamic and still provide no definition level.
Hmm... My knowledge of parquet_derive is limited, but I would have expected an optional field to map to `Option<T>` on the annotated struct.
It might also be that it simply doesn't support nulls, in which case I'm a little unsure about adding partial support in a manner that might prevent adding such support in future
> Hmm... My knowledge of parquet_derive is limited, but I would have expected an optional field to map to `Option<T>` on the annotated struct.
>
> It might also be that it simply doesn't support nulls, in which case I'm a little unsure about adding partial support in a manner that might prevent adding such support in future
I understand your concern, and that is why I said this in the description:
> but I don't know if this solution is reasonable in the scope of the whole arrow project.
Yes, I agree it is more natural and rigorous to map and OPTIONAL column to `Option<T>` in theory. The pipeline should be like this:
```text
OPTIONAL columns --> struct with Option<T> (by parquet_derive, not implemented) --> struct without Option<T> (by user)
```
However, in practice, when write a parquet file, the default attribute of a column is OPTIONAL (see https://arrow.apache.org/docs/python/generated/pyarrow.field.html), no matter whether there is a NULL. Those APIs are not even exposed to user in higher level APIs. So, most of the parquet files users deal with have OPTIONAL columns everywhere, though values in those columns are in fact all valid. I don't think it is handy for users to declare a struct with all fields in `Option<T>`.
Another point I want to say is, this change DOES NOT mean that the reader support `Option<T>` in struct now, if you derive `ParquetRecordReader` for a struct with `Option<T>`, it fails to compile as before:
```text
help: message: not implemented: Unsupported: Option(...)
```
The only difference is that if a parquet file is written with OPTIONAL columns, but in fact the values in those columns are in fact all valid, the reader should still be able to load the records into a struct WITHOUT `Option<T>`, i.e., the pipeline becomes:
```text
OPTIONAL columns --> struct without Option<T> (by parquet_derive, with checks)
```
This change is only to relax parquet_derive's restriction against parquet input, without introducing risk since checks are done after parsing. If user's input does have NULL values, the parser will panic, like what it is doing now.
To sum up, I think this change does not make things worse or unsafe. I really appreciate your time to review this issue, and even better if you can invite more experts to review it.
> However, in practice, when write a parquet file, the default attribute of a column is OPTIONAL
Is this the case if you set `nullable` to `false`? If so I would probably raise a bug on pyarrow as that is incorrect.
> This change is only to relax parquet_derive's restriction against parquet input, without introducing risk since checks are done after parsing. If user's input does have NULL values, the parser will panic, like what it is doing now.
So long as we don't regress performance for existing workloads I suppose this is an acceptable workaround. I will try to take a look next week at your PR, although I will need to allocate enough time to get up to speed on that crate (there isn't really anyone maintaining it actively anymore).
FWIW reading parquet via the arrow interface will be faster, especially for string columns, but appreciate if you'd rather stick to a row-oriented model
> Is this the case if you set nullable to false? If so I would probably raise a bug on pyarrow as that is incorrect.
`pyarrow` is not the culprit. I believe "convention" is the one to blame. `pandas` has a [to_parquet](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_parquet.html) interface, and it does not accept schema before https://github.com/pandas-dev/pandas/pull/30270 . Even after this improvement, most people use the default schema, which falls in to `OPTIONAL` columns by default (nullable=True in `pyarrow`).
> I will try to take a look next week at your PR, although I will need to allocate enough time to get up to speed on that crate
I really appreciate your time, my use case requires a row-oriented model, and this crate is still very useful to our project, that's why I raise this issue. I'm willing to spend time polishing this pull request.
|
2024-05-04T11:18:22Z
|
51.0
|
30767a687b48d0dbd2e030eef327826c39095123
|
apache/arrow-rs
| 5,698
|
apache__arrow-rs-5698
|
[
"3462"
] |
a61f1dc8ea132add731e4426e11d341a1de5ca92
|
diff --git a/arrow-flight/src/client.rs b/arrow-flight/src/client.rs
index b2abfb0c17b2..a7e15fe24cc5 100644
--- a/arrow-flight/src/client.rs
+++ b/arrow-flight/src/client.rs
@@ -417,9 +417,7 @@ impl FlightClient {
///
/// // encode the batch as a stream of `FlightData`
/// let flight_data_stream = FlightDataEncoderBuilder::new()
- /// .build(futures::stream::iter(vec![Ok(batch)]))
- /// // data encoder return Results, but do_exchange requires FlightData
- /// .map(|batch|batch.unwrap());
+ /// .build(futures::stream::iter(vec![Ok(batch)]));
///
/// // send the stream and get the results as `RecordBatches`
/// let response: Vec<RecordBatch> = client
@@ -431,20 +429,40 @@ impl FlightClient {
/// .expect("error calling do_exchange");
/// # }
/// ```
- pub async fn do_exchange<S: Stream<Item = FlightData> + Send + 'static>(
+ pub async fn do_exchange<S: Stream<Item = Result<FlightData>> + Send + 'static>(
&mut self,
request: S,
) -> Result<FlightRecordBatchStream> {
- let request = self.make_request(request);
+ let (sender, mut receiver) = futures::channel::oneshot::channel();
- let response = self
- .inner
- .do_exchange(request)
- .await?
- .into_inner()
- .map_err(FlightError::Tonic);
+ // Intercepts client errors and sends them to the oneshot channel above
+ let mut request = Box::pin(request); // Pin to heap
+ let mut sender = Some(sender); // Wrap into Option so can be taken
+ let request_stream = futures::stream::poll_fn(move |cx| {
+ Poll::Ready(match ready!(request.poll_next_unpin(cx)) {
+ Some(Ok(data)) => Some(data),
+ Some(Err(e)) => {
+ let _ = sender.take().unwrap().send(e);
+ None
+ }
+ None => None,
+ })
+ });
+
+ let request = self.make_request(request_stream);
+ let mut response_stream = self.inner.do_exchange(request).await?.into_inner();
+
+ // Forwards errors from the error oneshot with priority over responses from server
+ let error_stream = futures::stream::poll_fn(move |cx| {
+ if let Poll::Ready(Ok(err)) = receiver.poll_unpin(cx) {
+ return Poll::Ready(Some(Err(err)));
+ }
+ let next = ready!(response_stream.poll_next_unpin(cx));
+ Poll::Ready(next.map(|x| x.map_err(FlightError::Tonic)))
+ });
- Ok(FlightRecordBatchStream::new_from_flight_data(response))
+ // combine the response from the server and any error from the client
+ Ok(FlightRecordBatchStream::new_from_flight_data(error_stream))
}
/// Make a `ListFlights` call to the server with the provided
|
diff --git a/arrow-flight/tests/client.rs b/arrow-flight/tests/client.rs
index 47565334cb63..478938d939a9 100644
--- a/arrow-flight/tests/client.rs
+++ b/arrow-flight/tests/client.rs
@@ -493,7 +493,7 @@ async fn test_do_exchange() {
.set_do_exchange_response(output_flight_data.clone().into_iter().map(Ok).collect());
let response_stream = client
- .do_exchange(futures::stream::iter(input_flight_data.clone()))
+ .do_exchange(futures::stream::iter(input_flight_data.clone()).map(Ok))
.await
.expect("error making request");
@@ -528,7 +528,7 @@ async fn test_do_exchange_error() {
let input_flight_data = test_flight_data().await;
let response = client
- .do_exchange(futures::stream::iter(input_flight_data.clone()))
+ .do_exchange(futures::stream::iter(input_flight_data.clone()).map(Ok))
.await;
let response = match response {
Ok(_) => panic!("unexpected success"),
@@ -572,7 +572,7 @@ async fn test_do_exchange_error_stream() {
test_server.set_do_exchange_response(response);
let response_stream = client
- .do_exchange(futures::stream::iter(input_flight_data.clone()))
+ .do_exchange(futures::stream::iter(input_flight_data.clone()).map(Ok))
.await
.expect("error making request");
@@ -593,6 +593,97 @@ async fn test_do_exchange_error_stream() {
.await;
}
+#[tokio::test]
+async fn test_do_exchange_error_stream_client() {
+ do_test(|test_server, mut client| async move {
+ client.add_header("foo-header", "bar-header-value").unwrap();
+
+ let e = Status::invalid_argument("bad arg: client");
+
+ // input stream to client sends good FlightData followed by an error
+ let input_flight_data = test_flight_data().await;
+ let input_stream = futures::stream::iter(input_flight_data.clone())
+ .map(Ok)
+ .chain(futures::stream::iter(vec![Err(FlightError::from(
+ e.clone(),
+ ))]));
+
+ let output_flight_data = FlightData::new()
+ .with_descriptor(FlightDescriptor::new_cmd("Sample command"))
+ .with_data_body("body".as_bytes())
+ .with_data_header("header".as_bytes())
+ .with_app_metadata("metadata".as_bytes());
+
+ // server responds with one good message
+ let response = vec![Ok(output_flight_data)];
+ test_server.set_do_exchange_response(response);
+
+ let response_stream = client
+ .do_exchange(input_stream)
+ .await
+ .expect("error making request");
+
+ let response: Result<Vec<_>, _> = response_stream.try_collect().await;
+ let response = match response {
+ Ok(_) => panic!("unexpected success"),
+ Err(e) => e,
+ };
+
+ // expect to the error made from the client
+ expect_status(response, e);
+ // server still got the request messages until the client sent the error
+ assert_eq!(
+ test_server.take_do_exchange_request(),
+ Some(input_flight_data)
+ );
+ ensure_metadata(&client, &test_server);
+ })
+ .await;
+}
+
+#[tokio::test]
+async fn test_do_exchange_error_client_and_server() {
+ do_test(|test_server, mut client| async move {
+ client.add_header("foo-header", "bar-header-value").unwrap();
+
+ let e_client = Status::invalid_argument("bad arg: client");
+ let e_server = Status::invalid_argument("bad arg: server");
+
+ // input stream to client sends good FlightData followed by an error
+ let input_flight_data = test_flight_data().await;
+ let input_stream = futures::stream::iter(input_flight_data.clone())
+ .map(Ok)
+ .chain(futures::stream::iter(vec![Err(FlightError::from(
+ e_client.clone(),
+ ))]));
+
+ // server responds with an error (e.g. because it got truncated data)
+ let response = vec![Err(e_server)];
+ test_server.set_do_exchange_response(response);
+
+ let response_stream = client
+ .do_exchange(input_stream)
+ .await
+ .expect("error making request");
+
+ let response: Result<Vec<_>, _> = response_stream.try_collect().await;
+ let response = match response {
+ Ok(_) => panic!("unexpected success"),
+ Err(e) => e,
+ };
+
+ // expect to the error made from the client (not the server)
+ expect_status(response, e_client);
+ // server still got the request messages until the client sent the error
+ assert_eq!(
+ test_server.take_do_exchange_request(),
+ Some(input_flight_data)
+ );
+ ensure_metadata(&client, &test_server);
+ })
+ .await;
+}
+
#[tokio::test]
async fn test_get_schema() {
do_test(|test_server, mut client| async move {
|
Flight Client should accept fallible streams (`do_put` and `do_exchange`)
Perhaps this should accept a `Stream<Item=Result<FlightData>>`, otherwise I'm not sure how one could use this to stream a fallible computation without panicking?
_Originally posted by @tustvold in https://github.com/apache/arrow-rs/pull/3402#discussion_r1061346970_
|
Update is that we implemented this for `do_put` here: https://github.com/apache/arrow-rs/pull/3464
What is needed to close this ticket is to apply the same pattern to `do_exchange`
Since the pattern and testing framework are all in place, I think this would be a good first project.
So this is repeating the pattern of do_put for do_exchange, right? Is the same for the test case? if so I can take it
> So this is repeating the pattern of do_put for do_exchange, right? Is the same for the test case? if so I can take it
That is my understanding -- thank you @shourya5
Please ping me on the PR and I will review it
Not sure about the progress of this issue, I'll pick this up for now. Happy to close my MR if it's not needed.
|
2024-04-27T16:19:58Z
|
51.0
|
30767a687b48d0dbd2e030eef327826c39095123
|
apache/arrow-rs
| 5,679
|
apache__arrow-rs-5679
|
[
"5678"
] |
7568178e37812424d9189c625f3958b165ec13cf
|
diff --git a/arrow-csv/src/reader/mod.rs b/arrow-csv/src/reader/mod.rs
index 4d7d60e10cf6..09087ca31958 100644
--- a/arrow-csv/src/reader/mod.rs
+++ b/arrow-csv/src/reader/mod.rs
@@ -231,6 +231,7 @@ pub struct Format {
quote: Option<u8>,
terminator: Option<u8>,
null_regex: NullRegex,
+ truncated_rows: bool,
}
impl Format {
@@ -265,6 +266,17 @@ impl Format {
self
}
+ /// Whether to allow truncated rows when parsing.
+ ///
+ /// By default this is set to `false` and will error if the CSV rows have different lengths.
+ /// When set to true then it will allow records with less than the expected number of columns
+ /// and fill the missing columns with nulls. If the record's schema is not nullable, then it
+ /// will still return an error.
+ pub fn with_truncated_rows(mut self, allow: bool) -> Self {
+ self.truncated_rows = allow;
+ self
+ }
+
/// Infer schema of CSV records from the provided `reader`
///
/// If `max_records` is `None`, all records will be read, otherwise up to `max_records`
@@ -329,6 +341,7 @@ impl Format {
fn build_reader<R: Read>(&self, reader: R) -> csv::Reader<R> {
let mut builder = csv::ReaderBuilder::new();
builder.has_headers(self.header);
+ builder.flexible(self.truncated_rows);
if let Some(c) = self.delimiter {
builder.delimiter(c);
@@ -1121,6 +1134,17 @@ impl ReaderBuilder {
self
}
+ /// Whether to allow truncated rows when parsing.
+ ///
+ /// By default this is set to `false` and will error if the CSV rows have different lengths.
+ /// When set to true then it will allow records with less than the expected number of columns
+ /// and fill the missing columns with nulls. If the record's schema is not nullable, then it
+ /// will still return an error.
+ pub fn with_truncated_rows(mut self, allow: bool) -> Self {
+ self.format.truncated_rows = allow;
+ self
+ }
+
/// Create a new `Reader` from a non-buffered reader
///
/// If `R: BufRead` consider using [`Self::build_buffered`] to avoid unnecessary additional
@@ -1140,7 +1164,11 @@ impl ReaderBuilder {
/// Builds a decoder that can be used to decode CSV from an arbitrary byte stream
pub fn build_decoder(self) -> Decoder {
let delimiter = self.format.build_parser();
- let record_decoder = RecordDecoder::new(delimiter, self.schema.fields().len());
+ let record_decoder = RecordDecoder::new(
+ delimiter,
+ self.schema.fields().len(),
+ self.format.truncated_rows,
+ );
let header = self.format.header as usize;
@@ -2164,6 +2192,133 @@ mod tests {
assert!(c.is_null(3));
}
+ #[test]
+ fn test_truncated_rows() {
+ let data = "a,b,c\n1,2,3\n4,5\n\n6,7,8";
+ let schema = Arc::new(Schema::new(vec![
+ Field::new("a", DataType::Int32, true),
+ Field::new("b", DataType::Int32, true),
+ Field::new("c", DataType::Int32, true),
+ ]));
+
+ let reader = ReaderBuilder::new(schema.clone())
+ .with_header(true)
+ .with_truncated_rows(true)
+ .build(Cursor::new(data))
+ .unwrap();
+
+ let batches = reader.collect::<Result<Vec<_>, _>>();
+ assert!(batches.is_ok());
+ let batch = batches.unwrap().into_iter().next().unwrap();
+ // Empty rows are skipped by the underlying csv parser
+ assert_eq!(batch.num_rows(), 3);
+
+ let reader = ReaderBuilder::new(schema.clone())
+ .with_header(true)
+ .with_truncated_rows(false)
+ .build(Cursor::new(data))
+ .unwrap();
+
+ let batches = reader.collect::<Result<Vec<_>, _>>();
+ assert!(match batches {
+ Err(ArrowError::CsvError(e)) => e.to_string().contains("incorrect number of fields"),
+ _ => false,
+ });
+ }
+
+ #[test]
+ fn test_truncated_rows_csv() {
+ let file = File::open("test/data/truncated_rows.csv").unwrap();
+ let schema = Arc::new(Schema::new(vec![
+ Field::new("Name", DataType::Utf8, true),
+ Field::new("Age", DataType::UInt32, true),
+ Field::new("Occupation", DataType::Utf8, true),
+ Field::new("DOB", DataType::Date32, true),
+ ]));
+ let reader = ReaderBuilder::new(schema.clone())
+ .with_header(true)
+ .with_batch_size(24)
+ .with_truncated_rows(true);
+ let csv = reader.build(file).unwrap();
+ let batches = csv.collect::<Result<Vec<_>, _>>().unwrap();
+
+ assert_eq!(batches.len(), 1);
+ let batch = &batches[0];
+ assert_eq!(batch.num_rows(), 6);
+ assert_eq!(batch.num_columns(), 4);
+ let name = batch
+ .column(0)
+ .as_any()
+ .downcast_ref::<StringArray>()
+ .unwrap();
+ let age = batch
+ .column(1)
+ .as_any()
+ .downcast_ref::<UInt32Array>()
+ .unwrap();
+ let occupation = batch
+ .column(2)
+ .as_any()
+ .downcast_ref::<StringArray>()
+ .unwrap();
+ let dob = batch
+ .column(3)
+ .as_any()
+ .downcast_ref::<Date32Array>()
+ .unwrap();
+
+ assert_eq!(name.value(0), "A1");
+ assert_eq!(name.value(1), "B2");
+ assert!(name.is_null(2));
+ assert_eq!(name.value(3), "C3");
+ assert_eq!(name.value(4), "D4");
+ assert_eq!(name.value(5), "E5");
+
+ assert_eq!(age.value(0), 34);
+ assert_eq!(age.value(1), 29);
+ assert!(age.is_null(2));
+ assert_eq!(age.value(3), 45);
+ assert!(age.is_null(4));
+ assert_eq!(age.value(5), 31);
+
+ assert_eq!(occupation.value(0), "Engineer");
+ assert_eq!(occupation.value(1), "Doctor");
+ assert!(occupation.is_null(2));
+ assert_eq!(occupation.value(3), "Artist");
+ assert!(occupation.is_null(4));
+ assert!(occupation.is_null(5));
+
+ assert_eq!(dob.value(0), 5675);
+ assert!(dob.is_null(1));
+ assert!(dob.is_null(2));
+ assert_eq!(dob.value(3), -1858);
+ assert!(dob.is_null(4));
+ assert!(dob.is_null(5));
+ }
+
+ #[test]
+ fn test_truncated_rows_not_nullable_error() {
+ let data = "a,b,c\n1,2,3\n4,5";
+ let schema = Arc::new(Schema::new(vec![
+ Field::new("a", DataType::Int32, false),
+ Field::new("b", DataType::Int32, false),
+ Field::new("c", DataType::Int32, false),
+ ]));
+
+ let reader = ReaderBuilder::new(schema.clone())
+ .with_header(true)
+ .with_truncated_rows(true)
+ .build(Cursor::new(data))
+ .unwrap();
+
+ let batches = reader.collect::<Result<Vec<_>, _>>();
+ assert!(match batches {
+ Err(ArrowError::InvalidArgumentError(e)) =>
+ e.to_string().contains("contains null values"),
+ _ => false,
+ });
+ }
+
#[test]
fn test_buffered() {
let tests = [
diff --git a/arrow-csv/src/reader/records.rs b/arrow-csv/src/reader/records.rs
index 877cfb3ee653..a07fc9c94ffa 100644
--- a/arrow-csv/src/reader/records.rs
+++ b/arrow-csv/src/reader/records.rs
@@ -56,10 +56,16 @@ pub struct RecordDecoder {
///
/// We track this independently of Vec to avoid re-zeroing memory
data_len: usize,
+
+ /// Whether rows with less than expected columns are considered valid
+ ///
+ /// Default value is false
+ /// When enabled fills in missing columns with null
+ truncated_rows: bool,
}
impl RecordDecoder {
- pub fn new(delimiter: Reader, num_columns: usize) -> Self {
+ pub fn new(delimiter: Reader, num_columns: usize, truncated_rows: bool) -> Self {
Self {
delimiter,
num_columns,
@@ -70,6 +76,7 @@ impl RecordDecoder {
data_len: 0,
data: vec![],
num_rows: 0,
+ truncated_rows,
}
}
@@ -127,10 +134,19 @@ impl RecordDecoder {
}
ReadRecordResult::Record => {
if self.current_field != self.num_columns {
- return Err(ArrowError::CsvError(format!(
- "incorrect number of fields for line {}, expected {} got {}",
- self.line_number, self.num_columns, self.current_field
- )));
+ if self.truncated_rows && self.current_field < self.num_columns {
+ // If the number of fields is less than expected, pad with nulls
+ let fill_count = self.num_columns - self.current_field;
+ let fill_value = self.offsets[self.offsets_len - 1];
+ self.offsets[self.offsets_len..self.offsets_len + fill_count]
+ .fill(fill_value);
+ self.offsets_len += fill_count;
+ } else {
+ return Err(ArrowError::CsvError(format!(
+ "incorrect number of fields for line {}, expected {} got {}",
+ self.line_number, self.num_columns, self.current_field
+ )));
+ }
}
read += 1;
self.current_field = 0;
@@ -299,7 +315,7 @@ mod tests {
.into_iter();
let mut reader = BufReader::with_capacity(3, Cursor::new(csv.as_bytes()));
- let mut decoder = RecordDecoder::new(Reader::new(), 3);
+ let mut decoder = RecordDecoder::new(Reader::new(), 3, false);
loop {
let to_read = 3;
@@ -333,7 +349,7 @@ mod tests {
#[test]
fn test_invalid_fields() {
let csv = "a,b\nb,c\na\n";
- let mut decoder = RecordDecoder::new(Reader::new(), 2);
+ let mut decoder = RecordDecoder::new(Reader::new(), 2, false);
let err = decoder.decode(csv.as_bytes(), 4).unwrap_err().to_string();
let expected = "Csv error: incorrect number of fields for line 3, expected 2 got 1";
@@ -341,7 +357,7 @@ mod tests {
assert_eq!(err, expected);
// Test with initial skip
- let mut decoder = RecordDecoder::new(Reader::new(), 2);
+ let mut decoder = RecordDecoder::new(Reader::new(), 2, false);
let (skipped, bytes) = decoder.decode(csv.as_bytes(), 1).unwrap();
assert_eq!(skipped, 1);
decoder.clear();
@@ -354,9 +370,18 @@ mod tests {
#[test]
fn test_skip_insufficient_rows() {
let csv = "a\nv\n";
- let mut decoder = RecordDecoder::new(Reader::new(), 1);
+ let mut decoder = RecordDecoder::new(Reader::new(), 1, false);
let (read, bytes) = decoder.decode(csv.as_bytes(), 3).unwrap();
assert_eq!(read, 2);
assert_eq!(bytes, csv.len());
}
+
+ #[test]
+ fn test_truncated_rows() {
+ let csv = "a,b\nv\n,1\n,2\n,3\n";
+ let mut decoder = RecordDecoder::new(Reader::new(), 2, true);
+ let (read, bytes) = decoder.decode(csv.as_bytes(), 5).unwrap();
+ assert_eq!(read, 5);
+ assert_eq!(bytes, csv.len());
+ }
}
|
diff --git a/arrow-csv/test/data/truncated_rows.csv b/arrow-csv/test/data/truncated_rows.csv
new file mode 100644
index 000000000000..0b2af5740095
--- /dev/null
+++ b/arrow-csv/test/data/truncated_rows.csv
@@ -0,0 +1,8 @@
+Name,Age,Occupation,DOB
+A1,34,Engineer,1985-07-16
+B2,29,Doctor
+,
+C3,45,Artist,1964-11-30
+
+D4
+E5,31,,
|
Optionally support flexible column lengths
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
Add the ability to parse csv files that have flexible number of columns. Specifically a large subset of CSVs have columns missing from the ends of rows, and expect them to be treated as null.
**Describe the solution you'd like**
The ability to configure via the format or reader builder the option to enable flexible columns.
**Describe alternatives you've considered**
I have tried python and rust solutions, and while pandas and polars work for the general case, they both have poor support for streaming reads of csv into arrow buffers. Specifically they require either memory mapped files, or buffering most of the file in memory to work, unlike the convenience of the build/build_buffered methods offered by arrow-csv. And while the Rust csv crate is excellent, it is limited to row at a time parsing, and from basic testing I've done arrow-csv outperforms it when it comes to loading large datasets into arrow buffers.
**Additional context**
Example from other implementations:
Rust csv
https://docs.rs/csv/latest/csv/struct.ReaderBuilder.html#method.flexible
https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html#pandas-read-csv
Pandas doesn't specify, but testing shows it allows missing trailing columns by default.
Similarly Polars behaves the same as Pandas and Rust.
https://docs.pola.rs/py-polars/html/reference/api/polars.read_csv.html
However one conflict is that the arrow-cpp csv parser doesn't allow ragged/flexible columns like the current arrow-csv.
|
2024-04-22T15:43:20Z
|
51.0
|
30767a687b48d0dbd2e030eef327826c39095123
|
|
apache/arrow-rs
| 5,652
|
apache__arrow-rs-5652
|
[
"5435"
] |
f2765283b67e64a6923352ed23398ca9ca194ef2
|
diff --git a/object_store/src/aws/client.rs b/object_store/src/aws/client.rs
index e81ef6aa220c..4a4dc178d5b0 100644
--- a/object_store/src/aws/client.rs
+++ b/object_store/src/aws/client.rs
@@ -19,8 +19,8 @@ use crate::aws::builder::S3EncryptionHeaders;
use crate::aws::checksum::Checksum;
use crate::aws::credential::{AwsCredential, CredentialExt};
use crate::aws::{
- AwsAuthorizer, AwsCredentialProvider, S3ConditionalPut, S3CopyIfNotExists, STORE,
- STRICT_PATH_ENCODE_SET,
+ AwsAuthorizer, AwsCredentialProvider, S3ConditionalPut, S3CopyIfNotExists, COPY_SOURCE_HEADER,
+ STORE, STRICT_PATH_ENCODE_SET, TAGS_HEADER,
};
use crate::client::get::GetClient;
use crate::client::header::{get_etag, HeaderConfig};
@@ -35,16 +35,16 @@ use crate::client::GetOptionsExt;
use crate::multipart::PartId;
use crate::path::DELIMITER;
use crate::{
- Attribute, Attributes, ClientOptions, GetOptions, ListResult, MultipartId, Path, PutPayload,
- PutResult, Result, RetryConfig,
+ Attribute, Attributes, ClientOptions, GetOptions, ListResult, MultipartId, Path,
+ PutMultipartOpts, PutPayload, PutResult, Result, RetryConfig, TagSet,
};
use async_trait::async_trait;
use base64::prelude::BASE64_STANDARD;
use base64::Engine;
use bytes::{Buf, Bytes};
use hyper::header::{CACHE_CONTROL, CONTENT_LENGTH};
-use hyper::http;
use hyper::http::HeaderName;
+use hyper::{http, HeaderMap};
use itertools::Itertools;
use md5::{Digest, Md5};
use percent_encoding::{utf8_percent_encode, PercentEncode};
@@ -98,9 +98,6 @@ pub(crate) enum Error {
#[snafu(display("Error getting list response body: {}", source))]
ListResponseBody { source: reqwest::Error },
- #[snafu(display("Error performing create multipart request: {}", source))]
- CreateMultipartRequest { source: crate::client::retry::Error },
-
#[snafu(display("Error getting create multipart response body: {}", source))]
CreateMultipartResponseBody { source: reqwest::Error },
@@ -289,8 +286,75 @@ impl<'a> Request<'a> {
Self { builder, ..self }
}
- pub fn idempotent(mut self, idempotent: bool) -> Self {
- self.idempotent = idempotent;
+ pub fn headers(self, headers: HeaderMap) -> Self {
+ let builder = self.builder.headers(headers);
+ Self { builder, ..self }
+ }
+
+ pub fn idempotent(self, idempotent: bool) -> Self {
+ Self { idempotent, ..self }
+ }
+
+ pub fn with_encryption_headers(self) -> Self {
+ let headers = self.config.encryption_headers.clone().into();
+ let builder = self.builder.headers(headers);
+ Self { builder, ..self }
+ }
+
+ pub fn with_session_creds(self, use_session_creds: bool) -> Self {
+ Self {
+ use_session_creds,
+ ..self
+ }
+ }
+
+ pub fn with_tags(mut self, tags: TagSet) -> Self {
+ let tags = tags.encoded();
+ if !tags.is_empty() && !self.config.disable_tagging {
+ self.builder = self.builder.header(&TAGS_HEADER, tags);
+ }
+ self
+ }
+
+ pub fn with_attributes(self, attributes: Attributes) -> Self {
+ let mut has_content_type = false;
+ let mut builder = self.builder;
+ for (k, v) in &attributes {
+ builder = match k {
+ Attribute::CacheControl => builder.header(CACHE_CONTROL, v.as_ref()),
+ Attribute::ContentType => {
+ has_content_type = true;
+ builder.header(CONTENT_TYPE, v.as_ref())
+ }
+ };
+ }
+
+ if !has_content_type {
+ if let Some(value) = self.config.client_options.get_content_type(self.path) {
+ builder = builder.header(CONTENT_TYPE, value);
+ }
+ }
+ Self { builder, ..self }
+ }
+
+ pub fn with_payload(mut self, payload: PutPayload) -> Self {
+ if !self.config.skip_signature || self.config.checksum.is_some() {
+ let mut sha256 = Context::new(&digest::SHA256);
+ payload.iter().for_each(|x| sha256.update(x));
+ let payload_sha256 = sha256.finish();
+
+ if let Some(Checksum::SHA256) = self.config.checksum {
+ self.builder = self.builder.header(
+ "x-amz-checksum-sha256",
+ BASE64_STANDARD.encode(payload_sha256),
+ );
+ }
+ self.payload_sha256 = Some(payload_sha256);
+ }
+
+ let content_length = payload.content_length();
+ self.builder = self.builder.header(CONTENT_LENGTH, content_length);
+ self.payload = Some(payload);
self
}
@@ -335,81 +399,19 @@ impl S3Client {
Ok(Self { config, client })
}
- /// Make an S3 PUT request <https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObject.html>
- ///
- /// Returns the ETag
- pub fn put_request<'a>(
- &'a self,
- path: &'a Path,
- payload: PutPayload,
- attributes: Attributes,
- with_encryption_headers: bool,
- ) -> Request<'a> {
+ pub fn request<'a>(&'a self, method: Method, path: &'a Path) -> Request<'a> {
let url = self.config.path_url(path);
- let mut builder = self.client.request(Method::PUT, url);
- if with_encryption_headers {
- builder = builder.headers(self.config.encryption_headers.clone().into());
- }
-
- let mut sha256 = Context::new(&digest::SHA256);
- payload.iter().for_each(|x| sha256.update(x));
- let payload_sha256 = sha256.finish();
-
- if let Some(Checksum::SHA256) = self.config.checksum {
- builder = builder.header(
- "x-amz-checksum-sha256",
- BASE64_STANDARD.encode(payload_sha256),
- )
- }
-
- let mut has_content_type = false;
- for (k, v) in &attributes {
- builder = match k {
- Attribute::CacheControl => builder.header(CACHE_CONTROL, v.as_ref()),
- Attribute::ContentType => {
- has_content_type = true;
- builder.header(CONTENT_TYPE, v.as_ref())
- }
- };
- }
-
- if !has_content_type {
- if let Some(value) = self.config.client_options.get_content_type(path) {
- builder = builder.header(CONTENT_TYPE, value);
- }
- }
-
Request {
path,
- builder: builder.header(CONTENT_LENGTH, payload.content_length()),
- payload: Some(payload),
- payload_sha256: Some(payload_sha256),
+ builder: self.client.request(method, url),
+ payload: None,
+ payload_sha256: None,
config: &self.config,
use_session_creds: true,
idempotent: false,
}
}
- /// Make an S3 Delete request <https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteObject.html>
- pub async fn delete_request<T: Serialize + ?Sized + Sync>(
- &self,
- path: &Path,
- query: &T,
- ) -> Result<()> {
- let credential = self.config.get_session_credential().await?;
- let url = self.config.path_url(path);
-
- self.client
- .request(Method::DELETE, url)
- .query(query)
- .with_aws_sigv4(credential.authorizer(), None)
- .send_retry(&self.config.retry_config)
- .await
- .map_err(|e| e.error(STORE, path.to_string()))?;
-
- Ok(())
- }
-
/// Make an S3 Delete Objects request <https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteObjects.html>
///
/// Produces a vector of results, one for each path in the input vector. If
@@ -513,41 +515,29 @@ impl S3Client {
}
/// Make an S3 Copy request <https://docs.aws.amazon.com/AmazonS3/latest/API/API_CopyObject.html>
- pub fn copy_request<'a>(&'a self, from: &'a Path, to: &Path) -> Request<'a> {
- let url = self.config.path_url(to);
+ pub fn copy_request<'a>(&'a self, from: &Path, to: &'a Path) -> Request<'a> {
let source = format!("{}/{}", self.config.bucket, encode_path(from));
-
- let builder = self
- .client
- .request(Method::PUT, url)
- .header("x-amz-copy-source", source)
- .headers(self.config.encryption_headers.clone().into());
-
- Request {
- builder,
- path: from,
- config: &self.config,
- payload: None,
- payload_sha256: None,
- use_session_creds: false,
- idempotent: false,
- }
+ self.request(Method::PUT, to)
+ .idempotent(true)
+ .header(©_SOURCE_HEADER, &source)
+ .headers(self.config.encryption_headers.clone().into())
+ .with_session_creds(false)
}
- pub async fn create_multipart(&self, location: &Path) -> Result<MultipartId> {
- let credential = self.config.get_session_credential().await?;
- let url = format!("{}?uploads=", self.config.path_url(location),);
-
+ pub async fn create_multipart(
+ &self,
+ location: &Path,
+ opts: PutMultipartOpts,
+ ) -> Result<MultipartId> {
let response = self
- .client
- .request(Method::POST, url)
- .headers(self.config.encryption_headers.clone().into())
- .with_aws_sigv4(credential.authorizer(), None)
- .retryable(&self.config.retry_config)
+ .request(Method::POST, location)
+ .query(&[("uploads", "")])
+ .with_encryption_headers()
+ .with_attributes(opts.attributes)
+ .with_tags(opts.tags)
.idempotent(true)
.send()
- .await
- .context(CreateMultipartRequestSnafu)?
+ .await?
.bytes()
.await
.context(CreateMultipartResponseBodySnafu)?;
@@ -568,7 +558,8 @@ impl S3Client {
let part = (part_idx + 1).to_string();
let response = self
- .put_request(path, data, Attributes::default(), false)
+ .request(Method::PUT, path)
+ .with_payload(data)
.query(&[("partNumber", &part), ("uploadId", upload_id)])
.idempotent(true)
.send()
diff --git a/object_store/src/aws/mod.rs b/object_store/src/aws/mod.rs
index 43bd38a6de2e..7f1edf12faf8 100644
--- a/object_store/src/aws/mod.rs
+++ b/object_store/src/aws/mod.rs
@@ -45,10 +45,12 @@ use crate::signer::Signer;
use crate::util::STRICT_ENCODE_SET;
use crate::{
Error, GetOptions, GetResult, ListResult, MultipartId, MultipartUpload, ObjectMeta,
- ObjectStore, Path, PutMode, PutOptions, PutPayload, PutResult, Result, UploadPart,
+ ObjectStore, Path, PutMode, PutMultipartOpts, PutOptions, PutPayload, PutResult, Result,
+ UploadPart,
};
static TAGS_HEADER: HeaderName = HeaderName::from_static("x-amz-tagging");
+static COPY_SOURCE_HEADER: HeaderName = HeaderName::from_static("x-amz-copy-source");
mod builder;
mod checksum;
@@ -156,12 +158,13 @@ impl ObjectStore for AmazonS3 {
payload: PutPayload,
opts: PutOptions,
) -> Result<PutResult> {
- let attrs = opts.attributes;
- let mut request = self.client.put_request(location, payload, attrs, true);
- let tags = opts.tags.encoded();
- if !tags.is_empty() && !self.client.config.disable_tagging {
- request = request.header(&TAGS_HEADER, tags);
- }
+ let request = self
+ .client
+ .request(Method::PUT, location)
+ .with_payload(payload)
+ .with_attributes(opts.attributes)
+ .with_tags(opts.tags)
+ .with_encryption_headers();
match (opts.mode, &self.client.config.conditional_put) {
(PutMode::Overwrite, _) => request.idempotent(true).do_put().await,
@@ -204,8 +207,12 @@ impl ObjectStore for AmazonS3 {
}
}
- async fn put_multipart(&self, location: &Path) -> Result<Box<dyn MultipartUpload>> {
- let upload_id = self.client.create_multipart(location).await?;
+ async fn put_multipart_opts(
+ &self,
+ location: &Path,
+ opts: PutMultipartOpts,
+ ) -> Result<Box<dyn MultipartUpload>> {
+ let upload_id = self.client.create_multipart(location, opts).await?;
Ok(Box::new(S3MultiPartUpload {
part_idx: 0,
@@ -223,7 +230,8 @@ impl ObjectStore for AmazonS3 {
}
async fn delete(&self, location: &Path) -> Result<()> {
- self.client.delete_request(location, &()).await
+ self.client.request(Method::DELETE, location).send().await?;
+ Ok(())
}
fn delete_stream<'a>(
@@ -351,15 +359,22 @@ impl MultipartUpload for S3MultiPartUpload {
async fn abort(&mut self) -> Result<()> {
self.state
.client
- .delete_request(&self.state.location, &[("uploadId", &self.state.upload_id)])
- .await
+ .request(Method::DELETE, &self.state.location)
+ .query(&[("uploadId", &self.state.upload_id)])
+ .idempotent(true)
+ .send()
+ .await?;
+
+ Ok(())
}
}
#[async_trait]
impl MultipartStore for AmazonS3 {
async fn create_multipart(&self, path: &Path) -> Result<MultipartId> {
- self.client.create_multipart(path).await
+ self.client
+ .create_multipart(path, PutMultipartOpts::default())
+ .await
}
async fn put_part(
@@ -382,7 +397,12 @@ impl MultipartStore for AmazonS3 {
}
async fn abort_multipart(&self, path: &Path, id: &MultipartId) -> Result<()> {
- self.client.delete_request(path, &[("uploadId", id)]).await
+ self.client
+ .request(Method::DELETE, path)
+ .query(&[("uploadId", id)])
+ .send()
+ .await?;
+ Ok(())
}
}
diff --git a/object_store/src/azure/client.rs b/object_store/src/azure/client.rs
index 134609eb262e..918fcd047ae1 100644
--- a/object_store/src/azure/client.rs
+++ b/object_store/src/azure/client.rs
@@ -28,16 +28,14 @@ use crate::path::DELIMITER;
use crate::util::{deserialize_rfc1123, GetRange};
use crate::{
Attribute, Attributes, ClientOptions, GetOptions, ListResult, ObjectMeta, Path, PutMode,
- PutOptions, PutPayload, PutResult, Result, RetryConfig,
+ PutMultipartOpts, PutOptions, PutPayload, PutResult, Result, RetryConfig, TagSet,
};
use async_trait::async_trait;
use base64::prelude::BASE64_STANDARD;
use base64::Engine;
use bytes::{Buf, Bytes};
use chrono::{DateTime, Utc};
-use hyper::header::CACHE_CONTROL;
use hyper::http::HeaderName;
-use reqwest::header::CONTENT_TYPE;
use reqwest::{
header::{HeaderValue, CONTENT_LENGTH, IF_MATCH, IF_NONE_MATCH},
Client as ReqwestClient, Method, RequestBuilder, Response,
@@ -50,6 +48,8 @@ use std::time::Duration;
use url::Url;
const VERSION_HEADER: &str = "x-ms-version-id";
+static MS_CACHE_CONTROL: HeaderName = HeaderName::from_static("x-ms-blob-cache-control");
+static MS_CONTENT_TYPE: HeaderName = HeaderName::from_static("x-ms-blob-content-type");
static TAGS_HEADER: HeaderName = HeaderName::from_static("x-ms-tags");
@@ -188,10 +188,39 @@ impl<'a> PutRequest<'a> {
Self { builder, ..self }
}
- fn set_idempotent(self, idempotent: bool) -> Self {
+ fn idempotent(self, idempotent: bool) -> Self {
Self { idempotent, ..self }
}
+ fn with_tags(mut self, tags: TagSet) -> Self {
+ let tags = tags.encoded();
+ if !tags.is_empty() && !self.config.disable_tagging {
+ self.builder = self.builder.header(&TAGS_HEADER, tags);
+ }
+ self
+ }
+
+ fn with_attributes(self, attributes: Attributes) -> Self {
+ let mut builder = self.builder;
+ let mut has_content_type = false;
+ for (k, v) in &attributes {
+ builder = match k {
+ Attribute::CacheControl => builder.header(&MS_CACHE_CONTROL, v.as_ref()),
+ Attribute::ContentType => {
+ has_content_type = true;
+ builder.header(&MS_CONTENT_TYPE, v.as_ref())
+ }
+ };
+ }
+
+ if !has_content_type {
+ if let Some(value) = self.config.client_options.get_content_type(self.path) {
+ builder = builder.header(&MS_CONTENT_TYPE, value);
+ }
+ }
+ Self { builder, ..self }
+ }
+
async fn send(self) -> Result<Response> {
let credential = self.config.get_credential().await?;
let response = self
@@ -233,32 +262,9 @@ impl AzureClient {
self.config.get_credential().await
}
- fn put_request<'a>(
- &'a self,
- path: &'a Path,
- payload: PutPayload,
- attributes: Attributes,
- ) -> PutRequest<'a> {
+ fn put_request<'a>(&'a self, path: &'a Path, payload: PutPayload) -> PutRequest<'a> {
let url = self.config.path_url(path);
-
- let mut builder = self.client.request(Method::PUT, url);
-
- let mut has_content_type = false;
- for (k, v) in &attributes {
- builder = match k {
- Attribute::CacheControl => builder.header(CACHE_CONTROL, v.as_ref()),
- Attribute::ContentType => {
- has_content_type = true;
- builder.header(CONTENT_TYPE, v.as_ref())
- }
- };
- }
-
- if !has_content_type {
- if let Some(value) = self.config.client_options.get_content_type(path) {
- builder = builder.header(CONTENT_TYPE, value);
- }
- }
+ let builder = self.client.request(Method::PUT, url);
PutRequest {
path,
@@ -276,10 +282,13 @@ impl AzureClient {
payload: PutPayload,
opts: PutOptions,
) -> Result<PutResult> {
- let builder = self.put_request(path, payload, opts.attributes);
+ let builder = self
+ .put_request(path, payload)
+ .with_attributes(opts.attributes)
+ .with_tags(opts.tags);
let builder = match &opts.mode {
- PutMode::Overwrite => builder.set_idempotent(true),
+ PutMode::Overwrite => builder.idempotent(true),
PutMode::Create => builder.header(&IF_NONE_MATCH, "*"),
PutMode::Update(v) => {
let etag = v.e_tag.as_ref().context(MissingETagSnafu)?;
@@ -287,11 +296,6 @@ impl AzureClient {
}
};
- let builder = match (opts.tags.encoded(), self.config.disable_tagging) {
- ("", _) | (_, true) => builder,
- (tags, false) => builder.header(&TAGS_HEADER, tags),
- };
-
let response = builder.header(&BLOB_TYPE, "BlockBlob").send().await?;
Ok(get_put_result(response.headers(), VERSION_HEADER).context(MetadataSnafu)?)
}
@@ -306,9 +310,9 @@ impl AzureClient {
let content_id = format!("{part_idx:20}");
let block_id = BASE64_STANDARD.encode(&content_id);
- self.put_request(path, payload, Attributes::default())
+ self.put_request(path, payload)
.query(&[("comp", "block"), ("blockid", &block_id)])
- .set_idempotent(true)
+ .idempotent(true)
.send()
.await?;
@@ -316,7 +320,12 @@ impl AzureClient {
}
/// PUT a block list <https://learn.microsoft.com/en-us/rest/api/storageservices/put-block-list>
- pub async fn put_block_list(&self, path: &Path, parts: Vec<PartId>) -> Result<PutResult> {
+ pub async fn put_block_list(
+ &self,
+ path: &Path,
+ parts: Vec<PartId>,
+ opts: PutMultipartOpts,
+ ) -> Result<PutResult> {
let blocks = parts
.into_iter()
.map(|part| BlockId::from(part.content_id))
@@ -324,9 +333,11 @@ impl AzureClient {
let payload = BlockList { blocks }.to_xml().into();
let response = self
- .put_request(path, payload, Attributes::default())
+ .put_request(path, payload)
+ .with_attributes(opts.attributes)
+ .with_tags(opts.tags)
.query(&[("comp", "blocklist")])
- .set_idempotent(true)
+ .idempotent(true)
.send()
.await?;
diff --git a/object_store/src/azure/mod.rs b/object_store/src/azure/mod.rs
index 3bb57c45aa6b..25ae6dda68a8 100644
--- a/object_store/src/azure/mod.rs
+++ b/object_store/src/azure/mod.rs
@@ -27,7 +27,7 @@ use crate::{
path::Path,
signer::Signer,
GetOptions, GetResult, ListResult, MultipartId, MultipartUpload, ObjectMeta, ObjectStore,
- PutOptions, PutPayload, PutResult, Result, UploadPart,
+ PutMultipartOpts, PutOptions, PutPayload, PutResult, Result, UploadPart,
};
use async_trait::async_trait;
use futures::stream::BoxStream;
@@ -95,9 +95,14 @@ impl ObjectStore for MicrosoftAzure {
self.client.put_blob(location, payload, opts).await
}
- async fn put_multipart(&self, location: &Path) -> Result<Box<dyn MultipartUpload>> {
+ async fn put_multipart_opts(
+ &self,
+ location: &Path,
+ opts: PutMultipartOpts,
+ ) -> Result<Box<dyn MultipartUpload>> {
Ok(Box::new(AzureMultiPartUpload {
part_idx: 0,
+ opts,
state: Arc::new(UploadState {
client: Arc::clone(&self.client),
location: location.clone(),
@@ -196,6 +201,7 @@ impl Signer for MicrosoftAzure {
struct AzureMultiPartUpload {
part_idx: usize,
state: Arc<UploadState>,
+ opts: PutMultipartOpts,
}
#[derive(Debug)]
@@ -223,7 +229,7 @@ impl MultipartUpload for AzureMultiPartUpload {
self.state
.client
- .put_block_list(&self.state.location, parts)
+ .put_block_list(&self.state.location, parts, std::mem::take(&mut self.opts))
.await
}
@@ -255,7 +261,9 @@ impl MultipartStore for MicrosoftAzure {
_: &MultipartId,
parts: Vec<PartId>,
) -> Result<PutResult> {
- self.client.put_block_list(path, parts).await
+ self.client
+ .put_block_list(path, parts, Default::default())
+ .await
}
async fn abort_multipart(&self, _: &Path, _: &MultipartId) -> Result<()> {
diff --git a/object_store/src/chunked.rs b/object_store/src/chunked.rs
index 9abe49dbfce9..a3bd76267875 100644
--- a/object_store/src/chunked.rs
+++ b/object_store/src/chunked.rs
@@ -29,7 +29,7 @@ use futures::StreamExt;
use crate::path::Path;
use crate::{
GetOptions, GetResult, GetResultPayload, ListResult, MultipartUpload, ObjectMeta, ObjectStore,
- PutOptions, PutResult,
+ PutMultipartOpts, PutOptions, PutResult,
};
use crate::{PutPayload, Result};
@@ -75,6 +75,14 @@ impl ObjectStore for ChunkedStore {
self.inner.put_multipart(location).await
}
+ async fn put_multipart_opts(
+ &self,
+ location: &Path,
+ opts: PutMultipartOpts,
+ ) -> Result<Box<dyn MultipartUpload>> {
+ self.inner.put_multipart_opts(location, opts).await
+ }
+
async fn get_opts(&self, location: &Path, options: GetOptions) -> Result<GetResult> {
let r = self.inner.get_opts(location, options).await?;
let stream = match r.payload {
diff --git a/object_store/src/gcp/client.rs b/object_store/src/gcp/client.rs
index 4ee03eaad629..9c39efe6b237 100644
--- a/object_store/src/gcp/client.rs
+++ b/object_store/src/gcp/client.rs
@@ -29,8 +29,8 @@ use crate::multipart::PartId;
use crate::path::{Path, DELIMITER};
use crate::util::hex_encode;
use crate::{
- Attribute, Attributes, ClientOptions, GetOptions, ListResult, MultipartId, PutMode, PutOptions,
- PutPayload, PutResult, Result, RetryConfig,
+ Attribute, Attributes, ClientOptions, GetOptions, ListResult, MultipartId, PutMode,
+ PutMultipartOpts, PutOptions, PutPayload, PutResult, Result, RetryConfig,
};
use async_trait::async_trait;
use base64::prelude::BASE64_STANDARD;
@@ -39,7 +39,7 @@ use bytes::Buf;
use hyper::header::{CACHE_CONTROL, CONTENT_LENGTH, CONTENT_TYPE};
use percent_encoding::{percent_encode, utf8_percent_encode, NON_ALPHANUMERIC};
use reqwest::header::HeaderName;
-use reqwest::{header, Client, Method, RequestBuilder, Response, StatusCode};
+use reqwest::{Client, Method, RequestBuilder, Response, StatusCode};
use serde::{Deserialize, Serialize};
use snafu::{OptionExt, ResultExt, Snafu};
use std::sync::Arc;
@@ -66,14 +66,8 @@ enum Error {
path: String,
},
- #[snafu(display("Error performing delete request {}: {}", path, source))]
- DeleteRequest {
- source: crate::client::retry::Error,
- path: String,
- },
-
- #[snafu(display("Error performing put request {}: {}", path, source))]
- PutRequest {
+ #[snafu(display("Error performing request {}: {}", path, source))]
+ Request {
source: crate::client::retry::Error,
path: String,
},
@@ -120,9 +114,9 @@ enum Error {
impl From<Error> for crate::Error {
fn from(err: Error) -> Self {
match err {
- Error::GetRequest { source, path }
- | Error::DeleteRequest { source, path }
- | Error::PutRequest { source, path } => source.error(STORE, path),
+ Error::GetRequest { source, path } | Error::Request { source, path } => {
+ source.error(STORE, path)
+ }
_ => Self::Generic {
store: STORE,
source: Box::new(err),
@@ -171,15 +165,15 @@ impl GoogleCloudStorageConfig {
}
/// A builder for a put request allowing customisation of the headers and query string
-pub struct PutRequest<'a> {
+pub struct Request<'a> {
path: &'a Path,
config: &'a GoogleCloudStorageConfig,
- payload: PutPayload,
+ payload: Option<PutPayload>,
builder: RequestBuilder,
idempotent: bool,
}
-impl<'a> PutRequest<'a> {
+impl<'a> Request<'a> {
fn header(self, k: &HeaderName, v: &str) -> Self {
let builder = self.builder.header(k, v);
Self { builder, ..self }
@@ -190,26 +184,58 @@ impl<'a> PutRequest<'a> {
Self { builder, ..self }
}
- fn set_idempotent(mut self, idempotent: bool) -> Self {
+ fn idempotent(mut self, idempotent: bool) -> Self {
self.idempotent = idempotent;
self
}
- async fn send(self) -> Result<PutResult> {
+ fn with_attributes(self, attributes: Attributes) -> Self {
+ let mut builder = self.builder;
+ let mut has_content_type = false;
+ for (k, v) in &attributes {
+ builder = match k {
+ Attribute::CacheControl => builder.header(CACHE_CONTROL, v.as_ref()),
+ Attribute::ContentType => {
+ has_content_type = true;
+ builder.header(CONTENT_TYPE, v.as_ref())
+ }
+ };
+ }
+
+ if !has_content_type {
+ let value = self.config.client_options.get_content_type(self.path);
+ builder = builder.header(CONTENT_TYPE, value.unwrap_or(DEFAULT_CONTENT_TYPE))
+ }
+ Self { builder, ..self }
+ }
+
+ fn with_payload(self, payload: PutPayload) -> Self {
+ let content_length = payload.content_length();
+ Self {
+ builder: self.builder.header(CONTENT_LENGTH, content_length),
+ payload: Some(payload),
+ ..self
+ }
+ }
+
+ async fn send(self) -> Result<Response> {
let credential = self.config.credentials.get_credential().await?;
- let response = self
+ let resp = self
.builder
.bearer_auth(&credential.bearer)
- .header(CONTENT_LENGTH, self.payload.content_length())
.retryable(&self.config.retry_config)
.idempotent(self.idempotent)
- .payload(Some(self.payload))
+ .payload(self.payload)
.send()
.await
- .context(PutRequestSnafu {
+ .context(RequestSnafu {
path: self.path.as_ref(),
})?;
+ Ok(resp)
+ }
+ async fn do_put(self) -> Result<PutResult> {
+ let response = self.send().await?;
Ok(get_put_result(response.headers(), VERSION_HEADER).context(MetadataSnafu)?)
}
}
@@ -324,36 +350,13 @@ impl GoogleCloudStorageClient {
/// Perform a put request <https://cloud.google.com/storage/docs/xml-api/put-object-upload>
///
/// Returns the new ETag
- pub fn put_request<'a>(
- &'a self,
- path: &'a Path,
- payload: PutPayload,
- attributes: Attributes,
- ) -> PutRequest<'a> {
- let url = self.object_url(path);
- let mut builder = self.client.request(Method::PUT, url);
-
- let mut has_content_type = false;
- for (k, v) in &attributes {
- builder = match k {
- Attribute::CacheControl => builder.header(CACHE_CONTROL, v.as_ref()),
- Attribute::ContentType => {
- has_content_type = true;
- builder.header(CONTENT_TYPE, v.as_ref())
- }
- };
- }
+ pub fn request<'a>(&'a self, method: Method, path: &'a Path) -> Request<'a> {
+ let builder = self.client.request(method, self.object_url(path));
- if !has_content_type {
- let opts = &self.config.client_options;
- let value = opts.get_content_type(path).unwrap_or(DEFAULT_CONTENT_TYPE);
- builder = builder.header(CONTENT_TYPE, value)
- }
-
- PutRequest {
+ Request {
path,
builder,
- payload,
+ payload: None,
config: &self.config,
idempotent: false,
}
@@ -365,10 +368,13 @@ impl GoogleCloudStorageClient {
payload: PutPayload,
opts: PutOptions,
) -> Result<PutResult> {
- let builder = self.put_request(path, payload, opts.attributes);
+ let builder = self
+ .request(Method::PUT, path)
+ .with_payload(payload)
+ .with_attributes(opts.attributes);
let builder = match &opts.mode {
- PutMode::Overwrite => builder.set_idempotent(true),
+ PutMode::Overwrite => builder.idempotent(true),
PutMode::Create => builder.header(&VERSION_MATCH, "0"),
PutMode::Update(v) => {
let etag = v.version.as_ref().context(MissingVersionSnafu)?;
@@ -376,7 +382,7 @@ impl GoogleCloudStorageClient {
}
};
- match (opts.mode, builder.send().await) {
+ match (opts.mode, builder.do_put().await) {
(PutMode::Create, Err(crate::Error::Precondition { path, source })) => {
Err(crate::Error::AlreadyExists { path, source })
}
@@ -399,10 +405,11 @@ impl GoogleCloudStorageClient {
("uploadId", upload_id),
];
let result = self
- .put_request(path, data, Attributes::new())
+ .request(Method::PUT, path)
+ .with_payload(data)
.query(query)
- .set_idempotent(true)
- .send()
+ .idempotent(true)
+ .do_put()
.await?;
Ok(PartId {
@@ -411,30 +418,18 @@ impl GoogleCloudStorageClient {
}
/// Initiate a multipart upload <https://cloud.google.com/storage/docs/xml-api/post-object-multipart>
- pub async fn multipart_initiate(&self, path: &Path) -> Result<MultipartId> {
- let credential = self.get_credential().await?;
- let url = self.object_url(path);
-
- let content_type = self
- .config
- .client_options
- .get_content_type(path)
- .unwrap_or("application/octet-stream");
-
+ pub async fn multipart_initiate(
+ &self,
+ path: &Path,
+ opts: PutMultipartOpts,
+ ) -> Result<MultipartId> {
let response = self
- .client
- .request(Method::POST, &url)
- .bearer_auth(&credential.bearer)
- .header(header::CONTENT_TYPE, content_type)
- .header(header::CONTENT_LENGTH, "0")
+ .request(Method::POST, path)
+ .with_attributes(opts.attributes)
+ .header(&CONTENT_LENGTH, "0")
.query(&[("uploads", "")])
- .retryable(&self.config.retry_config)
- .idempotent(true)
.send()
- .await
- .context(PutRequestSnafu {
- path: path.as_ref(),
- })?;
+ .await?;
let data = response.bytes().await.context(PutResponseBodySnafu)?;
let result: InitiateMultipartUploadResult =
@@ -451,12 +446,12 @@ impl GoogleCloudStorageClient {
self.client
.request(Method::DELETE, &url)
.bearer_auth(&credential.bearer)
- .header(header::CONTENT_TYPE, "application/octet-stream")
- .header(header::CONTENT_LENGTH, "0")
+ .header(CONTENT_TYPE, "application/octet-stream")
+ .header(CONTENT_LENGTH, "0")
.query(&[("uploadId", multipart_id)])
.send_retry(&self.config.retry_config)
.await
- .context(PutRequestSnafu {
+ .context(RequestSnafu {
path: path.as_ref(),
})?;
@@ -472,9 +467,9 @@ impl GoogleCloudStorageClient {
if completed_parts.is_empty() {
// GCS doesn't allow empty multipart uploads
let result = self
- .put_request(path, Default::default(), Attributes::new())
- .set_idempotent(true)
- .send()
+ .request(Method::PUT, path)
+ .idempotent(true)
+ .do_put()
.await?;
self.multipart_cleanup(path, multipart_id).await?;
return Ok(result);
@@ -523,18 +518,7 @@ impl GoogleCloudStorageClient {
/// Perform a delete request <https://cloud.google.com/storage/docs/xml-api/delete-object>
pub async fn delete_request(&self, path: &Path) -> Result<()> {
- let credential = self.get_credential().await?;
- let url = self.object_url(path);
-
- let builder = self.client.request(Method::DELETE, url);
- builder
- .bearer_auth(&credential.bearer)
- .send_retry(&self.config.retry_config)
- .await
- .context(DeleteRequestSnafu {
- path: path.as_ref(),
- })?;
-
+ self.request(Method::DELETE, path).send().await?;
Ok(())
}
diff --git a/object_store/src/gcp/mod.rs b/object_store/src/gcp/mod.rs
index af6e671cbc35..0ec6e7e82644 100644
--- a/object_store/src/gcp/mod.rs
+++ b/object_store/src/gcp/mod.rs
@@ -42,7 +42,8 @@ use crate::gcp::credential::GCSAuthorizer;
use crate::signer::Signer;
use crate::{
multipart::PartId, path::Path, GetOptions, GetResult, ListResult, MultipartId, MultipartUpload,
- ObjectMeta, ObjectStore, PutOptions, PutPayload, PutResult, Result, UploadPart,
+ ObjectMeta, ObjectStore, PutMultipartOpts, PutOptions, PutPayload, PutResult, Result,
+ UploadPart,
};
use async_trait::async_trait;
use client::GoogleCloudStorageClient;
@@ -156,8 +157,12 @@ impl ObjectStore for GoogleCloudStorage {
self.client.put(location, payload, opts).await
}
- async fn put_multipart(&self, location: &Path) -> Result<Box<dyn MultipartUpload>> {
- let upload_id = self.client.multipart_initiate(location).await?;
+ async fn put_multipart_opts(
+ &self,
+ location: &Path,
+ opts: PutMultipartOpts,
+ ) -> Result<Box<dyn MultipartUpload>> {
+ let upload_id = self.client.multipart_initiate(location, opts).await?;
Ok(Box::new(GCSMultipartUpload {
part_idx: 0,
@@ -206,7 +211,9 @@ impl ObjectStore for GoogleCloudStorage {
#[async_trait]
impl MultipartStore for GoogleCloudStorage {
async fn create_multipart(&self, path: &Path) -> Result<MultipartId> {
- self.client.multipart_initiate(path).await
+ self.client
+ .multipart_initiate(path, PutMultipartOpts::default())
+ .await
}
async fn put_part(
diff --git a/object_store/src/http/mod.rs b/object_store/src/http/mod.rs
index d6ba4f4d913d..404211e578de 100644
--- a/object_store/src/http/mod.rs
+++ b/object_store/src/http/mod.rs
@@ -44,7 +44,7 @@ use crate::http::client::Client;
use crate::path::Path;
use crate::{
ClientConfigKey, ClientOptions, GetOptions, GetResult, ListResult, MultipartUpload, ObjectMeta,
- ObjectStore, PutMode, PutOptions, PutPayload, PutResult, Result, RetryConfig,
+ ObjectStore, PutMode, PutMultipartOpts, PutOptions, PutPayload, PutResult, Result, RetryConfig,
};
mod client;
@@ -118,7 +118,11 @@ impl ObjectStore for HttpStore {
})
}
- async fn put_multipart(&self, _location: &Path) -> Result<Box<dyn MultipartUpload>> {
+ async fn put_multipart_opts(
+ &self,
+ _location: &Path,
+ _opts: PutMultipartOpts,
+ ) -> Result<Box<dyn MultipartUpload>> {
Err(crate::Error::NotImplemented)
}
diff --git a/object_store/src/lib.rs b/object_store/src/lib.rs
index b492d93894a7..ad72bd29ef76 100644
--- a/object_store/src/lib.rs
+++ b/object_store/src/lib.rs
@@ -597,7 +597,20 @@ pub trait ObjectStore: std::fmt::Display + Send + Sync + Debug + 'static {
///
/// Client should prefer [`ObjectStore::put`] for small payloads, as streaming uploads
/// typically require multiple separate requests. See [`MultipartUpload`] for more information
- async fn put_multipart(&self, location: &Path) -> Result<Box<dyn MultipartUpload>>;
+ async fn put_multipart(&self, location: &Path) -> Result<Box<dyn MultipartUpload>> {
+ self.put_multipart_opts(location, PutMultipartOpts::default())
+ .await
+ }
+
+ /// Perform a multipart upload with options
+ ///
+ /// Client should prefer [`ObjectStore::put`] for small payloads, as streaming uploads
+ /// typically require multiple separate requests. See [`MultipartUpload`] for more information
+ async fn put_multipart_opts(
+ &self,
+ location: &Path,
+ opts: PutMultipartOpts,
+ ) -> Result<Box<dyn MultipartUpload>>;
/// Return the bytes that are stored at the specified location.
async fn get(&self, location: &Path) -> Result<GetResult> {
@@ -785,6 +798,14 @@ macro_rules! as_ref_impl {
self.as_ref().put_multipart(location).await
}
+ async fn put_multipart_opts(
+ &self,
+ location: &Path,
+ opts: PutMultipartOpts,
+ ) -> Result<Box<dyn MultipartUpload>> {
+ self.as_ref().put_multipart_opts(location, opts).await
+ }
+
async fn get(&self, location: &Path) -> Result<GetResult> {
self.as_ref().get(location).await
}
@@ -1144,6 +1165,46 @@ impl From<TagSet> for PutOptions {
}
}
+impl From<Attributes> for PutOptions {
+ fn from(attributes: Attributes) -> Self {
+ Self {
+ attributes,
+ ..Default::default()
+ }
+ }
+}
+
+/// Options for [`ObjectStore::put_multipart_opts`]
+#[derive(Debug, Clone, PartialEq, Eq, Default)]
+pub struct PutMultipartOpts {
+ /// Provide a [`TagSet`] for this object
+ ///
+ /// Implementations that don't support object tagging should ignore this
+ pub tags: TagSet,
+ /// Provide a set of [`Attributes`]
+ ///
+ /// Implementations that don't support an attribute should return an error
+ pub attributes: Attributes,
+}
+
+impl From<TagSet> for PutMultipartOpts {
+ fn from(tags: TagSet) -> Self {
+ Self {
+ tags,
+ ..Default::default()
+ }
+ }
+}
+
+impl From<Attributes> for PutMultipartOpts {
+ fn from(attributes: Attributes) -> Self {
+ Self {
+ attributes,
+ ..Default::default()
+ }
+ }
+}
+
/// Result for a put request
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PutResult {
@@ -1688,10 +1749,7 @@ mod tests {
]);
let path = Path::from("attributes");
- let opts = PutOptions {
- attributes: attributes.clone(),
- ..Default::default()
- };
+ let opts = attributes.clone().into();
match integration.put_opts(&path, "foo".into(), opts).await {
Ok(_) => {
let r = integration.get(&path).await.unwrap();
@@ -1700,6 +1758,19 @@ mod tests {
Err(Error::NotImplemented) => {}
Err(e) => panic!("{e}"),
}
+
+ let opts = attributes.clone().into();
+ match integration.put_multipart_opts(&path, opts).await {
+ Ok(mut w) => {
+ w.put_part("foo".into()).await.unwrap();
+ w.complete().await.unwrap();
+
+ let r = integration.get(&path).await.unwrap();
+ assert_eq!(r.attributes, attributes);
+ }
+ Err(Error::NotImplemented) => {}
+ Err(e) => panic!("{e}"),
+ }
}
pub(crate) async fn get_opts(storage: &dyn ObjectStore) {
@@ -2332,21 +2403,32 @@ mod tests {
let path = Path::from("tag_test");
storage
- .put_opts(&path, "test".into(), tag_set.into())
+ .put_opts(&path, "test".into(), tag_set.clone().into())
.await
.unwrap();
+ let multi_path = Path::from("tag_test_multi");
+ let mut write = storage
+ .put_multipart_opts(&multi_path, tag_set.into())
+ .await
+ .unwrap();
+
+ write.put_part("foo".into()).await.unwrap();
+ write.complete().await.unwrap();
+
// Write should always succeed, but certain configurations may simply ignore tags
if !validate {
return;
}
- let resp = get_tags(path.clone()).await.unwrap();
- let body = resp.bytes().await.unwrap();
+ for path in [path, multi_path] {
+ let resp = get_tags(path.clone()).await.unwrap();
+ let body = resp.bytes().await.unwrap();
- let mut resp: Tagging = quick_xml::de::from_reader(body.reader()).unwrap();
- resp.list.tags.sort_by(|a, b| a.key.cmp(&b.key));
- assert_eq!(resp.list.tags, tags);
+ let mut resp: Tagging = quick_xml::de::from_reader(body.reader()).unwrap();
+ resp.list.tags.sort_by(|a, b| a.key.cmp(&b.key));
+ assert_eq!(resp.list.tags, tags);
+ }
}
async fn delete_fixtures(storage: &DynObjectStore) {
diff --git a/object_store/src/limit.rs b/object_store/src/limit.rs
index b94aa05b8b6e..f3e1d4296fe1 100644
--- a/object_store/src/limit.rs
+++ b/object_store/src/limit.rs
@@ -19,7 +19,8 @@
use crate::{
BoxStream, GetOptions, GetResult, GetResultPayload, ListResult, MultipartUpload, ObjectMeta,
- ObjectStore, Path, PutOptions, PutPayload, PutResult, Result, StreamExt, UploadPart,
+ ObjectStore, Path, PutMultipartOpts, PutOptions, PutPayload, PutResult, Result, StreamExt,
+ UploadPart,
};
use async_trait::async_trait;
use bytes::Bytes;
@@ -91,6 +92,19 @@ impl<T: ObjectStore> ObjectStore for LimitStore<T> {
upload,
}))
}
+
+ async fn put_multipart_opts(
+ &self,
+ location: &Path,
+ opts: PutMultipartOpts,
+ ) -> Result<Box<dyn MultipartUpload>> {
+ let upload = self.inner.put_multipart_opts(location, opts).await?;
+ Ok(Box::new(LimitUpload {
+ semaphore: Arc::clone(&self.semaphore),
+ upload,
+ }))
+ }
+
async fn get(&self, location: &Path) -> Result<GetResult> {
let permit = Arc::clone(&self.semaphore).acquire_owned().await.unwrap();
let r = self.inner.get(location).await?;
diff --git a/object_store/src/local.rs b/object_store/src/local.rs
index a3695ad91744..8dec5bee0a2f 100644
--- a/object_store/src/local.rs
+++ b/object_store/src/local.rs
@@ -39,7 +39,7 @@ use crate::{
path::{absolute_path_to_url, Path},
util::InvalidGetRange,
Attributes, GetOptions, GetResult, GetResultPayload, ListResult, MultipartUpload, ObjectMeta,
- ObjectStore, PutMode, PutOptions, PutPayload, PutResult, Result, UploadPart,
+ ObjectStore, PutMode, PutMultipartOpts, PutOptions, PutPayload, PutResult, Result, UploadPart,
};
/// A specialized `Error` for filesystem object store-related errors
@@ -404,7 +404,15 @@ impl ObjectStore for LocalFileSystem {
.await
}
- async fn put_multipart(&self, location: &Path) -> Result<Box<dyn MultipartUpload>> {
+ async fn put_multipart_opts(
+ &self,
+ location: &Path,
+ opts: PutMultipartOpts,
+ ) -> Result<Box<dyn MultipartUpload>> {
+ if !opts.attributes.is_empty() {
+ return Err(crate::Error::NotImplemented);
+ }
+
let dest = self.path_to_filesystem(location)?;
let (file, src) = new_staged_upload(&dest)?;
Ok(Box::new(LocalUpload::new(src, dest, file)))
diff --git a/object_store/src/memory.rs b/object_store/src/memory.rs
index e34b28fd27c5..daf14e175108 100644
--- a/object_store/src/memory.rs
+++ b/object_store/src/memory.rs
@@ -31,8 +31,8 @@ use crate::multipart::{MultipartStore, PartId};
use crate::util::InvalidGetRange;
use crate::{
path::Path, Attributes, GetRange, GetResult, GetResultPayload, ListResult, MultipartId,
- MultipartUpload, ObjectMeta, ObjectStore, PutMode, PutOptions, PutResult, Result,
- UpdateVersion, UploadPart,
+ MultipartUpload, ObjectMeta, ObjectStore, PutMode, PutMultipartOpts, PutOptions, PutResult,
+ Result, UpdateVersion, UploadPart,
};
use crate::{GetOptions, PutPayload};
@@ -223,9 +223,14 @@ impl ObjectStore for InMemory {
})
}
- async fn put_multipart(&self, location: &Path) -> Result<Box<dyn MultipartUpload>> {
+ async fn put_multipart_opts(
+ &self,
+ location: &Path,
+ opts: PutMultipartOpts,
+ ) -> Result<Box<dyn MultipartUpload>> {
Ok(Box::new(InMemoryUpload {
location: location.clone(),
+ attributes: opts.attributes,
parts: vec![],
storage: Arc::clone(&self.storage),
}))
@@ -487,6 +492,7 @@ impl InMemory {
#[derive(Debug)]
struct InMemoryUpload {
location: Path,
+ attributes: Attributes,
parts: Vec<PutPayload>,
storage: Arc<RwLock<Storage>>,
}
@@ -503,10 +509,11 @@ impl MultipartUpload for InMemoryUpload {
let mut buf = Vec::with_capacity(cap);
let parts = self.parts.iter().flatten();
parts.for_each(|x| buf.extend_from_slice(x));
- let etag = self
- .storage
- .write()
- .insert(&self.location, buf.into(), Attributes::new());
+ let etag = self.storage.write().insert(
+ &self.location,
+ buf.into(),
+ std::mem::take(&mut self.attributes),
+ );
Ok(PutResult {
e_tag: Some(etag.to_string()),
diff --git a/object_store/src/prefix.rs b/object_store/src/prefix.rs
index 1d1ffeed8c63..7c9ea5804c33 100644
--- a/object_store/src/prefix.rs
+++ b/object_store/src/prefix.rs
@@ -22,8 +22,8 @@ use std::ops::Range;
use crate::path::Path;
use crate::{
- GetOptions, GetResult, ListResult, MultipartUpload, ObjectMeta, ObjectStore, PutOptions,
- PutPayload, PutResult, Result,
+ GetOptions, GetResult, ListResult, MultipartUpload, ObjectMeta, ObjectStore, PutMultipartOpts,
+ PutOptions, PutPayload, PutResult, Result,
};
#[doc(hidden)]
@@ -100,6 +100,15 @@ impl<T: ObjectStore> ObjectStore for PrefixStore<T> {
self.inner.put_multipart(&full_path).await
}
+ async fn put_multipart_opts(
+ &self,
+ location: &Path,
+ opts: PutMultipartOpts,
+ ) -> Result<Box<dyn MultipartUpload>> {
+ let full_path = self.full_path(location);
+ self.inner.put_multipart_opts(&full_path, opts).await
+ }
+
async fn get(&self, location: &Path) -> Result<GetResult> {
let full_path = self.full_path(location);
self.inner.get(&full_path).await
diff --git a/object_store/src/throttle.rs b/object_store/src/throttle.rs
index d089784668e9..38b6d7c3bf4f 100644
--- a/object_store/src/throttle.rs
+++ b/object_store/src/throttle.rs
@@ -23,7 +23,7 @@ use std::{convert::TryInto, sync::Arc};
use crate::multipart::{MultipartStore, PartId};
use crate::{
path::Path, GetResult, GetResultPayload, ListResult, MultipartId, MultipartUpload, ObjectMeta,
- ObjectStore, PutOptions, PutPayload, PutResult, Result,
+ ObjectStore, PutMultipartOpts, PutOptions, PutPayload, PutResult, Result,
};
use crate::{GetOptions, UploadPart};
use async_trait::async_trait;
@@ -171,6 +171,18 @@ impl<T: ObjectStore> ObjectStore for ThrottledStore<T> {
}))
}
+ async fn put_multipart_opts(
+ &self,
+ location: &Path,
+ opts: PutMultipartOpts,
+ ) -> Result<Box<dyn MultipartUpload>> {
+ let upload = self.inner.put_multipart_opts(location, opts).await?;
+ Ok(Box::new(ThrottledUpload {
+ upload,
+ sleep: self.config().wait_put_per_call,
+ }))
+ }
+
async fn get(&self, location: &Path) -> Result<GetResult> {
sleep(self.config().wait_get_per_call).await;
|
diff --git a/object_store/tests/get_range_file.rs b/object_store/tests/get_range_file.rs
index 59c593400450..c5550ac21728 100644
--- a/object_store/tests/get_range_file.rs
+++ b/object_store/tests/get_range_file.rs
@@ -46,7 +46,11 @@ impl ObjectStore for MyStore {
self.0.put_opts(location, payload, opts).await
}
- async fn put_multipart(&self, _location: &Path) -> Result<Box<dyn MultipartUpload>> {
+ async fn put_multipart_opts(
+ &self,
+ _location: &Path,
+ _opts: PutMultipartOpts,
+ ) -> Result<Box<dyn MultipartUpload>> {
todo!()
}
|
Add ObjectStore::put_multipart_opts
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
<!--
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
(This section helps Arrow developers understand the context and *why* for this feature, in addition to the *what*)
-->
Following #4984 added `ObjectStore::put_opts` taking a `PutOptions` containing a `PutMode`. #4999 extended this to support specifying a `TagSet`. #5334 proposes extending this to support broader categories of metadata.
Whilst `PutMode` does not apply to `put_multipart`, as no stores AFAIK support conditional multipart uploads, but `TagSet` and `Attributes` would be applicable to multipart uploads, as pointed out by @Xuanwo on https://github.com/apache/arrow-rs/pull/5431#discussion_r1502309316
**Describe the solution you'd like**
<!--
A clear and concise description of what you want to happen.
-->
I would propose introducing a new `PutMultipartOptions` and a corresponding `ObjectStore::put_multipart_opts`, with a default implementation of `ObjectStore::put_multipart` calling through with `PutMultipartOptions::default()`.
**Describe alternatives you've considered**
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
We could not do this, however, this would create an unfortunate bifurcation in functionality between multipart and non-multipart uploads.
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
|
Going to proceed with https://github.com/apache/arrow-rs/issues/5458 instead
|
2024-04-16T13:30:21Z
|
51.0
|
30767a687b48d0dbd2e030eef327826c39095123
|
apache/arrow-rs
| 5,630
|
apache__arrow-rs-5630
|
[
"5606"
] |
36a6e515f99866eae5332dfc887c6cb5f8135064
|
diff --git a/parquet/src/arrow/arrow_reader/mod.rs b/parquet/src/arrow/arrow_reader/mod.rs
index 3b4c09314374..c942461f37e7 100644
--- a/parquet/src/arrow/arrow_reader/mod.rs
+++ b/parquet/src/arrow/arrow_reader/mod.rs
@@ -1436,6 +1436,46 @@ mod tests {
assert_eq!(row_count, 300);
}
+ #[test]
+ fn test_read_incorrect_map_schema_file() {
+ let testdata = arrow::util::test_util::parquet_test_data();
+ // see https://github.com/apache/parquet-testing/pull/47
+ let path = format!("{testdata}/incorrect_map_schema.parquet");
+ let file = File::open(path).unwrap();
+ let mut record_reader = ParquetRecordBatchReader::try_new(file, 32).unwrap();
+
+ let batch = record_reader.next().unwrap().unwrap();
+ assert_eq!(batch.num_rows(), 1);
+
+ let expected_schema = Schema::new(Fields::from(vec![Field::new(
+ "my_map",
+ ArrowDataType::Map(
+ Arc::new(Field::new(
+ "key_value",
+ ArrowDataType::Struct(Fields::from(vec![
+ Field::new("key", ArrowDataType::Utf8, false),
+ Field::new("value", ArrowDataType::Utf8, true),
+ ])),
+ false,
+ )),
+ false,
+ ),
+ true,
+ )]));
+ assert_eq!(batch.schema().as_ref(), &expected_schema);
+
+ assert_eq!(batch.num_rows(), 1);
+ assert_eq!(batch.column(0).null_count(), 0);
+ assert_eq!(
+ batch.column(0).as_map().keys().as_ref(),
+ &StringArray::from(vec!["parent", "name"])
+ );
+ assert_eq!(
+ batch.column(0).as_map().values().as_ref(),
+ &StringArray::from(vec!["another", "report"])
+ );
+ }
+
/// Parameters for single_column_reader_test
#[derive(Clone)]
struct TestOptions {
diff --git a/parquet/src/arrow/schema/complex.rs b/parquet/src/arrow/schema/complex.rs
index 9f85b2c284c6..3107a282e0db 100644
--- a/parquet/src/arrow/schema/complex.rs
+++ b/parquet/src/arrow/schema/complex.rs
@@ -286,8 +286,16 @@ impl Visitor {
let map_key = &map_key_value.get_fields()[0];
let map_value = &map_key_value.get_fields()[1];
- if map_key.get_basic_info().repetition() != Repetition::REQUIRED {
- return Err(arrow_err!("Map keys must be required"));
+ match map_key.get_basic_info().repetition() {
+ Repetition::REPEATED => {
+ return Err(arrow_err!("Map keys cannot be repeated"));
+ }
+ Repetition::REQUIRED | Repetition::OPTIONAL => {
+ // Relaxed check for having repetition REQUIRED as there exists
+ // parquet writers and files that do not conform to this standard.
+ // This allows us to consume a broader range of existing files even
+ // if they are out of spec.
+ }
}
if map_value.get_basic_info().repetition() == Repetition::REPEATED {
@@ -346,7 +354,11 @@ impl Visitor {
// Need both columns to be projected
match (maybe_key, maybe_value) {
(Some(key), Some(value)) => {
- let key_field = Arc::new(convert_field(map_key, &key, arrow_key));
+ let key_field = Arc::new(
+ convert_field(map_key, &key, arrow_key)
+ // The key is always non-nullable (#5630)
+ .with_nullable(false),
+ );
let value_field = Arc::new(convert_field(map_value, &value, arrow_value));
let field_metadata = match arrow_map {
Some(field) => field.metadata().clone(),
diff --git a/parquet/src/arrow/schema/mod.rs b/parquet/src/arrow/schema/mod.rs
index e50016fd5b10..37f368b203ac 100644
--- a/parquet/src/arrow/schema/mod.rs
+++ b/parquet/src/arrow/schema/mod.rs
@@ -1018,6 +1018,12 @@ mod tests {
OPTIONAL int32 value;
}
}
+ REQUIRED group my_map4 (MAP) {
+ REPEATED group map {
+ OPTIONAL binary key (UTF8);
+ REQUIRED int32 value;
+ }
+ }
}
";
@@ -1075,6 +1081,24 @@ mod tests {
));
}
+ // // Map<String, Integer> (non-compliant nullable key)
+ // group my_map (MAP_KEY_VALUE) {
+ // repeated group map {
+ // optional binary key (UTF8);
+ // required int32 value;
+ // }
+ // }
+ {
+ arrow_fields.push(Field::new_map(
+ "my_map4",
+ "map",
+ Field::new("key", DataType::Utf8, false), // The key is always non-nullable (#5630)
+ Field::new("value", DataType::Int32, false),
+ false,
+ false,
+ ));
+ }
+
let parquet_group_type = parse_message_type(message_type).unwrap();
let parquet_schema = SchemaDescriptor::new(Arc::new(parquet_group_type));
|
diff --git a/parquet-testing b/parquet-testing
index 4cb3cff24c96..1ba34478f535 160000
--- a/parquet-testing
+++ b/parquet-testing
@@ -1,1 +1,1 @@
-Subproject commit 4cb3cff24c965fb329cdae763eabce47395a68a0
+Subproject commit 1ba34478f535c89382263c42c675a9af4f57f2dd
|
Cannot read Parquet files that do not specify Map keys as required
**Describe the bug**
The [Parquet Format](https://github.com/apache/parquet-format/blob/master/LogicalTypes.md#maps) specifies that:
> The `key` field encodes the map's key type. This field must have repetition `required` and must always be present.
I.e.
```
<map-repetition> group <name> (MAP) {
repeated group key_value {
required <key-type> key;
<value-repetition> <value-type> value;
}
}
```
However, most implementations of the format do not appear to enforce this in the Thrift schema, and producers such as Hive/Spark/Presto/Trino/AWS Athena do not produce Parquet files like this. A huge number of such files are widely found on data lakes everywhere, and rewriting such files in order to comply with this does not seem feasable.
**To Reproduce**
```rs
let url_str = "https://overturemaps-us-west-2.s3.us-west-2.amazonaws.com/release/2023-07-26-alpha.0/theme%3Dtransportation/type%3Dconnector/20230726_134827_00007_dg6b6_01b086fc-f35b-487c-8d4e-5cdbbdc1785d";
let url = Url::parse(url_str).unwrap();
let storage_container = Arc::new(HttpBuilder::new().with_url(url).build().unwrap());
let location = Path::from("");
let meta = storage_container.head(&location).await.unwrap();
let mut reader = ParquetObjectReader::new(storage_container, meta);
// Parquet schema can be printed
let mut p_metadata = reader.get_metadata().await.unwrap();
print_schema(&mut std::io::stdout(), p_metadata.file_metadata().schema());
// Metadata cannot be loaded
let metadata = ArrowReaderMetadata::load_async(&mut reader, Default::default())
.await
.unwrap();
```
Results in:
```
thread 'main' panicked at src/main.rs:79:10:
called `Result::unwrap()` on an `Err` value: ArrowError("Map keys must be required")
```
**Expected behavior**
Map keys are assumed to be required, regardless of explicit specification in the Thrift schema, and data is read accordingly.
**Additional context**
This has come up in a PyArrow issue: https://github.com/apache/arrow/issues/37389
Enforced here: https://github.com/apache/arrow-rs/blob/9fda7eab0c9fb55c90194865ca921c094b78dae9/parquet/src/arrow/schema/complex.rs#L289-L291
|
It was hard to say whether this should be regarded as a bug or feature request. It's a bug from the perspective that we'd expect broad compatibility.
The conclusion of https://github.com/apache/arrow/issues/37389 appears to be that we are correct to refuse to read such malformed files, am I missing something here?
It was discussed, but I don't think that was the conclusion. The creator's issue was resolved by rewriting a file.
In order to operate with precious Parquet files from huge data lakes (e.g. DataFusion probably would want to support files produced by other systems), I'm of the opinion that it should tolerate this like most of the other implementations do (e.g. DuckDB, parquet-tools, and probably many more).
I'm all for correctness, but in this particular case you need to consider the intention and purpose.
There is no way that an optional key can be intentional. Being compatible with a vast amount of data is the purpose of Parquet integration.
Also consider: https://en.wikipedia.org/wiki/Robustness_principle#:~:text=In%20computing%2C%20the%20robustness%20principle,what%20you%20accept%20from%20others%22.
> In other words, programs that send messages to other machines (or to other programs on the same machine) should conform completely to the specifications, but programs that receive messages should accept non-conformant input as long as the meaning is clear.
We could probably just ignore the malformed map logical type and decode such columns as a regular list of structs. This would allow the data to be read, without needing to implement custom dremel shredding logic to handle the case of malformed MapArray, and allowing users to determine how they wish to handle this situation.
Tagging @mapleFU who may have further thoughts on this
|
2024-04-11T16:43:08Z
|
51.0
|
30767a687b48d0dbd2e030eef327826c39095123
|
apache/arrow-rs
| 5,623
|
apache__arrow-rs-5623
|
[
"5613"
] |
68d1eef689f2b71304003ae7f1f813f3ebb20b5a
|
diff --git a/arrow-array/src/array/union_array.rs b/arrow-array/src/array/union_array.rs
index 22d4cf90a092..ea4853cd1528 100644
--- a/arrow-array/src/array/union_array.rs
+++ b/arrow-array/src/array/union_array.rs
@@ -17,13 +17,12 @@
use crate::{make_array, Array, ArrayRef};
use arrow_buffer::buffer::NullBuffer;
-use arrow_buffer::{Buffer, ScalarBuffer};
+use arrow_buffer::ScalarBuffer;
use arrow_data::{ArrayData, ArrayDataBuilder};
-use arrow_schema::{ArrowError, DataType, Field, UnionFields, UnionMode};
+use arrow_schema::{ArrowError, DataType, UnionFields, UnionMode};
/// Contains the `UnionArray` type.
///
use std::any::Any;
-use std::collections::HashMap;
use std::sync::Arc;
/// An array of [values of varying types](https://arrow.apache.org/docs/format/Columnar.html#union-layout)
@@ -43,25 +42,30 @@ use std::sync::Arc;
/// # Examples
/// ## Create a dense UnionArray `[1, 3.2, 34]`
/// ```
-/// use arrow_buffer::Buffer;
+/// use arrow_buffer::ScalarBuffer;
/// use arrow_schema::*;
/// use std::sync::Arc;
/// use arrow_array::{Array, Int32Array, Float64Array, UnionArray};
///
/// let int_array = Int32Array::from(vec![1, 34]);
/// let float_array = Float64Array::from(vec![3.2]);
-/// let type_id_buffer = Buffer::from_slice_ref(&[0_i8, 1, 0]);
-/// let value_offsets_buffer = Buffer::from_slice_ref(&[0_i32, 0, 1]);
+/// let type_ids = [0, 1, 0].into_iter().collect::<ScalarBuffer<i8>>();
+/// let offsets = [0, 0, 1].into_iter().collect::<ScalarBuffer<i32>>();
///
-/// let children: Vec<(Field, Arc<dyn Array>)> = vec![
-/// (Field::new("A", DataType::Int32, false), Arc::new(int_array)),
-/// (Field::new("B", DataType::Float64, false), Arc::new(float_array)),
+/// let union_fields = [
+/// (0, Arc::new(Field::new("A", DataType::Int32, false))),
+/// (1, Arc::new(Field::new("B", DataType::Float64, false))),
+/// ].into_iter().collect::<UnionFields>();
+///
+/// let children = vec![
+/// Arc::new(int_array) as Arc<dyn Array>,
+/// Arc::new(float_array),
/// ];
///
/// let array = UnionArray::try_new(
-/// &vec![0, 1],
-/// type_id_buffer,
-/// Some(value_offsets_buffer),
+/// union_fields,
+/// type_ids,
+/// Some(offsets),
/// children,
/// ).unwrap();
///
@@ -77,23 +81,28 @@ use std::sync::Arc;
///
/// ## Create a sparse UnionArray `[1, 3.2, 34]`
/// ```
-/// use arrow_buffer::Buffer;
+/// use arrow_buffer::ScalarBuffer;
/// use arrow_schema::*;
/// use std::sync::Arc;
/// use arrow_array::{Array, Int32Array, Float64Array, UnionArray};
///
/// let int_array = Int32Array::from(vec![Some(1), None, Some(34)]);
/// let float_array = Float64Array::from(vec![None, Some(3.2), None]);
-/// let type_id_buffer = Buffer::from_slice_ref(&[0_i8, 1, 0]);
+/// let type_ids = [0_i8, 1, 0].into_iter().collect::<ScalarBuffer<i8>>();
+///
+/// let union_fields = [
+/// (0, Arc::new(Field::new("A", DataType::Int32, false))),
+/// (1, Arc::new(Field::new("B", DataType::Float64, false))),
+/// ].into_iter().collect::<UnionFields>();
///
-/// let children: Vec<(Field, Arc<dyn Array>)> = vec![
-/// (Field::new("A", DataType::Int32, false), Arc::new(int_array)),
-/// (Field::new("B", DataType::Float64, false), Arc::new(float_array)),
+/// let children = vec![
+/// Arc::new(int_array) as Arc<dyn Array>,
+/// Arc::new(float_array),
/// ];
///
/// let array = UnionArray::try_new(
-/// &vec![0, 1],
-/// type_id_buffer,
+/// union_fields,
+/// type_ids,
/// None,
/// children,
/// ).unwrap();
@@ -125,102 +134,99 @@ impl UnionArray {
///
/// # Safety
///
- /// The `type_ids` `Buffer` should contain `i8` values. These values should be greater than
- /// zero and must be less than the number of children provided in `child_arrays`. These values
- /// are used to index into the `child_arrays`.
+ /// The `type_ids` values should be positive and must match one of the type ids of the fields provided in `fields`.
+ /// These values are used to index into the `children` arrays.
///
- /// The `value_offsets` `Buffer` is only provided in the case of a dense union, sparse unions
- /// should use `None`. If provided the `value_offsets` `Buffer` should contain `i32` values.
- /// The values in this array should be greater than zero and must be less than the length of the
- /// overall array.
+ /// The `offsets` is provided in the case of a dense union, sparse unions should use `None`.
+ /// If provided the `offsets` values should be positive and must be less than the length of the
+ /// corresponding array.
///
/// In both cases above we use signed integer types to maintain compatibility with other
/// Arrow implementations.
- ///
- /// In both of the cases above we are accepting `Buffer`'s which are assumed to be representing
- /// `i8` and `i32` values respectively. `Buffer` objects are untyped and no attempt is made
- /// to ensure that the data provided is valid.
pub unsafe fn new_unchecked(
- field_type_ids: &[i8],
- type_ids: Buffer,
- value_offsets: Option<Buffer>,
- child_arrays: Vec<(Field, ArrayRef)>,
+ fields: UnionFields,
+ type_ids: ScalarBuffer<i8>,
+ offsets: Option<ScalarBuffer<i32>>,
+ children: Vec<ArrayRef>,
) -> Self {
- let (fields, field_values): (Vec<_>, Vec<_>) = child_arrays.into_iter().unzip();
- let len = type_ids.len();
-
- let mode = if value_offsets.is_some() {
+ let mode = if offsets.is_some() {
UnionMode::Dense
} else {
UnionMode::Sparse
};
- let builder = ArrayData::builder(DataType::Union(
- UnionFields::new(field_type_ids.iter().copied(), fields),
- mode,
- ))
- .add_buffer(type_ids)
- .child_data(field_values.into_iter().map(|a| a.into_data()).collect())
- .len(len);
+ let len = type_ids.len();
+ let builder = ArrayData::builder(DataType::Union(fields, mode))
+ .add_buffer(type_ids.into_inner())
+ .child_data(children.into_iter().map(Array::into_data).collect())
+ .len(len);
- let data = match value_offsets {
- Some(b) => builder.add_buffer(b).build_unchecked(),
+ let data = match offsets {
+ Some(offsets) => builder.add_buffer(offsets.into_inner()).build_unchecked(),
None => builder.build_unchecked(),
};
Self::from(data)
}
/// Attempts to create a new `UnionArray`, validating the inputs provided.
+ ///
+ /// The order of child arrays child array order must match the fields order
pub fn try_new(
- field_type_ids: &[i8],
- type_ids: Buffer,
- value_offsets: Option<Buffer>,
- child_arrays: Vec<(Field, ArrayRef)>,
+ fields: UnionFields,
+ type_ids: ScalarBuffer<i8>,
+ offsets: Option<ScalarBuffer<i32>>,
+ children: Vec<ArrayRef>,
) -> Result<Self, ArrowError> {
- if let Some(b) = &value_offsets {
- if ((type_ids.len()) * 4) != b.len() {
+ // There must be a child array for every field.
+ if fields.len() != children.len() {
+ return Err(ArrowError::InvalidArgumentError(
+ "Union fields length must match child arrays length".to_string(),
+ ));
+ }
+
+ // There must be an offset value for every type id value.
+ if let Some(offsets) = &offsets {
+ if offsets.len() != type_ids.len() {
return Err(ArrowError::InvalidArgumentError(
- "Type Ids and Offsets represent a different number of array slots.".to_string(),
+ "Type Ids and Offsets lengths must match".to_string(),
));
}
}
- // Check the type_ids
- let type_id_slice: &[i8] = type_ids.typed_data();
- let invalid_type_ids = type_id_slice
- .iter()
- .filter(|i| *i < &0)
- .collect::<Vec<&i8>>();
- if !invalid_type_ids.is_empty() {
- return Err(ArrowError::InvalidArgumentError(format!(
- "Type Ids must be positive and cannot be greater than the number of \
- child arrays, found:\n{invalid_type_ids:?}"
- )));
+ // Create mapping from type id to array lengths.
+ let max_id = fields.iter().map(|(i, _)| i).max().unwrap_or_default() as usize;
+ let mut array_lens = vec![i32::MIN; max_id + 1];
+ for (cd, (field_id, _)) in children.iter().zip(fields.iter()) {
+ array_lens[field_id as usize] = cd.len() as i32;
}
- // Check the value offsets if provided
- if let Some(offset_buffer) = &value_offsets {
- let max_len = type_ids.len() as i32;
- let offsets_slice: &[i32] = offset_buffer.typed_data();
- let invalid_offsets = offsets_slice
- .iter()
- .filter(|i| *i < &0 || *i > &max_len)
- .collect::<Vec<&i32>>();
- if !invalid_offsets.is_empty() {
- return Err(ArrowError::InvalidArgumentError(format!(
- "Offsets must be positive and within the length of the Array, \
- found:\n{invalid_offsets:?}"
- )));
+ // Type id values must match one of the fields.
+ for id in &type_ids {
+ match array_lens.get(*id as usize) {
+ Some(x) if *x != i32::MIN => {}
+ _ => {
+ return Err(ArrowError::InvalidArgumentError(
+ "Type Ids values must match one of the field type ids".to_owned(),
+ ))
+ }
}
}
- // Unsafe Justification: arguments were validated above (and
- // re-revalidated as part of data().validate() below)
- let new_self =
- unsafe { Self::new_unchecked(field_type_ids, type_ids, value_offsets, child_arrays) };
- new_self.to_data().validate()?;
+ // Check the value offsets are in bounds.
+ if let Some(offsets) = &offsets {
+ let mut iter = type_ids.iter().zip(offsets.iter());
+ if iter.any(|(type_id, &offset)| offset < 0 || offset >= array_lens[*type_id as usize])
+ {
+ return Err(ArrowError::InvalidArgumentError(
+ "Offsets must be positive and within the length of the Array".to_owned(),
+ ));
+ }
+ }
- Ok(new_self)
+ // Safety:
+ // - Arguments validated above.
+ let union_array = unsafe { Self::new_unchecked(fields, type_ids, offsets, children) };
+ Ok(union_array)
}
/// Accesses the child array for `type_id`.
@@ -336,14 +342,14 @@ impl UnionArray {
/// let union_array = builder.build()?;
///
/// // Deconstruct into parts
- /// let (type_ids, offsets, field_type_ids, fields) = union_array.into_parts();
+ /// let (union_fields, type_ids, offsets, children) = union_array.into_parts();
///
/// // Reconstruct from parts
/// let union_array = UnionArray::try_new(
- /// &field_type_ids,
- /// type_ids.into_inner(),
- /// offsets.map(ScalarBuffer::into_inner),
- /// fields,
+ /// union_fields,
+ /// type_ids,
+ /// offsets,
+ /// children,
/// );
/// # Ok(())
/// # }
@@ -352,34 +358,24 @@ impl UnionArray {
pub fn into_parts(
self,
) -> (
+ UnionFields,
ScalarBuffer<i8>,
Option<ScalarBuffer<i32>>,
- Vec<i8>,
- Vec<(Field, ArrayRef)>,
+ Vec<ArrayRef>,
) {
let Self {
data_type,
type_ids,
offsets,
- fields,
+ mut fields,
} = self;
match data_type {
DataType::Union(union_fields, _) => {
- let union_fields = union_fields.iter().collect::<HashMap<_, _>>();
- let (field_type_ids, fields) = fields
- .into_iter()
- .enumerate()
- .flat_map(|(type_id, array_ref)| {
- array_ref.map(|array_ref| {
- let type_id = type_id as i8;
- (
- type_id,
- ((*Arc::clone(union_fields[&type_id])).clone(), array_ref),
- )
- })
- })
- .unzip();
- (type_ids, offsets, field_type_ids, fields)
+ let children = union_fields
+ .iter()
+ .map(|(type_id, _)| fields[type_id as usize].take().unwrap())
+ .collect();
+ (union_fields, type_ids, offsets, children)
}
_ => unreachable!(),
}
@@ -569,6 +565,7 @@ impl std::fmt::Debug for UnionArray {
#[cfg(test)]
mod tests {
use super::*;
+ use std::collections::HashSet;
use crate::array::Int8Type;
use crate::builder::UnionBuilder;
@@ -576,7 +573,8 @@ mod tests {
use crate::types::{Float32Type, Float64Type, Int32Type, Int64Type};
use crate::RecordBatch;
use crate::{Float64Array, Int32Array, Int64Array, StringArray};
- use arrow_schema::Schema;
+ use arrow_buffer::Buffer;
+ use arrow_schema::{Field, Schema};
#[test]
fn test_dense_i32() {
@@ -809,30 +807,27 @@ mod tests {
let int_array = Int32Array::from(vec![5, 6]);
let float_array = Float64Array::from(vec![10.0]);
- let type_ids = [1_i8, 0, 0, 2, 0, 1];
- let offsets = [0_i32, 0, 1, 0, 2, 1];
-
- let type_id_buffer = Buffer::from_slice_ref(type_ids);
- let value_offsets_buffer = Buffer::from_slice_ref(offsets);
-
- let children: Vec<(Field, Arc<dyn Array>)> = vec![
- (
- Field::new("A", DataType::Utf8, false),
- Arc::new(string_array),
- ),
- (Field::new("B", DataType::Int32, false), Arc::new(int_array)),
- (
- Field::new("C", DataType::Float64, false),
- Arc::new(float_array),
- ),
- ];
- let array = UnionArray::try_new(
- &[0, 1, 2],
- type_id_buffer,
- Some(value_offsets_buffer),
- children,
- )
- .unwrap();
+ let type_ids = [1, 0, 0, 2, 0, 1].into_iter().collect::<ScalarBuffer<i8>>();
+ let offsets = [0, 0, 1, 0, 2, 1]
+ .into_iter()
+ .collect::<ScalarBuffer<i32>>();
+
+ let fields = [
+ (0, Arc::new(Field::new("A", DataType::Utf8, false))),
+ (1, Arc::new(Field::new("B", DataType::Int32, false))),
+ (2, Arc::new(Field::new("C", DataType::Float64, false))),
+ ]
+ .into_iter()
+ .collect::<UnionFields>();
+ let children = [
+ Arc::new(string_array) as Arc<dyn Array>,
+ Arc::new(int_array),
+ Arc::new(float_array),
+ ]
+ .into_iter()
+ .collect();
+ let array =
+ UnionArray::try_new(fields, type_ids.clone(), Some(offsets.clone()), children).unwrap();
// Check type ids
assert_eq!(*array.type_ids(), type_ids);
@@ -1277,29 +1272,22 @@ mod tests {
let dense_union = builder.build().unwrap();
let field = [
- Field::new("a", DataType::Int32, false),
- Field::new("b", DataType::Int8, false),
+ &Arc::new(Field::new("a", DataType::Int32, false)),
+ &Arc::new(Field::new("b", DataType::Int8, false)),
];
- let (type_ids, offsets, field_type_ids, fields) = dense_union.into_parts();
- assert_eq!(field_type_ids, [0, 1]);
+ let (union_fields, type_ids, offsets, children) = dense_union.into_parts();
assert_eq!(
- field.to_vec(),
- fields
+ union_fields
.iter()
- .cloned()
- .map(|(field, _)| field)
- .collect::<Vec<_>>()
+ .map(|(_, field)| field)
+ .collect::<Vec<_>>(),
+ field
);
assert_eq!(type_ids, [0, 1, 0]);
assert!(offsets.is_some());
assert_eq!(offsets.as_ref().unwrap(), &[0, 0, 1]);
- let result = UnionArray::try_new(
- &field_type_ids,
- type_ids.into_inner(),
- offsets.map(ScalarBuffer::into_inner),
- fields,
- );
+ let result = UnionArray::try_new(union_fields, type_ids, offsets, children);
assert!(result.is_ok());
assert_eq!(result.unwrap().len(), 3);
@@ -1309,23 +1297,18 @@ mod tests {
builder.append::<Int32Type>("a", 3).unwrap();
let sparse_union = builder.build().unwrap();
- let (type_ids, offsets, field_type_ids, fields) = sparse_union.into_parts();
+ let (union_fields, type_ids, offsets, children) = sparse_union.into_parts();
assert_eq!(type_ids, [0, 1, 0]);
assert!(offsets.is_none());
- let result = UnionArray::try_new(
- &field_type_ids,
- type_ids.into_inner(),
- offsets.map(ScalarBuffer::into_inner),
- fields,
- );
+ let result = UnionArray::try_new(union_fields, type_ids, offsets, children);
assert!(result.is_ok());
assert_eq!(result.unwrap().len(), 3);
}
#[test]
fn into_parts_custom_type_ids() {
- let mut set_field_type_ids: [i8; 3] = [8, 4, 9];
+ let set_field_type_ids: [i8; 3] = [8, 4, 9];
let data_type = DataType::Union(
UnionFields::new(
set_field_type_ids,
@@ -1354,17 +1337,80 @@ mod tests {
.unwrap();
let array = UnionArray::from(data);
- let (type_ids, offsets, field_type_ids, fields) = array.into_parts();
- set_field_type_ids.sort();
- assert_eq!(field_type_ids, set_field_type_ids);
- let result = UnionArray::try_new(
- &field_type_ids,
- type_ids.into_inner(),
- offsets.map(ScalarBuffer::into_inner),
- fields,
+ let (union_fields, type_ids, offsets, children) = array.into_parts();
+ assert_eq!(
+ type_ids.iter().collect::<HashSet<_>>(),
+ set_field_type_ids.iter().collect::<HashSet<_>>()
);
+ let result = UnionArray::try_new(union_fields, type_ids, offsets, children);
assert!(result.is_ok());
let array = result.unwrap();
assert_eq!(array.len(), 7);
}
+
+ #[test]
+ fn test_invalid() {
+ let fields = UnionFields::new(
+ [3, 2],
+ [
+ Field::new("a", DataType::Utf8, false),
+ Field::new("b", DataType::Utf8, false),
+ ],
+ );
+ let children = vec![
+ Arc::new(StringArray::from_iter_values(["a", "b"])) as _,
+ Arc::new(StringArray::from_iter_values(["c", "d"])) as _,
+ ];
+
+ let type_ids = vec![3, 3, 2].into();
+ UnionArray::try_new(fields.clone(), type_ids, None, children.clone()).unwrap();
+
+ let type_ids = vec![1, 2].into();
+ let err =
+ UnionArray::try_new(fields.clone(), type_ids, None, children.clone()).unwrap_err();
+ assert_eq!(
+ err.to_string(),
+ "Invalid argument error: Type Ids values must match one of the field type ids"
+ );
+
+ let type_ids = vec![7, 2].into();
+ let err = UnionArray::try_new(fields.clone(), type_ids, None, children).unwrap_err();
+ assert_eq!(
+ err.to_string(),
+ "Invalid argument error: Type Ids values must match one of the field type ids"
+ );
+
+ let children = vec![
+ Arc::new(StringArray::from_iter_values(["a", "b"])) as _,
+ Arc::new(StringArray::from_iter_values(["c"])) as _,
+ ];
+ let type_ids = ScalarBuffer::from(vec![3_i8, 3, 2]);
+ let offsets = Some(vec![0, 1, 0].into());
+ UnionArray::try_new(fields.clone(), type_ids.clone(), offsets, children.clone()).unwrap();
+
+ let offsets = Some(vec![0, 1, 1].into());
+ let err = UnionArray::try_new(fields.clone(), type_ids.clone(), offsets, children.clone())
+ .unwrap_err();
+
+ assert_eq!(
+ err.to_string(),
+ "Invalid argument error: Offsets must be positive and within the length of the Array"
+ );
+
+ let offsets = Some(vec![0, 1].into());
+ let err =
+ UnionArray::try_new(fields.clone(), type_ids.clone(), offsets, children).unwrap_err();
+
+ assert_eq!(
+ err.to_string(),
+ "Invalid argument error: Type Ids and Offsets lengths must match"
+ );
+
+ let err = UnionArray::try_new(fields.clone(), type_ids, None, vec![]).unwrap_err();
+
+ assert_eq!(
+ err.to_string(),
+ "Invalid argument error: Union fields length must match child arrays length"
+ );
+ }
}
diff --git a/arrow-array/src/builder/union_builder.rs b/arrow-array/src/builder/union_builder.rs
index 4f88c9d41b9a..e6184f4ac6d2 100644
--- a/arrow-array/src/builder/union_builder.rs
+++ b/arrow-array/src/builder/union_builder.rs
@@ -23,7 +23,8 @@ use arrow_buffer::{ArrowNativeType, Buffer};
use arrow_data::ArrayDataBuilder;
use arrow_schema::{ArrowError, DataType, Field};
use std::any::Any;
-use std::collections::HashMap;
+use std::collections::BTreeMap;
+use std::sync::Arc;
/// `FieldData` is a helper struct to track the state of the fields in the `UnionBuilder`.
#[derive(Debug)]
@@ -142,7 +143,7 @@ pub struct UnionBuilder {
/// The current number of slots in the array
len: usize,
/// Maps field names to `FieldData` instances which track the builders for that field
- fields: HashMap<String, FieldData>,
+ fields: BTreeMap<String, FieldData>,
/// Builder to keep track of type ids
type_id_builder: Int8BufferBuilder,
/// Builder to keep track of offsets (`None` for sparse unions)
@@ -165,7 +166,7 @@ impl UnionBuilder {
pub fn with_capacity_dense(capacity: usize) -> Self {
Self {
len: 0,
- fields: HashMap::default(),
+ fields: Default::default(),
type_id_builder: Int8BufferBuilder::new(capacity),
value_offset_builder: Some(Int32BufferBuilder::new(capacity)),
initial_capacity: capacity,
@@ -176,7 +177,7 @@ impl UnionBuilder {
pub fn with_capacity_sparse(capacity: usize) -> Self {
Self {
len: 0,
- fields: HashMap::default(),
+ fields: Default::default(),
type_id_builder: Int8BufferBuilder::new(capacity),
value_offset_builder: None,
initial_capacity: capacity,
@@ -274,40 +275,39 @@ impl UnionBuilder {
}
/// Builds this builder creating a new `UnionArray`.
- pub fn build(mut self) -> Result<UnionArray, ArrowError> {
- let type_id_buffer = self.type_id_builder.finish();
- let value_offsets_buffer = self.value_offset_builder.map(|mut b| b.finish());
- let mut children = Vec::new();
- for (
- name,
- FieldData {
- type_id,
- data_type,
- mut values_buffer,
- slots,
- null_buffer_builder: mut bitmap_builder,
- },
- ) in self.fields.into_iter()
- {
- let buffer = values_buffer.finish();
- let arr_data_builder = ArrayDataBuilder::new(data_type.clone())
- .add_buffer(buffer)
- .len(slots)
- .nulls(bitmap_builder.finish());
-
- let arr_data_ref = unsafe { arr_data_builder.build_unchecked() };
- let array_ref = make_array(arr_data_ref);
- children.push((type_id, (Field::new(name, data_type, false), array_ref)))
- }
-
- children.sort_by(|a, b| {
- a.0.partial_cmp(&b.0)
- .expect("This will never be None as type ids are always i8 values.")
- });
- let children: Vec<_> = children.into_iter().map(|(_, b)| b).collect();
-
- let type_ids: Vec<i8> = (0_i8..children.len() as i8).collect();
-
- UnionArray::try_new(&type_ids, type_id_buffer, value_offsets_buffer, children)
+ pub fn build(self) -> Result<UnionArray, ArrowError> {
+ let mut children = Vec::with_capacity(self.fields.len());
+ let union_fields = self
+ .fields
+ .into_iter()
+ .map(
+ |(
+ name,
+ FieldData {
+ type_id,
+ data_type,
+ mut values_buffer,
+ slots,
+ mut null_buffer_builder,
+ },
+ )| {
+ let array_ref = make_array(unsafe {
+ ArrayDataBuilder::new(data_type.clone())
+ .add_buffer(values_buffer.finish())
+ .len(slots)
+ .nulls(null_buffer_builder.finish())
+ .build_unchecked()
+ });
+ children.push(array_ref);
+ (type_id, Arc::new(Field::new(name, data_type, false)))
+ },
+ )
+ .collect();
+ UnionArray::try_new(
+ union_fields,
+ self.type_id_builder.into(),
+ self.value_offset_builder.map(Into::into),
+ children,
+ )
}
}
diff --git a/arrow-cast/src/pretty.rs b/arrow-cast/src/pretty.rs
index da7c5e9bb6b4..00bba928114f 100644
--- a/arrow-cast/src/pretty.rs
+++ b/arrow-cast/src/pretty.rs
@@ -142,7 +142,7 @@ mod tests {
use arrow_array::builder::*;
use arrow_array::types::*;
use arrow_array::*;
- use arrow_buffer::Buffer;
+ use arrow_buffer::ScalarBuffer;
use arrow_schema::*;
use crate::display::array_value_to_string;
@@ -851,14 +851,18 @@ mod tests {
// Can't use UnionBuilder with non-primitive types, so manually build outer UnionArray
let a_array = Int32Array::from(vec![None, None, None, Some(1234), Some(23)]);
- let type_ids = Buffer::from_slice_ref([1_i8, 1, 0, 0, 1]);
+ let type_ids = [1, 1, 0, 0, 1].into_iter().collect::<ScalarBuffer<i8>>();
- let children: Vec<(Field, Arc<dyn Array>)> = vec![
- (Field::new("a", DataType::Int32, true), Arc::new(a_array)),
- (inner_field.clone(), Arc::new(inner)),
- ];
+ let children = vec![Arc::new(a_array) as Arc<dyn Array>, Arc::new(inner)];
+
+ let union_fields = [
+ (0, Arc::new(Field::new("a", DataType::Int32, true))),
+ (1, Arc::new(inner_field.clone())),
+ ]
+ .into_iter()
+ .collect();
- let outer = UnionArray::try_new(&[0, 1], type_ids, None, children).unwrap();
+ let outer = UnionArray::try_new(union_fields, type_ids, None, children).unwrap();
let schema = Schema::new(vec![Field::new_union(
"Teamsters",
diff --git a/arrow-flight/src/encode.rs b/arrow-flight/src/encode.rs
index 7604f3cd4d62..f59c29e68173 100644
--- a/arrow-flight/src/encode.rs
+++ b/arrow-flight/src/encode.rs
@@ -597,20 +597,17 @@ fn hydrate_dictionary(array: &ArrayRef, data_type: &DataType) -> Result<ArrayRef
(DataType::Union(_, UnionMode::Sparse), DataType::Union(fields, UnionMode::Sparse)) => {
let union_arr = array.as_any().downcast_ref::<UnionArray>().unwrap();
- let (type_ids, fields): (Vec<i8>, Vec<&FieldRef>) = fields.iter().unzip();
-
Arc::new(UnionArray::try_new(
- &type_ids,
- union_arr.type_ids().inner().clone(),
+ fields.clone(),
+ union_arr.type_ids().clone(),
None,
fields
.iter()
- .enumerate()
- .map(|(col, field)| {
- Ok((
- field.as_ref().clone(),
- arrow_cast::cast(union_arr.child(col as i8), field.data_type())?,
- ))
+ .map(|(type_id, field)| {
+ Ok(arrow_cast::cast(
+ union_arr.child(type_id),
+ field.data_type(),
+ )?)
})
.collect::<Result<Vec<_>>>()?,
)?)
@@ -625,10 +622,10 @@ mod tests {
use arrow_array::builder::StringDictionaryBuilder;
use arrow_array::*;
use arrow_array::{cast::downcast_array, types::*};
- use arrow_buffer::Buffer;
+ use arrow_buffer::ScalarBuffer;
use arrow_cast::pretty::pretty_format_batches;
use arrow_ipc::MetadataVersion;
- use arrow_schema::UnionMode;
+ use arrow_schema::{UnionFields, UnionMode};
use std::collections::HashMap;
use crate::decode::{DecodedPayload, FlightDataDecoder};
@@ -849,16 +846,23 @@ mod tests {
true,
)];
- let type_ids = vec![0, 1, 2];
- let union_fields = vec![
- Field::new_list(
- "dict_list",
- Field::new_dictionary("item", DataType::UInt16, DataType::Utf8, true),
- true,
+ let union_fields = [
+ (
+ 0,
+ Arc::new(Field::new_list(
+ "dict_list",
+ Field::new_dictionary("item", DataType::UInt16, DataType::Utf8, true),
+ true,
+ )),
),
- Field::new_struct("struct", struct_fields.clone(), true),
- Field::new("string", DataType::Utf8, true),
- ];
+ (
+ 1,
+ Arc::new(Field::new_struct("struct", struct_fields.clone(), true)),
+ ),
+ (2, Arc::new(Field::new("string", DataType::Utf8, true))),
+ ]
+ .into_iter()
+ .collect::<UnionFields>();
let struct_fields = vec![Field::new_list(
"dict_list",
@@ -872,21 +876,15 @@ mod tests {
let arr1 = builder.finish();
- let type_id_buffer = Buffer::from_slice_ref([0_i8]);
+ let type_id_buffer = [0].into_iter().collect::<ScalarBuffer<i8>>();
let arr1 = UnionArray::try_new(
- &type_ids,
+ union_fields.clone(),
type_id_buffer,
None,
vec![
- (union_fields[0].clone(), Arc::new(arr1)),
- (
- union_fields[1].clone(),
- new_null_array(union_fields[1].data_type(), 1),
- ),
- (
- union_fields[2].clone(),
- new_null_array(union_fields[2].data_type(), 1),
- ),
+ Arc::new(arr1) as Arc<dyn Array>,
+ new_null_array(union_fields.iter().nth(1).unwrap().1.data_type(), 1),
+ new_null_array(union_fields.iter().nth(2).unwrap().1.data_type(), 1),
],
)
.unwrap();
@@ -896,47 +894,36 @@ mod tests {
let arr2 = Arc::new(builder.finish());
let arr2 = StructArray::new(struct_fields.clone().into(), vec![arr2], None);
- let type_id_buffer = Buffer::from_slice_ref([1_i8]);
+ let type_id_buffer = [1].into_iter().collect::<ScalarBuffer<i8>>();
let arr2 = UnionArray::try_new(
- &type_ids,
+ union_fields.clone(),
type_id_buffer,
None,
vec![
- (
- union_fields[0].clone(),
- new_null_array(union_fields[0].data_type(), 1),
- ),
- (union_fields[1].clone(), Arc::new(arr2)),
- (
- union_fields[2].clone(),
- new_null_array(union_fields[2].data_type(), 1),
- ),
+ new_null_array(union_fields.iter().next().unwrap().1.data_type(), 1),
+ Arc::new(arr2),
+ new_null_array(union_fields.iter().nth(2).unwrap().1.data_type(), 1),
],
)
.unwrap();
- let type_id_buffer = Buffer::from_slice_ref([2_i8]);
+ let type_id_buffer = [2].into_iter().collect::<ScalarBuffer<i8>>();
let arr3 = UnionArray::try_new(
- &type_ids,
+ union_fields.clone(),
type_id_buffer,
None,
vec![
- (
- union_fields[0].clone(),
- new_null_array(union_fields[0].data_type(), 1),
- ),
- (
- union_fields[1].clone(),
- new_null_array(union_fields[1].data_type(), 1),
- ),
- (
- union_fields[2].clone(),
- Arc::new(StringArray::from(vec!["e"])),
- ),
+ new_null_array(union_fields.iter().next().unwrap().1.data_type(), 1),
+ new_null_array(union_fields.iter().nth(1).unwrap().1.data_type(), 1),
+ Arc::new(StringArray::from(vec!["e"])),
],
)
.unwrap();
+ let (type_ids, union_fields): (Vec<_>, Vec<_>) = union_fields
+ .iter()
+ .map(|(type_id, field_ref)| (type_id, (*Arc::clone(field_ref)).clone()))
+ .unzip();
let schema = Arc::new(Schema::new(vec![Field::new_union(
"union",
type_ids.clone(),
diff --git a/arrow-ipc/src/reader.rs b/arrow-ipc/src/reader.rs
index 8eac17e20761..3c203a7f3654 100644
--- a/arrow-ipc/src/reader.rs
+++ b/arrow-ipc/src/reader.rs
@@ -31,7 +31,7 @@ use std::io::{BufReader, Read, Seek, SeekFrom};
use std::sync::Arc;
use arrow_array::*;
-use arrow_buffer::{ArrowNativeType, Buffer, MutableBuffer};
+use arrow_buffer::{ArrowNativeType, Buffer, MutableBuffer, ScalarBuffer};
use arrow_data::ArrayData;
use arrow_schema::*;
@@ -214,26 +214,25 @@ fn create_array(
reader.next_buffer()?;
}
- let type_ids: Buffer = reader.next_buffer()?[..len].into();
+ let type_ids: ScalarBuffer<i8> = reader.next_buffer()?.slice_with_length(0, len).into();
let value_offsets = match mode {
UnionMode::Dense => {
- let buffer = reader.next_buffer()?;
- Some(buffer[..len * 4].into())
+ let offsets: ScalarBuffer<i32> =
+ reader.next_buffer()?.slice_with_length(0, len * 4).into();
+ Some(offsets)
}
UnionMode::Sparse => None,
};
let mut children = Vec::with_capacity(fields.len());
- let mut ids = Vec::with_capacity(fields.len());
- for (id, field) in fields.iter() {
+ for (_id, field) in fields.iter() {
let child = create_array(reader, field, variadic_counts, require_alignment)?;
- children.push((field.as_ref().clone(), child));
- ids.push(id);
+ children.push(child);
}
- let array = UnionArray::try_new(&ids, type_ids, value_offsets, children)?;
+ let array = UnionArray::try_new(fields.clone(), type_ids, value_offsets, children)?;
Ok(Arc::new(array))
}
Null => {
diff --git a/arrow-ipc/src/writer.rs b/arrow-ipc/src/writer.rs
index 97136bd97c2f..ef08a6130e3a 100644
--- a/arrow-ipc/src/writer.rs
+++ b/arrow-ipc/src/writer.rs
@@ -1526,6 +1526,7 @@ mod tests {
use arrow_array::builder::UnionBuilder;
use arrow_array::builder::{PrimitiveRunBuilder, UInt32Builder};
use arrow_array::types::*;
+ use arrow_buffer::ScalarBuffer;
use crate::convert::fb_to_schema;
use crate::reader::*;
@@ -1800,12 +1801,12 @@ mod tests {
// Dict field with id 2
let dctfield = Field::new_dict("dict", array.data_type().clone(), false, 2, false);
+ let union_fields = [(0, Arc::new(dctfield))].into_iter().collect();
- let types = Buffer::from_slice_ref([0_i8, 0, 0]);
- let offsets = Buffer::from_slice_ref([0_i32, 1, 2]);
+ let types = [0, 0, 0].into_iter().collect::<ScalarBuffer<i8>>();
+ let offsets = [0, 1, 2].into_iter().collect::<ScalarBuffer<i32>>();
- let union =
- UnionArray::try_new(&[0], types, Some(offsets), vec![(dctfield, array)]).unwrap();
+ let union = UnionArray::try_new(union_fields, types, Some(offsets), vec![array]).unwrap();
let schema = Arc::new(Schema::new(vec![Field::new(
"union",
diff --git a/arrow-schema/src/fields.rs b/arrow-schema/src/fields.rs
index 5a1a6c84c256..63aef18ddf9c 100644
--- a/arrow-schema/src/fields.rs
+++ b/arrow-schema/src/fields.rs
@@ -420,8 +420,6 @@ impl UnionFields {
}
/// Returns an iterator over the fields and type ids in this [`UnionFields`]
- ///
- /// Note: the iteration order is not guaranteed
pub fn iter(&self) -> impl Iterator<Item = (i8, &FieldRef)> + '_ {
self.0.iter().map(|(id, f)| (*id, f))
}
diff --git a/arrow-select/src/take.rs b/arrow-select/src/take.rs
index 8939d3f719f0..a4dd2470ab6d 100644
--- a/arrow-select/src/take.rs
+++ b/arrow-select/src/take.rs
@@ -229,18 +229,15 @@ fn take_impl<IndexType: ArrowPrimitiveType>(
}
}
DataType::Union(fields, UnionMode::Sparse) => {
- let mut field_type_ids = Vec::with_capacity(fields.len());
let mut children = Vec::with_capacity(fields.len());
let values = values.as_any().downcast_ref::<UnionArray>().unwrap();
- let type_ids = take_native(values.type_ids(), indices).into_inner();
- for (type_id, field) in fields.iter() {
+ let type_ids = take_native(values.type_ids(), indices);
+ for (type_id, _field) in fields.iter() {
let values = values.child(type_id);
let values = take_impl(values, indices)?;
- let field = (**field).clone();
- children.push((field, values));
- field_type_ids.push(type_id);
+ children.push(values);
}
- let array = UnionArray::try_new(field_type_ids.as_slice(), type_ids, None, children)?;
+ let array = UnionArray::try_new(fields.clone(), type_ids, None, children)?;
Ok(Arc::new(array))
}
t => unimplemented!("Take not supported for data type {:?}", t)
@@ -2151,19 +2148,22 @@ mod tests {
None,
]);
let strings = StringArray::from(vec![Some("a"), None, Some("c"), None, Some("d")]);
- let type_ids = Buffer::from_slice_ref(vec![1i8; 5]);
+ let type_ids = [1; 5].into_iter().collect::<ScalarBuffer<i8>>();
- let children: Vec<(Field, Arc<dyn Array>)> = vec![
+ let union_fields = [
(
- Field::new("f1", structs.data_type().clone(), true),
- Arc::new(structs),
+ 0,
+ Arc::new(Field::new("f1", structs.data_type().clone(), true)),
),
(
- Field::new("f2", strings.data_type().clone(), true),
- Arc::new(strings),
+ 1,
+ Arc::new(Field::new("f2", strings.data_type().clone(), true)),
),
- ];
- let array = UnionArray::try_new(&[0, 1], type_ids, None, children).unwrap();
+ ]
+ .into_iter()
+ .collect();
+ let children = vec![Arc::new(structs) as Arc<dyn Array>, Arc::new(strings)];
+ let array = UnionArray::try_new(union_fields, type_ids, None, children).unwrap();
let indices = vec![0, 3, 1, 0, 2, 4];
let index = UInt32Array::from(indices.clone());
|
diff --git a/arrow-integration-test/src/lib.rs b/arrow-integration-test/src/lib.rs
index d6e0dda51a81..30f0ccfbe12d 100644
--- a/arrow-integration-test/src/lib.rs
+++ b/arrow-integration-test/src/lib.rs
@@ -21,6 +21,7 @@
//!
//! This is not a canonical format, but provides a human-readable way of verifying language implementations
+use arrow_buffer::ScalarBuffer;
use hex::decode;
use num::BigInt;
use num::Signed;
@@ -835,26 +836,18 @@ pub fn array_from_json(
));
};
- let offset: Option<Buffer> = json_col.offset.map(|offsets| {
- let offsets: Vec<i32> =
- offsets.iter().map(|v| v.as_i64().unwrap() as i32).collect();
- Buffer::from(&offsets.to_byte_slice())
- });
+ let offset: Option<ScalarBuffer<i32>> = json_col
+ .offset
+ .map(|offsets| offsets.iter().map(|v| v.as_i64().unwrap() as i32).collect());
- let mut children: Vec<(Field, Arc<dyn Array>)> = vec![];
+ let mut children = Vec::with_capacity(fields.len());
for ((_, field), col) in fields.iter().zip(json_col.children.unwrap()) {
let array = array_from_json(field, col, dictionaries)?;
- children.push((field.as_ref().clone(), array));
+ children.push(array);
}
- let field_type_ids = fields.iter().map(|(id, _)| id).collect::<Vec<_>>();
- let array = UnionArray::try_new(
- &field_type_ids,
- Buffer::from(&type_ids.to_byte_slice()),
- offset,
- children,
- )
- .unwrap();
+ let array =
+ UnionArray::try_new(fields.clone(), type_ids.into(), offset, children).unwrap();
Ok(Arc::new(array))
}
t => Err(ArrowError::JsonError(format!(
diff --git a/arrow/tests/array_transform.rs b/arrow/tests/array_transform.rs
index 83d3003a0586..42e4da7c4b4e 100644
--- a/arrow/tests/array_transform.rs
+++ b/arrow/tests/array_transform.rs
@@ -23,10 +23,10 @@ use arrow::array::{
};
use arrow::datatypes::Int16Type;
use arrow_array::StringViewArray;
-use arrow_buffer::Buffer;
+use arrow_buffer::{Buffer, ScalarBuffer};
use arrow_data::transform::MutableArrayData;
use arrow_data::ArrayData;
-use arrow_schema::{DataType, Field, Fields};
+use arrow_schema::{DataType, Field, Fields, UnionFields};
use std::sync::Arc;
#[allow(unused)]
@@ -482,17 +482,25 @@ fn test_union_dense() {
Some(4),
Some(5),
]));
- let offsets = Buffer::from_slice_ref([0, 0, 1, 1, 2, 2, 3, 4i32]);
- let type_ids = Buffer::from_slice_ref([42, 84, 42, 84, 84, 42, 84, 84i8]);
+ let offsets = [0, 0, 1, 1, 2, 2, 3, 4]
+ .into_iter()
+ .collect::<ScalarBuffer<i32>>();
+ let type_ids = [42, 84, 42, 84, 84, 42, 84, 84]
+ .into_iter()
+ .collect::<ScalarBuffer<i8>>();
+
+ let union_fields = [
+ (84, Arc::new(Field::new("int", DataType::Int32, false))),
+ (42, Arc::new(Field::new("string", DataType::Utf8, false))),
+ ]
+ .into_iter()
+ .collect::<UnionFields>();
let array = UnionArray::try_new(
- &[84, 42],
+ union_fields.clone(),
type_ids,
Some(offsets),
- vec![
- (Field::new("int", DataType::Int32, false), ints),
- (Field::new("string", DataType::Utf8, false), strings),
- ],
+ vec![ints, strings],
)
.unwrap()
.into_data();
@@ -507,19 +515,11 @@ fn test_union_dense() {
// Expected data
let strings: ArrayRef = Arc::new(StringArray::from(vec![Some("doe")]));
let ints: ArrayRef = Arc::new(Int32Array::from(vec![Some(3), Some(4)]));
- let offsets = Buffer::from_slice_ref([0, 0, 1i32]);
- let type_ids = Buffer::from_slice_ref([84, 42, 84i8]);
+ let offsets = [0, 0, 1].into_iter().collect::<ScalarBuffer<i32>>();
+ let type_ids = [84, 42, 84].into_iter().collect::<ScalarBuffer<i8>>();
- let expected = UnionArray::try_new(
- &[84, 42],
- type_ids,
- Some(offsets),
- vec![
- (Field::new("int", DataType::Int32, false), ints),
- (Field::new("string", DataType::Utf8, false), strings),
- ],
- )
- .unwrap();
+ let expected =
+ UnionArray::try_new(union_fields, type_ids, Some(offsets), vec![ints, strings]).unwrap();
assert_eq!(array.to_data(), expected.to_data());
}
|
Cleanup UnionArray Constructors
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
<!--
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
(This section helps Arrow developers understand the context and *why* for this feature, in addition to the *what*)
-->
The UnionArray constructors are somewhat at odds with the pattern followed for other array types.
**Describe the solution you'd like**
<!--
A clear and concise description of what you want to happen.
-->
I would like the signature to be updated to be
```
fn try_new(fields: UnionFields, type_ids: ScalarBuffer<i8>, offsets: Option<ScalarBuffer<i32>>, children: Vec<ArrayRef>)
-> Result<Self, ArrowError>
```
`into_parts` should then be updated to match
**Describe alternatives you've considered**
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
|
2024-04-10T14:45:05Z
|
51.0
|
30767a687b48d0dbd2e030eef327826c39095123
|
|
apache/arrow-rs
| 5,538
|
apache__arrow-rs-5538
|
[
"5514"
] |
2c4b321d3b8dcbb05c0590528abdf1859bc70cef
|
diff --git a/object_store/src/aws/checksum.rs b/object_store/src/aws/checksum.rs
index a50bd2d18b9c..d15bbf08df69 100644
--- a/object_store/src/aws/checksum.rs
+++ b/object_store/src/aws/checksum.rs
@@ -16,7 +16,6 @@
// under the License.
use crate::config::Parse;
-use ring::digest::{self, digest as ring_digest};
use std::str::FromStr;
#[allow(non_camel_case_types)]
@@ -27,20 +26,6 @@ pub enum Checksum {
SHA256,
}
-impl Checksum {
- pub(super) fn digest(&self, bytes: &[u8]) -> Vec<u8> {
- match self {
- Self::SHA256 => ring_digest(&digest::SHA256, bytes).as_ref().to_owned(),
- }
- }
-
- pub(super) fn header_name(&self) -> &'static str {
- match self {
- Self::SHA256 => "x-amz-checksum-sha256",
- }
- }
-}
-
impl std::fmt::Display for Checksum {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self {
diff --git a/object_store/src/aws/client.rs b/object_store/src/aws/client.rs
index 838bef8ac23b..c1789ed143e4 100644
--- a/object_store/src/aws/client.rs
+++ b/object_store/src/aws/client.rs
@@ -35,7 +35,8 @@ use crate::client::GetOptionsExt;
use crate::multipart::PartId;
use crate::path::DELIMITER;
use crate::{
- ClientOptions, GetOptions, ListResult, MultipartId, Path, PutResult, Result, RetryConfig,
+ ClientOptions, GetOptions, ListResult, MultipartId, Path, PutPayload, PutResult, Result,
+ RetryConfig,
};
use async_trait::async_trait;
use base64::prelude::BASE64_STANDARD;
@@ -51,11 +52,14 @@ use reqwest::{
header::{CONTENT_LENGTH, CONTENT_TYPE},
Client as ReqwestClient, Method, RequestBuilder, Response,
};
+use ring::digest;
+use ring::digest::Context;
use serde::{Deserialize, Serialize};
use snafu::{ResultExt, Snafu};
use std::sync::Arc;
const VERSION_HEADER: &str = "x-amz-version-id";
+const SHA256_CHECKSUM: &str = "x-amz-checksum-sha256";
/// A specialized `Error` for object store-related errors
#[derive(Debug, Snafu)]
@@ -266,7 +270,8 @@ pub(crate) struct Request<'a> {
path: &'a Path,
config: &'a S3Config,
builder: RequestBuilder,
- payload_sha256: Option<Vec<u8>>,
+ payload_sha256: Option<digest::Digest>,
+ payload: Option<PutPayload>,
use_session_creds: bool,
idempotent: bool,
}
@@ -286,7 +291,7 @@ impl<'a> Request<'a> {
Self { builder, ..self }
}
- pub fn set_idempotent(mut self, idempotent: bool) -> Self {
+ pub fn idempotent(mut self, idempotent: bool) -> Self {
self.idempotent = idempotent;
self
}
@@ -301,10 +306,15 @@ impl<'a> Request<'a> {
},
};
+ let sha = self.payload_sha256.as_ref().map(|x| x.as_ref());
+
let path = self.path.as_ref();
self.builder
- .with_aws_sigv4(credential.authorizer(), self.payload_sha256.as_deref())
- .send_retry_with_idempotency(&self.config.retry_config, self.idempotent)
+ .with_aws_sigv4(credential.authorizer(), sha)
+ .retryable(&self.config.retry_config)
+ .idempotent(self.idempotent)
+ .payload(self.payload)
+ .send()
.await
.context(RetrySnafu { path })
}
@@ -333,7 +343,7 @@ impl S3Client {
pub fn put_request<'a>(
&'a self,
path: &'a Path,
- bytes: Bytes,
+ payload: PutPayload,
with_encryption_headers: bool,
) -> Request<'a> {
let url = self.config.path_url(path);
@@ -341,20 +351,17 @@ impl S3Client {
if with_encryption_headers {
builder = builder.headers(self.config.encryption_headers.clone().into());
}
- let mut payload_sha256 = None;
- if let Some(checksum) = self.config.checksum {
- let digest = checksum.digest(&bytes);
- builder = builder.header(checksum.header_name(), BASE64_STANDARD.encode(&digest));
- if checksum == Checksum::SHA256 {
- payload_sha256 = Some(digest);
- }
- }
+ let mut sha256 = Context::new(&digest::SHA256);
+ payload.iter().for_each(|x| sha256.update(x));
+ let payload_sha256 = sha256.finish();
- builder = match bytes.is_empty() {
- true => builder.header(CONTENT_LENGTH, 0), // Handle empty uploads (#4514)
- false => builder.body(bytes),
- };
+ if let Some(Checksum::SHA256) = self.config.checksum {
+ builder = builder.header(
+ "x-amz-checksum-sha256",
+ BASE64_STANDARD.encode(payload_sha256),
+ )
+ }
if let Some(value) = self.config.client_options.get_content_type(path) {
builder = builder.header(CONTENT_TYPE, value);
@@ -362,8 +369,9 @@ impl S3Client {
Request {
path,
- builder,
- payload_sha256,
+ builder: builder.header(CONTENT_LENGTH, payload.content_length()),
+ payload: Some(payload),
+ payload_sha256: Some(payload_sha256),
config: &self.config,
use_session_creds: true,
idempotent: false,
@@ -446,16 +454,8 @@ impl S3Client {
let mut builder = self.client.request(Method::POST, url);
- // Compute checksum - S3 *requires* this for DeleteObjects requests, so we default to
- // their algorithm if the user hasn't specified one.
- let checksum = self.config.checksum.unwrap_or(Checksum::SHA256);
- let digest = checksum.digest(&body);
- builder = builder.header(checksum.header_name(), BASE64_STANDARD.encode(&digest));
- let payload_sha256 = if checksum == Checksum::SHA256 {
- Some(digest)
- } else {
- None
- };
+ let digest = digest::digest(&digest::SHA256, &body);
+ builder = builder.header(SHA256_CHECKSUM, BASE64_STANDARD.encode(digest));
// S3 *requires* DeleteObjects to include a Content-MD5 header:
// https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteObjects.html
@@ -468,8 +468,8 @@ impl S3Client {
let response = builder
.header(CONTENT_TYPE, "application/xml")
.body(body)
- .with_aws_sigv4(credential.authorizer(), payload_sha256.as_deref())
- .send_retry_with_idempotency(&self.config.retry_config, false)
+ .with_aws_sigv4(credential.authorizer(), Some(digest.as_ref()))
+ .send_retry(&self.config.retry_config)
.await
.context(DeleteObjectsRequestSnafu {})?
.bytes()
@@ -515,6 +515,7 @@ impl S3Client {
builder,
path: from,
config: &self.config,
+ payload: None,
payload_sha256: None,
use_session_creds: false,
idempotent: false,
@@ -530,7 +531,9 @@ impl S3Client {
.request(Method::POST, url)
.headers(self.config.encryption_headers.clone().into())
.with_aws_sigv4(credential.authorizer(), None)
- .send_retry_with_idempotency(&self.config.retry_config, true)
+ .retryable(&self.config.retry_config)
+ .idempotent(true)
+ .send()
.await
.context(CreateMultipartRequestSnafu)?
.bytes()
@@ -548,14 +551,14 @@ impl S3Client {
path: &Path,
upload_id: &MultipartId,
part_idx: usize,
- data: Bytes,
+ data: PutPayload,
) -> Result<PartId> {
let part = (part_idx + 1).to_string();
let response = self
.put_request(path, data, false)
.query(&[("partNumber", &part), ("uploadId", upload_id)])
- .set_idempotent(true)
+ .idempotent(true)
.send()
.await?;
@@ -573,7 +576,7 @@ impl S3Client {
// If no parts were uploaded, upload an empty part
// otherwise the completion request will fail
let part = self
- .put_part(location, &upload_id.to_string(), 0, Bytes::new())
+ .put_part(location, &upload_id.to_string(), 0, PutPayload::default())
.await?;
vec![part]
} else {
@@ -591,7 +594,9 @@ impl S3Client {
.query(&[("uploadId", upload_id)])
.body(body)
.with_aws_sigv4(credential.authorizer(), None)
- .send_retry_with_idempotency(&self.config.retry_config, true)
+ .retryable(&self.config.retry_config)
+ .idempotent(true)
+ .send()
.await
.context(CompleteMultipartRequestSnafu)?;
diff --git a/object_store/src/aws/credential.rs b/object_store/src/aws/credential.rs
index a7d1a9772aa1..08831fd51234 100644
--- a/object_store/src/aws/credential.rs
+++ b/object_store/src/aws/credential.rs
@@ -517,7 +517,9 @@ async fn instance_creds(
let token_result = client
.request(Method::PUT, token_url)
.header("X-aws-ec2-metadata-token-ttl-seconds", "600") // 10 minute TTL
- .send_retry_with_idempotency(retry_config, true)
+ .retryable(retry_config)
+ .idempotent(true)
+ .send()
.await;
let token = match token_result {
@@ -607,7 +609,9 @@ async fn web_identity(
("Version", "2011-06-15"),
("WebIdentityToken", &token),
])
- .send_retry_with_idempotency(retry_config, true)
+ .retryable(retry_config)
+ .idempotent(true)
+ .send()
.await?
.bytes()
.await?;
diff --git a/object_store/src/aws/dynamo.rs b/object_store/src/aws/dynamo.rs
index 2e60bbad2226..2390187e7f72 100644
--- a/object_store/src/aws/dynamo.rs
+++ b/object_store/src/aws/dynamo.rs
@@ -186,11 +186,7 @@ impl DynamoCommit {
to: &Path,
) -> Result<()> {
self.conditional_op(client, to, None, || async {
- client
- .copy_request(from, to)
- .set_idempotent(false)
- .send()
- .await?;
+ client.copy_request(from, to).send().await?;
Ok(())
})
.await
diff --git a/object_store/src/aws/mod.rs b/object_store/src/aws/mod.rs
index 16af4d3b4107..9e741c9142dd 100644
--- a/object_store/src/aws/mod.rs
+++ b/object_store/src/aws/mod.rs
@@ -29,7 +29,6 @@
//! [automatic cleanup]: https://aws.amazon.com/blogs/aws/s3-lifecycle-management-update-support-for-multipart-uploads-and-delete-markers/
use async_trait::async_trait;
-use bytes::Bytes;
use futures::stream::BoxStream;
use futures::{StreamExt, TryStreamExt};
use reqwest::header::{HeaderName, IF_MATCH, IF_NONE_MATCH};
@@ -46,7 +45,7 @@ use crate::signer::Signer;
use crate::util::STRICT_ENCODE_SET;
use crate::{
Error, GetOptions, GetResult, ListResult, MultipartId, MultipartUpload, ObjectMeta,
- ObjectStore, Path, PutMode, PutOptions, PutResult, Result, UploadPart,
+ ObjectStore, Path, PutMode, PutOptions, PutPayload, PutResult, Result, UploadPart,
};
static TAGS_HEADER: HeaderName = HeaderName::from_static("x-amz-tagging");
@@ -151,15 +150,20 @@ impl Signer for AmazonS3 {
#[async_trait]
impl ObjectStore for AmazonS3 {
- async fn put_opts(&self, location: &Path, bytes: Bytes, opts: PutOptions) -> Result<PutResult> {
- let mut request = self.client.put_request(location, bytes, true);
+ async fn put_opts(
+ &self,
+ location: &Path,
+ payload: PutPayload,
+ opts: PutOptions,
+ ) -> Result<PutResult> {
+ let mut request = self.client.put_request(location, payload, true);
let tags = opts.tags.encoded();
if !tags.is_empty() && !self.client.config.disable_tagging {
request = request.header(&TAGS_HEADER, tags);
}
match (opts.mode, &self.client.config.conditional_put) {
- (PutMode::Overwrite, _) => request.set_idempotent(true).do_put().await,
+ (PutMode::Overwrite, _) => request.idempotent(true).do_put().await,
(PutMode::Create | PutMode::Update(_), None) => Err(Error::NotImplemented),
(PutMode::Create, Some(S3ConditionalPut::ETagMatch)) => {
match request.header(&IF_NONE_MATCH, "*").do_put().await {
@@ -270,7 +274,7 @@ impl ObjectStore for AmazonS3 {
async fn copy(&self, from: &Path, to: &Path) -> Result<()> {
self.client
.copy_request(from, to)
- .set_idempotent(true)
+ .idempotent(true)
.send()
.await?;
Ok(())
@@ -320,7 +324,7 @@ struct UploadState {
#[async_trait]
impl MultipartUpload for S3MultiPartUpload {
- fn put_part(&mut self, data: Bytes) -> UploadPart {
+ fn put_part(&mut self, data: PutPayload) -> UploadPart {
let idx = self.part_idx;
self.part_idx += 1;
let state = Arc::clone(&self.state);
@@ -362,7 +366,7 @@ impl MultipartStore for AmazonS3 {
path: &Path,
id: &MultipartId,
part_idx: usize,
- data: Bytes,
+ data: PutPayload,
) -> Result<PartId> {
self.client.put_part(path, id, part_idx, data).await
}
@@ -385,7 +389,6 @@ impl MultipartStore for AmazonS3 {
mod tests {
use super::*;
use crate::{client::get::GetClient, tests::*};
- use bytes::Bytes;
use hyper::HeaderMap;
const NON_EXISTENT_NAME: &str = "nonexistentname";
@@ -474,7 +477,7 @@ mod tests {
let integration = config.build().unwrap();
let location = Path::from_iter([NON_EXISTENT_NAME]);
- let data = Bytes::from("arbitrary data");
+ let data = PutPayload::from("arbitrary data");
let err = integration.put(&location, data).await.unwrap_err();
assert!(matches!(err, crate::Error::NotFound { .. }), "{}", err);
@@ -531,7 +534,7 @@ mod tests {
async fn s3_encryption(store: &AmazonS3) {
crate::test_util::maybe_skip_integration!();
- let data = Bytes::from(vec![3u8; 1024]);
+ let data = PutPayload::from(vec![3u8; 1024]);
let encryption_headers: HeaderMap = store.client.config.encryption_headers.clone().into();
let expected_encryption =
diff --git a/object_store/src/azure/client.rs b/object_store/src/azure/client.rs
index 0e6af50fbf94..d5972d0a8c16 100644
--- a/object_store/src/azure/client.rs
+++ b/object_store/src/azure/client.rs
@@ -27,8 +27,8 @@ use crate::multipart::PartId;
use crate::path::DELIMITER;
use crate::util::{deserialize_rfc1123, GetRange};
use crate::{
- ClientOptions, GetOptions, ListResult, ObjectMeta, Path, PutMode, PutOptions, PutResult,
- Result, RetryConfig,
+ ClientOptions, GetOptions, ListResult, ObjectMeta, Path, PutMode, PutOptions, PutPayload,
+ PutResult, Result, RetryConfig,
};
use async_trait::async_trait;
use base64::prelude::BASE64_STANDARD;
@@ -171,6 +171,7 @@ impl AzureConfig {
struct PutRequest<'a> {
path: &'a Path,
config: &'a AzureConfig,
+ payload: PutPayload,
builder: RequestBuilder,
idempotent: bool,
}
@@ -195,8 +196,12 @@ impl<'a> PutRequest<'a> {
let credential = self.config.get_credential().await?;
let response = self
.builder
+ .header(CONTENT_LENGTH, self.payload.content_length())
.with_azure_authorization(&credential, &self.config.account)
- .send_retry_with_idempotency(&self.config.retry_config, self.idempotent)
+ .retryable(&self.config.retry_config)
+ .idempotent(true)
+ .payload(Some(self.payload))
+ .send()
.await
.context(PutRequestSnafu {
path: self.path.as_ref(),
@@ -228,7 +233,7 @@ impl AzureClient {
self.config.get_credential().await
}
- fn put_request<'a>(&'a self, path: &'a Path, bytes: Bytes) -> PutRequest<'a> {
+ fn put_request<'a>(&'a self, path: &'a Path, payload: PutPayload) -> PutRequest<'a> {
let url = self.config.path_url(path);
let mut builder = self.client.request(Method::PUT, url);
@@ -237,21 +242,23 @@ impl AzureClient {
builder = builder.header(CONTENT_TYPE, value);
}
- builder = builder
- .header(CONTENT_LENGTH, HeaderValue::from(bytes.len()))
- .body(bytes);
-
PutRequest {
path,
builder,
+ payload,
config: &self.config,
idempotent: false,
}
}
/// Make an Azure PUT request <https://docs.microsoft.com/en-us/rest/api/storageservices/put-blob>
- pub async fn put_blob(&self, path: &Path, bytes: Bytes, opts: PutOptions) -> Result<PutResult> {
- let builder = self.put_request(path, bytes);
+ pub async fn put_blob(
+ &self,
+ path: &Path,
+ payload: PutPayload,
+ opts: PutOptions,
+ ) -> Result<PutResult> {
+ let builder = self.put_request(path, payload);
let builder = match &opts.mode {
PutMode::Overwrite => builder.set_idempotent(true),
@@ -272,11 +279,16 @@ impl AzureClient {
}
/// PUT a block <https://learn.microsoft.com/en-us/rest/api/storageservices/put-block>
- pub async fn put_block(&self, path: &Path, part_idx: usize, data: Bytes) -> Result<PartId> {
+ pub async fn put_block(
+ &self,
+ path: &Path,
+ part_idx: usize,
+ payload: PutPayload,
+ ) -> Result<PartId> {
let content_id = format!("{part_idx:20}");
let block_id = BASE64_STANDARD.encode(&content_id);
- self.put_request(path, data)
+ self.put_request(path, payload)
.query(&[("comp", "block"), ("blockid", &block_id)])
.set_idempotent(true)
.send()
@@ -349,7 +361,9 @@ impl AzureClient {
builder
.with_azure_authorization(&credential, &self.config.account)
- .send_retry_with_idempotency(&self.config.retry_config, true)
+ .retryable(&self.config.retry_config)
+ .idempotent(overwrite)
+ .send()
.await
.map_err(|err| err.error(STORE, from.to_string()))?;
@@ -382,7 +396,9 @@ impl AzureClient {
.body(body)
.query(&[("restype", "service"), ("comp", "userdelegationkey")])
.with_azure_authorization(&credential, &self.config.account)
- .send_retry_with_idempotency(&self.config.retry_config, true)
+ .retryable(&self.config.retry_config)
+ .idempotent(true)
+ .send()
.await
.context(DelegationKeyRequestSnafu)?
.bytes()
diff --git a/object_store/src/azure/credential.rs b/object_store/src/azure/credential.rs
index 36845bd1d646..c8212a9290f5 100644
--- a/object_store/src/azure/credential.rs
+++ b/object_store/src/azure/credential.rs
@@ -615,7 +615,9 @@ impl TokenProvider for ClientSecretOAuthProvider {
("scope", AZURE_STORAGE_SCOPE),
("grant_type", "client_credentials"),
])
- .send_retry_with_idempotency(retry, true)
+ .retryable(retry)
+ .idempotent(true)
+ .send()
.await
.context(TokenRequestSnafu)?
.json()
@@ -797,7 +799,9 @@ impl TokenProvider for WorkloadIdentityOAuthProvider {
("scope", AZURE_STORAGE_SCOPE),
("grant_type", "client_credentials"),
])
- .send_retry_with_idempotency(retry, true)
+ .retryable(retry)
+ .idempotent(true)
+ .send()
.await
.context(TokenRequestSnafu)?
.json()
diff --git a/object_store/src/azure/mod.rs b/object_store/src/azure/mod.rs
index 5d3a405ccc93..8dc52422b7de 100644
--- a/object_store/src/azure/mod.rs
+++ b/object_store/src/azure/mod.rs
@@ -27,10 +27,9 @@ use crate::{
path::Path,
signer::Signer,
GetOptions, GetResult, ListResult, MultipartId, MultipartUpload, ObjectMeta, ObjectStore,
- PutOptions, PutResult, Result, UploadPart,
+ PutOptions, PutPayload, PutResult, Result, UploadPart,
};
use async_trait::async_trait;
-use bytes::Bytes;
use futures::stream::BoxStream;
use reqwest::Method;
use std::fmt::Debug;
@@ -87,8 +86,13 @@ impl std::fmt::Display for MicrosoftAzure {
#[async_trait]
impl ObjectStore for MicrosoftAzure {
- async fn put_opts(&self, location: &Path, bytes: Bytes, opts: PutOptions) -> Result<PutResult> {
- self.client.put_blob(location, bytes, opts).await
+ async fn put_opts(
+ &self,
+ location: &Path,
+ payload: PutPayload,
+ opts: PutOptions,
+ ) -> Result<PutResult> {
+ self.client.put_blob(location, payload, opts).await
}
async fn put_multipart(&self, location: &Path) -> Result<Box<dyn MultipartUpload>> {
@@ -203,7 +207,7 @@ struct UploadState {
#[async_trait]
impl MultipartUpload for AzureMultiPartUpload {
- fn put_part(&mut self, data: Bytes) -> UploadPart {
+ fn put_part(&mut self, data: PutPayload) -> UploadPart {
let idx = self.part_idx;
self.part_idx += 1;
let state = Arc::clone(&self.state);
@@ -240,7 +244,7 @@ impl MultipartStore for MicrosoftAzure {
path: &Path,
_: &MultipartId,
part_idx: usize,
- data: Bytes,
+ data: PutPayload,
) -> Result<PartId> {
self.client.put_block(path, part_idx, data).await
}
@@ -265,6 +269,7 @@ impl MultipartStore for MicrosoftAzure {
mod tests {
use super::*;
use crate::tests::*;
+ use bytes::Bytes;
#[tokio::test]
async fn azure_blob_test() {
@@ -309,7 +314,7 @@ mod tests {
let data = Bytes::from("hello world");
let path = Path::from("file.txt");
- integration.put(&path, data.clone()).await.unwrap();
+ integration.put(&path, data.clone().into()).await.unwrap();
let signed = integration
.signed_url(Method::GET, &path, Duration::from_secs(60))
diff --git a/object_store/src/buffered.rs b/object_store/src/buffered.rs
index de6d4eb1bb9c..d41224177a30 100644
--- a/object_store/src/buffered.rs
+++ b/object_store/src/buffered.rs
@@ -18,7 +18,7 @@
//! Utilities for performing tokio-style buffered IO
use crate::path::Path;
-use crate::{ObjectMeta, ObjectStore, WriteMultipart};
+use crate::{ObjectMeta, ObjectStore, PutPayloadMut, WriteMultipart};
use bytes::Bytes;
use futures::future::{BoxFuture, FutureExt};
use futures::ready;
@@ -231,7 +231,7 @@ impl std::fmt::Debug for BufWriter {
enum BufWriterState {
/// Buffer up to capacity bytes
- Buffer(Path, Vec<u8>),
+ Buffer(Path, PutPayloadMut),
/// [`ObjectStore::put_multipart`]
Prepare(BoxFuture<'static, std::io::Result<WriteMultipart>>),
/// Write to a multipart upload
@@ -252,7 +252,7 @@ impl BufWriter {
capacity,
store,
max_concurrency: 8,
- state: BufWriterState::Buffer(path, Vec::new()),
+ state: BufWriterState::Buffer(path, PutPayloadMut::new()),
}
}
@@ -303,14 +303,16 @@ impl AsyncWrite for BufWriter {
continue;
}
BufWriterState::Buffer(path, b) => {
- if b.len().saturating_add(buf.len()) >= cap {
+ if b.content_length().saturating_add(buf.len()) >= cap {
let buffer = std::mem::take(b);
let path = std::mem::take(path);
let store = Arc::clone(&self.store);
self.state = BufWriterState::Prepare(Box::pin(async move {
let upload = store.put_multipart(&path).await?;
- let mut chunked = WriteMultipart::new(upload);
- chunked.write(&buffer);
+ let mut chunked = WriteMultipart::new_with_chunk_size(upload, cap);
+ for chunk in buffer.freeze() {
+ chunked.put(chunk);
+ }
Ok(chunked)
}));
continue;
@@ -391,7 +393,7 @@ mod tests {
const BYTES: usize = 4096;
let data: Bytes = b"12345678".iter().cycle().copied().take(BYTES).collect();
- store.put(&existent, data.clone()).await.unwrap();
+ store.put(&existent, data.clone().into()).await.unwrap();
let meta = store.head(&existent).await.unwrap();
diff --git a/object_store/src/chunked.rs b/object_store/src/chunked.rs
index 6db7f4b35e24..9abe49dbfce9 100644
--- a/object_store/src/chunked.rs
+++ b/object_store/src/chunked.rs
@@ -27,11 +27,11 @@ use futures::stream::BoxStream;
use futures::StreamExt;
use crate::path::Path;
-use crate::Result;
use crate::{
GetOptions, GetResult, GetResultPayload, ListResult, MultipartUpload, ObjectMeta, ObjectStore,
PutOptions, PutResult,
};
+use crate::{PutPayload, Result};
/// Wraps a [`ObjectStore`] and makes its get response return chunks
/// in a controllable manner.
@@ -62,8 +62,13 @@ impl Display for ChunkedStore {
#[async_trait]
impl ObjectStore for ChunkedStore {
- async fn put_opts(&self, location: &Path, bytes: Bytes, opts: PutOptions) -> Result<PutResult> {
- self.inner.put_opts(location, bytes, opts).await
+ async fn put_opts(
+ &self,
+ location: &Path,
+ payload: PutPayload,
+ opts: PutOptions,
+ ) -> Result<PutResult> {
+ self.inner.put_opts(location, payload, opts).await
}
async fn put_multipart(&self, location: &Path) -> Result<Box<dyn MultipartUpload>> {
@@ -176,10 +181,7 @@ mod tests {
async fn test_chunked_basic() {
let location = Path::parse("test").unwrap();
let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
- store
- .put(&location, Bytes::from(vec![0; 1001]))
- .await
- .unwrap();
+ store.put(&location, vec![0; 1001].into()).await.unwrap();
for chunk_size in [10, 20, 31] {
let store = ChunkedStore::new(Arc::clone(&store), chunk_size);
diff --git a/object_store/src/client/retry.rs b/object_store/src/client/retry.rs
index f3fa7153e930..5dfdd55b6540 100644
--- a/object_store/src/client/retry.rs
+++ b/object_store/src/client/retry.rs
@@ -18,10 +18,10 @@
//! A shared HTTP client implementation incorporating retries
use crate::client::backoff::{Backoff, BackoffConfig};
+use crate::PutPayload;
use futures::future::BoxFuture;
-use futures::FutureExt;
use reqwest::header::LOCATION;
-use reqwest::{Response, StatusCode};
+use reqwest::{Client, Request, Response, StatusCode};
use snafu::Error as SnafuError;
use snafu::Snafu;
use std::time::{Duration, Instant};
@@ -166,26 +166,57 @@ impl Default for RetryConfig {
}
}
-fn send_retry_impl(
- builder: reqwest::RequestBuilder,
- config: &RetryConfig,
- is_idempotent: Option<bool>,
-) -> BoxFuture<'static, Result<Response>> {
- let mut backoff = Backoff::new(&config.backoff);
- let max_retries = config.max_retries;
- let retry_timeout = config.retry_timeout;
+pub struct RetryableRequest {
+ client: Client,
+ request: Request,
- let (client, req) = builder.build_split();
- let req = req.expect("request must be valid");
- let is_idempotent = is_idempotent.unwrap_or(req.method().is_safe());
+ max_retries: usize,
+ retry_timeout: Duration,
+ backoff: Backoff,
- async move {
+ idempotent: Option<bool>,
+ payload: Option<PutPayload>,
+}
+
+impl RetryableRequest {
+ /// Set whether this request is idempotent
+ ///
+ /// An idempotent request will be retried on timeout even if the request
+ /// method is not [safe](https://datatracker.ietf.org/doc/html/rfc7231#section-4.2.1)
+ pub fn idempotent(self, idempotent: bool) -> Self {
+ Self {
+ idempotent: Some(idempotent),
+ ..self
+ }
+ }
+
+ /// Provide a [`PutPayload`]
+ pub fn payload(self, payload: Option<PutPayload>) -> Self {
+ Self { payload, ..self }
+ }
+
+ pub async fn send(self) -> Result<Response> {
+ let max_retries = self.max_retries;
+ let retry_timeout = self.retry_timeout;
let mut retries = 0;
let now = Instant::now();
+ let mut backoff = self.backoff;
+ let is_idempotent = self
+ .idempotent
+ .unwrap_or_else(|| self.request.method().is_safe());
+
loop {
- let s = req.try_clone().expect("request body must be cloneable");
- match client.execute(s).await {
+ let mut request = self
+ .request
+ .try_clone()
+ .expect("request body must be cloneable");
+
+ if let Some(payload) = &self.payload {
+ *request.body_mut() = Some(payload.body());
+ }
+
+ match self.client.execute(request).await {
Ok(r) => match r.error_for_status_ref() {
Ok(_) if r.status().is_success() => return Ok(r),
Ok(r) if r.status() == StatusCode::NOT_MODIFIED => {
@@ -195,47 +226,44 @@ fn send_retry_impl(
})
}
Ok(r) => {
- let is_bare_redirect = r.status().is_redirection() && !r.headers().contains_key(LOCATION);
+ let is_bare_redirect =
+ r.status().is_redirection() && !r.headers().contains_key(LOCATION);
return match is_bare_redirect {
true => Err(Error::BareRedirect),
// Not actually sure if this is reachable, but here for completeness
false => Err(Error::Client {
body: None,
status: r.status(),
- })
- }
+ }),
+ };
}
Err(e) => {
let status = r.status();
if retries == max_retries
|| now.elapsed() > retry_timeout
- || !status.is_server_error() {
-
+ || !status.is_server_error()
+ {
return Err(match status.is_client_error() {
true => match r.text().await {
- Ok(body) => {
- Error::Client {
- body: Some(body).filter(|b| !b.is_empty()),
- status,
- }
- }
- Err(e) => {
- Error::Reqwest {
- retries,
- max_retries,
- elapsed: now.elapsed(),
- retry_timeout,
- source: e,
- }
- }
- }
+ Ok(body) => Error::Client {
+ body: Some(body).filter(|b| !b.is_empty()),
+ status,
+ },
+ Err(e) => Error::Reqwest {
+ retries,
+ max_retries,
+ elapsed: now.elapsed(),
+ retry_timeout,
+ source: e,
+ },
+ },
false => Error::Reqwest {
retries,
max_retries,
elapsed: now.elapsed(),
retry_timeout,
source: e,
- }
+ },
});
}
@@ -251,13 +279,13 @@ fn send_retry_impl(
tokio::time::sleep(sleep).await;
}
},
- Err(e) =>
- {
+ Err(e) => {
let mut do_retry = false;
if e.is_connect()
|| e.is_body()
|| (e.is_request() && !e.is_timeout())
- || (is_idempotent && e.is_timeout()) {
+ || (is_idempotent && e.is_timeout())
+ {
do_retry = true
} else {
let mut source = e.source();
@@ -267,7 +295,7 @@ fn send_retry_impl(
|| e.is_incomplete_message()
|| e.is_body_write_aborted()
|| (is_idempotent && e.is_timeout());
- break
+ break;
}
if let Some(e) = e.downcast_ref::<std::io::Error>() {
if e.kind() == std::io::ErrorKind::TimedOut {
@@ -276,9 +304,9 @@ fn send_retry_impl(
do_retry = matches!(
e.kind(),
std::io::ErrorKind::ConnectionReset
- | std::io::ErrorKind::ConnectionAborted
- | std::io::ErrorKind::BrokenPipe
- | std::io::ErrorKind::UnexpectedEof
+ | std::io::ErrorKind::ConnectionAborted
+ | std::io::ErrorKind::BrokenPipe
+ | std::io::ErrorKind::UnexpectedEof
);
}
break;
@@ -287,17 +315,14 @@ fn send_retry_impl(
}
}
- if retries == max_retries
- || now.elapsed() > retry_timeout
- || !do_retry {
-
+ if retries == max_retries || now.elapsed() > retry_timeout || !do_retry {
return Err(Error::Reqwest {
retries,
max_retries,
elapsed: now.elapsed(),
retry_timeout,
source: e,
- })
+ });
}
let sleep = backoff.next();
retries += 1;
@@ -313,39 +338,39 @@ fn send_retry_impl(
}
}
}
- .boxed()
}
pub trait RetryExt {
+ /// Return a [`RetryableRequest`]
+ fn retryable(self, config: &RetryConfig) -> RetryableRequest;
+
/// Dispatch a request with the given retry configuration
///
/// # Panic
///
/// This will panic if the request body is a stream
fn send_retry(self, config: &RetryConfig) -> BoxFuture<'static, Result<Response>>;
-
- /// Dispatch a request with the given retry configuration and idempotency
- ///
- /// # Panic
- ///
- /// This will panic if the request body is a stream
- fn send_retry_with_idempotency(
- self,
- config: &RetryConfig,
- is_idempotent: bool,
- ) -> BoxFuture<'static, Result<Response>>;
}
impl RetryExt for reqwest::RequestBuilder {
- fn send_retry(self, config: &RetryConfig) -> BoxFuture<'static, Result<Response>> {
- send_retry_impl(self, config, None)
+ fn retryable(self, config: &RetryConfig) -> RetryableRequest {
+ let (client, request) = self.build_split();
+ let request = request.expect("request must be valid");
+
+ RetryableRequest {
+ client,
+ request,
+ max_retries: config.max_retries,
+ retry_timeout: config.retry_timeout,
+ backoff: Backoff::new(&config.backoff),
+ idempotent: None,
+ payload: None,
+ }
}
- fn send_retry_with_idempotency(
- self,
- config: &RetryConfig,
- is_idempotent: bool,
- ) -> BoxFuture<'static, Result<Response>> {
- send_retry_impl(self, config, Some(is_idempotent))
+
+ fn send_retry(self, config: &RetryConfig) -> BoxFuture<'static, Result<Response>> {
+ let request = self.retryable(config);
+ Box::pin(async move { request.send().await })
}
}
diff --git a/object_store/src/gcp/client.rs b/object_store/src/gcp/client.rs
index 17404f9d5acd..c74d7abce4f2 100644
--- a/object_store/src/gcp/client.rs
+++ b/object_store/src/gcp/client.rs
@@ -29,13 +29,14 @@ use crate::multipart::PartId;
use crate::path::{Path, DELIMITER};
use crate::util::hex_encode;
use crate::{
- ClientOptions, GetOptions, ListResult, MultipartId, PutMode, PutOptions, PutResult, Result,
- RetryConfig,
+ ClientOptions, GetOptions, ListResult, MultipartId, PutMode, PutOptions, PutPayload, PutResult,
+ Result, RetryConfig,
};
use async_trait::async_trait;
use base64::prelude::BASE64_STANDARD;
use base64::Engine;
-use bytes::{Buf, Bytes};
+use bytes::Buf;
+use hyper::header::CONTENT_LENGTH;
use percent_encoding::{percent_encode, utf8_percent_encode, NON_ALPHANUMERIC};
use reqwest::header::HeaderName;
use reqwest::{header, Client, Method, RequestBuilder, Response, StatusCode};
@@ -172,6 +173,7 @@ impl GoogleCloudStorageConfig {
pub struct PutRequest<'a> {
path: &'a Path,
config: &'a GoogleCloudStorageConfig,
+ payload: PutPayload,
builder: RequestBuilder,
idempotent: bool,
}
@@ -197,7 +199,11 @@ impl<'a> PutRequest<'a> {
let response = self
.builder
.bearer_auth(&credential.bearer)
- .send_retry_with_idempotency(&self.config.retry_config, self.idempotent)
+ .header(CONTENT_LENGTH, self.payload.content_length())
+ .retryable(&self.config.retry_config)
+ .idempotent(self.idempotent)
+ .payload(Some(self.payload))
+ .send()
.await
.context(PutRequestSnafu {
path: self.path.as_ref(),
@@ -287,7 +293,9 @@ impl GoogleCloudStorageClient {
.post(&url)
.bearer_auth(&credential.bearer)
.json(&body)
- .send_retry_with_idempotency(&self.config.retry_config, true)
+ .retryable(&self.config.retry_config)
+ .idempotent(true)
+ .send()
.await
.context(SignBlobRequestSnafu)?;
@@ -315,7 +323,7 @@ impl GoogleCloudStorageClient {
/// Perform a put request <https://cloud.google.com/storage/docs/xml-api/put-object-upload>
///
/// Returns the new ETag
- pub fn put_request<'a>(&'a self, path: &'a Path, payload: Bytes) -> PutRequest<'a> {
+ pub fn put_request<'a>(&'a self, path: &'a Path, payload: PutPayload) -> PutRequest<'a> {
let url = self.object_url(path);
let content_type = self
@@ -327,20 +335,24 @@ impl GoogleCloudStorageClient {
let builder = self
.client
.request(Method::PUT, url)
- .header(header::CONTENT_TYPE, content_type)
- .header(header::CONTENT_LENGTH, payload.len())
- .body(payload);
+ .header(header::CONTENT_TYPE, content_type);
PutRequest {
path,
builder,
+ payload,
config: &self.config,
idempotent: false,
}
}
- pub async fn put(&self, path: &Path, data: Bytes, opts: PutOptions) -> Result<PutResult> {
- let builder = self.put_request(path, data);
+ pub async fn put(
+ &self,
+ path: &Path,
+ payload: PutPayload,
+ opts: PutOptions,
+ ) -> Result<PutResult> {
+ let builder = self.put_request(path, payload);
let builder = match &opts.mode {
PutMode::Overwrite => builder.set_idempotent(true),
@@ -367,7 +379,7 @@ impl GoogleCloudStorageClient {
path: &Path,
upload_id: &MultipartId,
part_idx: usize,
- data: Bytes,
+ data: PutPayload,
) -> Result<PartId> {
let query = &[
("partNumber", &format!("{}", part_idx + 1)),
@@ -403,7 +415,9 @@ impl GoogleCloudStorageClient {
.header(header::CONTENT_TYPE, content_type)
.header(header::CONTENT_LENGTH, "0")
.query(&[("uploads", "")])
- .send_retry_with_idempotency(&self.config.retry_config, true)
+ .retryable(&self.config.retry_config)
+ .idempotent(true)
+ .send()
.await
.context(PutRequestSnafu {
path: path.as_ref(),
@@ -472,7 +486,9 @@ impl GoogleCloudStorageClient {
.bearer_auth(&credential.bearer)
.query(&[("uploadId", upload_id)])
.body(data)
- .send_retry_with_idempotency(&self.config.retry_config, true)
+ .retryable(&self.config.retry_config)
+ .idempotent(true)
+ .send()
.await
.context(CompleteMultipartRequestSnafu)?;
@@ -530,8 +546,10 @@ impl GoogleCloudStorageClient {
.bearer_auth(&credential.bearer)
// Needed if reqwest is compiled with native-tls instead of rustls-tls
// See https://github.com/apache/arrow-rs/pull/3921
- .header(header::CONTENT_LENGTH, 0)
- .send_retry_with_idempotency(&self.config.retry_config, !if_not_exists)
+ .header(CONTENT_LENGTH, 0)
+ .retryable(&self.config.retry_config)
+ .idempotent(!if_not_exists)
+ .send()
.await
.map_err(|err| match err.status() {
Some(StatusCode::PRECONDITION_FAILED) => crate::Error::AlreadyExists {
diff --git a/object_store/src/gcp/credential.rs b/object_store/src/gcp/credential.rs
index 158716ce4c18..ed13dd9730e7 100644
--- a/object_store/src/gcp/credential.rs
+++ b/object_store/src/gcp/credential.rs
@@ -623,7 +623,9 @@ impl TokenProvider for AuthorizedUserCredentials {
("client_secret", &self.client_secret),
("refresh_token", &self.refresh_token),
])
- .send_retry_with_idempotency(retry, true)
+ .retryable(retry)
+ .idempotent(true)
+ .send()
.await
.context(TokenRequestSnafu)?
.json::<TokenResponse>()
diff --git a/object_store/src/gcp/mod.rs b/object_store/src/gcp/mod.rs
index 96afa45f2b61..149da76f559a 100644
--- a/object_store/src/gcp/mod.rs
+++ b/object_store/src/gcp/mod.rs
@@ -42,10 +42,9 @@ use crate::gcp::credential::GCSAuthorizer;
use crate::signer::Signer;
use crate::{
multipart::PartId, path::Path, GetOptions, GetResult, ListResult, MultipartId, MultipartUpload,
- ObjectMeta, ObjectStore, PutOptions, PutResult, Result, UploadPart,
+ ObjectMeta, ObjectStore, PutOptions, PutPayload, PutResult, Result, UploadPart,
};
use async_trait::async_trait;
-use bytes::Bytes;
use client::GoogleCloudStorageClient;
use futures::stream::BoxStream;
use hyper::Method;
@@ -115,14 +114,14 @@ struct UploadState {
#[async_trait]
impl MultipartUpload for GCSMultipartUpload {
- fn put_part(&mut self, data: Bytes) -> UploadPart {
+ fn put_part(&mut self, payload: PutPayload) -> UploadPart {
let idx = self.part_idx;
self.part_idx += 1;
let state = Arc::clone(&self.state);
Box::pin(async move {
let part = state
.client
- .put_part(&state.path, &state.multipart_id, idx, data)
+ .put_part(&state.path, &state.multipart_id, idx, payload)
.await?;
state.parts.put(idx, part);
Ok(())
@@ -148,8 +147,13 @@ impl MultipartUpload for GCSMultipartUpload {
#[async_trait]
impl ObjectStore for GoogleCloudStorage {
- async fn put_opts(&self, location: &Path, bytes: Bytes, opts: PutOptions) -> Result<PutResult> {
- self.client.put(location, bytes, opts).await
+ async fn put_opts(
+ &self,
+ location: &Path,
+ payload: PutPayload,
+ opts: PutOptions,
+ ) -> Result<PutResult> {
+ self.client.put(location, payload, opts).await
}
async fn put_multipart(&self, location: &Path) -> Result<Box<dyn MultipartUpload>> {
@@ -210,9 +214,9 @@ impl MultipartStore for GoogleCloudStorage {
path: &Path,
id: &MultipartId,
part_idx: usize,
- data: Bytes,
+ payload: PutPayload,
) -> Result<PartId> {
- self.client.put_part(path, id, part_idx, data).await
+ self.client.put_part(path, id, part_idx, payload).await
}
async fn complete_multipart(
@@ -260,7 +264,6 @@ impl Signer for GoogleCloudStorage {
#[cfg(test)]
mod test {
- use bytes::Bytes;
use credential::DEFAULT_GCS_BASE_URL;
use crate::tests::*;
@@ -391,7 +394,7 @@ mod test {
let integration = config.with_bucket_name(NON_EXISTENT_NAME).build().unwrap();
let location = Path::from_iter([NON_EXISTENT_NAME]);
- let data = Bytes::from("arbitrary data");
+ let data = PutPayload::from("arbitrary data");
let err = integration
.put(&location, data)
diff --git a/object_store/src/http/client.rs b/object_store/src/http/client.rs
index fdc8751c1ca1..39f68ece65a3 100644
--- a/object_store/src/http/client.rs
+++ b/object_store/src/http/client.rs
@@ -21,10 +21,11 @@ use crate::client::retry::{self, RetryConfig, RetryExt};
use crate::client::GetOptionsExt;
use crate::path::{Path, DELIMITER};
use crate::util::deserialize_rfc1123;
-use crate::{ClientOptions, GetOptions, ObjectMeta, Result};
+use crate::{ClientOptions, GetOptions, ObjectMeta, PutPayload, Result};
use async_trait::async_trait;
-use bytes::{Buf, Bytes};
+use bytes::Buf;
use chrono::{DateTime, Utc};
+use hyper::header::CONTENT_LENGTH;
use percent_encoding::percent_decode_str;
use reqwest::header::CONTENT_TYPE;
use reqwest::{Method, Response, StatusCode};
@@ -156,16 +157,24 @@ impl Client {
Ok(())
}
- pub async fn put(&self, location: &Path, bytes: Bytes) -> Result<Response> {
+ pub async fn put(&self, location: &Path, payload: PutPayload) -> Result<Response> {
let mut retry = false;
loop {
let url = self.path_url(location);
- let mut builder = self.client.put(url).body(bytes.clone());
+ let mut builder = self.client.put(url);
if let Some(value) = self.client_options.get_content_type(location) {
builder = builder.header(CONTENT_TYPE, value);
}
- match builder.send_retry(&self.retry_config).await {
+ let resp = builder
+ .header(CONTENT_LENGTH, payload.content_length())
+ .retryable(&self.retry_config)
+ .idempotent(true)
+ .payload(Some(payload.clone()))
+ .send()
+ .await;
+
+ match resp {
Ok(response) => return Ok(response),
Err(source) => match source.status() {
// Some implementations return 404 instead of 409
@@ -189,7 +198,9 @@ impl Client {
.client
.request(method, url)
.header("Depth", depth)
- .send_retry_with_idempotency(&self.retry_config, true)
+ .retryable(&self.retry_config)
+ .idempotent(true)
+ .send()
.await;
let response = match result {
diff --git a/object_store/src/http/mod.rs b/object_store/src/http/mod.rs
index 626337df27f9..a838a0f479d9 100644
--- a/object_store/src/http/mod.rs
+++ b/object_store/src/http/mod.rs
@@ -32,7 +32,6 @@
//! [WebDAV]: https://en.wikipedia.org/wiki/WebDAV
use async_trait::async_trait;
-use bytes::Bytes;
use futures::stream::BoxStream;
use futures::{StreamExt, TryStreamExt};
use itertools::Itertools;
@@ -45,7 +44,7 @@ use crate::http::client::Client;
use crate::path::Path;
use crate::{
ClientConfigKey, ClientOptions, GetOptions, GetResult, ListResult, MultipartUpload, ObjectMeta,
- ObjectStore, PutMode, PutOptions, PutResult, Result, RetryConfig,
+ ObjectStore, PutMode, PutOptions, PutPayload, PutResult, Result, RetryConfig,
};
mod client;
@@ -95,13 +94,18 @@ impl std::fmt::Display for HttpStore {
#[async_trait]
impl ObjectStore for HttpStore {
- async fn put_opts(&self, location: &Path, bytes: Bytes, opts: PutOptions) -> Result<PutResult> {
+ async fn put_opts(
+ &self,
+ location: &Path,
+ payload: PutPayload,
+ opts: PutOptions,
+ ) -> Result<PutResult> {
if opts.mode != PutMode::Overwrite {
// TODO: Add support for If header - https://datatracker.ietf.org/doc/html/rfc2518#section-9.4
return Err(crate::Error::NotImplemented);
}
- let response = self.client.put(location, bytes).await?;
+ let response = self.client.put(location, payload).await?;
let e_tag = match get_etag(response.headers()) {
Ok(e_tag) => Some(e_tag),
Err(crate::client::header::Error::MissingEtag) => None,
diff --git a/object_store/src/lib.rs b/object_store/src/lib.rs
index 97604a7dce68..157852ff9a6e 100644
--- a/object_store/src/lib.rs
+++ b/object_store/src/lib.rs
@@ -245,15 +245,14 @@
//! # }
//! ```
//!
-//! # Put Object
+//! # Put Object
//!
//! Use the [`ObjectStore::put`] method to atomically write data.
//!
//! ```
//! # use object_store::local::LocalFileSystem;
-//! # use object_store::ObjectStore;
+//! # use object_store::{ObjectStore, PutPayload};
//! # use std::sync::Arc;
-//! # use bytes::Bytes;
//! # use object_store::path::Path;
//! # fn get_object_store() -> Arc<dyn ObjectStore> {
//! # Arc::new(LocalFileSystem::new())
@@ -262,12 +261,12 @@
//! #
//! let object_store: Arc<dyn ObjectStore> = get_object_store();
//! let path = Path::from("data/file1");
-//! let bytes = Bytes::from_static(b"hello");
-//! object_store.put(&path, bytes).await.unwrap();
+//! let payload = PutPayload::from_static(b"hello");
+//! object_store.put(&path, payload).await.unwrap();
//! # }
//! ```
//!
-//! # Multipart Upload
+//! # Multipart Upload
//!
//! Use the [`ObjectStore::put_multipart`] method to atomically write a large amount of data
//!
@@ -320,6 +319,48 @@
//! # }
//! ```
//!
+//! # Vectored Write
+//!
+//! When writing data it is often the case that the size of the output is not known ahead of time.
+//!
+//! A common approach to handling this is to bump-allocate a `Vec`, whereby the underlying
+//! allocation is repeatedly reallocated, each time doubling the capacity. The performance of
+//! this is suboptimal as reallocating memory will often involve copying it to a new location.
+//!
+//! Fortunately, as [`PutPayload`] does not require memory regions to be contiguous, it is
+//! possible to instead allocate memory in chunks and avoid bump allocating. [`PutPayloadMut`]
+//! encapsulates this approach
+//!
+//! ```
+//! # use object_store::local::LocalFileSystem;
+//! # use object_store::{ObjectStore, PutPayloadMut};
+//! # use std::sync::Arc;
+//! # use bytes::Bytes;
+//! # use tokio::io::AsyncWriteExt;
+//! # use object_store::path::Path;
+//! # fn get_object_store() -> Arc<dyn ObjectStore> {
+//! # Arc::new(LocalFileSystem::new())
+//! # }
+//! # async fn multi_upload() {
+//! #
+//! let object_store: Arc<dyn ObjectStore> = get_object_store();
+//! let path = Path::from("data/large_file");
+//! let mut buffer = PutPayloadMut::new().with_block_size(8192);
+//! for _ in 0..22 {
+//! buffer.extend_from_slice(&[0; 1024]);
+//! }
+//! let payload = buffer.freeze();
+//!
+//! // Payload consists of 3 separate 8KB allocations
+//! assert_eq!(payload.as_ref().len(), 3);
+//! assert_eq!(payload.as_ref()[0].len(), 8192);
+//! assert_eq!(payload.as_ref()[1].len(), 8192);
+//! assert_eq!(payload.as_ref()[2].len(), 6144);
+//!
+//! object_store.put(&path, payload).await.unwrap();
+//! # }
+//! ```
+//!
//! # Conditional Fetch
//!
//! More complex object retrieval can be supported by [`ObjectStore::get_opts`].
@@ -427,7 +468,7 @@
//! let new = do_update(r.bytes().await.unwrap());
//!
//! // Attempt to commit transaction
-//! match store.put_opts(&path, new, PutMode::Update(version).into()).await {
+//! match store.put_opts(&path, new.into(), PutMode::Update(version).into()).await {
//! Ok(_) => break, // Successfully committed
//! Err(Error::Precondition { .. }) => continue, // Object has changed, try again
//! Err(e) => panic!("{e}")
@@ -498,17 +539,18 @@ pub use tags::TagSet;
pub mod multipart;
mod parse;
+mod payload;
mod upload;
mod util;
pub use parse::{parse_url, parse_url_opts};
+pub use payload::*;
pub use upload::*;
-pub use util::GetRange;
+pub use util::{coalesce_ranges, collect_bytes, GetRange, OBJECT_STORE_COALESCE_DEFAULT};
use crate::path::Path;
#[cfg(not(target_arch = "wasm32"))]
use crate::util::maybe_spawn_blocking;
-pub use crate::util::{coalesce_ranges, collect_bytes, OBJECT_STORE_COALESCE_DEFAULT};
use async_trait::async_trait;
use bytes::Bytes;
use chrono::{DateTime, Utc};
@@ -532,14 +574,20 @@ pub trait ObjectStore: std::fmt::Display + Send + Sync + Debug + 'static {
/// Save the provided bytes to the specified location
///
/// The operation is guaranteed to be atomic, it will either successfully
- /// write the entirety of `bytes` to `location`, or fail. No clients
+ /// write the entirety of `payload` to `location`, or fail. No clients
/// should be able to observe a partially written object
- async fn put(&self, location: &Path, bytes: Bytes) -> Result<PutResult> {
- self.put_opts(location, bytes, PutOptions::default()).await
+ async fn put(&self, location: &Path, payload: PutPayload) -> Result<PutResult> {
+ self.put_opts(location, payload, PutOptions::default())
+ .await
}
- /// Save the provided bytes to the specified location with the given options
- async fn put_opts(&self, location: &Path, bytes: Bytes, opts: PutOptions) -> Result<PutResult>;
+ /// Save the provided `payload` to `location` with the given options
+ async fn put_opts(
+ &self,
+ location: &Path,
+ payload: PutPayload,
+ opts: PutOptions,
+ ) -> Result<PutResult>;
/// Perform a multipart upload
///
@@ -616,11 +664,10 @@ pub trait ObjectStore: std::fmt::Display + Send + Sync + Debug + 'static {
/// # use object_store::{ObjectStore, ObjectMeta};
/// # use object_store::path::Path;
/// # use futures::{StreamExt, TryStreamExt};
- /// # use bytes::Bytes;
/// #
/// // Create two objects
- /// store.put(&Path::from("foo"), Bytes::from("foo")).await?;
- /// store.put(&Path::from("bar"), Bytes::from("bar")).await?;
+ /// store.put(&Path::from("foo"), "foo".into()).await?;
+ /// store.put(&Path::from("bar"), "bar".into()).await?;
///
/// // List object
/// let locations = store.list(None).map_ok(|m| m.location).boxed();
@@ -717,17 +764,17 @@ macro_rules! as_ref_impl {
($type:ty) => {
#[async_trait]
impl ObjectStore for $type {
- async fn put(&self, location: &Path, bytes: Bytes) -> Result<PutResult> {
- self.as_ref().put(location, bytes).await
+ async fn put(&self, location: &Path, payload: PutPayload) -> Result<PutResult> {
+ self.as_ref().put(location, payload).await
}
async fn put_opts(
&self,
location: &Path,
- bytes: Bytes,
+ payload: PutPayload,
opts: PutOptions,
) -> Result<PutResult> {
- self.as_ref().put_opts(location, bytes, opts).await
+ self.as_ref().put_opts(location, payload, opts).await
}
async fn put_multipart(&self, location: &Path) -> Result<Box<dyn MultipartUpload>> {
@@ -1219,8 +1266,7 @@ mod tests {
let location = Path::from("test_dir/test_file.json");
let data = Bytes::from("arbitrary data");
- let expected_data = data.clone();
- storage.put(&location, data).await.unwrap();
+ storage.put(&location, data.clone().into()).await.unwrap();
let root = Path::from("/");
@@ -1263,14 +1309,14 @@ mod tests {
assert!(content_list.is_empty());
let read_data = storage.get(&location).await.unwrap().bytes().await.unwrap();
- assert_eq!(&*read_data, expected_data);
+ assert_eq!(&*read_data, data);
// Test range request
let range = 3..7;
let range_result = storage.get_range(&location, range.clone()).await;
let bytes = range_result.unwrap();
- assert_eq!(bytes, expected_data.slice(range.clone()));
+ assert_eq!(bytes, data.slice(range.clone()));
let opts = GetOptions {
range: Some(GetRange::Bounded(2..5)),
@@ -1348,11 +1394,11 @@ mod tests {
let ranges = vec![0..1, 2..3, 0..5];
let bytes = storage.get_ranges(&location, &ranges).await.unwrap();
for (range, bytes) in ranges.iter().zip(bytes) {
- assert_eq!(bytes, expected_data.slice(range.clone()))
+ assert_eq!(bytes, data.slice(range.clone()))
}
let head = storage.head(&location).await.unwrap();
- assert_eq!(head.size, expected_data.len());
+ assert_eq!(head.size, data.len());
storage.delete(&location).await.unwrap();
@@ -1369,7 +1415,7 @@ mod tests {
let file_with_delimiter = Path::from_iter(["a", "b/c", "foo.file"]);
storage
- .put(&file_with_delimiter, Bytes::from("arbitrary"))
+ .put(&file_with_delimiter, "arbitrary".into())
.await
.unwrap();
@@ -1409,10 +1455,7 @@ mod tests {
let emoji_prefix = Path::from("🙀");
let emoji_file = Path::from("🙀/😀.parquet");
- storage
- .put(&emoji_file, Bytes::from("arbitrary"))
- .await
- .unwrap();
+ storage.put(&emoji_file, "arbitrary".into()).await.unwrap();
storage.head(&emoji_file).await.unwrap();
storage
@@ -1464,7 +1507,7 @@ mod tests {
let hello_prefix = Path::parse("%48%45%4C%4C%4F").unwrap();
let path = hello_prefix.child("foo.parquet");
- storage.put(&path, Bytes::from(vec![0, 1])).await.unwrap();
+ storage.put(&path, vec![0, 1].into()).await.unwrap();
let files = flatten_list_stream(storage, Some(&hello_prefix))
.await
.unwrap();
@@ -1504,7 +1547,7 @@ mod tests {
// Can also write non-percent encoded sequences
let path = Path::parse("%Q.parquet").unwrap();
- storage.put(&path, Bytes::from(vec![0, 1])).await.unwrap();
+ storage.put(&path, vec![0, 1].into()).await.unwrap();
let files = flatten_list_stream(storage, None).await.unwrap();
assert_eq!(files, vec![path.clone()]);
@@ -1512,7 +1555,7 @@ mod tests {
storage.delete(&path).await.unwrap();
let path = Path::parse("foo bar/I contain spaces.parquet").unwrap();
- storage.put(&path, Bytes::from(vec![0, 1])).await.unwrap();
+ storage.put(&path, vec![0, 1].into()).await.unwrap();
storage.head(&path).await.unwrap();
let files = flatten_list_stream(storage, Some(&Path::from("foo bar")))
@@ -1622,7 +1665,7 @@ mod tests {
delete_fixtures(storage).await;
let path = Path::from("empty");
- storage.put(&path, Bytes::new()).await.unwrap();
+ storage.put(&path, PutPayload::default()).await.unwrap();
let meta = storage.head(&path).await.unwrap();
assert_eq!(meta.size, 0);
let data = storage.get(&path).await.unwrap().bytes().await.unwrap();
@@ -1879,7 +1922,7 @@ mod tests {
let data = get_chunks(5 * 1024 * 1024, 3);
let bytes_expected = data.concat();
let mut upload = storage.put_multipart(&location).await.unwrap();
- let uploads = data.into_iter().map(|x| upload.put_part(x));
+ let uploads = data.into_iter().map(|x| upload.put_part(x.into()));
futures::future::try_join_all(uploads).await.unwrap();
// Object should not yet exist in store
@@ -1928,7 +1971,7 @@ mod tests {
// We can abort an in-progress write
let mut upload = storage.put_multipart(&location).await.unwrap();
upload
- .put_part(data.first().unwrap().clone())
+ .put_part(data.first().unwrap().clone().into())
.await
.unwrap();
@@ -1953,7 +1996,7 @@ mod tests {
let location1 = Path::from("foo/x.json");
let location2 = Path::from("foo.bar/y.json");
- let data = Bytes::from("arbitrary data");
+ let data = PutPayload::from("arbitrary data");
storage.put(&location1, data.clone()).await.unwrap();
storage.put(&location2, data).await.unwrap();
@@ -2011,8 +2054,7 @@ mod tests {
.collect();
for f in &files {
- let data = data.clone();
- storage.put(f, data).await.unwrap();
+ storage.put(f, data.clone().into()).await.unwrap();
}
// ==================== check: prefix-list `mydb/wb` (directory) ====================
@@ -2076,15 +2118,15 @@ mod tests {
let contents2 = Bytes::from("dogs");
// copy() make both objects identical
- storage.put(&path1, contents1.clone()).await.unwrap();
- storage.put(&path2, contents2.clone()).await.unwrap();
+ storage.put(&path1, contents1.clone().into()).await.unwrap();
+ storage.put(&path2, contents2.clone().into()).await.unwrap();
storage.copy(&path1, &path2).await.unwrap();
let new_contents = storage.get(&path2).await.unwrap().bytes().await.unwrap();
assert_eq!(&new_contents, &contents1);
// rename() copies contents and deletes original
- storage.put(&path1, contents1.clone()).await.unwrap();
- storage.put(&path2, contents2.clone()).await.unwrap();
+ storage.put(&path1, contents1.clone().into()).await.unwrap();
+ storage.put(&path2, contents2.clone().into()).await.unwrap();
storage.rename(&path1, &path2).await.unwrap();
let new_contents = storage.get(&path2).await.unwrap().bytes().await.unwrap();
assert_eq!(&new_contents, &contents1);
@@ -2104,8 +2146,8 @@ mod tests {
let contents2 = Bytes::from("dogs");
// copy_if_not_exists() errors if destination already exists
- storage.put(&path1, contents1.clone()).await.unwrap();
- storage.put(&path2, contents2.clone()).await.unwrap();
+ storage.put(&path1, contents1.clone().into()).await.unwrap();
+ storage.put(&path2, contents2.clone().into()).await.unwrap();
let result = storage.copy_if_not_exists(&path1, &path2).await;
assert!(result.is_err());
assert!(matches!(
@@ -2133,7 +2175,7 @@ mod tests {
// Create destination object
let path2 = Path::from("test2");
- storage.put(&path2, Bytes::from("hello")).await.unwrap();
+ storage.put(&path2, "hello".into()).await.unwrap();
// copy() errors if source does not exist
let result = storage.copy(&path1, &path2).await;
@@ -2164,7 +2206,7 @@ mod tests {
let parts: Vec<_> = futures::stream::iter(chunks)
.enumerate()
- .map(|(idx, b)| multipart.put_part(&path, &id, idx, b))
+ .map(|(idx, b)| multipart.put_part(&path, &id, idx, b.into()))
.buffered(2)
.try_collect()
.await
@@ -2204,7 +2246,7 @@ mod tests {
let data = Bytes::from("hello world");
let path = Path::from("file.txt");
- integration.put(&path, data.clone()).await.unwrap();
+ integration.put(&path, data.clone().into()).await.unwrap();
let signed = integration
.signed_url(Method::GET, &path, Duration::from_secs(60))
diff --git a/object_store/src/limit.rs b/object_store/src/limit.rs
index e5f6841638e1..b94aa05b8b6e 100644
--- a/object_store/src/limit.rs
+++ b/object_store/src/limit.rs
@@ -19,7 +19,7 @@
use crate::{
BoxStream, GetOptions, GetResult, GetResultPayload, ListResult, MultipartUpload, ObjectMeta,
- ObjectStore, Path, PutOptions, PutResult, Result, StreamExt, UploadPart,
+ ObjectStore, Path, PutOptions, PutPayload, PutResult, Result, StreamExt, UploadPart,
};
use async_trait::async_trait;
use bytes::Bytes;
@@ -70,14 +70,19 @@ impl<T: ObjectStore> std::fmt::Display for LimitStore<T> {
#[async_trait]
impl<T: ObjectStore> ObjectStore for LimitStore<T> {
- async fn put(&self, location: &Path, bytes: Bytes) -> Result<PutResult> {
+ async fn put(&self, location: &Path, payload: PutPayload) -> Result<PutResult> {
let _permit = self.semaphore.acquire().await.unwrap();
- self.inner.put(location, bytes).await
+ self.inner.put(location, payload).await
}
- async fn put_opts(&self, location: &Path, bytes: Bytes, opts: PutOptions) -> Result<PutResult> {
+ async fn put_opts(
+ &self,
+ location: &Path,
+ payload: PutPayload,
+ opts: PutOptions,
+ ) -> Result<PutResult> {
let _permit = self.semaphore.acquire().await.unwrap();
- self.inner.put_opts(location, bytes, opts).await
+ self.inner.put_opts(location, payload, opts).await
}
async fn put_multipart(&self, location: &Path) -> Result<Box<dyn MultipartUpload>> {
let upload = self.inner.put_multipart(location).await?;
@@ -232,7 +237,7 @@ impl LimitUpload {
#[async_trait]
impl MultipartUpload for LimitUpload {
- fn put_part(&mut self, data: Bytes) -> UploadPart {
+ fn put_part(&mut self, data: PutPayload) -> UploadPart {
let upload = self.upload.put_part(data);
let s = Arc::clone(&self.semaphore);
Box::pin(async move {
diff --git a/object_store/src/local.rs b/object_store/src/local.rs
index 6cc0c672af45..0d7c279b3190 100644
--- a/object_store/src/local.rs
+++ b/object_store/src/local.rs
@@ -39,7 +39,7 @@ use crate::{
path::{absolute_path_to_url, Path},
util::InvalidGetRange,
GetOptions, GetResult, GetResultPayload, ListResult, MultipartUpload, ObjectMeta, ObjectStore,
- PutMode, PutOptions, PutResult, Result, UploadPart,
+ PutMode, PutOptions, PutPayload, PutResult, Result, UploadPart,
};
/// A specialized `Error` for filesystem object store-related errors
@@ -336,7 +336,12 @@ fn is_valid_file_path(path: &Path) -> bool {
#[async_trait]
impl ObjectStore for LocalFileSystem {
- async fn put_opts(&self, location: &Path, bytes: Bytes, opts: PutOptions) -> Result<PutResult> {
+ async fn put_opts(
+ &self,
+ location: &Path,
+ payload: PutPayload,
+ opts: PutOptions,
+ ) -> Result<PutResult> {
if matches!(opts.mode, PutMode::Update(_)) {
return Err(crate::Error::NotImplemented);
}
@@ -346,7 +351,7 @@ impl ObjectStore for LocalFileSystem {
let (mut file, staging_path) = new_staged_upload(&path)?;
let mut e_tag = None;
- let err = match file.write_all(&bytes) {
+ let err = match payload.iter().try_for_each(|x| file.write_all(x)) {
Ok(_) => {
let metadata = file.metadata().map_err(|e| Error::Metadata {
source: e.into(),
@@ -724,9 +729,9 @@ impl LocalUpload {
#[async_trait]
impl MultipartUpload for LocalUpload {
- fn put_part(&mut self, data: Bytes) -> UploadPart {
+ fn put_part(&mut self, data: PutPayload) -> UploadPart {
let offset = self.offset;
- self.offset += data.len() as u64;
+ self.offset += data.content_length() as u64;
let s = Arc::clone(&self.state);
maybe_spawn_blocking(move || {
@@ -734,7 +739,11 @@ impl MultipartUpload for LocalUpload {
let file = f.as_mut().context(AbortedSnafu)?;
file.seek(SeekFrom::Start(offset))
.context(SeekSnafu { path: &s.dest })?;
- file.write_all(&data).context(UnableToCopyDataToFileSnafu)?;
+
+ data.iter()
+ .try_for_each(|x| file.write_all(x))
+ .context(UnableToCopyDataToFileSnafu)?;
+
Ok(())
})
.boxed()
@@ -1016,8 +1025,8 @@ mod tests {
// Can't use stream_get test as WriteMultipart uses a tokio JoinSet
let p = Path::from("manual_upload");
let mut upload = integration.put_multipart(&p).await.unwrap();
- upload.put_part(Bytes::from_static(b"123")).await.unwrap();
- upload.put_part(Bytes::from_static(b"45678")).await.unwrap();
+ upload.put_part("123".into()).await.unwrap();
+ upload.put_part("45678".into()).await.unwrap();
let r = upload.complete().await.unwrap();
let get = integration.get(&p).await.unwrap();
@@ -1035,9 +1044,11 @@ mod tests {
let location = Path::from("nested/file/test_file");
let data = Bytes::from("arbitrary data");
- let expected_data = data.clone();
- integration.put(&location, data).await.unwrap();
+ integration
+ .put(&location, data.clone().into())
+ .await
+ .unwrap();
let read_data = integration
.get(&location)
@@ -1046,7 +1057,7 @@ mod tests {
.bytes()
.await
.unwrap();
- assert_eq!(&*read_data, expected_data);
+ assert_eq!(&*read_data, data);
}
#[tokio::test]
@@ -1057,9 +1068,11 @@ mod tests {
let location = Path::from("some_file");
let data = Bytes::from("arbitrary data");
- let expected_data = data.clone();
- integration.put(&location, data).await.unwrap();
+ integration
+ .put(&location, data.clone().into())
+ .await
+ .unwrap();
let read_data = integration
.get(&location)
@@ -1068,7 +1081,7 @@ mod tests {
.bytes()
.await
.unwrap();
- assert_eq!(&*read_data, expected_data);
+ assert_eq!(&*read_data, data);
}
#[tokio::test]
@@ -1260,7 +1273,7 @@ mod tests {
// Adding a file through a symlink creates in both paths
integration
- .put(&Path::from("b/file.parquet"), Bytes::from(vec![0, 1, 2]))
+ .put(&Path::from("b/file.parquet"), vec![0, 1, 2].into())
.await
.unwrap();
@@ -1279,7 +1292,7 @@ mod tests {
let directory = Path::from("directory");
let object = directory.child("child.txt");
let data = Bytes::from("arbitrary");
- integration.put(&object, data.clone()).await.unwrap();
+ integration.put(&object, data.clone().into()).await.unwrap();
integration.head(&object).await.unwrap();
let result = integration.get(&object).await.unwrap();
assert_eq!(result.bytes().await.unwrap(), data);
@@ -1319,7 +1332,7 @@ mod tests {
let integration = LocalFileSystem::new_with_prefix(root.path()).unwrap();
let location = Path::from("some_file");
- let data = Bytes::from("arbitrary data");
+ let data = PutPayload::from("arbitrary data");
let mut u1 = integration.put_multipart(&location).await.unwrap();
u1.put_part(data.clone()).await.unwrap();
@@ -1418,12 +1431,10 @@ mod tests {
#[cfg(test)]
mod not_wasm_tests {
use std::time::Duration;
-
- use bytes::Bytes;
use tempfile::TempDir;
use crate::local::LocalFileSystem;
- use crate::{ObjectStore, Path};
+ use crate::{ObjectStore, Path, PutPayload};
#[tokio::test]
async fn test_cleanup_intermediate_files() {
@@ -1431,7 +1442,7 @@ mod not_wasm_tests {
let integration = LocalFileSystem::new_with_prefix(root.path()).unwrap();
let location = Path::from("some_file");
- let data = Bytes::from_static(b"hello");
+ let data = PutPayload::from_static(b"hello");
let mut upload = integration.put_multipart(&location).await.unwrap();
upload.put_part(data).await.unwrap();
diff --git a/object_store/src/memory.rs b/object_store/src/memory.rs
index 6c960d4f24fb..d42e6f231c04 100644
--- a/object_store/src/memory.rs
+++ b/object_store/src/memory.rs
@@ -29,11 +29,11 @@ use snafu::{OptionExt, ResultExt, Snafu};
use crate::multipart::{MultipartStore, PartId};
use crate::util::InvalidGetRange;
-use crate::GetOptions;
use crate::{
path::Path, GetRange, GetResult, GetResultPayload, ListResult, MultipartId, MultipartUpload,
ObjectMeta, ObjectStore, PutMode, PutOptions, PutResult, Result, UpdateVersion, UploadPart,
};
+use crate::{GetOptions, PutPayload};
/// A specialized `Error` for in-memory object store-related errors
#[derive(Debug, Snafu)]
@@ -192,10 +192,15 @@ impl std::fmt::Display for InMemory {
#[async_trait]
impl ObjectStore for InMemory {
- async fn put_opts(&self, location: &Path, bytes: Bytes, opts: PutOptions) -> Result<PutResult> {
+ async fn put_opts(
+ &self,
+ location: &Path,
+ payload: PutPayload,
+ opts: PutOptions,
+ ) -> Result<PutResult> {
let mut storage = self.storage.write();
let etag = storage.next_etag;
- let entry = Entry::new(bytes, Utc::now(), etag);
+ let entry = Entry::new(payload.into(), Utc::now(), etag);
match opts.mode {
PutMode::Overwrite => storage.overwrite(location, entry),
@@ -391,14 +396,14 @@ impl MultipartStore for InMemory {
_path: &Path,
id: &MultipartId,
part_idx: usize,
- data: Bytes,
+ payload: PutPayload,
) -> Result<PartId> {
let mut storage = self.storage.write();
let upload = storage.upload_mut(id)?;
if part_idx <= upload.parts.len() {
upload.parts.resize(part_idx + 1, None);
}
- upload.parts[part_idx] = Some(data);
+ upload.parts[part_idx] = Some(payload.into());
Ok(PartId {
content_id: Default::default(),
})
@@ -471,21 +476,22 @@ impl InMemory {
#[derive(Debug)]
struct InMemoryUpload {
location: Path,
- parts: Vec<Bytes>,
+ parts: Vec<PutPayload>,
storage: Arc<RwLock<Storage>>,
}
#[async_trait]
impl MultipartUpload for InMemoryUpload {
- fn put_part(&mut self, data: Bytes) -> UploadPart {
- self.parts.push(data);
+ fn put_part(&mut self, payload: PutPayload) -> UploadPart {
+ self.parts.push(payload);
Box::pin(futures::future::ready(Ok(())))
}
async fn complete(&mut self) -> Result<PutResult> {
- let cap = self.parts.iter().map(|x| x.len()).sum();
+ let cap = self.parts.iter().map(|x| x.content_length()).sum();
let mut buf = Vec::with_capacity(cap);
- self.parts.iter().for_each(|x| buf.extend_from_slice(x));
+ let parts = self.parts.iter().flatten();
+ parts.for_each(|x| buf.extend_from_slice(x));
let etag = self.storage.write().insert(&self.location, buf.into());
Ok(PutResult {
e_tag: Some(etag.to_string()),
@@ -552,9 +558,11 @@ mod tests {
let location = Path::from("some_file");
let data = Bytes::from("arbitrary data");
- let expected_data = data.clone();
- integration.put(&location, data).await.unwrap();
+ integration
+ .put(&location, data.clone().into())
+ .await
+ .unwrap();
let read_data = integration
.get(&location)
@@ -563,7 +571,7 @@ mod tests {
.bytes()
.await
.unwrap();
- assert_eq!(&*read_data, expected_data);
+ assert_eq!(&*read_data, data);
}
const NON_EXISTENT_NAME: &str = "nonexistentname";
diff --git a/object_store/src/multipart.rs b/object_store/src/multipart.rs
index 26cce3936244..d94e7f150513 100644
--- a/object_store/src/multipart.rs
+++ b/object_store/src/multipart.rs
@@ -22,10 +22,9 @@
//! especially useful when dealing with large files or high-throughput systems.
use async_trait::async_trait;
-use bytes::Bytes;
use crate::path::Path;
-use crate::{MultipartId, PutResult, Result};
+use crate::{MultipartId, PutPayload, PutResult, Result};
/// Represents a part of a file that has been successfully uploaded in a multipart upload process.
#[derive(Debug, Clone)]
@@ -64,7 +63,7 @@ pub trait MultipartStore: Send + Sync + 'static {
path: &Path,
id: &MultipartId,
part_idx: usize,
- data: Bytes,
+ data: PutPayload,
) -> Result<PartId>;
/// Completes a multipart upload
diff --git a/object_store/src/payload.rs b/object_store/src/payload.rs
new file mode 100644
index 000000000000..486bea3ea91f
--- /dev/null
+++ b/object_store/src/payload.rs
@@ -0,0 +1,314 @@
+// 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.
+
+use bytes::Bytes;
+use std::sync::Arc;
+
+/// A cheaply cloneable, ordered collection of [`Bytes`]
+#[derive(Debug, Clone)]
+pub struct PutPayload(Arc<[Bytes]>);
+
+impl Default for PutPayload {
+ fn default() -> Self {
+ Self(Arc::new([]))
+ }
+}
+
+impl PutPayload {
+ /// Create a new empty [`PutPayload`]
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Creates a [`PutPayload`] from a static slice
+ pub fn from_static(s: &'static [u8]) -> Self {
+ s.into()
+ }
+
+ /// Creates a [`PutPayload`] from a [`Bytes`]
+ pub fn from_bytes(s: Bytes) -> Self {
+ s.into()
+ }
+
+ #[cfg(feature = "cloud")]
+ pub(crate) fn body(&self) -> reqwest::Body {
+ reqwest::Body::wrap_stream(futures::stream::iter(
+ self.clone().into_iter().map(Ok::<_, crate::Error>),
+ ))
+ }
+
+ /// Returns the total length of the [`Bytes`] in this payload
+ pub fn content_length(&self) -> usize {
+ self.0.iter().map(|b| b.len()).sum()
+ }
+
+ /// Returns an iterator over the [`Bytes`] in this payload
+ pub fn iter(&self) -> PutPayloadIter<'_> {
+ PutPayloadIter(self.0.iter())
+ }
+}
+
+impl AsRef<[Bytes]> for PutPayload {
+ fn as_ref(&self) -> &[Bytes] {
+ self.0.as_ref()
+ }
+}
+
+impl<'a> IntoIterator for &'a PutPayload {
+ type Item = &'a Bytes;
+ type IntoIter = PutPayloadIter<'a>;
+
+ fn into_iter(self) -> Self::IntoIter {
+ self.iter()
+ }
+}
+
+impl IntoIterator for PutPayload {
+ type Item = Bytes;
+ type IntoIter = PutPayloadIntoIter;
+
+ fn into_iter(self) -> Self::IntoIter {
+ PutPayloadIntoIter {
+ payload: self,
+ idx: 0,
+ }
+ }
+}
+
+/// An iterator over [`PutPayload`]
+#[derive(Debug)]
+pub struct PutPayloadIter<'a>(std::slice::Iter<'a, Bytes>);
+
+impl<'a> Iterator for PutPayloadIter<'a> {
+ type Item = &'a Bytes;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ self.0.next()
+ }
+
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ self.0.size_hint()
+ }
+}
+
+/// An owning iterator of [`PutPayload`]
+#[derive(Debug)]
+pub struct PutPayloadIntoIter {
+ payload: PutPayload,
+ idx: usize,
+}
+
+impl Iterator for PutPayloadIntoIter {
+ type Item = Bytes;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ let p = self.payload.0.get(self.idx)?.clone();
+ self.idx += 1;
+ Some(p)
+ }
+
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ let l = self.payload.0.len() - self.idx;
+ (l, Some(l))
+ }
+}
+
+impl From<Bytes> for PutPayload {
+ fn from(value: Bytes) -> Self {
+ Self(Arc::new([value]))
+ }
+}
+
+impl From<Vec<u8>> for PutPayload {
+ fn from(value: Vec<u8>) -> Self {
+ Self(Arc::new([value.into()]))
+ }
+}
+
+impl From<&'static str> for PutPayload {
+ fn from(value: &'static str) -> Self {
+ Bytes::from(value).into()
+ }
+}
+
+impl From<&'static [u8]> for PutPayload {
+ fn from(value: &'static [u8]) -> Self {
+ Bytes::from(value).into()
+ }
+}
+
+impl From<String> for PutPayload {
+ fn from(value: String) -> Self {
+ Bytes::from(value).into()
+ }
+}
+
+impl FromIterator<u8> for PutPayload {
+ fn from_iter<T: IntoIterator<Item = u8>>(iter: T) -> Self {
+ Bytes::from_iter(iter).into()
+ }
+}
+
+impl FromIterator<Bytes> for PutPayload {
+ fn from_iter<T: IntoIterator<Item = Bytes>>(iter: T) -> Self {
+ Self(iter.into_iter().collect())
+ }
+}
+
+impl From<PutPayload> for Bytes {
+ fn from(value: PutPayload) -> Self {
+ match value.0.len() {
+ 0 => Self::new(),
+ 1 => value.0[0].clone(),
+ _ => {
+ let mut buf = Vec::with_capacity(value.content_length());
+ value.iter().for_each(|x| buf.extend_from_slice(x));
+ buf.into()
+ }
+ }
+ }
+}
+
+/// A builder for [`PutPayload`] that avoids reallocating memory
+///
+/// Data is allocated in fixed blocks, which are flushed to [`Bytes`] once full.
+/// Unlike [`Vec`] this avoids needing to repeatedly reallocate blocks of memory,
+/// which typically involves copying all the previously written data to a new
+/// contiguous memory region.
+#[derive(Debug)]
+pub struct PutPayloadMut {
+ len: usize,
+ completed: Vec<Bytes>,
+ in_progress: Vec<u8>,
+ block_size: usize,
+}
+
+impl Default for PutPayloadMut {
+ fn default() -> Self {
+ Self {
+ len: 0,
+ completed: vec![],
+ in_progress: vec![],
+
+ block_size: 8 * 1024,
+ }
+ }
+}
+
+impl PutPayloadMut {
+ /// Create a new [`PutPayloadMut`]
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Configures the minimum allocation size
+ ///
+ /// Defaults to 8KB
+ pub fn with_block_size(self, block_size: usize) -> Self {
+ Self { block_size, ..self }
+ }
+
+ /// Write bytes into this [`PutPayloadMut`]
+ ///
+ /// If there is an in-progress block, data will be first written to it, flushing
+ /// it to [`Bytes`] once full. If data remains to be written, a new block of memory
+ /// of at least the configured block size will be allocated, to hold the remaining data.
+ pub fn extend_from_slice(&mut self, slice: &[u8]) {
+ let remaining = self.in_progress.capacity() - self.in_progress.len();
+ let to_copy = remaining.min(slice.len());
+
+ self.in_progress.extend_from_slice(&slice[..to_copy]);
+ if self.in_progress.capacity() == self.in_progress.len() {
+ let new_cap = self.block_size.max(slice.len() - to_copy);
+ let completed = std::mem::replace(&mut self.in_progress, Vec::with_capacity(new_cap));
+ if !completed.is_empty() {
+ self.completed.push(completed.into())
+ }
+ self.in_progress.extend_from_slice(&slice[to_copy..])
+ }
+ self.len += slice.len();
+ }
+
+ /// Append a [`Bytes`] to this [`PutPayloadMut`] without copying
+ ///
+ /// This will close any currently buffered block populated by [`Self::extend_from_slice`],
+ /// and append `bytes` to this payload without copying.
+ pub fn push(&mut self, bytes: Bytes) {
+ if !self.in_progress.is_empty() {
+ let completed = std::mem::take(&mut self.in_progress);
+ self.completed.push(completed.into())
+ }
+ self.completed.push(bytes)
+ }
+
+ /// Returns `true` if this [`PutPayloadMut`] contains no bytes
+ #[inline]
+ pub fn is_empty(&self) -> bool {
+ self.len == 0
+ }
+
+ /// Returns the total length of the [`Bytes`] in this payload
+ #[inline]
+ pub fn content_length(&self) -> usize {
+ self.len
+ }
+
+ /// Convert into [`PutPayload`]
+ pub fn freeze(mut self) -> PutPayload {
+ if !self.in_progress.is_empty() {
+ let completed = std::mem::take(&mut self.in_progress).into();
+ self.completed.push(completed);
+ }
+ PutPayload(self.completed.into())
+ }
+}
+
+impl From<PutPayloadMut> for PutPayload {
+ fn from(value: PutPayloadMut) -> Self {
+ value.freeze()
+ }
+}
+
+#[cfg(test)]
+mod test {
+ use crate::PutPayloadMut;
+
+ #[test]
+ fn test_put_payload() {
+ let mut chunk = PutPayloadMut::new().with_block_size(23);
+ chunk.extend_from_slice(&[1; 16]);
+ chunk.extend_from_slice(&[2; 32]);
+ chunk.extend_from_slice(&[2; 5]);
+ chunk.extend_from_slice(&[2; 21]);
+ chunk.extend_from_slice(&[2; 40]);
+ chunk.extend_from_slice(&[0; 0]);
+ chunk.push("foobar".into());
+
+ let payload = chunk.freeze();
+ assert_eq!(payload.content_length(), 120);
+
+ let chunks = payload.as_ref();
+ assert_eq!(chunks.len(), 6);
+
+ assert_eq!(chunks[0].len(), 23);
+ assert_eq!(chunks[1].len(), 25); // 32 - (23 - 16)
+ assert_eq!(chunks[2].len(), 23);
+ assert_eq!(chunks[3].len(), 23);
+ assert_eq!(chunks[4].len(), 20);
+ assert_eq!(chunks[5].len(), 6);
+ }
+}
diff --git a/object_store/src/prefix.rs b/object_store/src/prefix.rs
index 053f71a2d063..1d1ffeed8c63 100644
--- a/object_store/src/prefix.rs
+++ b/object_store/src/prefix.rs
@@ -23,7 +23,7 @@ use std::ops::Range;
use crate::path::Path;
use crate::{
GetOptions, GetResult, ListResult, MultipartUpload, ObjectMeta, ObjectStore, PutOptions,
- PutResult, Result,
+ PutPayload, PutResult, Result,
};
#[doc(hidden)]
@@ -80,14 +80,19 @@ impl<T: ObjectStore> PrefixStore<T> {
#[async_trait::async_trait]
impl<T: ObjectStore> ObjectStore for PrefixStore<T> {
- async fn put(&self, location: &Path, bytes: Bytes) -> Result<PutResult> {
+ async fn put(&self, location: &Path, payload: PutPayload) -> Result<PutResult> {
let full_path = self.full_path(location);
- self.inner.put(&full_path, bytes).await
+ self.inner.put(&full_path, payload).await
}
- async fn put_opts(&self, location: &Path, bytes: Bytes, opts: PutOptions) -> Result<PutResult> {
+ async fn put_opts(
+ &self,
+ location: &Path,
+ payload: PutPayload,
+ opts: PutOptions,
+ ) -> Result<PutResult> {
let full_path = self.full_path(location);
- self.inner.put_opts(&full_path, bytes, opts).await
+ self.inner.put_opts(&full_path, payload, opts).await
}
async fn put_multipart(&self, location: &Path) -> Result<Box<dyn MultipartUpload>> {
@@ -218,9 +223,8 @@ mod tests {
let location = Path::from("prefix/test_file.json");
let data = Bytes::from("arbitrary data");
- let expected_data = data.clone();
- local.put(&location, data).await.unwrap();
+ local.put(&location, data.clone().into()).await.unwrap();
let prefix = PrefixStore::new(local, "prefix");
let location_prefix = Path::from("test_file.json");
@@ -239,11 +243,11 @@ mod tests {
.bytes()
.await
.unwrap();
- assert_eq!(&*read_data, expected_data);
+ assert_eq!(&*read_data, data);
let target_prefix = Path::from("/test_written.json");
prefix
- .put(&target_prefix, expected_data.clone())
+ .put(&target_prefix, data.clone().into())
.await
.unwrap();
@@ -256,6 +260,6 @@ mod tests {
let location = Path::from("prefix/test_written.json");
let read_data = local.get(&location).await.unwrap().bytes().await.unwrap();
- assert_eq!(&*read_data, expected_data)
+ assert_eq!(&*read_data, data)
}
}
diff --git a/object_store/src/throttle.rs b/object_store/src/throttle.rs
index 65fac5922f69..d089784668e9 100644
--- a/object_store/src/throttle.rs
+++ b/object_store/src/throttle.rs
@@ -23,7 +23,7 @@ use std::{convert::TryInto, sync::Arc};
use crate::multipart::{MultipartStore, PartId};
use crate::{
path::Path, GetResult, GetResultPayload, ListResult, MultipartId, MultipartUpload, ObjectMeta,
- ObjectStore, PutOptions, PutResult, Result,
+ ObjectStore, PutOptions, PutPayload, PutResult, Result,
};
use crate::{GetOptions, UploadPart};
use async_trait::async_trait;
@@ -148,14 +148,19 @@ impl<T: ObjectStore> std::fmt::Display for ThrottledStore<T> {
#[async_trait]
impl<T: ObjectStore> ObjectStore for ThrottledStore<T> {
- async fn put(&self, location: &Path, bytes: Bytes) -> Result<PutResult> {
+ async fn put(&self, location: &Path, payload: PutPayload) -> Result<PutResult> {
sleep(self.config().wait_put_per_call).await;
- self.inner.put(location, bytes).await
+ self.inner.put(location, payload).await
}
- async fn put_opts(&self, location: &Path, bytes: Bytes, opts: PutOptions) -> Result<PutResult> {
+ async fn put_opts(
+ &self,
+ location: &Path,
+ payload: PutPayload,
+ opts: PutOptions,
+ ) -> Result<PutResult> {
sleep(self.config().wait_put_per_call).await;
- self.inner.put_opts(location, bytes, opts).await
+ self.inner.put_opts(location, payload, opts).await
}
async fn put_multipart(&self, location: &Path) -> Result<Box<dyn MultipartUpload>> {
@@ -332,7 +337,7 @@ impl<T: MultipartStore> MultipartStore for ThrottledStore<T> {
path: &Path,
id: &MultipartId,
part_idx: usize,
- data: Bytes,
+ data: PutPayload,
) -> Result<PartId> {
sleep(self.config().wait_put_per_call).await;
self.inner.put_part(path, id, part_idx, data).await
@@ -360,7 +365,7 @@ struct ThrottledUpload {
#[async_trait]
impl MultipartUpload for ThrottledUpload {
- fn put_part(&mut self, data: Bytes) -> UploadPart {
+ fn put_part(&mut self, data: PutPayload) -> UploadPart {
let duration = self.sleep;
let put = self.upload.put_part(data);
Box::pin(async move {
@@ -382,7 +387,6 @@ impl MultipartUpload for ThrottledUpload {
mod tests {
use super::*;
use crate::{memory::InMemory, tests::*, GetResultPayload};
- use bytes::Bytes;
use futures::TryStreamExt;
use tokio::time::Duration;
use tokio::time::Instant;
@@ -536,8 +540,7 @@ mod tests {
if let Some(n_bytes) = n_bytes {
let data: Vec<_> = std::iter::repeat(1u8).take(n_bytes).collect();
- let bytes = Bytes::from(data);
- store.put(&path, bytes).await.unwrap();
+ store.put(&path, data.into()).await.unwrap();
} else {
// ensure object is absent
store.delete(&path).await.unwrap();
@@ -560,9 +563,7 @@ mod tests {
// create new entries
for i in 0..n_entries {
let path = prefix.child(i.to_string().as_str());
-
- let data = Bytes::from("bar");
- store.put(&path, data).await.unwrap();
+ store.put(&path, "bar".into()).await.unwrap();
}
prefix
@@ -630,10 +631,9 @@ mod tests {
async fn measure_put(store: &ThrottledStore<InMemory>, n_bytes: usize) -> Duration {
let data: Vec<_> = std::iter::repeat(1u8).take(n_bytes).collect();
- let bytes = Bytes::from(data);
let t0 = Instant::now();
- store.put(&Path::from("foo"), bytes).await.unwrap();
+ store.put(&Path::from("foo"), data.into()).await.unwrap();
t0.elapsed()
}
diff --git a/object_store/src/upload.rs b/object_store/src/upload.rs
index fe864e2821c9..9805df0dda73 100644
--- a/object_store/src/upload.rs
+++ b/object_store/src/upload.rs
@@ -17,14 +17,13 @@
use std::task::{Context, Poll};
+use crate::{PutPayload, PutPayloadMut, PutResult, Result};
use async_trait::async_trait;
use bytes::Bytes;
use futures::future::BoxFuture;
use futures::ready;
use tokio::task::JoinSet;
-use crate::{PutResult, Result};
-
/// An upload part request
pub type UploadPart = BoxFuture<'static, Result<()>>;
@@ -65,7 +64,7 @@ pub trait MultipartUpload: Send + std::fmt::Debug {
/// ```
///
/// [R2]: https://developers.cloudflare.com/r2/objects/multipart-objects/#limitations
- fn put_part(&mut self, data: Bytes) -> UploadPart;
+ fn put_part(&mut self, data: PutPayload) -> UploadPart;
/// Complete the multipart upload
///
@@ -106,7 +105,9 @@ pub trait MultipartUpload: Send + std::fmt::Debug {
pub struct WriteMultipart {
upload: Box<dyn MultipartUpload>,
- buffer: Vec<u8>,
+ buffer: PutPayloadMut,
+
+ chunk_size: usize,
tasks: JoinSet<Result<()>>,
}
@@ -121,7 +122,8 @@ impl WriteMultipart {
pub fn new_with_chunk_size(upload: Box<dyn MultipartUpload>, chunk_size: usize) -> Self {
Self {
upload,
- buffer: Vec::with_capacity(chunk_size),
+ chunk_size,
+ buffer: PutPayloadMut::new(),
tasks: Default::default(),
}
}
@@ -149,6 +151,9 @@ impl WriteMultipart {
/// Write data to this [`WriteMultipart`]
///
+ /// Data is buffered using [`PutPayloadMut::extend_from_slice`]. Implementations looking to
+ /// write data from owned buffers may prefer [`Self::put`] as this avoids copying.
+ ///
/// Note this method is synchronous (not `async`) and will immediately
/// start new uploads as soon as the internal `chunk_size` is hit,
/// regardless of how many outstanding uploads are already in progress.
@@ -157,19 +162,38 @@ impl WriteMultipart {
/// [`Self::wait_for_capacity`] prior to calling this method
pub fn write(&mut self, mut buf: &[u8]) {
while !buf.is_empty() {
- let capacity = self.buffer.capacity();
- let remaining = capacity - self.buffer.len();
+ let remaining = self.chunk_size - self.buffer.content_length();
let to_read = buf.len().min(remaining);
self.buffer.extend_from_slice(&buf[..to_read]);
if to_read == remaining {
- let part = std::mem::replace(&mut self.buffer, Vec::with_capacity(capacity));
- self.put_part(part.into())
+ let buffer = std::mem::take(&mut self.buffer);
+ self.put_part(buffer.into())
}
buf = &buf[to_read..]
}
}
- fn put_part(&mut self, part: Bytes) {
+ /// Put a chunk of data into this [`WriteMultipart`] without copying
+ ///
+ /// Data is buffered using [`PutPayloadMut::push`]. Implementations looking to
+ /// perform writes from non-owned buffers should prefer [`Self::write`] as this
+ /// will allow multiple calls to share the same underlying allocation.
+ ///
+ /// See [`Self::write`] for information on backpressure
+ pub fn put(&mut self, mut bytes: Bytes) {
+ while !bytes.is_empty() {
+ let remaining = self.chunk_size - self.buffer.content_length();
+ if bytes.len() < remaining {
+ self.buffer.push(bytes);
+ return;
+ }
+ self.buffer.push(bytes.split_to(remaining));
+ let buffer = std::mem::take(&mut self.buffer);
+ self.put_part(buffer.into())
+ }
+ }
+
+ pub(crate) fn put_part(&mut self, part: PutPayload) {
self.tasks.spawn(self.upload.put_part(part));
}
|
diff --git a/object_store/tests/get_range_file.rs b/object_store/tests/get_range_file.rs
index 309a86d8fe9d..59c593400450 100644
--- a/object_store/tests/get_range_file.rs
+++ b/object_store/tests/get_range_file.rs
@@ -37,8 +37,13 @@ impl std::fmt::Display for MyStore {
#[async_trait]
impl ObjectStore for MyStore {
- async fn put_opts(&self, path: &Path, data: Bytes, opts: PutOptions) -> Result<PutResult> {
- self.0.put_opts(path, data, opts).await
+ async fn put_opts(
+ &self,
+ location: &Path,
+ payload: PutPayload,
+ opts: PutOptions,
+ ) -> Result<PutResult> {
+ self.0.put_opts(location, payload, opts).await
}
async fn put_multipart(&self, _location: &Path) -> Result<Box<dyn MultipartUpload>> {
@@ -77,7 +82,7 @@ async fn test_get_range() {
let path = Path::from("foo");
let expected = Bytes::from_static(b"hello world");
- store.put(&path, expected.clone()).await.unwrap();
+ store.put(&path, expected.clone().into()).await.unwrap();
let fetched = store.get(&path).await.unwrap().bytes().await.unwrap();
assert_eq!(expected, fetched);
@@ -101,7 +106,7 @@ async fn test_get_opts_over_range() {
let path = Path::from("foo");
let expected = Bytes::from_static(b"hello world");
- store.put(&path, expected.clone()).await.unwrap();
+ store.put(&path, expected.clone().into()).await.unwrap();
let opts = GetOptions {
range: Some(GetRange::Bounded(0..(expected.len() * 2))),
|
[ObjectStore] Non-Contiguous Write Payloads
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
<!--
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
(This section helps Arrow developers understand the context and *why* for this feature, in addition to the *what*)
-->
Currently `ObjectStore::put` accepts a `Bytes` object, which is a contiguous memory region. This is simple and efficient where payload sizes are known ahead of time, and buffers can therefore be sized appropriately up-front, however, it may force additional copies in situations where this is not known.
**Describe the solution you'd like**
<!--
A clear and concise description of what you want to happen.
-->
I am not sure, the HTTP-based stores are fairly coupled to HTTP requests containing a `Bytes` body, and whilst `reqwest` does have the ability to wrap a byte stream, this would break retries, AWS content signing and possibly some other things.
**Describe alternatives you've considered**
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
With #5500 it becomes possible to do chunked writes with no additional copies, this potentially reduces the need for this functionality as users can just allocate data in 5 MiB chunks.
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
https://github.com/apache/arrow-rs/pull/5500 adds a put_part API with a similar requirement
|
2024-03-21T01:24:21Z
|
51.0
|
30767a687b48d0dbd2e030eef327826c39095123
|
|
apache/arrow-rs
| 5,531
|
apache__arrow-rs-5531
|
[
"1207"
] |
f41c2a4e5a33e482e12351051d77d0e059f28e33
|
diff --git a/arrow-buffer/src/buffer/immutable.rs b/arrow-buffer/src/buffer/immutable.rs
index 552e3f1615c7..f26cde05b7ab 100644
--- a/arrow-buffer/src/buffer/immutable.rs
+++ b/arrow-buffer/src/buffer/immutable.rs
@@ -171,23 +171,33 @@ impl Buffer {
/// Returns a new [Buffer] that is a slice of this buffer starting at `offset`.
/// Doing so allows the same memory region to be shared between buffers.
+ ///
/// # Panics
+ ///
/// Panics iff `offset` is larger than `len`.
pub fn slice(&self, offset: usize) -> Self {
+ let mut s = self.clone();
+ s.advance(offset);
+ s
+ }
+
+ /// Increases the offset of this buffer by `offset`
+ ///
+ /// # Panics
+ ///
+ /// Panics iff `offset` is larger than `len`.
+ #[inline]
+ pub fn advance(&mut self, offset: usize) {
assert!(
offset <= self.length,
"the offset of the new Buffer cannot exceed the existing length"
);
+ self.length -= offset;
// Safety:
// This cannot overflow as
// `self.offset + self.length < self.data.len()`
// `offset < self.length`
- let ptr = unsafe { self.ptr.add(offset) };
- Self {
- data: self.data.clone(),
- length: self.length - offset,
- ptr,
- }
+ self.ptr = unsafe { self.ptr.add(offset) };
}
/// Returns a new [Buffer] that is a slice of this buffer starting at `offset`,
diff --git a/arrow-ipc/src/convert.rs b/arrow-ipc/src/convert.rs
index b2e580241adc..51e54215ea7f 100644
--- a/arrow-ipc/src/convert.rs
+++ b/arrow-ipc/src/convert.rs
@@ -17,12 +17,17 @@
//! Utilities for converting between IPC types and native Arrow types
+use arrow_buffer::Buffer;
use arrow_schema::*;
-use flatbuffers::{FlatBufferBuilder, ForwardsUOffset, UnionWIPOffset, Vector, WIPOffset};
+use flatbuffers::{
+ FlatBufferBuilder, ForwardsUOffset, UnionWIPOffset, Vector, Verifiable, Verifier,
+ VerifierOptions, WIPOffset,
+};
use std::collections::HashMap;
+use std::fmt::{Debug, Formatter};
use std::sync::Arc;
-use crate::{size_prefixed_root_as_message, KeyValue, CONTINUATION_MARKER};
+use crate::{size_prefixed_root_as_message, KeyValue, Message, CONTINUATION_MARKER};
use DataType::*;
/// Serialize a schema in IPC format
@@ -806,6 +811,45 @@ pub(crate) fn get_fb_dictionary<'a>(
builder.finish()
}
+/// An owned container for a validated [`Message`]
+///
+/// Safely decoding a flatbuffer requires validating the various embedded offsets,
+/// see [`Verifier`]. This is a potentially expensive operation, and it is therefore desirable
+/// to only do this once. [`crate::root_as_message`] performs this validation on construction,
+/// however, it returns a [`Message`] borrowing the provided byte slice. This prevents
+/// storing this [`Message`] in the same data structure that owns the buffer, as this
+/// would require self-referential borrows.
+///
+/// [`MessageBuffer`] solves this problem by providing a safe API for a [`Message`]
+/// without a lifetime bound.
+#[derive(Clone)]
+pub struct MessageBuffer(Buffer);
+
+impl Debug for MessageBuffer {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ self.as_ref().fmt(f)
+ }
+}
+
+impl MessageBuffer {
+ /// Try to create a [`MessageBuffer`] from the provided [`Buffer`]
+ pub fn try_new(buf: Buffer) -> Result<Self, ArrowError> {
+ let opts = VerifierOptions::default();
+ let mut v = Verifier::new(&opts, &buf);
+ <ForwardsUOffset<Message>>::run_verifier(&mut v, 0).map_err(|err| {
+ ArrowError::ParseError(format!("Unable to get root as message: {err:?}"))
+ })?;
+ Ok(Self(buf))
+ }
+
+ /// Return the [`Message`]
+ #[inline]
+ pub fn as_ref(&self) -> Message<'_> {
+ // SAFETY: Run verifier on construction
+ unsafe { crate::root_as_message_unchecked(&self.0) }
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/arrow-ipc/src/reader.rs b/arrow-ipc/src/reader.rs
index f015674d6813..dd0365da4bc7 100644
--- a/arrow-ipc/src/reader.rs
+++ b/arrow-ipc/src/reader.rs
@@ -20,6 +20,10 @@
//! The `FileReader` and `StreamReader` have similar interfaces,
//! however the `FileReader` expects a reader that supports `Seek`ing
+mod stream;
+
+pub use stream::*;
+
use flatbuffers::{VectorIter, VerifierOptions};
use std::collections::HashMap;
use std::fmt;
diff --git a/arrow-ipc/src/reader/stream.rs b/arrow-ipc/src/reader/stream.rs
new file mode 100644
index 000000000000..7807228175ac
--- /dev/null
+++ b/arrow-ipc/src/reader/stream.rs
@@ -0,0 +1,297 @@
+// 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.
+
+use std::collections::HashMap;
+use std::fmt::Debug;
+use std::sync::Arc;
+
+use arrow_array::{ArrayRef, RecordBatch};
+use arrow_buffer::{Buffer, MutableBuffer};
+use arrow_schema::{ArrowError, SchemaRef};
+
+use crate::convert::MessageBuffer;
+use crate::reader::{read_dictionary, read_record_batch};
+use crate::{MessageHeader, CONTINUATION_MARKER};
+
+/// A low-level interface for reading [`RecordBatch`] data from a stream of bytes
+///
+/// See [StreamReader](crate::reader::StreamReader) for a higher-level interface
+#[derive(Debug, Default)]
+pub struct StreamDecoder {
+ /// The schema of this decoder, if read
+ schema: Option<SchemaRef>,
+ /// Lookup table for dictionaries by ID
+ dictionaries: HashMap<i64, ArrayRef>,
+ /// The decoder state
+ state: DecoderState,
+ /// A scratch buffer when a read is split across multiple `Buffer`
+ buf: MutableBuffer,
+}
+
+#[derive(Debug)]
+enum DecoderState {
+ /// Decoding the message header
+ Header {
+ /// Temporary buffer
+ buf: [u8; 4],
+ /// Number of bytes read into buf
+ read: u8,
+ /// If we have read a continuation token
+ continuation: bool,
+ },
+ /// Decoding the message flatbuffer
+ Message {
+ /// The size of the message flatbuffer
+ size: u32,
+ },
+ /// Decoding the message body
+ Body {
+ /// The message flatbuffer
+ message: MessageBuffer,
+ },
+ /// Reached the end of the stream
+ Finished,
+}
+
+impl Default for DecoderState {
+ fn default() -> Self {
+ Self::Header {
+ buf: [0; 4],
+ read: 0,
+ continuation: false,
+ }
+ }
+}
+
+impl StreamDecoder {
+ /// Create a new [`StreamDecoder`]
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Try to read the next [`RecordBatch`] from the provided [`Buffer`]
+ ///
+ /// [`Buffer::advance`] will be called on `buffer` for any consumed bytes.
+ ///
+ /// The push-based interface facilitates integration with sources that yield arbitrarily
+ /// delimited bytes ranges, such as a chunked byte stream received from object storage
+ ///
+ /// ```
+ /// # use arrow_array::RecordBatch;
+ /// # use arrow_buffer::Buffer;
+ /// # use arrow_ipc::reader::StreamDecoder;
+ /// # use arrow_schema::ArrowError;
+ /// #
+ /// fn print_stream<I>(src: impl Iterator<Item = Buffer>) -> Result<(), ArrowError> {
+ /// let mut decoder = StreamDecoder::new();
+ /// for mut x in src {
+ /// while !x.is_empty() {
+ /// if let Some(x) = decoder.decode(&mut x)? {
+ /// println!("{x:?}");
+ /// }
+ /// }
+ /// }
+ /// decoder.finish().unwrap();
+ /// Ok(())
+ /// }
+ /// ```
+ pub fn decode(&mut self, buffer: &mut Buffer) -> Result<Option<RecordBatch>, ArrowError> {
+ while !buffer.is_empty() {
+ match &mut self.state {
+ DecoderState::Header {
+ buf,
+ read,
+ continuation,
+ } => {
+ let offset_buf = &mut buf[*read as usize..];
+ let to_read = buffer.len().min(offset_buf.len());
+ offset_buf[..to_read].copy_from_slice(&buffer[..to_read]);
+ *read += to_read as u8;
+ buffer.advance(to_read);
+ if *read == 4 {
+ if !*continuation && buf == &CONTINUATION_MARKER {
+ *continuation = true;
+ *read = 0;
+ continue;
+ }
+ let size = u32::from_le_bytes(*buf);
+
+ if size == 0 {
+ self.state = DecoderState::Finished;
+ continue;
+ }
+ self.state = DecoderState::Message { size };
+ }
+ }
+ DecoderState::Message { size } => {
+ let len = *size as usize;
+ if self.buf.is_empty() && buffer.len() > len {
+ let message = MessageBuffer::try_new(buffer.slice_with_length(0, len))?;
+ self.state = DecoderState::Body { message };
+ buffer.advance(len);
+ continue;
+ }
+
+ let to_read = buffer.len().min(len - self.buf.len());
+ self.buf.extend_from_slice(&buffer[..to_read]);
+ buffer.advance(to_read);
+ if self.buf.len() == len {
+ let message = MessageBuffer::try_new(std::mem::take(&mut self.buf).into())?;
+ self.state = DecoderState::Body { message };
+ }
+ }
+ DecoderState::Body { message } => {
+ let message = message.as_ref();
+ let body_length = message.bodyLength() as usize;
+
+ let body = if self.buf.is_empty() && buffer.len() >= body_length {
+ let body = buffer.slice_with_length(0, body_length);
+ buffer.advance(body_length);
+ body
+ } else {
+ let to_read = buffer.len().min(body_length - self.buf.len());
+ self.buf.extend_from_slice(&buffer[..to_read]);
+ buffer.advance(to_read);
+
+ if self.buf.len() != body_length {
+ continue;
+ }
+ std::mem::take(&mut self.buf).into()
+ };
+
+ let version = message.version();
+ match message.header_type() {
+ MessageHeader::Schema => {
+ if self.schema.is_some() {
+ return Err(ArrowError::IpcError(
+ "Not expecting a schema when messages are read".to_string(),
+ ));
+ }
+
+ let ipc_schema = message.header_as_schema().unwrap();
+ let schema = crate::convert::fb_to_schema(ipc_schema);
+ self.state = DecoderState::default();
+ self.schema = Some(Arc::new(schema));
+ }
+ MessageHeader::RecordBatch => {
+ let batch = message.header_as_record_batch().unwrap();
+ let schema = self.schema.clone().ok_or_else(|| {
+ ArrowError::IpcError("Missing schema".to_string())
+ })?;
+ let batch = read_record_batch(
+ &body,
+ batch,
+ schema,
+ &self.dictionaries,
+ None,
+ &version,
+ )?;
+ self.state = DecoderState::default();
+ return Ok(Some(batch));
+ }
+ MessageHeader::DictionaryBatch => {
+ let dictionary = message.header_as_dictionary_batch().unwrap();
+ let schema = self.schema.as_deref().ok_or_else(|| {
+ ArrowError::IpcError("Missing schema".to_string())
+ })?;
+ read_dictionary(
+ &body,
+ dictionary,
+ schema,
+ &mut self.dictionaries,
+ &version,
+ )?;
+ self.state = DecoderState::default();
+ }
+ MessageHeader::NONE => {
+ self.state = DecoderState::default();
+ }
+ t => {
+ return Err(ArrowError::IpcError(format!(
+ "Message type unsupported by StreamDecoder: {t:?}"
+ )))
+ }
+ }
+ }
+ DecoderState::Finished => {
+ return Err(ArrowError::IpcError("Unexpected EOS".to_string()))
+ }
+ }
+ }
+ Ok(None)
+ }
+
+ /// Signal the end of stream
+ ///
+ /// Returns an error if any partial data remains in the stream
+ pub fn finish(&mut self) -> Result<(), ArrowError> {
+ match self.state {
+ DecoderState::Finished
+ | DecoderState::Header {
+ read: 0,
+ continuation: false,
+ ..
+ } => Ok(()),
+ _ => Err(ArrowError::IpcError("Unexpected End of Stream".to_string())),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::writer::StreamWriter;
+ use arrow_array::{Int32Array, Int64Array, RecordBatch};
+ use arrow_schema::{DataType, Field, Schema};
+
+ // Further tests in arrow-integration-testing/tests/ipc_reader.rs
+
+ #[test]
+ fn test_eos() {
+ let schema = Arc::new(Schema::new(vec![
+ Field::new("int32", DataType::Int32, false),
+ Field::new("int64", DataType::Int64, false),
+ ]));
+
+ let input = RecordBatch::try_new(
+ schema.clone(),
+ vec![
+ Arc::new(Int32Array::from(vec![1, 2, 3])) as _,
+ Arc::new(Int64Array::from(vec![1, 2, 3])) as _,
+ ],
+ )
+ .unwrap();
+
+ let mut buf = Vec::with_capacity(1024);
+ let mut s = StreamWriter::try_new(&mut buf, &schema).unwrap();
+ s.write(&input).unwrap();
+ s.finish().unwrap();
+ drop(s);
+
+ let buffer = Buffer::from_vec(buf);
+
+ let mut b = buffer.slice_with_length(0, buffer.len() - 1);
+ let mut decoder = StreamDecoder::new();
+ let output = decoder.decode(&mut b).unwrap().unwrap();
+ assert_eq!(output, input);
+ assert_eq!(b.len(), 7); // 8 byte EOS truncated by 1 byte
+ assert!(decoder.decode(&mut b).unwrap().is_none());
+
+ let err = decoder.finish().unwrap_err().to_string();
+ assert_eq!(err, "Ipc error: Unexpected End of Stream");
+ }
+}
diff --git a/arrow-ipc/src/writer.rs b/arrow-ipc/src/writer.rs
index 4e32b04b0fba..22edfbc2454d 100644
--- a/arrow-ipc/src/writer.rs
+++ b/arrow-ipc/src/writer.rs
@@ -677,6 +677,7 @@ impl DictionaryTracker {
}
}
+/// Writer for an IPC file
pub struct FileWriter<W: Write> {
/// The object to write to
writer: BufWriter<W>,
@@ -701,13 +702,13 @@ pub struct FileWriter<W: Write> {
}
impl<W: Write> FileWriter<W> {
- /// Try create a new writer, with the schema written as part of the header
+ /// Try to create a new writer, with the schema written as part of the header
pub fn try_new(writer: W, schema: &Schema) -> Result<Self, ArrowError> {
let write_options = IpcWriteOptions::default();
Self::try_new_with_options(writer, schema, write_options)
}
- /// Try create a new writer with IpcWriteOptions
+ /// Try to create a new writer with IpcWriteOptions
pub fn try_new_with_options(
writer: W,
schema: &Schema,
@@ -857,6 +858,7 @@ impl<W: Write> RecordBatchWriter for FileWriter<W> {
}
}
+/// Writer for an IPC stream
pub struct StreamWriter<W: Write> {
/// The object to write to
writer: BufWriter<W>,
@@ -871,7 +873,7 @@ pub struct StreamWriter<W: Write> {
}
impl<W: Write> StreamWriter<W> {
- /// Try create a new writer, with the schema written as part of the header
+ /// Try to create a new writer, with the schema written as part of the header
pub fn try_new(writer: W, schema: &Schema) -> Result<Self, ArrowError> {
let write_options = IpcWriteOptions::default();
Self::try_new_with_options(writer, schema, write_options)
diff --git a/arrow-json/src/reader/mod.rs b/arrow-json/src/reader/mod.rs
index 99055573345a..628e5c96693d 100644
--- a/arrow-json/src/reader/mod.rs
+++ b/arrow-json/src/reader/mod.rs
@@ -416,7 +416,7 @@ impl Decoder {
/// should be included in the next call to [`Self::decode`]
///
/// There is no requirement that `buf` contains a whole number of records, facilitating
- /// integration with arbitrary byte streams, such as that yielded by [`BufRead`]
+ /// integration with arbitrary byte streams, such as those yielded by [`BufRead`]
pub fn decode(&mut self, buf: &[u8]) -> Result<usize, ArrowError> {
self.tape_decoder.decode(buf)
}
|
diff --git a/arrow-integration-testing/tests/ipc_reader.rs b/arrow-integration-testing/tests/ipc_reader.rs
index 88cdad64f92f..a683075990c7 100644
--- a/arrow-integration-testing/tests/ipc_reader.rs
+++ b/arrow-integration-testing/tests/ipc_reader.rs
@@ -19,10 +19,12 @@
//! in `testing/arrow-ipc-stream/integration/...`
use arrow::error::ArrowError;
-use arrow::ipc::reader::{FileReader, StreamReader};
+use arrow::ipc::reader::{FileReader, StreamDecoder, StreamReader};
use arrow::util::test_util::arrow_test_data;
+use arrow_buffer::Buffer;
use arrow_integration_testing::read_gzip_json;
use std::fs::File;
+use std::io::Read;
#[test]
fn read_0_1_4() {
@@ -182,18 +184,45 @@ fn verify_arrow_stream(testdata: &str, version: &str, path: &str) {
let filename = format!("{testdata}/arrow-ipc-stream/integration/{version}/{path}.stream");
println!("Verifying {filename}");
+ // read expected JSON output
+ let arrow_json = read_gzip_json(version, path);
+
// Compare contents to the expected output format in JSON
{
println!(" verifying content");
let file = File::open(&filename).unwrap();
let mut reader = StreamReader::try_new(file, None).unwrap();
- // read expected JSON output
- let arrow_json = read_gzip_json(version, path);
assert!(arrow_json.equals_reader(&mut reader).unwrap());
// the next batch must be empty
assert!(reader.next().is_none());
// the stream must indicate that it's finished
assert!(reader.is_finished());
}
+
+ // Test stream decoder
+ let expected = arrow_json.get_record_batches().unwrap();
+ for chunk_sizes in [1, 2, 8, 123] {
+ let mut decoder = StreamDecoder::new();
+ let stream = chunked_file(&filename, chunk_sizes);
+ let mut actual = Vec::with_capacity(expected.len());
+ for mut x in stream {
+ while !x.is_empty() {
+ if let Some(x) = decoder.decode(&mut x).unwrap() {
+ actual.push(x);
+ }
+ }
+ }
+ decoder.finish().unwrap();
+ assert_eq!(expected, actual);
+ }
+}
+
+fn chunked_file(filename: &str, chunk_size: u64) -> impl Iterator<Item = Buffer> {
+ let mut file = File::open(filename).unwrap();
+ std::iter::from_fn(move || {
+ let mut buf = vec![];
+ let read = (&mut file).take(chunk_size).read_to_end(&mut buf).unwrap();
+ (read != 0).then(|| Buffer::from_vec(buf))
+ })
}
|
Async IPC Reader/Writer
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
The current IPCReader and IPCWriter require a sync Reader/Writer complicating their use in async systems such as DataFusion. Once such use case can be found in https://github.com/apache/arrow-datafusion/pull/1596 where it is used for spilling buffers
**Describe the solution you'd like**
The encoding/decoding logic to/from Flatbuffers is already largely broken out, it should be a relatively straightforward task of writing an async muxer for this. Ultimately I'm not aware of a way to avoid reading/writing the flatbuffer to an intermediate buffer first, and so I don't think it is possible to do better than this - e.g. by having the codecs read/write directly to/from the file.
|
@tustvold I was going to create a similar issue but found this. Is something related to flatbuffer serialization blocking IPC streamwriter and filewriter from being async.
Looking at the code it feels like operations can be made async by switching out std::io with tokio::io. If it is actually that trivial to make the change then probably the next question is about how or if arrow-ipc crate should provides both async and sync readers/writers.
I will create a seperate issue if this issue is not related to arrow-ipc filewriter/streamwriter
> Looking at the code it feels like operations can be made async by switching out std::io with tokio::io
For writing it should simply be a case of taking the output of `IpcDataGenerator::encoded_batch` and feeding the result to the appropriate async IO primitive.
The read side will be slightly more complicated, but as you say is large similar to the current sync approach. I think the hard part will be avoiding large amounts of code duplication, which will likely require splitting out various utility functions to contain the common logic
I might pick this work up because I want to play around with IPC files a bit and most of the surrounding is already async. Any thoughts about module structure? In my mind there are two alternatives:
1. Adding a new `sync` module for the existing reader/writer and a feature-flagged `async` module, I think that's more elegant with shorter `use` statements but its a breaking change.
2. using the similar structure to `parquet` where the async reader/writer each have their own module and both are behind the `async` feature flag.
I think https://github.com/apache/arrow-rs/pull/5249 is largely all that is needed for the read side, I think all that remains is showing how it can be hooked to to object_store or similar.
Similarly the write side is much the same, we already provide free functions for encoding batches
|
2024-03-19T06:19:19Z
|
51.0
|
30767a687b48d0dbd2e030eef327826c39095123
|
apache/arrow-rs
| 5,500
|
apache__arrow-rs-5500
|
[
"5526"
] |
f41c2a4e5a33e482e12351051d77d0e059f28e33
|
diff --git a/object_store/src/aws/mod.rs b/object_store/src/aws/mod.rs
index b11f4513b6df..b33771de9a86 100644
--- a/object_store/src/aws/mod.rs
+++ b/object_store/src/aws/mod.rs
@@ -17,17 +17,14 @@
//! An object store implementation for S3
//!
-//! ## Multi-part uploads
+//! ## Multipart uploads
//!
-//! Multi-part uploads can be initiated with the [ObjectStore::put_multipart] method.
-//! Data passed to the writer is automatically buffered to meet the minimum size
-//! requirements for a part. Multiple parts are uploaded concurrently.
+//! Multipart uploads can be initiated with the [ObjectStore::put_multipart] method.
//!
//! If the writer fails for any reason, you may have parts uploaded to AWS but not
-//! used that you may be charged for. Use the [ObjectStore::abort_multipart] method
-//! to abort the upload and drop those unneeded parts. In addition, you may wish to
-//! consider implementing [automatic cleanup] of unused parts that are older than one
-//! week.
+//! used that you will be charged for. [`MultipartUpload::abort`] may be invoked to drop
+//! these unneeded parts, however, it is recommended that you consider implementing
+//! [automatic cleanup] of unused parts that are older than some threshold.
//!
//! [automatic cleanup]: https://aws.amazon.com/blogs/aws/s3-lifecycle-management-update-support-for-multipart-uploads-and-delete-markers/
@@ -38,18 +35,17 @@ use futures::{StreamExt, TryStreamExt};
use reqwest::header::{HeaderName, IF_MATCH, IF_NONE_MATCH};
use reqwest::{Method, StatusCode};
use std::{sync::Arc, time::Duration};
-use tokio::io::AsyncWrite;
use url::Url;
use crate::aws::client::{RequestError, S3Client};
use crate::client::get::GetClientExt;
use crate::client::list::ListClientExt;
use crate::client::CredentialProvider;
-use crate::multipart::{MultiPartStore, PartId, PutPart, WriteMultiPart};
+use crate::multipart::{MultipartStore, PartId};
use crate::signer::Signer;
use crate::{
- Error, GetOptions, GetResult, ListResult, MultipartId, ObjectMeta, ObjectStore, Path, PutMode,
- PutOptions, PutResult, Result,
+ Error, GetOptions, GetResult, ListResult, MultipartId, MultipartUpload, ObjectMeta,
+ ObjectStore, Path, PutMode, PutOptions, PutResult, Result, UploadPart,
};
static TAGS_HEADER: HeaderName = HeaderName::from_static("x-amz-tagging");
@@ -85,6 +81,7 @@ const STORE: &str = "S3";
/// [`CredentialProvider`] for [`AmazonS3`]
pub type AwsCredentialProvider = Arc<dyn CredentialProvider<Credential = AwsCredential>>;
+use crate::client::parts::Parts;
pub use credential::{AwsAuthorizer, AwsCredential};
/// Interface for [Amazon S3](https://aws.amazon.com/s3/).
@@ -211,25 +208,18 @@ impl ObjectStore for AmazonS3 {
}
}
- async fn put_multipart(
- &self,
- location: &Path,
- ) -> Result<(MultipartId, Box<dyn AsyncWrite + Unpin + Send>)> {
- let id = self.client.create_multipart(location).await?;
-
- let upload = S3MultiPartUpload {
- location: location.clone(),
- upload_id: id.clone(),
- client: Arc::clone(&self.client),
- };
-
- Ok((id, Box::new(WriteMultiPart::new(upload, 8))))
- }
-
- async fn abort_multipart(&self, location: &Path, multipart_id: &MultipartId) -> Result<()> {
- self.client
- .delete_request(location, &[("uploadId", multipart_id)])
- .await
+ async fn put_multipart(&self, location: &Path) -> Result<Box<dyn MultipartUpload>> {
+ let upload_id = self.client.create_multipart(location).await?;
+
+ Ok(Box::new(S3MultiPartUpload {
+ part_idx: 0,
+ state: Arc::new(UploadState {
+ client: Arc::clone(&self.client),
+ location: location.clone(),
+ upload_id: upload_id.clone(),
+ parts: Default::default(),
+ }),
+ }))
}
async fn get_opts(&self, location: &Path, options: GetOptions) -> Result<GetResult> {
@@ -319,30 +309,55 @@ impl ObjectStore for AmazonS3 {
}
}
+#[derive(Debug)]
struct S3MultiPartUpload {
+ part_idx: usize,
+ state: Arc<UploadState>,
+}
+
+#[derive(Debug)]
+struct UploadState {
+ parts: Parts,
location: Path,
upload_id: String,
client: Arc<S3Client>,
}
#[async_trait]
-impl PutPart for S3MultiPartUpload {
- async fn put_part(&self, buf: Vec<u8>, part_idx: usize) -> Result<PartId> {
- self.client
- .put_part(&self.location, &self.upload_id, part_idx, buf.into())
+impl MultipartUpload for S3MultiPartUpload {
+ fn put_part(&mut self, data: Bytes) -> UploadPart {
+ let idx = self.part_idx;
+ self.part_idx += 1;
+ let state = Arc::clone(&self.state);
+ Box::pin(async move {
+ let part = state
+ .client
+ .put_part(&state.location, &state.upload_id, idx, data)
+ .await?;
+ state.parts.put(idx, part);
+ Ok(())
+ })
+ }
+
+ async fn complete(&mut self) -> Result<PutResult> {
+ let parts = self.state.parts.finish(self.part_idx)?;
+
+ self.state
+ .client
+ .complete_multipart(&self.state.location, &self.state.upload_id, parts)
.await
}
- async fn complete(&self, completed_parts: Vec<PartId>) -> Result<()> {
- self.client
- .complete_multipart(&self.location, &self.upload_id, completed_parts)
- .await?;
- Ok(())
+ async fn abort(&mut self) -> Result<()> {
+ self.state
+ .client
+ .delete_request(&self.state.location, &[("uploadId", &self.state.upload_id)])
+ .await
}
}
#[async_trait]
-impl MultiPartStore for AmazonS3 {
+impl MultipartStore for AmazonS3 {
async fn create_multipart(&self, path: &Path) -> Result<MultipartId> {
self.client.create_multipart(path).await
}
@@ -377,7 +392,6 @@ mod tests {
use crate::{client::get::GetClient, tests::*};
use bytes::Bytes;
use hyper::HeaderMap;
- use tokio::io::AsyncWriteExt;
const NON_EXISTENT_NAME: &str = "nonexistentname";
@@ -542,9 +556,9 @@ mod tests {
store.put(&locations[0], data.clone()).await.unwrap();
store.copy(&locations[0], &locations[1]).await.unwrap();
- let (_, mut writer) = store.put_multipart(&locations[2]).await.unwrap();
- writer.write_all(&data).await.unwrap();
- writer.shutdown().await.unwrap();
+ let mut upload = store.put_multipart(&locations[2]).await.unwrap();
+ upload.put_part(data.clone()).await.unwrap();
+ upload.complete().await.unwrap();
for location in &locations {
let res = store
diff --git a/object_store/src/azure/mod.rs b/object_store/src/azure/mod.rs
index 712b7a36c56a..5d3a405ccc93 100644
--- a/object_store/src/azure/mod.rs
+++ b/object_store/src/azure/mod.rs
@@ -19,19 +19,15 @@
//!
//! ## Streaming uploads
//!
-//! [ObjectStore::put_multipart] will upload data in blocks and write a blob from those
-//! blocks. Data is buffered internally to make blocks of at least 5MB and blocks
-//! are uploaded concurrently.
+//! [ObjectStore::put_multipart] will upload data in blocks and write a blob from those blocks.
//!
-//! [ObjectStore::abort_multipart] is a no-op, since Azure Blob Store doesn't provide
-//! a way to drop old blocks. Instead unused blocks are automatically cleaned up
-//! after 7 days.
+//! Unused blocks will automatically be dropped after 7 days.
use crate::{
- multipart::{MultiPartStore, PartId, PutPart, WriteMultiPart},
+ multipart::{MultipartStore, PartId},
path::Path,
signer::Signer,
- GetOptions, GetResult, ListResult, MultipartId, ObjectMeta, ObjectStore, PutOptions, PutResult,
- Result,
+ GetOptions, GetResult, ListResult, MultipartId, MultipartUpload, ObjectMeta, ObjectStore,
+ PutOptions, PutResult, Result, UploadPart,
};
use async_trait::async_trait;
use bytes::Bytes;
@@ -40,7 +36,6 @@ use reqwest::Method;
use std::fmt::Debug;
use std::sync::Arc;
use std::time::Duration;
-use tokio::io::AsyncWrite;
use url::Url;
use crate::client::get::GetClientExt;
@@ -54,6 +49,8 @@ mod credential;
/// [`CredentialProvider`] for [`MicrosoftAzure`]
pub type AzureCredentialProvider = Arc<dyn CredentialProvider<Credential = AzureCredential>>;
+use crate::azure::client::AzureClient;
+use crate::client::parts::Parts;
pub use builder::{AzureConfigKey, MicrosoftAzureBuilder};
pub use credential::AzureCredential;
@@ -94,21 +91,15 @@ impl ObjectStore for MicrosoftAzure {
self.client.put_blob(location, bytes, opts).await
}
- async fn put_multipart(
- &self,
- location: &Path,
- ) -> Result<(MultipartId, Box<dyn AsyncWrite + Unpin + Send>)> {
- let inner = AzureMultiPartUpload {
- client: Arc::clone(&self.client),
- location: location.to_owned(),
- };
- Ok((String::new(), Box::new(WriteMultiPart::new(inner, 8))))
- }
-
- async fn abort_multipart(&self, _location: &Path, _multipart_id: &MultipartId) -> Result<()> {
- // There is no way to drop blocks that have been uploaded. Instead, they simply
- // expire in 7 days.
- Ok(())
+ async fn put_multipart(&self, location: &Path) -> Result<Box<dyn MultipartUpload>> {
+ Ok(Box::new(AzureMultiPartUpload {
+ part_idx: 0,
+ state: Arc::new(UploadState {
+ client: Arc::clone(&self.client),
+ location: location.clone(),
+ parts: Default::default(),
+ }),
+ }))
}
async fn get_opts(&self, location: &Path, options: GetOptions) -> Result<GetResult> {
@@ -197,26 +188,49 @@ impl Signer for MicrosoftAzure {
/// put_multipart_part -> PUT block
/// complete -> PUT block list
/// abort -> No equivalent; blocks are simply dropped after 7 days
-#[derive(Debug, Clone)]
+#[derive(Debug)]
struct AzureMultiPartUpload {
- client: Arc<client::AzureClient>,
+ part_idx: usize,
+ state: Arc<UploadState>,
+}
+
+#[derive(Debug)]
+struct UploadState {
location: Path,
+ parts: Parts,
+ client: Arc<AzureClient>,
}
#[async_trait]
-impl PutPart for AzureMultiPartUpload {
- async fn put_part(&self, buf: Vec<u8>, idx: usize) -> Result<PartId> {
- self.client.put_block(&self.location, idx, buf.into()).await
+impl MultipartUpload for AzureMultiPartUpload {
+ fn put_part(&mut self, data: Bytes) -> UploadPart {
+ let idx = self.part_idx;
+ self.part_idx += 1;
+ let state = Arc::clone(&self.state);
+ Box::pin(async move {
+ let part = state.client.put_block(&state.location, idx, data).await?;
+ state.parts.put(idx, part);
+ Ok(())
+ })
+ }
+
+ async fn complete(&mut self) -> Result<PutResult> {
+ let parts = self.state.parts.finish(self.part_idx)?;
+
+ self.state
+ .client
+ .put_block_list(&self.state.location, parts)
+ .await
}
- async fn complete(&self, parts: Vec<PartId>) -> Result<()> {
- self.client.put_block_list(&self.location, parts).await?;
+ async fn abort(&mut self) -> Result<()> {
+ // Nothing to do
Ok(())
}
}
#[async_trait]
-impl MultiPartStore for MicrosoftAzure {
+impl MultipartStore for MicrosoftAzure {
async fn create_multipart(&self, _: &Path) -> Result<MultipartId> {
Ok(String::new())
}
diff --git a/object_store/src/buffered.rs b/object_store/src/buffered.rs
index 9299e1147bc1..39f8eafbef7e 100644
--- a/object_store/src/buffered.rs
+++ b/object_store/src/buffered.rs
@@ -18,7 +18,7 @@
//! Utilities for performing tokio-style buffered IO
use crate::path::Path;
-use crate::{MultipartId, ObjectMeta, ObjectStore};
+use crate::{ObjectMeta, ObjectStore, WriteMultipart};
use bytes::Bytes;
use futures::future::{BoxFuture, FutureExt};
use futures::ready;
@@ -27,7 +27,7 @@ use std::io::{Error, ErrorKind, SeekFrom};
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
-use tokio::io::{AsyncBufRead, AsyncRead, AsyncSeek, AsyncWrite, AsyncWriteExt, ReadBuf};
+use tokio::io::{AsyncBufRead, AsyncRead, AsyncSeek, AsyncWrite, ReadBuf};
/// The default buffer size used by [`BufReader`]
pub const DEFAULT_BUFFER_SIZE: usize = 1024 * 1024;
@@ -217,7 +217,6 @@ impl AsyncBufRead for BufReader {
pub struct BufWriter {
capacity: usize,
state: BufWriterState,
- multipart_id: Option<MultipartId>,
store: Arc<dyn ObjectStore>,
}
@@ -225,22 +224,19 @@ impl std::fmt::Debug for BufWriter {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BufWriter")
.field("capacity", &self.capacity)
- .field("multipart_id", &self.multipart_id)
.finish()
}
}
-type MultipartResult = (MultipartId, Box<dyn AsyncWrite + Send + Unpin>);
-
enum BufWriterState {
/// Buffer up to capacity bytes
Buffer(Path, Vec<u8>),
/// [`ObjectStore::put_multipart`]
- Prepare(BoxFuture<'static, std::io::Result<MultipartResult>>),
+ Prepare(BoxFuture<'static, std::io::Result<WriteMultipart>>),
/// Write to a multipart upload
- Write(Box<dyn AsyncWrite + Send + Unpin>),
+ Write(Option<WriteMultipart>),
/// [`ObjectStore::put`]
- Put(BoxFuture<'static, std::io::Result<()>>),
+ Flush(BoxFuture<'static, std::io::Result<()>>),
}
impl BufWriter {
@@ -255,14 +251,20 @@ impl BufWriter {
capacity,
store,
state: BufWriterState::Buffer(path, Vec::new()),
- multipart_id: None,
}
}
- /// Returns the [`MultipartId`] of the multipart upload created by this
- /// writer, if any.
- pub fn multipart_id(&self) -> Option<&MultipartId> {
- self.multipart_id.as_ref()
+ /// Abort this writer, cleaning up any partially uploaded state
+ ///
+ /// # Panic
+ ///
+ /// Panics if this writer has already been shutdown or aborted
+ pub async fn abort(&mut self) -> crate::Result<()> {
+ match &mut self.state {
+ BufWriterState::Buffer(_, _) | BufWriterState::Prepare(_) => Ok(()),
+ BufWriterState::Flush(_) => panic!("Already shut down"),
+ BufWriterState::Write(x) => x.take().unwrap().abort().await,
+ }
}
}
@@ -275,12 +277,15 @@ impl AsyncWrite for BufWriter {
let cap = self.capacity;
loop {
return match &mut self.state {
- BufWriterState::Write(write) => Pin::new(write).poll_write(cx, buf),
- BufWriterState::Put(_) => panic!("Already shut down"),
+ BufWriterState::Write(Some(write)) => {
+ write.write(buf);
+ Poll::Ready(Ok(buf.len()))
+ }
+ BufWriterState::Write(None) | BufWriterState::Flush(_) => {
+ panic!("Already shut down")
+ }
BufWriterState::Prepare(f) => {
- let (id, w) = ready!(f.poll_unpin(cx)?);
- self.state = BufWriterState::Write(w);
- self.multipart_id = Some(id);
+ self.state = BufWriterState::Write(ready!(f.poll_unpin(cx)?).into());
continue;
}
BufWriterState::Buffer(path, b) => {
@@ -289,9 +294,10 @@ impl AsyncWrite for BufWriter {
let path = std::mem::take(path);
let store = Arc::clone(&self.store);
self.state = BufWriterState::Prepare(Box::pin(async move {
- let (id, mut writer) = store.put_multipart(&path).await?;
- writer.write_all(&buffer).await?;
- Ok((id, writer))
+ let upload = store.put_multipart(&path).await?;
+ let mut chunked = WriteMultipart::new(upload);
+ chunked.write(&buffer);
+ Ok(chunked)
}));
continue;
}
@@ -305,13 +311,10 @@ impl AsyncWrite for BufWriter {
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Error>> {
loop {
return match &mut self.state {
- BufWriterState::Buffer(_, _) => Poll::Ready(Ok(())),
- BufWriterState::Write(write) => Pin::new(write).poll_flush(cx),
- BufWriterState::Put(_) => panic!("Already shut down"),
+ BufWriterState::Write(_) | BufWriterState::Buffer(_, _) => Poll::Ready(Ok(())),
+ BufWriterState::Flush(_) => panic!("Already shut down"),
BufWriterState::Prepare(f) => {
- let (id, w) = ready!(f.poll_unpin(cx)?);
- self.state = BufWriterState::Write(w);
- self.multipart_id = Some(id);
+ self.state = BufWriterState::Write(ready!(f.poll_unpin(cx)?).into());
continue;
}
};
@@ -322,21 +325,28 @@ impl AsyncWrite for BufWriter {
loop {
match &mut self.state {
BufWriterState::Prepare(f) => {
- let (id, w) = ready!(f.poll_unpin(cx)?);
- self.state = BufWriterState::Write(w);
- self.multipart_id = Some(id);
+ self.state = BufWriterState::Write(ready!(f.poll_unpin(cx)?).into());
}
BufWriterState::Buffer(p, b) => {
let buf = std::mem::take(b);
let path = std::mem::take(p);
let store = Arc::clone(&self.store);
- self.state = BufWriterState::Put(Box::pin(async move {
+ self.state = BufWriterState::Flush(Box::pin(async move {
store.put(&path, buf.into()).await?;
Ok(())
}));
}
- BufWriterState::Put(f) => return f.poll_unpin(cx),
- BufWriterState::Write(w) => return Pin::new(w).poll_shutdown(cx),
+ BufWriterState::Flush(f) => return f.poll_unpin(cx),
+ BufWriterState::Write(x) => {
+ let upload = x.take().unwrap();
+ self.state = BufWriterState::Flush(
+ async move {
+ upload.finish().await?;
+ Ok(())
+ }
+ .boxed(),
+ )
+ }
}
}
}
@@ -357,7 +367,7 @@ mod tests {
use super::*;
use crate::memory::InMemory;
use crate::path::Path;
- use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncSeekExt};
+ use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
#[tokio::test]
async fn test_buf_reader() {
@@ -448,9 +458,7 @@ mod tests {
writer.write_all(&[0; 20]).await.unwrap();
writer.flush().await.unwrap();
writer.write_all(&[0; 5]).await.unwrap();
- assert!(writer.multipart_id().is_none());
writer.shutdown().await.unwrap();
- assert!(writer.multipart_id().is_none());
assert_eq!(store.head(&path).await.unwrap().size, 25);
// Test multipart
@@ -458,9 +466,7 @@ mod tests {
writer.write_all(&[0; 20]).await.unwrap();
writer.flush().await.unwrap();
writer.write_all(&[0; 20]).await.unwrap();
- assert!(writer.multipart_id().is_some());
writer.shutdown().await.unwrap();
- assert!(writer.multipart_id().is_some());
assert_eq!(store.head(&path).await.unwrap().size, 40);
}
diff --git a/object_store/src/chunked.rs b/object_store/src/chunked.rs
index d33556f4b12e..6db7f4b35e24 100644
--- a/object_store/src/chunked.rs
+++ b/object_store/src/chunked.rs
@@ -25,14 +25,13 @@ use async_trait::async_trait;
use bytes::{BufMut, Bytes, BytesMut};
use futures::stream::BoxStream;
use futures::StreamExt;
-use tokio::io::AsyncWrite;
use crate::path::Path;
+use crate::Result;
use crate::{
- GetOptions, GetResult, GetResultPayload, ListResult, ObjectMeta, ObjectStore, PutOptions,
- PutResult,
+ GetOptions, GetResult, GetResultPayload, ListResult, MultipartUpload, ObjectMeta, ObjectStore,
+ PutOptions, PutResult,
};
-use crate::{MultipartId, Result};
/// Wraps a [`ObjectStore`] and makes its get response return chunks
/// in a controllable manner.
@@ -67,17 +66,10 @@ impl ObjectStore for ChunkedStore {
self.inner.put_opts(location, bytes, opts).await
}
- async fn put_multipart(
- &self,
- location: &Path,
- ) -> Result<(MultipartId, Box<dyn AsyncWrite + Unpin + Send>)> {
+ async fn put_multipart(&self, location: &Path) -> Result<Box<dyn MultipartUpload>> {
self.inner.put_multipart(location).await
}
- async fn abort_multipart(&self, location: &Path, multipart_id: &MultipartId) -> Result<()> {
- self.inner.abort_multipart(location, multipart_id).await
- }
-
async fn get_opts(&self, location: &Path, options: GetOptions) -> Result<GetResult> {
let r = self.inner.get_opts(location, options).await?;
let stream = match r.payload {
diff --git a/object_store/src/client/mod.rs b/object_store/src/client/mod.rs
index 252e9fdcadf5..7728f38954f9 100644
--- a/object_store/src/client/mod.rs
+++ b/object_store/src/client/mod.rs
@@ -40,6 +40,9 @@ pub mod header;
#[cfg(any(feature = "aws", feature = "gcp"))]
pub mod s3;
+#[cfg(any(feature = "aws", feature = "gcp", feature = "azure"))]
+pub mod parts;
+
use async_trait::async_trait;
use std::collections::HashMap;
use std::str::FromStr;
diff --git a/object_store/src/client/parts.rs b/object_store/src/client/parts.rs
new file mode 100644
index 000000000000..9fc301edcf81
--- /dev/null
+++ b/object_store/src/client/parts.rs
@@ -0,0 +1,48 @@
+// 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.
+
+use crate::multipart::PartId;
+use parking_lot::Mutex;
+
+/// An interior mutable collection of upload parts and their corresponding part index
+#[derive(Debug, Default)]
+pub(crate) struct Parts(Mutex<Vec<(usize, PartId)>>);
+
+impl Parts {
+ /// Record the [`PartId`] for a given index
+ ///
+ /// Note: calling this method multiple times with the same `part_idx`
+ /// will result in multiple [`PartId`] in the final output
+ pub(crate) fn put(&self, part_idx: usize, id: PartId) {
+ self.0.lock().push((part_idx, id))
+ }
+
+ /// Produce the final list of [`PartId`] ordered by `part_idx`
+ ///
+ /// `expected` is the number of parts expected in the final result
+ pub(crate) fn finish(&self, expected: usize) -> crate::Result<Vec<PartId>> {
+ let mut parts = self.0.lock();
+ if parts.len() != expected {
+ return Err(crate::Error::Generic {
+ store: "Parts",
+ source: "Missing part".to_string().into(),
+ });
+ }
+ parts.sort_unstable_by_key(|(idx, _)| *idx);
+ Ok(parts.drain(..).map(|(_, v)| v).collect())
+ }
+}
diff --git a/object_store/src/gcp/client.rs b/object_store/src/gcp/client.rs
index e4b0f9af7d15..def53beefe78 100644
--- a/object_store/src/gcp/client.rs
+++ b/object_store/src/gcp/client.rs
@@ -272,7 +272,7 @@ impl GoogleCloudStorageClient {
})
}
- /// Initiate a multi-part upload <https://cloud.google.com/storage/docs/xml-api/post-object-multipart>
+ /// Initiate a multipart upload <https://cloud.google.com/storage/docs/xml-api/post-object-multipart>
pub async fn multipart_initiate(&self, path: &Path) -> Result<MultipartId> {
let credential = self.get_credential().await?;
let url = self.object_url(path);
diff --git a/object_store/src/gcp/mod.rs b/object_store/src/gcp/mod.rs
index 8633abbfb4dc..2058d1f8055b 100644
--- a/object_store/src/gcp/mod.rs
+++ b/object_store/src/gcp/mod.rs
@@ -17,18 +17,14 @@
//! An object store implementation for Google Cloud Storage
//!
-//! ## Multi-part uploads
+//! ## Multipart uploads
//!
-//! [Multi-part uploads](https://cloud.google.com/storage/docs/multipart-uploads)
-//! can be initiated with the [ObjectStore::put_multipart] method.
-//! Data passed to the writer is automatically buffered to meet the minimum size
-//! requirements for a part. Multiple parts are uploaded concurrently.
-//!
-//! If the writer fails for any reason, you may have parts uploaded to GCS but not
-//! used that you may be charged for. Use the [ObjectStore::abort_multipart] method
-//! to abort the upload and drop those unneeded parts. In addition, you may wish to
-//! consider implementing automatic clean up of unused parts that are older than one
-//! week.
+//! [Multipart uploads](https://cloud.google.com/storage/docs/multipart-uploads)
+//! can be initiated with the [ObjectStore::put_multipart] method. If neither
+//! [`MultipartUpload::complete`] nor [`MultipartUpload::abort`] is invoked, you may
+//! have parts uploaded to GCS but not used, that you will be charged for. It is recommended
+//! you configure a [lifecycle rule] to abort incomplete multipart uploads after a certain
+//! period of time to avoid being charged for storing partial uploads.
//!
//! ## Using HTTP/2
//!
@@ -36,24 +32,24 @@
//! because it allows much higher throughput in our benchmarks (see
//! [#5194](https://github.com/apache/arrow-rs/issues/5194)). HTTP/2 can be
//! enabled by setting [crate::ClientConfigKey::Http1Only] to false.
+//!
+//! [lifecycle rule]: https://cloud.google.com/storage/docs/lifecycle#abort-mpu
use std::sync::Arc;
use crate::client::CredentialProvider;
use crate::{
- multipart::{PartId, PutPart, WriteMultiPart},
- path::Path,
- GetOptions, GetResult, ListResult, MultipartId, ObjectMeta, ObjectStore, PutOptions, PutResult,
- Result,
+ multipart::PartId, path::Path, GetOptions, GetResult, ListResult, MultipartId, MultipartUpload,
+ ObjectMeta, ObjectStore, PutOptions, PutResult, Result, UploadPart,
};
use async_trait::async_trait;
use bytes::Bytes;
use client::GoogleCloudStorageClient;
use futures::stream::BoxStream;
-use tokio::io::AsyncWrite;
use crate::client::get::GetClientExt;
use crate::client::list::ListClientExt;
-use crate::multipart::MultiPartStore;
+use crate::client::parts::Parts;
+use crate::multipart::MultipartStore;
pub use builder::{GoogleCloudStorageBuilder, GoogleConfigKey};
pub use credential::GcpCredential;
@@ -89,27 +85,50 @@ impl GoogleCloudStorage {
}
}
+#[derive(Debug)]
struct GCSMultipartUpload {
+ state: Arc<UploadState>,
+ part_idx: usize,
+}
+
+#[derive(Debug)]
+struct UploadState {
client: Arc<GoogleCloudStorageClient>,
path: Path,
multipart_id: MultipartId,
+ parts: Parts,
}
#[async_trait]
-impl PutPart for GCSMultipartUpload {
- /// Upload an object part <https://cloud.google.com/storage/docs/xml-api/put-object-multipart>
- async fn put_part(&self, buf: Vec<u8>, part_idx: usize) -> Result<PartId> {
- self.client
- .put_part(&self.path, &self.multipart_id, part_idx, buf.into())
+impl MultipartUpload for GCSMultipartUpload {
+ fn put_part(&mut self, data: Bytes) -> UploadPart {
+ let idx = self.part_idx;
+ self.part_idx += 1;
+ let state = Arc::clone(&self.state);
+ Box::pin(async move {
+ let part = state
+ .client
+ .put_part(&state.path, &state.multipart_id, idx, data)
+ .await?;
+ state.parts.put(idx, part);
+ Ok(())
+ })
+ }
+
+ async fn complete(&mut self) -> Result<PutResult> {
+ let parts = self.state.parts.finish(self.part_idx)?;
+
+ self.state
+ .client
+ .multipart_complete(&self.state.path, &self.state.multipart_id, parts)
.await
}
- /// Complete a multipart upload <https://cloud.google.com/storage/docs/xml-api/post-object-complete>
- async fn complete(&self, completed_parts: Vec<PartId>) -> Result<()> {
- self.client
- .multipart_complete(&self.path, &self.multipart_id, completed_parts)
- .await?;
- Ok(())
+ async fn abort(&mut self) -> Result<()> {
+ self.state
+ .client
+ .multipart_cleanup(&self.state.path, &self.state.multipart_id)
+ .await
}
}
@@ -119,27 +138,18 @@ impl ObjectStore for GoogleCloudStorage {
self.client.put(location, bytes, opts).await
}
- async fn put_multipart(
- &self,
- location: &Path,
- ) -> Result<(MultipartId, Box<dyn AsyncWrite + Unpin + Send>)> {
+ async fn put_multipart(&self, location: &Path) -> Result<Box<dyn MultipartUpload>> {
let upload_id = self.client.multipart_initiate(location).await?;
- let inner = GCSMultipartUpload {
- client: Arc::clone(&self.client),
- path: location.clone(),
- multipart_id: upload_id.clone(),
- };
-
- Ok((upload_id, Box::new(WriteMultiPart::new(inner, 8))))
- }
-
- async fn abort_multipart(&self, location: &Path, multipart_id: &MultipartId) -> Result<()> {
- self.client
- .multipart_cleanup(location, multipart_id)
- .await?;
-
- Ok(())
+ Ok(Box::new(GCSMultipartUpload {
+ part_idx: 0,
+ state: Arc::new(UploadState {
+ client: Arc::clone(&self.client),
+ path: location.clone(),
+ multipart_id: upload_id.clone(),
+ parts: Default::default(),
+ }),
+ }))
}
async fn get_opts(&self, location: &Path, options: GetOptions) -> Result<GetResult> {
@@ -176,7 +186,7 @@ impl ObjectStore for GoogleCloudStorage {
}
#[async_trait]
-impl MultiPartStore for GoogleCloudStorage {
+impl MultipartStore for GoogleCloudStorage {
async fn create_multipart(&self, path: &Path) -> Result<MultipartId> {
self.client.multipart_initiate(path).await
}
diff --git a/object_store/src/http/mod.rs b/object_store/src/http/mod.rs
index f1d11db4762c..626337df27f9 100644
--- a/object_store/src/http/mod.rs
+++ b/object_store/src/http/mod.rs
@@ -37,7 +37,6 @@ use futures::stream::BoxStream;
use futures::{StreamExt, TryStreamExt};
use itertools::Itertools;
use snafu::{OptionExt, ResultExt, Snafu};
-use tokio::io::AsyncWrite;
use url::Url;
use crate::client::get::GetClientExt;
@@ -45,7 +44,7 @@ use crate::client::header::get_etag;
use crate::http::client::Client;
use crate::path::Path;
use crate::{
- ClientConfigKey, ClientOptions, GetOptions, GetResult, ListResult, MultipartId, ObjectMeta,
+ ClientConfigKey, ClientOptions, GetOptions, GetResult, ListResult, MultipartUpload, ObjectMeta,
ObjectStore, PutMode, PutOptions, PutResult, Result, RetryConfig,
};
@@ -115,15 +114,8 @@ impl ObjectStore for HttpStore {
})
}
- async fn put_multipart(
- &self,
- _location: &Path,
- ) -> Result<(MultipartId, Box<dyn AsyncWrite + Unpin + Send>)> {
- Err(super::Error::NotImplemented)
- }
-
- async fn abort_multipart(&self, _location: &Path, _multipart_id: &MultipartId) -> Result<()> {
- Err(super::Error::NotImplemented)
+ async fn put_multipart(&self, _location: &Path) -> Result<Box<dyn MultipartUpload>> {
+ Err(crate::Error::NotImplemented)
}
async fn get_opts(&self, location: &Path, options: GetOptions) -> Result<GetResult> {
diff --git a/object_store/src/lib.rs b/object_store/src/lib.rs
index 4960f3ba390a..e02675d88abe 100644
--- a/object_store/src/lib.rs
+++ b/object_store/src/lib.rs
@@ -269,12 +269,11 @@
//!
//! # Multipart Upload
//!
-//! Use the [`ObjectStore::put_multipart`] method to atomically write a large amount of data,
-//! with implementations automatically handling parallel, chunked upload where appropriate.
+//! Use the [`ObjectStore::put_multipart`] method to atomically write a large amount of data
//!
//! ```
//! # use object_store::local::LocalFileSystem;
-//! # use object_store::ObjectStore;
+//! # use object_store::{ObjectStore, WriteMultipart};
//! # use std::sync::Arc;
//! # use bytes::Bytes;
//! # use tokio::io::AsyncWriteExt;
@@ -286,12 +285,10 @@
//! #
//! let object_store: Arc<dyn ObjectStore> = get_object_store();
//! let path = Path::from("data/large_file");
-//! let (_id, mut writer) = object_store.put_multipart(&path).await.unwrap();
-//!
-//! let bytes = Bytes::from_static(b"hello");
-//! writer.write_all(&bytes).await.unwrap();
-//! writer.flush().await.unwrap();
-//! writer.shutdown().await.unwrap();
+//! let upload = object_store.put_multipart(&path).await.unwrap();
+//! let mut write = WriteMultipart::new(upload);
+//! write.write(b"hello");
+//! write.finish().await.unwrap();
//! # }
//! ```
//!
@@ -501,9 +498,11 @@ pub use tags::TagSet;
pub mod multipart;
mod parse;
+mod upload;
mod util;
pub use parse::{parse_url, parse_url_opts};
+pub use upload::*;
pub use util::GetRange;
use crate::path::Path;
@@ -520,12 +519,11 @@ use std::fmt::{Debug, Formatter};
use std::io::{Read, Seek, SeekFrom};
use std::ops::Range;
use std::sync::Arc;
-use tokio::io::AsyncWrite;
/// An alias for a dynamically dispatched object store implementation.
pub type DynObjectStore = dyn ObjectStore;
-/// Id type for multi-part uploads.
+/// Id type for multipart uploads.
pub type MultipartId = String;
/// Universal API to multiple object store services.
@@ -543,48 +541,11 @@ pub trait ObjectStore: std::fmt::Display + Send + Sync + Debug + 'static {
/// Save the provided bytes to the specified location with the given options
async fn put_opts(&self, location: &Path, bytes: Bytes, opts: PutOptions) -> Result<PutResult>;
- /// Get a multi-part upload that allows writing data in chunks.
- ///
- /// Most cloud-based uploads will buffer and upload parts in parallel.
- ///
- /// To complete the upload, [AsyncWrite::poll_shutdown] must be called
- /// to completion. This operation is guaranteed to be atomic, it will either
- /// make all the written data available at `location`, or fail. No clients
- /// should be able to observe a partially written object.
- ///
- /// For some object stores (S3, GCS, and local in particular), if the
- /// writer fails or panics, you must call [ObjectStore::abort_multipart]
- /// to clean up partially written data.
- ///
- /// <div class="warning">
- /// It is recommended applications wait for any in-flight requests to complete by calling `flush`, if
- /// there may be a significant gap in time (> ~30s) before the next write.
- /// These gaps can include times where the function returns control to the
- /// caller while keeping the writer open. If `flush` is not called, futures
- /// for in-flight requests may be left unpolled long enough for the requests
- /// to time out, causing the write to fail.
- /// </div>
- ///
- /// For applications requiring fine-grained control of multipart uploads
- /// see [`MultiPartStore`], although note that this interface cannot be
- /// supported by all [`ObjectStore`] backends.
- ///
- /// For applications looking to implement this interface for a custom
- /// multipart API, see [`WriteMultiPart`] which handles the complexities
- /// of performing parallel uploads of fixed size parts.
- ///
- /// [`WriteMultiPart`]: multipart::WriteMultiPart
- /// [`MultiPartStore`]: multipart::MultiPartStore
- async fn put_multipart(
- &self,
- location: &Path,
- ) -> Result<(MultipartId, Box<dyn AsyncWrite + Unpin + Send>)>;
-
- /// Cleanup an aborted upload.
+ /// Perform a multipart upload
///
- /// See documentation for individual stores for exact behavior, as capabilities
- /// vary by object store.
- async fn abort_multipart(&self, location: &Path, multipart_id: &MultipartId) -> Result<()>;
+ /// Client should prefer [`ObjectStore::put`] for small payloads, as streaming uploads
+ /// typically require multiple separate requests. See [`MultipartUpload`] for more information
+ async fn put_multipart(&self, location: &Path) -> Result<Box<dyn MultipartUpload>>;
/// Return the bytes that are stored at the specified location.
async fn get(&self, location: &Path) -> Result<GetResult> {
@@ -769,21 +730,10 @@ macro_rules! as_ref_impl {
self.as_ref().put_opts(location, bytes, opts).await
}
- async fn put_multipart(
- &self,
- location: &Path,
- ) -> Result<(MultipartId, Box<dyn AsyncWrite + Unpin + Send>)> {
+ async fn put_multipart(&self, location: &Path) -> Result<Box<dyn MultipartUpload>> {
self.as_ref().put_multipart(location).await
}
- async fn abort_multipart(
- &self,
- location: &Path,
- multipart_id: &MultipartId,
- ) -> Result<()> {
- self.as_ref().abort_multipart(location, multipart_id).await
- }
-
async fn get(&self, location: &Path) -> Result<GetResult> {
self.as_ref().get(location).await
}
@@ -1246,14 +1196,12 @@ mod test_util {
#[cfg(test)]
mod tests {
use super::*;
- use crate::multipart::MultiPartStore;
+ use crate::multipart::MultipartStore;
use crate::test_util::flatten_list_stream;
use chrono::TimeZone;
use futures::stream::FuturesUnordered;
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
- use std::future::Future;
- use tokio::io::AsyncWriteExt;
pub(crate) async fn put_get_delete_list(storage: &DynObjectStore) {
put_get_delete_list_opts(storage).await
@@ -1928,12 +1876,11 @@ mod tests {
let location = Path::from("test_dir/test_upload_file.txt");
// Can write to storage
- let data = get_chunks(5_000, 10);
+ let data = get_chunks(5 * 1024 * 1024, 3);
let bytes_expected = data.concat();
- let (_, mut writer) = storage.put_multipart(&location).await.unwrap();
- for chunk in &data {
- writer.write_all(chunk).await.unwrap();
- }
+ let mut upload = storage.put_multipart(&location).await.unwrap();
+ let uploads = data.into_iter().map(|x| upload.put_part(x));
+ futures::future::try_join_all(uploads).await.unwrap();
// Object should not yet exist in store
let meta_res = storage.head(&location).await;
@@ -1949,7 +1896,8 @@ mod tests {
let result = storage.list_with_delimiter(None).await.unwrap();
assert_eq!(&result.objects, &[]);
- writer.shutdown().await.unwrap();
+ upload.complete().await.unwrap();
+
let bytes_written = storage.get(&location).await.unwrap().bytes().await.unwrap();
assert_eq!(bytes_expected, bytes_written);
@@ -1957,22 +1905,19 @@ mod tests {
// Sizes chosen to ensure we write three parts
let data = get_chunks(3_200_000, 7);
let bytes_expected = data.concat();
- let (_, mut writer) = storage.put_multipart(&location).await.unwrap();
+ let upload = storage.put_multipart(&location).await.unwrap();
+ let mut writer = WriteMultipart::new(upload);
for chunk in &data {
- writer.write_all(chunk).await.unwrap();
+ writer.write(chunk)
}
- writer.shutdown().await.unwrap();
+ writer.finish().await.unwrap();
let bytes_written = storage.get(&location).await.unwrap().bytes().await.unwrap();
assert_eq!(bytes_expected, bytes_written);
// We can abort an empty write
let location = Path::from("test_dir/test_abort_upload.txt");
- let (upload_id, writer) = storage.put_multipart(&location).await.unwrap();
- drop(writer);
- storage
- .abort_multipart(&location, &upload_id)
- .await
- .unwrap();
+ let mut upload = storage.put_multipart(&location).await.unwrap();
+ upload.abort().await.unwrap();
let get_res = storage.get(&location).await;
assert!(get_res.is_err());
assert!(matches!(
@@ -1981,17 +1926,13 @@ mod tests {
));
// We can abort an in-progress write
- let (upload_id, mut writer) = storage.put_multipart(&location).await.unwrap();
- if let Some(chunk) = data.first() {
- writer.write_all(chunk).await.unwrap();
- let _ = writer.write(chunk).await.unwrap();
- }
- drop(writer);
-
- storage
- .abort_multipart(&location, &upload_id)
+ let mut upload = storage.put_multipart(&location).await.unwrap();
+ upload
+ .put_part(data.first().unwrap().clone())
.await
.unwrap();
+
+ upload.abort().await.unwrap();
let get_res = storage.get(&location).await;
assert!(get_res.is_err());
assert!(matches!(
@@ -2186,7 +2127,7 @@ mod tests {
storage.delete(&path2).await.unwrap();
}
- pub(crate) async fn multipart(storage: &dyn ObjectStore, multipart: &dyn MultiPartStore) {
+ pub(crate) async fn multipart(storage: &dyn ObjectStore, multipart: &dyn MultipartStore) {
let path = Path::from("test_multipart");
let chunk_size = 5 * 1024 * 1024;
@@ -2253,7 +2194,7 @@ mod tests {
pub(crate) async fn tagging<F, Fut>(storage: &dyn ObjectStore, validate: bool, get_tags: F)
where
F: Fn(Path) -> Fut + Send + Sync,
- Fut: Future<Output = Result<reqwest::Response>> + Send,
+ Fut: std::future::Future<Output = Result<reqwest::Response>> + Send,
{
use bytes::Buf;
use serde::Deserialize;
diff --git a/object_store/src/limit.rs b/object_store/src/limit.rs
index d1363d9a4d46..e5f6841638e1 100644
--- a/object_store/src/limit.rs
+++ b/object_store/src/limit.rs
@@ -18,18 +18,16 @@
//! An object store that limits the maximum concurrency of the wrapped implementation
use crate::{
- BoxStream, GetOptions, GetResult, GetResultPayload, ListResult, MultipartId, ObjectMeta,
- ObjectStore, Path, PutOptions, PutResult, Result, StreamExt,
+ BoxStream, GetOptions, GetResult, GetResultPayload, ListResult, MultipartUpload, ObjectMeta,
+ ObjectStore, Path, PutOptions, PutResult, Result, StreamExt, UploadPart,
};
use async_trait::async_trait;
use bytes::Bytes;
use futures::{FutureExt, Stream};
-use std::io::{Error, IoSlice};
use std::ops::Range;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
-use tokio::io::AsyncWrite;
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
/// Store wrapper that wraps an inner store and limits the maximum number of concurrent
@@ -81,18 +79,12 @@ impl<T: ObjectStore> ObjectStore for LimitStore<T> {
let _permit = self.semaphore.acquire().await.unwrap();
self.inner.put_opts(location, bytes, opts).await
}
- async fn put_multipart(
- &self,
- location: &Path,
- ) -> Result<(MultipartId, Box<dyn AsyncWrite + Unpin + Send>)> {
- let permit = Arc::clone(&self.semaphore).acquire_owned().await.unwrap();
- let (id, write) = self.inner.put_multipart(location).await?;
- Ok((id, Box::new(PermitWrapper::new(write, permit))))
- }
-
- async fn abort_multipart(&self, location: &Path, multipart_id: &MultipartId) -> Result<()> {
- let _permit = self.semaphore.acquire().await.unwrap();
- self.inner.abort_multipart(location, multipart_id).await
+ async fn put_multipart(&self, location: &Path) -> Result<Box<dyn MultipartUpload>> {
+ let upload = self.inner.put_multipart(location).await?;
+ Ok(Box::new(LimitUpload {
+ semaphore: Arc::clone(&self.semaphore),
+ upload,
+ }))
}
async fn get(&self, location: &Path) -> Result<GetResult> {
let permit = Arc::clone(&self.semaphore).acquire_owned().await.unwrap();
@@ -221,39 +213,42 @@ impl<T: Stream + Unpin> Stream for PermitWrapper<T> {
}
}
-impl<T: AsyncWrite + Unpin> AsyncWrite for PermitWrapper<T> {
- fn poll_write(
- mut self: Pin<&mut Self>,
- cx: &mut Context<'_>,
- buf: &[u8],
- ) -> Poll<std::result::Result<usize, Error>> {
- Pin::new(&mut self.inner).poll_write(cx, buf)
- }
+/// An [`MultipartUpload`] wrapper that limits the maximum number of concurrent requests
+#[derive(Debug)]
+pub struct LimitUpload {
+ upload: Box<dyn MultipartUpload>,
+ semaphore: Arc<Semaphore>,
+}
- fn poll_flush(
- mut self: Pin<&mut Self>,
- cx: &mut Context<'_>,
- ) -> Poll<std::result::Result<(), Error>> {
- Pin::new(&mut self.inner).poll_flush(cx)
+impl LimitUpload {
+ /// Create a new [`LimitUpload`] limiting `upload` to `max_concurrency` concurrent requests
+ pub fn new(upload: Box<dyn MultipartUpload>, max_concurrency: usize) -> Self {
+ Self {
+ upload,
+ semaphore: Arc::new(Semaphore::new(max_concurrency)),
+ }
}
+}
- fn poll_shutdown(
- mut self: Pin<&mut Self>,
- cx: &mut Context<'_>,
- ) -> Poll<std::result::Result<(), Error>> {
- Pin::new(&mut self.inner).poll_shutdown(cx)
+#[async_trait]
+impl MultipartUpload for LimitUpload {
+ fn put_part(&mut self, data: Bytes) -> UploadPart {
+ let upload = self.upload.put_part(data);
+ let s = Arc::clone(&self.semaphore);
+ Box::pin(async move {
+ let _permit = s.acquire().await.unwrap();
+ upload.await
+ })
}
- fn poll_write_vectored(
- mut self: Pin<&mut Self>,
- cx: &mut Context<'_>,
- bufs: &[IoSlice<'_>],
- ) -> Poll<std::result::Result<usize, Error>> {
- Pin::new(&mut self.inner).poll_write_vectored(cx, bufs)
+ async fn complete(&mut self) -> Result<PutResult> {
+ let _permit = self.semaphore.acquire().await.unwrap();
+ self.upload.complete().await
}
- fn is_write_vectored(&self) -> bool {
- self.inner.is_write_vectored()
+ async fn abort(&mut self) -> Result<()> {
+ let _permit = self.semaphore.acquire().await.unwrap();
+ self.upload.abort().await
}
}
diff --git a/object_store/src/local.rs b/object_store/src/local.rs
index d631771778db..a7eb4661f686 100644
--- a/object_store/src/local.rs
+++ b/object_store/src/local.rs
@@ -16,34 +16,32 @@
// under the License.
//! An object store implementation for a local filesystem
-use crate::{
- maybe_spawn_blocking,
- path::{absolute_path_to_url, Path},
- util::InvalidGetRange,
- GetOptions, GetResult, GetResultPayload, ListResult, MultipartId, ObjectMeta, ObjectStore,
- PutMode, PutOptions, PutResult, Result,
-};
-use async_trait::async_trait;
-use bytes::Bytes;
-use chrono::{DateTime, Utc};
-use futures::future::BoxFuture;
-use futures::ready;
-use futures::{stream::BoxStream, StreamExt};
-use futures::{FutureExt, TryStreamExt};
-use snafu::{ensure, ResultExt, Snafu};
use std::fs::{metadata, symlink_metadata, File, Metadata, OpenOptions};
use std::io::{ErrorKind, Read, Seek, SeekFrom, Write};
use std::ops::Range;
-use std::pin::Pin;
use std::sync::Arc;
-use std::task::Poll;
use std::time::SystemTime;
use std::{collections::BTreeSet, convert::TryFrom, io};
use std::{collections::VecDeque, path::PathBuf};
-use tokio::io::AsyncWrite;
+
+use async_trait::async_trait;
+use bytes::Bytes;
+use chrono::{DateTime, Utc};
+use futures::{stream::BoxStream, StreamExt};
+use futures::{FutureExt, TryStreamExt};
+use parking_lot::Mutex;
+use snafu::{ensure, OptionExt, ResultExt, Snafu};
use url::Url;
use walkdir::{DirEntry, WalkDir};
+use crate::{
+ maybe_spawn_blocking,
+ path::{absolute_path_to_url, Path},
+ util::InvalidGetRange,
+ GetOptions, GetResult, GetResultPayload, ListResult, MultipartUpload, ObjectMeta, ObjectStore,
+ PutMode, PutOptions, PutResult, Result, UploadPart,
+};
+
/// A specialized `Error` for filesystem object store-related errors
#[derive(Debug, Snafu)]
#[allow(missing_docs)]
@@ -155,6 +153,9 @@ pub(crate) enum Error {
InvalidPath {
path: String,
},
+
+ #[snafu(display("Upload aborted"))]
+ Aborted,
}
impl From<Error> for super::Error {
@@ -342,8 +343,7 @@ impl ObjectStore for LocalFileSystem {
let path = self.path_to_filesystem(location)?;
maybe_spawn_blocking(move || {
- let (mut file, suffix) = new_staged_upload(&path)?;
- let staging_path = staged_upload_path(&path, &suffix);
+ let (mut file, staging_path) = new_staged_upload(&path)?;
let mut e_tag = None;
let err = match file.write_all(&bytes) {
@@ -395,31 +395,10 @@ impl ObjectStore for LocalFileSystem {
.await
}
- async fn put_multipart(
- &self,
- location: &Path,
- ) -> Result<(MultipartId, Box<dyn AsyncWrite + Unpin + Send>)> {
- let dest = self.path_to_filesystem(location)?;
-
- let (file, suffix) = new_staged_upload(&dest)?;
- Ok((
- suffix.clone(),
- Box::new(LocalUpload::new(dest, suffix, Arc::new(file))),
- ))
- }
-
- async fn abort_multipart(&self, location: &Path, multipart_id: &MultipartId) -> Result<()> {
+ async fn put_multipart(&self, location: &Path) -> Result<Box<dyn MultipartUpload>> {
let dest = self.path_to_filesystem(location)?;
- let path: PathBuf = staged_upload_path(&dest, multipart_id);
-
- maybe_spawn_blocking(move || match std::fs::remove_file(&path) {
- Ok(_) => Ok(()),
- Err(source) => match source.kind() {
- ErrorKind::NotFound => Ok(()), // Already deleted
- _ => Err(Error::UnableToDeleteFile { path, source }.into()),
- },
- })
- .await
+ let (file, src) = new_staged_upload(&dest)?;
+ Ok(Box::new(LocalUpload::new(src, dest, file)))
}
async fn get_opts(&self, location: &Path, options: GetOptions) -> Result<GetResult> {
@@ -677,17 +656,17 @@ fn create_parent_dirs(path: &std::path::Path, source: io::Error) -> Result<()> {
Ok(())
}
-/// Generates a unique file path `{base}#{suffix}`, returning the opened `File` and `suffix`
+/// Generates a unique file path `{base}#{suffix}`, returning the opened `File` and `path`
///
/// Creates any directories if necessary
-fn new_staged_upload(base: &std::path::Path) -> Result<(File, String)> {
+fn new_staged_upload(base: &std::path::Path) -> Result<(File, PathBuf)> {
let mut multipart_id = 1;
loop {
let suffix = multipart_id.to_string();
let path = staged_upload_path(base, &suffix);
let mut options = OpenOptions::new();
match options.read(true).write(true).create_new(true).open(&path) {
- Ok(f) => return Ok((f, suffix)),
+ Ok(f) => return Ok((f, path)),
Err(source) => match source.kind() {
ErrorKind::AlreadyExists => multipart_id += 1,
ErrorKind::NotFound => create_parent_dirs(&path, source)?,
@@ -705,194 +684,91 @@ fn staged_upload_path(dest: &std::path::Path, suffix: &str) -> PathBuf {
staging_path.into()
}
-enum LocalUploadState {
- /// Upload is ready to send new data
- Idle(Arc<File>),
- /// In the middle of a write
- Writing(Arc<File>, BoxFuture<'static, Result<usize, io::Error>>),
- /// In the middle of syncing data and closing file.
- ///
- /// Future will contain last reference to file, so it will call drop on completion.
- ShuttingDown(BoxFuture<'static, Result<(), io::Error>>),
- /// File is being moved from it's temporary location to the final location
- Committing(BoxFuture<'static, Result<(), io::Error>>),
- /// Upload is complete
- Complete,
+#[derive(Debug)]
+struct LocalUpload {
+ /// The upload state
+ state: Arc<UploadState>,
+ /// The location of the temporary file
+ src: Option<PathBuf>,
+ /// The next offset to write into the file
+ offset: u64,
}
-struct LocalUpload {
- inner_state: LocalUploadState,
+#[derive(Debug)]
+struct UploadState {
dest: PathBuf,
- multipart_id: MultipartId,
+ file: Mutex<Option<File>>,
}
impl LocalUpload {
- pub fn new(dest: PathBuf, multipart_id: MultipartId, file: Arc<File>) -> Self {
+ pub fn new(src: PathBuf, dest: PathBuf, file: File) -> Self {
Self {
- inner_state: LocalUploadState::Idle(file),
- dest,
- multipart_id,
+ state: Arc::new(UploadState {
+ dest,
+ file: Mutex::new(Some(file)),
+ }),
+ src: Some(src),
+ offset: 0,
}
}
}
-impl AsyncWrite for LocalUpload {
- fn poll_write(
- mut self: Pin<&mut Self>,
- cx: &mut std::task::Context<'_>,
- buf: &[u8],
- ) -> Poll<Result<usize, io::Error>> {
- let invalid_state = |condition: &str| -> Poll<Result<usize, io::Error>> {
- Poll::Ready(Err(io::Error::new(
- ErrorKind::InvalidInput,
- format!("Tried to write to file {condition}."),
- )))
- };
+#[async_trait]
+impl MultipartUpload for LocalUpload {
+ fn put_part(&mut self, data: Bytes) -> UploadPart {
+ let offset = self.offset;
+ self.offset += data.len() as u64;
- if let Ok(runtime) = tokio::runtime::Handle::try_current() {
- let mut data: Vec<u8> = buf.to_vec();
- let data_len = data.len();
-
- loop {
- match &mut self.inner_state {
- LocalUploadState::Idle(file) => {
- let file = Arc::clone(file);
- let file2 = Arc::clone(&file);
- let data: Vec<u8> = std::mem::take(&mut data);
- self.inner_state = LocalUploadState::Writing(
- file,
- Box::pin(
- runtime
- .spawn_blocking(move || (&*file2).write_all(&data))
- .map(move |res| match res {
- Err(err) => Err(io::Error::new(ErrorKind::Other, err)),
- Ok(res) => res.map(move |_| data_len),
- }),
- ),
- );
- }
- LocalUploadState::Writing(file, inner_write) => {
- let res = ready!(inner_write.poll_unpin(cx));
- self.inner_state = LocalUploadState::Idle(Arc::clone(file));
- return Poll::Ready(res);
- }
- LocalUploadState::ShuttingDown(_) => {
- return invalid_state("when writer is shutting down");
- }
- LocalUploadState::Committing(_) => {
- return invalid_state("when writer is committing data");
- }
- LocalUploadState::Complete => {
- return invalid_state("when writer is complete");
- }
- }
- }
- } else if let LocalUploadState::Idle(file) = &self.inner_state {
- let file = Arc::clone(file);
- (&*file).write_all(buf)?;
- Poll::Ready(Ok(buf.len()))
- } else {
- // If we are running on this thread, then only possible states are Idle and Complete.
- invalid_state("when writer is already complete.")
- }
+ let s = Arc::clone(&self.state);
+ maybe_spawn_blocking(move || {
+ let mut f = s.file.lock();
+ let file = f.as_mut().context(AbortedSnafu)?;
+ file.seek(SeekFrom::Start(offset))
+ .context(SeekSnafu { path: &s.dest })?;
+ file.write_all(&data).context(UnableToCopyDataToFileSnafu)?;
+ Ok(())
+ })
+ .boxed()
}
- fn poll_flush(
- self: Pin<&mut Self>,
- _cx: &mut std::task::Context<'_>,
- ) -> Poll<Result<(), io::Error>> {
- Poll::Ready(Ok(()))
+ async fn complete(&mut self) -> Result<PutResult> {
+ let src = self.src.take().context(AbortedSnafu)?;
+ let s = Arc::clone(&self.state);
+ maybe_spawn_blocking(move || {
+ // Ensure no inflight writes
+ let f = s.file.lock().take().context(AbortedSnafu)?;
+ std::fs::rename(&src, &s.dest).context(UnableToRenameFileSnafu)?;
+ let metadata = f.metadata().map_err(|e| Error::Metadata {
+ source: e.into(),
+ path: src.to_string_lossy().to_string(),
+ })?;
+
+ Ok(PutResult {
+ e_tag: Some(get_etag(&metadata)),
+ version: None,
+ })
+ })
+ .await
}
- fn poll_shutdown(
- mut self: Pin<&mut Self>,
- cx: &mut std::task::Context<'_>,
- ) -> Poll<Result<(), io::Error>> {
- if let Ok(runtime) = tokio::runtime::Handle::try_current() {
- loop {
- match &mut self.inner_state {
- LocalUploadState::Idle(file) => {
- // We are moving file into the future, and it will be dropped on it's completion, closing the file.
- let file = Arc::clone(file);
- self.inner_state = LocalUploadState::ShuttingDown(Box::pin(
- runtime
- .spawn_blocking(move || (*file).sync_all())
- .map(move |res| match res {
- Err(err) => Err(io::Error::new(io::ErrorKind::Other, err)),
- Ok(res) => res,
- }),
- ));
- }
- LocalUploadState::ShuttingDown(fut) => match fut.poll_unpin(cx) {
- Poll::Ready(res) => {
- res?;
- let staging_path = staged_upload_path(&self.dest, &self.multipart_id);
- let dest = self.dest.clone();
- self.inner_state = LocalUploadState::Committing(Box::pin(
- runtime
- .spawn_blocking(move || std::fs::rename(&staging_path, &dest))
- .map(move |res| match res {
- Err(err) => Err(io::Error::new(io::ErrorKind::Other, err)),
- Ok(res) => res,
- }),
- ));
- }
- Poll::Pending => {
- return Poll::Pending;
- }
- },
- LocalUploadState::Writing(_, _) => {
- return Poll::Ready(Err(io::Error::new(
- io::ErrorKind::InvalidInput,
- "Tried to commit a file where a write is in progress.",
- )));
- }
- LocalUploadState::Committing(fut) => {
- let res = ready!(fut.poll_unpin(cx));
- self.inner_state = LocalUploadState::Complete;
- return Poll::Ready(res);
- }
- LocalUploadState::Complete => {
- return Poll::Ready(Err(io::Error::new(
- io::ErrorKind::Other,
- "Already complete",
- )))
- }
- }
- }
- } else {
- let staging_path = staged_upload_path(&self.dest, &self.multipart_id);
- match &mut self.inner_state {
- LocalUploadState::Idle(file) => {
- let file = Arc::clone(file);
- self.inner_state = LocalUploadState::Complete;
- file.sync_all()?;
- drop(file);
- std::fs::rename(staging_path, &self.dest)?;
- Poll::Ready(Ok(()))
- }
- _ => {
- // If we are running on this thread, then only possible states are Idle and Complete.
- Poll::Ready(Err(io::Error::new(ErrorKind::Other, "Already complete")))
- }
- }
- }
+ async fn abort(&mut self) -> Result<()> {
+ let src = self.src.take().context(AbortedSnafu)?;
+ maybe_spawn_blocking(move || {
+ std::fs::remove_file(&src).context(UnableToDeleteFileSnafu { path: &src })?;
+ Ok(())
+ })
+ .await
}
}
impl Drop for LocalUpload {
fn drop(&mut self) {
- match self.inner_state {
- LocalUploadState::Complete => (),
- _ => {
- self.inner_state = LocalUploadState::Complete;
- let path = staged_upload_path(&self.dest, &self.multipart_id);
- // Try to cleanup intermediate file ignoring any error
- match tokio::runtime::Handle::try_current() {
- Ok(r) => drop(r.spawn_blocking(move || std::fs::remove_file(path))),
- Err(_) => drop(std::fs::remove_file(path)),
- };
- }
+ if let Some(src) = self.src.take() {
+ // Try to clean up intermediate file ignoring any error
+ match tokio::runtime::Handle::try_current() {
+ Ok(r) => drop(r.spawn_blocking(move || std::fs::remove_file(src))),
+ Err(_) => drop(std::fs::remove_file(src)),
+ };
}
}
}
@@ -1095,12 +971,13 @@ fn convert_walkdir_result(
#[cfg(test)]
mod tests {
- use super::*;
- use crate::test_util::flatten_list_stream;
- use crate::tests::*;
use futures::TryStreamExt;
use tempfile::{NamedTempFile, TempDir};
- use tokio::io::AsyncWriteExt;
+
+ use crate::test_util::flatten_list_stream;
+ use crate::tests::*;
+
+ use super::*;
#[tokio::test]
async fn file_test() {
@@ -1125,7 +1002,18 @@ mod tests {
put_get_delete_list(&integration).await;
list_uses_directories_correctly(&integration).await;
list_with_delimiter(&integration).await;
- stream_get(&integration).await;
+
+ // Can't use stream_get test as WriteMultipart uses a tokio JoinSet
+ let p = Path::from("manual_upload");
+ let mut upload = integration.put_multipart(&p).await.unwrap();
+ upload.put_part(Bytes::from_static(b"123")).await.unwrap();
+ upload.put_part(Bytes::from_static(b"45678")).await.unwrap();
+ let r = upload.complete().await.unwrap();
+
+ let get = integration.get(&p).await.unwrap();
+ assert_eq!(get.meta.e_tag.as_ref().unwrap(), r.e_tag.as_ref().unwrap());
+ let actual = get.bytes().await.unwrap();
+ assert_eq!(actual.as_ref(), b"12345678");
});
}
@@ -1422,12 +1310,11 @@ mod tests {
let location = Path::from("some_file");
let data = Bytes::from("arbitrary data");
- let (multipart_id, mut writer) = integration.put_multipart(&location).await.unwrap();
- writer.write_all(&data).await.unwrap();
+ let mut u1 = integration.put_multipart(&location).await.unwrap();
+ u1.put_part(data.clone()).await.unwrap();
- let (multipart_id_2, mut writer_2) = integration.put_multipart(&location).await.unwrap();
- assert_ne!(multipart_id, multipart_id_2);
- writer_2.write_all(&data).await.unwrap();
+ let mut u2 = integration.put_multipart(&location).await.unwrap();
+ u2.put_part(data).await.unwrap();
let list = flatten_list_stream(&integration, None).await.unwrap();
assert_eq!(list.len(), 0);
@@ -1520,11 +1407,13 @@ mod tests {
#[cfg(not(target_arch = "wasm32"))]
#[cfg(test)]
mod not_wasm_tests {
- use crate::local::LocalFileSystem;
- use crate::{ObjectStore, Path};
use std::time::Duration;
+
+ use bytes::Bytes;
use tempfile::TempDir;
- use tokio::io::AsyncWriteExt;
+
+ use crate::local::LocalFileSystem;
+ use crate::{ObjectStore, Path};
#[tokio::test]
async fn test_cleanup_intermediate_files() {
@@ -1532,12 +1421,13 @@ mod not_wasm_tests {
let integration = LocalFileSystem::new_with_prefix(root.path()).unwrap();
let location = Path::from("some_file");
- let (_, mut writer) = integration.put_multipart(&location).await.unwrap();
- writer.write_all(b"hello").await.unwrap();
+ let data = Bytes::from_static(b"hello");
+ let mut upload = integration.put_multipart(&location).await.unwrap();
+ upload.put_part(data).await.unwrap();
let file_count = std::fs::read_dir(root.path()).unwrap().count();
assert_eq!(file_count, 1);
- drop(writer);
+ drop(upload);
tokio::time::sleep(Duration::from_millis(1)).await;
@@ -1549,13 +1439,15 @@ mod not_wasm_tests {
#[cfg(target_family = "unix")]
#[cfg(test)]
mod unix_test {
- use crate::local::LocalFileSystem;
- use crate::{ObjectStore, Path};
+ use std::fs::OpenOptions;
+
use nix::sys::stat;
use nix::unistd;
- use std::fs::OpenOptions;
use tempfile::TempDir;
+ use crate::local::LocalFileSystem;
+ use crate::{ObjectStore, Path};
+
#[tokio::test]
async fn test_fifo() {
let filename = "some_file";
diff --git a/object_store/src/memory.rs b/object_store/src/memory.rs
index 41ee1091a3b2..6c960d4f24fb 100644
--- a/object_store/src/memory.rs
+++ b/object_store/src/memory.rs
@@ -16,27 +16,24 @@
// under the License.
//! An in-memory object store implementation
-use crate::multipart::{MultiPartStore, PartId};
-use crate::util::InvalidGetRange;
-use crate::{
- path::Path, GetRange, GetResult, GetResultPayload, ListResult, ObjectMeta, ObjectStore,
- PutMode, PutOptions, PutResult, Result, UpdateVersion,
-};
-use crate::{GetOptions, MultipartId};
+use std::collections::{BTreeMap, BTreeSet, HashMap};
+use std::ops::Range;
+use std::sync::Arc;
+
use async_trait::async_trait;
use bytes::Bytes;
use chrono::{DateTime, Utc};
use futures::{stream::BoxStream, StreamExt};
use parking_lot::RwLock;
use snafu::{OptionExt, ResultExt, Snafu};
-use std::collections::BTreeSet;
-use std::collections::{BTreeMap, HashMap};
-use std::io;
-use std::ops::Range;
-use std::pin::Pin;
-use std::sync::Arc;
-use std::task::Poll;
-use tokio::io::AsyncWrite;
+
+use crate::multipart::{MultipartStore, PartId};
+use crate::util::InvalidGetRange;
+use crate::GetOptions;
+use crate::{
+ path::Path, GetRange, GetResult, GetResultPayload, ListResult, MultipartId, MultipartUpload,
+ ObjectMeta, ObjectStore, PutMode, PutOptions, PutResult, Result, UpdateVersion, UploadPart,
+};
/// A specialized `Error` for in-memory object store-related errors
#[derive(Debug, Snafu)]
@@ -213,23 +210,12 @@ impl ObjectStore for InMemory {
})
}
- async fn put_multipart(
- &self,
- location: &Path,
- ) -> Result<(MultipartId, Box<dyn AsyncWrite + Unpin + Send>)> {
- Ok((
- String::new(),
- Box::new(InMemoryUpload {
- location: location.clone(),
- data: Vec::new(),
- storage: Arc::clone(&self.storage),
- }),
- ))
- }
-
- async fn abort_multipart(&self, _location: &Path, _multipart_id: &MultipartId) -> Result<()> {
- // Nothing to clean up
- Ok(())
+ async fn put_multipart(&self, location: &Path) -> Result<Box<dyn MultipartUpload>> {
+ Ok(Box::new(InMemoryUpload {
+ location: location.clone(),
+ parts: vec![],
+ storage: Arc::clone(&self.storage),
+ }))
}
async fn get_opts(&self, location: &Path, options: GetOptions) -> Result<GetResult> {
@@ -391,7 +377,7 @@ impl ObjectStore for InMemory {
}
#[async_trait]
-impl MultiPartStore for InMemory {
+impl MultipartStore for InMemory {
async fn create_multipart(&self, _path: &Path) -> Result<MultipartId> {
let mut storage = self.storage.write();
let etag = storage.next_etag;
@@ -482,45 +468,42 @@ impl InMemory {
}
}
+#[derive(Debug)]
struct InMemoryUpload {
location: Path,
- data: Vec<u8>,
+ parts: Vec<Bytes>,
storage: Arc<RwLock<Storage>>,
}
-impl AsyncWrite for InMemoryUpload {
- fn poll_write(
- mut self: Pin<&mut Self>,
- _cx: &mut std::task::Context<'_>,
- buf: &[u8],
- ) -> Poll<Result<usize, io::Error>> {
- self.data.extend_from_slice(buf);
- Poll::Ready(Ok(buf.len()))
+#[async_trait]
+impl MultipartUpload for InMemoryUpload {
+ fn put_part(&mut self, data: Bytes) -> UploadPart {
+ self.parts.push(data);
+ Box::pin(futures::future::ready(Ok(())))
}
- fn poll_flush(
- self: Pin<&mut Self>,
- _cx: &mut std::task::Context<'_>,
- ) -> Poll<Result<(), io::Error>> {
- Poll::Ready(Ok(()))
+ async fn complete(&mut self) -> Result<PutResult> {
+ let cap = self.parts.iter().map(|x| x.len()).sum();
+ let mut buf = Vec::with_capacity(cap);
+ self.parts.iter().for_each(|x| buf.extend_from_slice(x));
+ let etag = self.storage.write().insert(&self.location, buf.into());
+ Ok(PutResult {
+ e_tag: Some(etag.to_string()),
+ version: None,
+ })
}
- fn poll_shutdown(
- mut self: Pin<&mut Self>,
- _cx: &mut std::task::Context<'_>,
- ) -> Poll<Result<(), io::Error>> {
- let data = Bytes::from(std::mem::take(&mut self.data));
- self.storage.write().insert(&self.location, data);
- Poll::Ready(Ok(()))
+ async fn abort(&mut self) -> Result<()> {
+ Ok(())
}
}
#[cfg(test)]
mod tests {
- use super::*;
-
use crate::tests::*;
+ use super::*;
+
#[tokio::test]
async fn in_memory_test() {
let integration = InMemory::new();
diff --git a/object_store/src/multipart.rs b/object_store/src/multipart.rs
index 1dcd5a6f4960..26cce3936244 100644
--- a/object_store/src/multipart.rs
+++ b/object_store/src/multipart.rs
@@ -17,34 +17,16 @@
//! Cloud Multipart Upload
//!
-//! This crate provides an asynchronous interface for multipart file uploads to cloud storage services.
-//! It's designed to offer efficient, non-blocking operations,
+//! This crate provides an asynchronous interface for multipart file uploads to
+//! cloud storage services. It's designed to offer efficient, non-blocking operations,
//! especially useful when dealing with large files or high-throughput systems.
use async_trait::async_trait;
use bytes::Bytes;
-use futures::{stream::FuturesUnordered, Future, StreamExt};
-use std::{io, pin::Pin, sync::Arc, task::Poll};
-use tokio::io::AsyncWrite;
use crate::path::Path;
use crate::{MultipartId, PutResult, Result};
-type BoxedTryFuture<T> = Pin<Box<dyn Future<Output = Result<T, io::Error>> + Send>>;
-
-/// A trait used in combination with [`WriteMultiPart`] to implement
-/// [`AsyncWrite`] on top of an API for multipart upload
-#[async_trait]
-pub trait PutPart: Send + Sync + 'static {
- /// Upload a single part
- async fn put_part(&self, buf: Vec<u8>, part_idx: usize) -> Result<PartId>;
-
- /// Complete the upload with the provided parts
- ///
- /// `completed_parts` is in order of part number
- async fn complete(&self, completed_parts: Vec<PartId>) -> Result<()>;
-}
-
/// Represents a part of a file that has been successfully uploaded in a multipart upload process.
#[derive(Debug, Clone)]
pub struct PartId {
@@ -52,222 +34,6 @@ pub struct PartId {
pub content_id: String,
}
-/// Wrapper around a [`PutPart`] that implements [`AsyncWrite`]
-///
-/// Data will be uploaded in fixed size chunks of 10 MiB in parallel,
-/// up to the configured maximum concurrency
-pub struct WriteMultiPart<T: PutPart> {
- inner: Arc<T>,
- /// A list of completed parts, in sequential order.
- completed_parts: Vec<Option<PartId>>,
- /// Part upload tasks currently running
- tasks: FuturesUnordered<BoxedTryFuture<(usize, PartId)>>,
- /// Maximum number of upload tasks to run concurrently
- max_concurrency: usize,
- /// Buffer that will be sent in next upload.
- current_buffer: Vec<u8>,
- /// Size of each part.
- ///
- /// While S3 and Minio support variable part sizes, R2 requires they all be
- /// exactly the same size.
- part_size: usize,
- /// Index of current part
- current_part_idx: usize,
- /// The completion task
- completion_task: Option<BoxedTryFuture<()>>,
-}
-
-impl<T: PutPart> WriteMultiPart<T> {
- /// Create a new multipart upload with the implementation and the given maximum concurrency
- pub fn new(inner: T, max_concurrency: usize) -> Self {
- Self {
- inner: Arc::new(inner),
- completed_parts: Vec::new(),
- tasks: FuturesUnordered::new(),
- max_concurrency,
- current_buffer: Vec::new(),
- // TODO: Should self vary by provider?
- // TODO: Should we automatically increase then when part index gets large?
-
- // Minimum size of 5 MiB
- // https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html
- // https://cloud.google.com/storage/quotas#requests
- part_size: 10 * 1024 * 1024,
- current_part_idx: 0,
- completion_task: None,
- }
- }
-
- // Add data to the current buffer, returning the number of bytes added
- fn add_to_buffer(mut self: Pin<&mut Self>, buf: &[u8], offset: usize) -> usize {
- let remaining_capacity = self.part_size - self.current_buffer.len();
- let to_copy = std::cmp::min(remaining_capacity, buf.len() - offset);
- self.current_buffer
- .extend_from_slice(&buf[offset..offset + to_copy]);
- to_copy
- }
-
- /// Poll current tasks
- fn poll_tasks(
- mut self: Pin<&mut Self>,
- cx: &mut std::task::Context<'_>,
- ) -> Result<(), io::Error> {
- if self.tasks.is_empty() {
- return Ok(());
- }
- while let Poll::Ready(Some(res)) = self.tasks.poll_next_unpin(cx) {
- let (part_idx, part) = res?;
- let total_parts = self.completed_parts.len();
- self.completed_parts
- .resize(std::cmp::max(part_idx + 1, total_parts), None);
- self.completed_parts[part_idx] = Some(part);
- }
- Ok(())
- }
-
- // The `poll_flush` function will only flush the in-progress tasks.
- // The `final_flush` method called during `poll_shutdown` will flush
- // the `current_buffer` along with in-progress tasks.
- // Please see https://github.com/apache/arrow-rs/issues/3390 for more details.
- fn final_flush(
- mut self: Pin<&mut Self>,
- cx: &mut std::task::Context<'_>,
- ) -> Poll<Result<(), io::Error>> {
- // Poll current tasks
- self.as_mut().poll_tasks(cx)?;
-
- // If current_buffer is not empty, see if it can be submitted
- if !self.current_buffer.is_empty() && self.tasks.len() < self.max_concurrency {
- let out_buffer: Vec<u8> = std::mem::take(&mut self.current_buffer);
- let inner = Arc::clone(&self.inner);
- let part_idx = self.current_part_idx;
- self.tasks.push(Box::pin(async move {
- let upload_part = inner.put_part(out_buffer, part_idx).await?;
- Ok((part_idx, upload_part))
- }));
- }
-
- self.as_mut().poll_tasks(cx)?;
-
- // If tasks and current_buffer are empty, return Ready
- if self.tasks.is_empty() && self.current_buffer.is_empty() {
- Poll::Ready(Ok(()))
- } else {
- Poll::Pending
- }
- }
-}
-
-impl<T: PutPart> AsyncWrite for WriteMultiPart<T> {
- fn poll_write(
- mut self: Pin<&mut Self>,
- cx: &mut std::task::Context<'_>,
- buf: &[u8],
- ) -> Poll<Result<usize, io::Error>> {
- // Poll current tasks
- self.as_mut().poll_tasks(cx)?;
-
- let mut offset = 0;
-
- loop {
- // Fill up current buffer
- offset += self.as_mut().add_to_buffer(buf, offset);
-
- // If we don't have a full buffer or we have too many tasks, break
- if self.current_buffer.len() < self.part_size
- || self.tasks.len() >= self.max_concurrency
- {
- break;
- }
-
- let new_buffer = Vec::with_capacity(self.part_size);
- let out_buffer = std::mem::replace(&mut self.current_buffer, new_buffer);
- let inner = Arc::clone(&self.inner);
- let part_idx = self.current_part_idx;
- self.tasks.push(Box::pin(async move {
- let upload_part = inner.put_part(out_buffer, part_idx).await?;
- Ok((part_idx, upload_part))
- }));
- self.current_part_idx += 1;
-
- // We need to poll immediately after adding to setup waker
- self.as_mut().poll_tasks(cx)?;
- }
-
- // If offset is zero, then we didn't write anything because we didn't
- // have capacity for more tasks and our buffer is full.
- if offset == 0 && !buf.is_empty() {
- Poll::Pending
- } else {
- Poll::Ready(Ok(offset))
- }
- }
-
- fn poll_flush(
- mut self: Pin<&mut Self>,
- cx: &mut std::task::Context<'_>,
- ) -> Poll<Result<(), io::Error>> {
- // Poll current tasks
- self.as_mut().poll_tasks(cx)?;
-
- // If tasks is empty, return Ready
- if self.tasks.is_empty() {
- Poll::Ready(Ok(()))
- } else {
- Poll::Pending
- }
- }
-
- fn poll_shutdown(
- mut self: Pin<&mut Self>,
- cx: &mut std::task::Context<'_>,
- ) -> Poll<Result<(), io::Error>> {
- // First, poll flush
- match self.as_mut().final_flush(cx) {
- Poll::Pending => return Poll::Pending,
- Poll::Ready(res) => res?,
- };
-
- // If shutdown task is not set, set it
- let parts = std::mem::take(&mut self.completed_parts);
- let parts = parts
- .into_iter()
- .enumerate()
- .map(|(idx, part)| {
- part.ok_or_else(|| {
- io::Error::new(
- io::ErrorKind::Other,
- format!("Missing information for upload part {idx}"),
- )
- })
- })
- .collect::<Result<_, _>>()?;
-
- let inner = Arc::clone(&self.inner);
- let completion_task = self.completion_task.get_or_insert_with(|| {
- Box::pin(async move {
- inner.complete(parts).await?;
- Ok(())
- })
- });
-
- Pin::new(completion_task).poll(cx)
- }
-}
-
-impl<T: PutPart> std::fmt::Debug for WriteMultiPart<T> {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- f.debug_struct("WriteMultiPart")
- .field("completed_parts", &self.completed_parts)
- .field("tasks", &self.tasks)
- .field("max_concurrency", &self.max_concurrency)
- .field("current_buffer", &self.current_buffer)
- .field("part_size", &self.part_size)
- .field("current_part_idx", &self.current_part_idx)
- .finish()
- }
-}
-
/// A low-level interface for interacting with multipart upload APIs
///
/// Most use-cases should prefer [`ObjectStore::put_multipart`] as this is supported by more
@@ -277,7 +43,7 @@ impl<T: PutPart> std::fmt::Debug for WriteMultiPart<T> {
/// [`ObjectStore::put_multipart`]: crate::ObjectStore::put_multipart
/// [`LocalFileSystem`]: crate::local::LocalFileSystem
#[async_trait]
-pub trait MultiPartStore: Send + Sync + 'static {
+pub trait MultipartStore: Send + Sync + 'static {
/// Creates a new multipart upload, returning the [`MultipartId`]
async fn create_multipart(&self, path: &Path) -> Result<MultipartId>;
@@ -288,10 +54,11 @@ pub trait MultiPartStore: Send + Sync + 'static {
///
/// Most stores require that all parts excluding the last are at least 5 MiB, and some
/// further require that all parts excluding the last be the same size, e.g. [R2].
- /// [`WriteMultiPart`] performs writes in fixed size blocks of 10 MiB, and clients wanting
+ /// [`WriteMultipart`] performs writes in fixed size blocks of 5 MiB, and clients wanting
/// to maximise compatibility should look to do likewise.
///
/// [R2]: https://developers.cloudflare.com/r2/objects/multipart-objects/#limitations
+ /// [`WriteMultipart`]: crate::upload::WriteMultipart
async fn put_part(
&self,
path: &Path,
diff --git a/object_store/src/prefix.rs b/object_store/src/prefix.rs
index 38f9b07bbd05..053f71a2d063 100644
--- a/object_store/src/prefix.rs
+++ b/object_store/src/prefix.rs
@@ -19,12 +19,11 @@
use bytes::Bytes;
use futures::{stream::BoxStream, StreamExt, TryStreamExt};
use std::ops::Range;
-use tokio::io::AsyncWrite;
use crate::path::Path;
use crate::{
- GetOptions, GetResult, ListResult, MultipartId, ObjectMeta, ObjectStore, PutOptions, PutResult,
- Result,
+ GetOptions, GetResult, ListResult, MultipartUpload, ObjectMeta, ObjectStore, PutOptions,
+ PutResult, Result,
};
#[doc(hidden)]
@@ -91,18 +90,11 @@ impl<T: ObjectStore> ObjectStore for PrefixStore<T> {
self.inner.put_opts(&full_path, bytes, opts).await
}
- async fn put_multipart(
- &self,
- location: &Path,
- ) -> Result<(MultipartId, Box<dyn AsyncWrite + Unpin + Send>)> {
+ async fn put_multipart(&self, location: &Path) -> Result<Box<dyn MultipartUpload>> {
let full_path = self.full_path(location);
self.inner.put_multipart(&full_path).await
}
- async fn abort_multipart(&self, location: &Path, multipart_id: &MultipartId) -> Result<()> {
- let full_path = self.full_path(location);
- self.inner.abort_multipart(&full_path, multipart_id).await
- }
async fn get(&self, location: &Path) -> Result<GetResult> {
let full_path = self.full_path(location);
self.inner.get(&full_path).await
diff --git a/object_store/src/throttle.rs b/object_store/src/throttle.rs
index 252256a4599e..5ca1eedbf739 100644
--- a/object_store/src/throttle.rs
+++ b/object_store/src/throttle.rs
@@ -20,16 +20,15 @@ use parking_lot::Mutex;
use std::ops::Range;
use std::{convert::TryInto, sync::Arc};
+use crate::GetOptions;
use crate::{
- path::Path, GetResult, GetResultPayload, ListResult, ObjectMeta, ObjectStore, PutOptions,
- PutResult, Result,
+ path::Path, GetResult, GetResultPayload, ListResult, MultipartUpload, ObjectMeta, ObjectStore,
+ PutOptions, PutResult, Result,
};
-use crate::{GetOptions, MultipartId};
use async_trait::async_trait;
use bytes::Bytes;
use futures::{stream::BoxStream, FutureExt, StreamExt};
use std::time::Duration;
-use tokio::io::AsyncWrite;
/// Configuration settings for throttled store
#[derive(Debug, Default, Clone, Copy)]
@@ -158,14 +157,7 @@ impl<T: ObjectStore> ObjectStore for ThrottledStore<T> {
self.inner.put_opts(location, bytes, opts).await
}
- async fn put_multipart(
- &self,
- _location: &Path,
- ) -> Result<(MultipartId, Box<dyn AsyncWrite + Unpin + Send>)> {
- Err(super::Error::NotImplemented)
- }
-
- async fn abort_multipart(&self, _location: &Path, _multipart_id: &MultipartId) -> Result<()> {
+ async fn put_multipart(&self, _location: &Path) -> Result<Box<dyn MultipartUpload>> {
Err(super::Error::NotImplemented)
}
diff --git a/object_store/src/upload.rs b/object_store/src/upload.rs
new file mode 100644
index 000000000000..6f8bfa8a5f73
--- /dev/null
+++ b/object_store/src/upload.rs
@@ -0,0 +1,175 @@
+// 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.
+
+use crate::{PutResult, Result};
+use async_trait::async_trait;
+use bytes::Bytes;
+use futures::future::BoxFuture;
+use tokio::task::JoinSet;
+
+/// An upload part request
+pub type UploadPart = BoxFuture<'static, Result<()>>;
+
+/// A trait allowing writing an object in fixed size chunks
+///
+/// Consecutive chunks of data can be written by calling [`MultipartUpload::put_part`] and polling
+/// the returned futures to completion. Multiple futures returned by [`MultipartUpload::put_part`]
+/// may be polled in parallel, allowing for concurrent uploads.
+///
+/// Once all part uploads have been polled to completion, the upload can be completed by
+/// calling [`MultipartUpload::complete`]. This will make the entire uploaded object visible
+/// as an atomic operation.It is implementation behind behaviour if [`MultipartUpload::complete`]
+/// is called before all [`UploadPart`] have been polled to completion.
+#[async_trait]
+pub trait MultipartUpload: Send + std::fmt::Debug {
+ /// Upload the next part
+ ///
+ /// Most stores require that all parts excluding the last are at least 5 MiB, and some
+ /// further require that all parts excluding the last be the same size, e.g. [R2].
+ /// Clients wanting to maximise compatibility should therefore perform writes in
+ /// fixed size blocks larger than 5 MiB.
+ ///
+ /// Implementations may invoke this method multiple times and then await on the
+ /// returned futures in parallel
+ ///
+ /// ```no_run
+ /// # use futures::StreamExt;
+ /// # use object_store::MultipartUpload;
+ /// #
+ /// # async fn test() {
+ /// #
+ /// let mut upload: Box<&dyn MultipartUpload> = todo!();
+ /// let p1 = upload.put_part(vec![0; 10 * 1024 * 1024].into());
+ /// let p2 = upload.put_part(vec![1; 10 * 1024 * 1024].into());
+ /// futures::future::try_join(p1, p2).await.unwrap();
+ /// upload.complete().await.unwrap();
+ /// # }
+ /// ```
+ ///
+ /// [R2]: https://developers.cloudflare.com/r2/objects/multipart-objects/#limitations
+ fn put_part(&mut self, data: Bytes) -> UploadPart;
+
+ /// Complete the multipart upload
+ ///
+ /// It is implementation defined behaviour if this method is called before polling
+ /// all [`UploadPart`] returned by [`MultipartUpload::put_part`] to completion. Additionally,
+ /// it is implementation defined behaviour to call [`MultipartUpload::complete`]
+ /// on an already completed or aborted [`MultipartUpload`].
+ async fn complete(&mut self) -> Result<PutResult>;
+
+ /// Abort the multipart upload
+ ///
+ /// If a [`MultipartUpload`] is dropped without calling [`MultipartUpload::complete`],
+ /// some object stores will automatically clean up any previously uploaded parts.
+ /// However, some stores, such as S3 and GCS, cannot perform cleanup on drop.
+ /// As such [`MultipartUpload::abort`] can be invoked to perform this cleanup.
+ ///
+ /// It will not be possible to call `abort` in all failure scenarios, for example
+ /// non-graceful shutdown of the calling application. It is therefore recommended
+ /// object stores are configured with lifecycle rules to automatically cleanup
+ /// unused parts older than some threshold. See [crate::aws] and [crate::gcp]
+ /// for more information.
+ ///
+ /// It is implementation defined behaviour to call [`MultipartUpload::abort`]
+ /// on an already completed or aborted [`MultipartUpload`]
+ async fn abort(&mut self) -> Result<()>;
+}
+
+/// A synchronous write API for uploading data in parallel in fixed size chunks
+///
+/// Uses multiple tokio tasks in a [`JoinSet`] to multiplex upload tasks in parallel
+///
+/// The design also takes inspiration from [`Sink`] with [`WriteMultipart::wait_for_capacity`]
+/// allowing back pressure on producers, prior to buffering the next part. However, unlike
+/// [`Sink`] this back pressure is optional, allowing integration with synchronous producers
+///
+/// [`Sink`]: futures::sink::Sink
+#[derive(Debug)]
+pub struct WriteMultipart {
+ upload: Box<dyn MultipartUpload>,
+
+ buffer: Vec<u8>,
+
+ tasks: JoinSet<Result<()>>,
+}
+
+impl WriteMultipart {
+ /// Create a new [`WriteMultipart`] that will upload using 5MB chunks
+ pub fn new(upload: Box<dyn MultipartUpload>) -> Self {
+ Self::new_with_capacity(upload, 5 * 1024 * 1024)
+ }
+
+ /// Create a new [`WriteMultipart`] that will upload in fixed `capacity` sized chunks
+ pub fn new_with_capacity(upload: Box<dyn MultipartUpload>, capacity: usize) -> Self {
+ Self {
+ upload,
+ buffer: Vec::with_capacity(capacity),
+ tasks: Default::default(),
+ }
+ }
+
+ /// Wait until there are `max_concurrency` or fewer requests in-flight
+ pub async fn wait_for_capacity(&mut self, max_concurrency: usize) -> Result<()> {
+ while self.tasks.len() > max_concurrency {
+ self.tasks.join_next().await.unwrap()??;
+ }
+ Ok(())
+ }
+
+ /// Write data to this [`WriteMultipart`]
+ ///
+ /// Note this method is synchronous (not `async`) and will immediately start new uploads
+ /// as soon as the internal `capacity` is hit, regardless of
+ /// how many outstanding uploads are already in progress.
+ ///
+ /// Back pressure can optionally be applied to producers by calling
+ /// [`Self::wait_for_capacity`] prior to calling this method
+ pub fn write(&mut self, mut buf: &[u8]) {
+ while !buf.is_empty() {
+ let capacity = self.buffer.capacity();
+ let remaining = capacity - self.buffer.len();
+ let to_read = buf.len().min(remaining);
+ self.buffer.extend_from_slice(&buf[..to_read]);
+ if to_read == remaining {
+ let part = std::mem::replace(&mut self.buffer, Vec::with_capacity(capacity));
+ self.put_part(part.into())
+ }
+ buf = &buf[to_read..]
+ }
+ }
+
+ fn put_part(&mut self, part: Bytes) {
+ self.tasks.spawn(self.upload.put_part(part));
+ }
+
+ /// Abort this upload, attempting to clean up any successfully uploaded parts
+ pub async fn abort(mut self) -> Result<()> {
+ self.tasks.shutdown().await;
+ self.upload.abort().await
+ }
+
+ /// Flush final chunk, and await completion of all in-flight requests
+ pub async fn finish(mut self) -> Result<PutResult> {
+ if !self.buffer.is_empty() {
+ let part = std::mem::take(&mut self.buffer);
+ self.put_part(part.into())
+ }
+
+ self.wait_for_capacity(0).await?;
+ self.upload.complete().await
+ }
+}
|
diff --git a/object_store/tests/get_range_file.rs b/object_store/tests/get_range_file.rs
index f73d78578f08..309a86d8fe9d 100644
--- a/object_store/tests/get_range_file.rs
+++ b/object_store/tests/get_range_file.rs
@@ -25,7 +25,6 @@ use object_store::path::Path;
use object_store::*;
use std::fmt::Formatter;
use tempfile::tempdir;
-use tokio::io::AsyncWrite;
#[derive(Debug)]
struct MyStore(LocalFileSystem);
@@ -42,14 +41,7 @@ impl ObjectStore for MyStore {
self.0.put_opts(path, data, opts).await
}
- async fn put_multipart(
- &self,
- _: &Path,
- ) -> Result<(MultipartId, Box<dyn AsyncWrite + Unpin + Send>)> {
- todo!()
- }
-
- async fn abort_multipart(&self, _: &Path, _: &MultipartId) -> Result<()> {
+ async fn put_multipart(&self, _location: &Path) -> Result<Box<dyn MultipartUpload>> {
todo!()
}
|
Inconsistent Multipart Nomenclature
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
<!--
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
(This section helps Arrow developers understand the context and *why* for this feature, in addition to the *what*)
-->
The object_store crate inconsistently used `multipart` `multi-part` and `multi part` to refer to the ability to upload in chunks.
**Describe the solution you'd like**
<!--
A clear and concise description of what you want to happen.
-->
We should mirror the AWS naming, and using `multipart` as a single word - https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateMultipartUpload.html
**Describe alternatives you've considered**
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
|
2024-03-13T08:46:10Z
|
51.0
|
30767a687b48d0dbd2e030eef327826c39095123
|
|
apache/arrow-rs
| 5,493
|
apache__arrow-rs-5493
|
[
"5492"
] |
82fc0df73ab97e239ce5c748a05c57ce582f3d5d
|
diff --git a/arrow-data/src/data.rs b/arrow-data/src/data.rs
index 2ddc2d845b01..914e90d96c22 100644
--- a/arrow-data/src/data.rs
+++ b/arrow-data/src/data.rs
@@ -119,12 +119,20 @@ pub(crate) fn new_buffers(data_type: &DataType, capacity: usize) -> [MutableBuff
buffer.push(0i32);
[buffer, empty_buffer]
}
+ DataType::ListView(_) => [
+ MutableBuffer::new(capacity * mem::size_of::<i32>()),
+ MutableBuffer::new(capacity * mem::size_of::<i32>()),
+ ],
DataType::LargeList(_) => {
// offset buffer always starts with a zero
let mut buffer = MutableBuffer::new((1 + capacity) * mem::size_of::<i64>());
buffer.push(0i64);
[buffer, empty_buffer]
}
+ DataType::LargeListView(_) => [
+ MutableBuffer::new(capacity * mem::size_of::<i64>()),
+ MutableBuffer::new(capacity * mem::size_of::<i64>()),
+ ],
DataType::FixedSizeBinary(size) => {
[MutableBuffer::new(capacity * *size as usize), empty_buffer]
}
@@ -1550,6 +1558,9 @@ pub fn layout(data_type: &DataType) -> DataTypeLayout {
}
DataType::FixedSizeList(_, _) => DataTypeLayout::new_empty(), // all in child data
DataType::List(_) => DataTypeLayout::new_fixed_width::<i32>(),
+ DataType::ListView(_) | DataType::LargeListView(_) => {
+ unimplemented!("ListView/LargeListView not implemented")
+ }
DataType::LargeList(_) => DataTypeLayout::new_fixed_width::<i64>(),
DataType::Map(_, _) => DataTypeLayout::new_fixed_width::<i32>(),
DataType::Struct(_) => DataTypeLayout::new_empty(), // all in child data,
diff --git a/arrow-data/src/equal/mod.rs b/arrow-data/src/equal/mod.rs
index 1255ff39e097..0987fd4c5637 100644
--- a/arrow-data/src/equal/mod.rs
+++ b/arrow-data/src/equal/mod.rs
@@ -100,6 +100,9 @@ fn equal_values(
unimplemented!("BinaryView/Utf8View not yet implemented")
}
DataType::List(_) => list_equal::<i32>(lhs, rhs, lhs_start, rhs_start, len),
+ DataType::ListView(_) | DataType::LargeListView(_) => {
+ unimplemented!("ListView/LargeListView not yet implemented")
+ }
DataType::LargeList(_) => list_equal::<i64>(lhs, rhs, lhs_start, rhs_start, len),
DataType::FixedSizeList(_, _) => fixed_list_equal(lhs, rhs, lhs_start, rhs_start, len),
DataType::Struct(_) => struct_equal(lhs, rhs, lhs_start, rhs_start, len),
diff --git a/arrow-data/src/transform/mod.rs b/arrow-data/src/transform/mod.rs
index ef53efac2373..b14f6e771033 100644
--- a/arrow-data/src/transform/mod.rs
+++ b/arrow-data/src/transform/mod.rs
@@ -228,6 +228,9 @@ fn build_extend(array: &ArrayData) -> Extend {
unimplemented!("BinaryView/Utf8View not implemented")
}
DataType::Map(_, _) | DataType::List(_) => list::build_extend::<i32>(array),
+ DataType::ListView(_) | DataType::LargeListView(_) => {
+ unimplemented!("ListView/LargeListView not implemented")
+ }
DataType::LargeList(_) => list::build_extend::<i64>(array),
DataType::Dictionary(_, _) => unreachable!("should use build_extend_dictionary"),
DataType::Struct(_) => structure::build_extend(array),
@@ -273,6 +276,9 @@ fn build_extend_nulls(data_type: &DataType) -> ExtendNulls {
unimplemented!("BinaryView/Utf8View not implemented")
}
DataType::Map(_, _) | DataType::List(_) => list::extend_nulls::<i32>,
+ DataType::ListView(_) | DataType::LargeListView(_) => {
+ unimplemented!("ListView/LargeListView not implemented")
+ }
DataType::LargeList(_) => list::extend_nulls::<i64>,
DataType::Dictionary(child_data_type, _) => match child_data_type.as_ref() {
DataType::UInt8 => primitive::extend_nulls::<u8>,
@@ -428,6 +434,9 @@ impl<'a> MutableArrayData<'a> {
DataType::BinaryView | DataType::Utf8View => {
unimplemented!("BinaryView/Utf8View not implemented")
}
+ DataType::ListView(_) | DataType::LargeListView(_) => {
+ unimplemented!("ListView/LargeListView not implemented")
+ }
DataType::Map(_, _) | DataType::List(_) | DataType::LargeList(_) => {
let children = arrays
.iter()
diff --git a/arrow-ipc/src/convert.rs b/arrow-ipc/src/convert.rs
index a2ffd4380203..a821008d89ab 100644
--- a/arrow-ipc/src/convert.rs
+++ b/arrow-ipc/src/convert.rs
@@ -664,6 +664,7 @@ pub(crate) fn get_fb_field_type<'a>(
children: Some(fbb.create_vector(&[child])),
}
}
+ ListView(_) | LargeListView(_) => unimplemented!("ListView/LargeListView not implemented"),
LargeList(ref list_type) => {
let child = build_field(fbb, list_type);
FBFieldType {
diff --git a/arrow-schema/src/datatype.rs b/arrow-schema/src/datatype.rs
index b3d89b011e66..6472495697ba 100644
--- a/arrow-schema/src/datatype.rs
+++ b/arrow-schema/src/datatype.rs
@@ -228,12 +228,30 @@ pub enum DataType {
///
/// A single List array can store up to [`i32::MAX`] elements in total.
List(FieldRef),
+
+ /// (NOT YET FULLY SUPPORTED) A list of some logical data type with variable length.
+ ///
+ /// Note this data type is not yet fully supported. Using it with arrow APIs may result in `panic`s.
+ ///
+ /// The ListView layout is defined by three buffers:
+ /// a validity bitmap, an offsets buffer, and an additional sizes buffer.
+ /// Sizes and offsets are both 32 bits for this type
+ ListView(FieldRef),
/// A list of some logical data type with fixed length.
FixedSizeList(FieldRef, i32),
/// A list of some logical data type with variable length and 64-bit offsets.
///
/// A single LargeList array can store up to [`i64::MAX`] elements in total.
LargeList(FieldRef),
+
+ /// (NOT YET FULLY SUPPORTED) A list of some logical data type with variable length and 64-bit offsets.
+ ///
+ /// Note this data type is not yet fully supported. Using it with arrow APIs may result in `panic`s.
+ ///
+ /// The LargeListView layout is defined by three buffers:
+ /// a validity bitmap, an offsets buffer, and an additional sizes buffer.
+ /// Sizes and offsets are both 64 bits for this type
+ LargeListView(FieldRef),
/// A nested datatype that contains a number of sub-fields.
Struct(Fields),
/// A nested datatype that can represent slots of differing types. Components:
@@ -536,7 +554,11 @@ impl DataType {
DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View => None,
DataType::Binary | DataType::LargeBinary | DataType::BinaryView => None,
DataType::FixedSizeBinary(_) => None,
- DataType::List(_) | DataType::LargeList(_) | DataType::Map(_, _) => None,
+ DataType::List(_)
+ | DataType::ListView(_)
+ | DataType::LargeList(_)
+ | DataType::LargeListView(_)
+ | DataType::Map(_, _) => None,
DataType::FixedSizeList(_, _) => None,
DataType::Struct(_) => None,
DataType::Union(_, _) => None,
@@ -581,8 +603,10 @@ impl DataType {
| DataType::Decimal256(_, _) => 0,
DataType::Timestamp(_, s) => s.as_ref().map(|s| s.len()).unwrap_or_default(),
DataType::List(field)
+ | DataType::ListView(field)
| DataType::FixedSizeList(field, _)
| DataType::LargeList(field)
+ | DataType::LargeListView(field)
| DataType::Map(field, _) => field.size(),
DataType::Struct(fields) => fields.size(),
DataType::Union(fields, _) => fields.size(),
diff --git a/arrow-schema/src/field.rs b/arrow-schema/src/field.rs
index 70a3e2b21a3c..c91200105935 100644
--- a/arrow-schema/src/field.rs
+++ b/arrow-schema/src/field.rs
@@ -510,7 +510,9 @@ impl Field {
| DataType::BinaryView
| DataType::Interval(_)
| DataType::LargeList(_)
+ | DataType::LargeListView(_)
| DataType::List(_)
+ | DataType::ListView(_)
| DataType::Map(_, _)
| DataType::Dictionary(_, _)
| DataType::RunEndEncoded(_, _)
diff --git a/parquet/src/arrow/schema/mod.rs b/parquet/src/arrow/schema/mod.rs
index a8bef98d9e8c..4a78db05ed2d 100644
--- a/parquet/src/arrow/schema/mod.rs
+++ b/parquet/src/arrow/schema/mod.rs
@@ -528,6 +528,7 @@ fn arrow_to_parquet_type(field: &Field) -> Result<Type> {
.with_id(id)
.build()
}
+ DataType::ListView(_) | DataType::LargeListView(_) => unimplemented!("ListView/LargeListView not implemented"),
DataType::Struct(fields) => {
if fields.is_empty() {
return Err(
|
diff --git a/arrow-integration-test/src/datatype.rs b/arrow-integration-test/src/datatype.rs
index a04db1cf3538..e45e94c24e07 100644
--- a/arrow-integration-test/src/datatype.rs
+++ b/arrow-integration-test/src/datatype.rs
@@ -281,6 +281,9 @@ pub fn data_type_to_json(data_type: &DataType) -> serde_json::Value {
DataType::Union(_, _) => json!({"name": "union"}),
DataType::List(_) => json!({ "name": "list"}),
DataType::LargeList(_) => json!({ "name": "largelist"}),
+ DataType::ListView(_) | DataType::LargeListView(_) => {
+ unimplemented!("ListView/LargeListView not implemented")
+ }
DataType::FixedSizeList(_, length) => {
json!({"name":"fixedsizelist", "listSize": length})
}
|
Add DataType::ListView and DataType::LargeListView
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
<!--
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
(This section helps Arrow developers understand the context and *why* for this feature, in addition to the *what*)
-->
This is part of a larger feature #5375 , broken down into smaller tasks to facilitate better tracking and to avoid large pr.
- First, the relevant DataType definitions have been completed.
- Secondly, it is ensured that the called APIs will return an "unimplemented error."
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
To maintain a more uniform code appearance, reference to: https://github.com/apache/arrow-rs/pull/5470.
|
2024-03-10T13:45:35Z
|
50.0
|
82fc0df73ab97e239ce5c748a05c57ce582f3d5d
|
|
apache/arrow-rs
| 5,481
|
apache__arrow-rs-5481
|
[
"5469"
] |
ad3b4c92508a17ea679c9695a89f85c2cdcc4fcf
|
diff --git a/arrow-array/src/array/byte_array.rs b/arrow-array/src/array/byte_array.rs
index db825bbea97d..a57abc5b1e71 100644
--- a/arrow-array/src/array/byte_array.rs
+++ b/arrow-array/src/array/byte_array.rs
@@ -94,7 +94,7 @@ pub struct GenericByteArray<T: ByteArrayType> {
impl<T: ByteArrayType> Clone for GenericByteArray<T> {
fn clone(&self) -> Self {
Self {
- data_type: self.data_type.clone(),
+ data_type: T::DATA_TYPE,
value_offsets: self.value_offsets.clone(),
value_data: self.value_data.clone(),
nulls: self.nulls.clone(),
@@ -323,7 +323,7 @@ impl<T: ByteArrayType> GenericByteArray<T> {
/// Returns a zero-copy slice of this array with the indicated offset and length.
pub fn slice(&self, offset: usize, length: usize) -> Self {
Self {
- data_type: self.data_type.clone(),
+ data_type: T::DATA_TYPE,
value_offsets: self.value_offsets.slice(offset, length),
value_data: self.value_data.clone(),
nulls: self.nulls.as_ref().map(|n| n.slice(offset, length)),
@@ -511,7 +511,7 @@ impl<T: ByteArrayType> From<ArrayData> for GenericByteArray<T> {
Self {
value_offsets,
value_data,
- data_type: data.data_type().clone(),
+ data_type: T::DATA_TYPE,
nulls: data.nulls().cloned(),
}
}
diff --git a/arrow-array/src/array/byte_view_array.rs b/arrow-array/src/array/byte_view_array.rs
new file mode 100644
index 000000000000..e22e9b1688bb
--- /dev/null
+++ b/arrow-array/src/array/byte_view_array.rs
@@ -0,0 +1,480 @@
+// 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.
+
+use crate::array::print_long_array;
+use crate::builder::GenericByteViewBuilder;
+use crate::iterator::ArrayIter;
+use crate::types::bytes::ByteArrayNativeType;
+use crate::types::{BinaryViewType, ByteViewType, StringViewType};
+use crate::{Array, ArrayAccessor, ArrayRef};
+use arrow_buffer::{Buffer, NullBuffer, ScalarBuffer};
+use arrow_data::{ArrayData, ArrayDataBuilder, ByteView};
+use arrow_schema::{ArrowError, DataType};
+use std::any::Any;
+use std::fmt::Debug;
+use std::marker::PhantomData;
+use std::sync::Arc;
+
+/// [Variable-size Binary View Layout]: An array of variable length bytes view arrays.
+///
+/// Different than [`crate::GenericByteArray`] as it stores both an offset and length
+/// meaning that take / filter operations can be implemented without copying the underlying data.
+///
+/// [Variable-size Binary View Layout]: https://arrow.apache.org/docs/format/Columnar.html#variable-size-binary-view-layout
+pub struct GenericByteViewArray<T: ByteViewType + ?Sized> {
+ data_type: DataType,
+ views: ScalarBuffer<u128>,
+ buffers: Vec<Buffer>,
+ phantom: PhantomData<T>,
+ nulls: Option<NullBuffer>,
+}
+
+impl<T: ByteViewType + ?Sized> Clone for GenericByteViewArray<T> {
+ fn clone(&self) -> Self {
+ Self {
+ data_type: T::DATA_TYPE,
+ views: self.views.clone(),
+ buffers: self.buffers.clone(),
+ nulls: self.nulls.clone(),
+ phantom: Default::default(),
+ }
+ }
+}
+
+impl<T: ByteViewType + ?Sized> GenericByteViewArray<T> {
+ /// Create a new [`GenericByteViewArray`] from the provided parts, panicking on failure
+ ///
+ /// # Panics
+ ///
+ /// Panics if [`GenericByteViewArray::try_new`] returns an error
+ pub fn new(views: ScalarBuffer<u128>, buffers: Vec<Buffer>, nulls: Option<NullBuffer>) -> Self {
+ Self::try_new(views, buffers, nulls).unwrap()
+ }
+
+ /// Create a new [`GenericByteViewArray`] from the provided parts, returning an error on failure
+ ///
+ /// # Errors
+ ///
+ /// * `views.len() != nulls.len()`
+ /// * [ByteViewType::validate] fails
+ pub fn try_new(
+ views: ScalarBuffer<u128>,
+ buffers: Vec<Buffer>,
+ nulls: Option<NullBuffer>,
+ ) -> Result<Self, ArrowError> {
+ T::validate(&views, &buffers)?;
+
+ if let Some(n) = nulls.as_ref() {
+ if n.len() != views.len() {
+ return Err(ArrowError::InvalidArgumentError(format!(
+ "Incorrect length of null buffer for {}ViewArray, expected {} got {}",
+ T::PREFIX,
+ views.len(),
+ n.len(),
+ )));
+ }
+ }
+
+ Ok(Self {
+ data_type: T::DATA_TYPE,
+ views,
+ buffers,
+ nulls,
+ phantom: Default::default(),
+ })
+ }
+
+ /// Create a new [`GenericByteViewArray`] from the provided parts, without validation
+ ///
+ /// # Safety
+ ///
+ /// Safe if [`Self::try_new`] would not error
+ pub unsafe fn new_unchecked(
+ views: ScalarBuffer<u128>,
+ buffers: Vec<Buffer>,
+ nulls: Option<NullBuffer>,
+ ) -> Self {
+ Self {
+ data_type: T::DATA_TYPE,
+ phantom: Default::default(),
+ views,
+ buffers,
+ nulls,
+ }
+ }
+
+ /// Create a new [`GenericByteViewArray`] of length `len` where all values are null
+ pub fn new_null(len: usize) -> Self {
+ Self {
+ data_type: T::DATA_TYPE,
+ views: vec![0; len].into(),
+ buffers: vec![],
+ nulls: Some(NullBuffer::new_null(len)),
+ phantom: Default::default(),
+ }
+ }
+
+ /// Creates a [`GenericByteViewArray`] based on an iterator of values without nulls
+ pub fn from_iter_values<Ptr, I>(iter: I) -> Self
+ where
+ Ptr: AsRef<T::Native>,
+ I: IntoIterator<Item = Ptr>,
+ {
+ let iter = iter.into_iter();
+ let mut builder = GenericByteViewBuilder::<T>::with_capacity(iter.size_hint().0);
+ for v in iter {
+ builder.append_value(v);
+ }
+ builder.finish()
+ }
+
+ /// Deconstruct this array into its constituent parts
+ pub fn into_parts(self) -> (ScalarBuffer<u128>, Vec<Buffer>, Option<NullBuffer>) {
+ (self.views, self.buffers, self.nulls)
+ }
+
+ /// Returns the views buffer
+ #[inline]
+ pub fn views(&self) -> &ScalarBuffer<u128> {
+ &self.views
+ }
+
+ /// Returns the buffers storing string data
+ #[inline]
+ pub fn data_buffers(&self) -> &[Buffer] {
+ &self.buffers
+ }
+
+ /// Returns the element at index `i`
+ /// # Panics
+ /// Panics if index `i` is out of bounds.
+ pub fn value(&self, i: usize) -> &T::Native {
+ assert!(
+ i < self.len(),
+ "Trying to access an element at index {} from a {}ViewArray of length {}",
+ i,
+ T::PREFIX,
+ self.len()
+ );
+
+ unsafe { self.value_unchecked(i) }
+ }
+
+ /// Returns the element at index `i`
+ /// # Safety
+ /// Caller is responsible for ensuring that the index is within the bounds of the array
+ pub unsafe fn value_unchecked(&self, idx: usize) -> &T::Native {
+ let v = self.views.get_unchecked(idx);
+ let len = *v as u32;
+ let b = if len <= 12 {
+ let ptr = self.views.as_ptr() as *const u8;
+ std::slice::from_raw_parts(ptr.add(idx * 16 + 4), len as usize)
+ } else {
+ let view = ByteView::from(*v);
+ let data = self.buffers.get_unchecked(view.buffer_index as usize);
+ let offset = view.offset as usize;
+ data.get_unchecked(offset..offset + len as usize)
+ };
+ T::Native::from_bytes_unchecked(b)
+ }
+
+ /// constructs a new iterator
+ pub fn iter(&self) -> ArrayIter<&Self> {
+ ArrayIter::new(self)
+ }
+
+ /// Returns a zero-copy slice of this array with the indicated offset and length.
+ pub fn slice(&self, offset: usize, length: usize) -> Self {
+ Self {
+ data_type: T::DATA_TYPE,
+ views: self.views.slice(offset, length),
+ buffers: self.buffers.clone(),
+ nulls: self.nulls.as_ref().map(|n| n.slice(offset, length)),
+ phantom: Default::default(),
+ }
+ }
+}
+
+impl<T: ByteViewType + ?Sized> Debug for GenericByteViewArray<T> {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ write!(f, "{}ViewArray\n[\n", T::PREFIX)?;
+ print_long_array(self, f, |array, index, f| {
+ std::fmt::Debug::fmt(&array.value(index), f)
+ })?;
+ write!(f, "]")
+ }
+}
+
+impl<T: ByteViewType + ?Sized> Array for GenericByteViewArray<T> {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn to_data(&self) -> ArrayData {
+ self.clone().into()
+ }
+
+ fn into_data(self) -> ArrayData {
+ self.into()
+ }
+
+ fn data_type(&self) -> &DataType {
+ &self.data_type
+ }
+
+ fn slice(&self, offset: usize, length: usize) -> ArrayRef {
+ Arc::new(self.slice(offset, length))
+ }
+
+ fn len(&self) -> usize {
+ self.views.len()
+ }
+
+ fn is_empty(&self) -> bool {
+ self.views.is_empty()
+ }
+
+ fn offset(&self) -> usize {
+ 0
+ }
+
+ fn nulls(&self) -> Option<&NullBuffer> {
+ self.nulls.as_ref()
+ }
+
+ fn get_buffer_memory_size(&self) -> usize {
+ let mut sum = self.buffers.iter().map(|b| b.capacity()).sum::<usize>();
+ sum += self.views.inner().capacity();
+ if let Some(x) = &self.nulls {
+ sum += x.buffer().capacity()
+ }
+ sum
+ }
+
+ fn get_array_memory_size(&self) -> usize {
+ std::mem::size_of::<Self>() + self.get_buffer_memory_size()
+ }
+}
+
+impl<'a, T: ByteViewType + ?Sized> ArrayAccessor for &'a GenericByteViewArray<T> {
+ type Item = &'a T::Native;
+
+ fn value(&self, index: usize) -> Self::Item {
+ GenericByteViewArray::value(self, index)
+ }
+
+ unsafe fn value_unchecked(&self, index: usize) -> Self::Item {
+ GenericByteViewArray::value_unchecked(self, index)
+ }
+}
+
+impl<'a, T: ByteViewType + ?Sized> IntoIterator for &'a GenericByteViewArray<T> {
+ type Item = Option<&'a T::Native>;
+ type IntoIter = ArrayIter<Self>;
+
+ fn into_iter(self) -> Self::IntoIter {
+ ArrayIter::new(self)
+ }
+}
+
+impl<T: ByteViewType + ?Sized> From<ArrayData> for GenericByteViewArray<T> {
+ fn from(value: ArrayData) -> Self {
+ let views = value.buffers()[0].clone();
+ let views = ScalarBuffer::new(views, value.offset(), value.len());
+ let buffers = value.buffers()[1..].to_vec();
+ Self {
+ data_type: T::DATA_TYPE,
+ views,
+ buffers,
+ nulls: value.nulls().cloned(),
+ phantom: Default::default(),
+ }
+ }
+}
+
+impl<T: ByteViewType + ?Sized> From<GenericByteViewArray<T>> for ArrayData {
+ fn from(mut array: GenericByteViewArray<T>) -> Self {
+ let len = array.len();
+ array.buffers.insert(0, array.views.into_inner());
+ let builder = ArrayDataBuilder::new(T::DATA_TYPE)
+ .len(len)
+ .buffers(array.buffers)
+ .nulls(array.nulls);
+
+ unsafe { builder.build_unchecked() }
+ }
+}
+
+impl<Ptr, T: ByteViewType + ?Sized> FromIterator<Option<Ptr>> for GenericByteViewArray<T>
+where
+ Ptr: AsRef<T::Native>,
+{
+ fn from_iter<I: IntoIterator<Item = Option<Ptr>>>(iter: I) -> Self {
+ let iter = iter.into_iter();
+ let mut builder = GenericByteViewBuilder::<T>::with_capacity(iter.size_hint().0);
+ builder.extend(iter);
+ builder.finish()
+ }
+}
+
+/// A [`GenericByteViewArray`] of `[u8]`
+pub type BinaryViewArray = GenericByteViewArray<BinaryViewType>;
+
+/// A [`GenericByteViewArray`] of `str`
+///
+/// ```
+/// use arrow_array::StringViewArray;
+/// let array = StringViewArray::from_iter_values(vec!["hello", "world", "lulu", "large payload over 12 bytes"]);
+/// assert_eq!(array.value(0), "hello");
+/// assert_eq!(array.value(3), "large payload over 12 bytes");
+/// ```
+pub type StringViewArray = GenericByteViewArray<StringViewType>;
+
+impl From<Vec<&str>> for StringViewArray {
+ fn from(v: Vec<&str>) -> Self {
+ Self::from_iter_values(v)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::builder::StringViewBuilder;
+ use crate::{Array, BinaryViewArray, StringViewArray};
+ use arrow_buffer::{Buffer, ScalarBuffer};
+ use arrow_data::ByteView;
+
+ #[test]
+ fn try_new() {
+ let array = StringViewArray::from_iter_values(vec![
+ "hello",
+ "world",
+ "lulu",
+ "large payload over 12 bytes",
+ ]);
+ assert_eq!(array.value(0), "hello");
+ assert_eq!(array.value(3), "large payload over 12 bytes");
+
+ let array = BinaryViewArray::from_iter_values(vec![
+ b"hello".as_slice(),
+ b"world".as_slice(),
+ b"lulu".as_slice(),
+ b"large payload over 12 bytes".as_slice(),
+ ]);
+ assert_eq!(array.value(0), b"hello");
+ assert_eq!(array.value(3), b"large payload over 12 bytes");
+
+ // test empty array
+ let array = {
+ let mut builder = StringViewBuilder::new();
+ builder.finish()
+ };
+ assert!(array.is_empty());
+
+ // test builder append
+ let array = {
+ let mut builder = StringViewBuilder::new();
+ builder.append_value("hello");
+ builder.append_null();
+ builder.append_option(Some("large payload over 12 bytes"));
+ builder.finish()
+ };
+ assert_eq!(array.value(0), "hello");
+ assert!(array.is_null(1));
+ assert_eq!(array.value(2), "large payload over 12 bytes");
+
+ // test builder's in_progress re-created
+ let array = {
+ // make a builder with small block size.
+ let mut builder = StringViewBuilder::new().with_block_size(14);
+ builder.append_value("large payload over 12 bytes");
+ builder.append_option(Some("another large payload over 12 bytes that double than the first one, so that we can trigger the in_progress in builder re-created"));
+ builder.finish()
+ };
+ assert_eq!(array.value(0), "large payload over 12 bytes");
+ assert_eq!(array.value(1), "another large payload over 12 bytes that double than the first one, so that we can trigger the in_progress in builder re-created");
+ assert_eq!(2, array.buffers.len());
+ }
+
+ #[test]
+ #[should_panic(expected = "Invalid buffer index at 0: got index 3 but only has 1 buffers")]
+ fn new_with_invalid_view_data() {
+ let v = "large payload over 12 bytes";
+ let view = ByteView {
+ length: 13,
+ prefix: u32::from_le_bytes(v.as_bytes()[0..4].try_into().unwrap()),
+ buffer_index: 3,
+ offset: 1,
+ };
+ let views = ScalarBuffer::from(vec![view.into()]);
+ let buffers = vec![Buffer::from_slice_ref(v)];
+ StringViewArray::new(views, buffers, None);
+ }
+
+ #[test]
+ #[should_panic(
+ expected = "Encountered non-UTF-8 data at index 0: invalid utf-8 sequence of 1 bytes from index 0"
+ )]
+ fn new_with_invalid_utf8_data() {
+ let v: Vec<u8> = vec![0xf0, 0x80, 0x80, 0x80];
+ let view = ByteView {
+ length: v.len() as u32,
+ prefix: u32::from_le_bytes(v[0..4].try_into().unwrap()),
+ buffer_index: 0,
+ offset: 0,
+ };
+ let views = ScalarBuffer::from(vec![view.into()]);
+ let buffers = vec![Buffer::from_slice_ref(v)];
+ StringViewArray::new(views, buffers, None);
+ }
+
+ #[test]
+ #[should_panic(expected = "View at index 0 contained non-zero padding for string of length 1")]
+ fn new_with_invalid_zero_padding() {
+ let mut data = [0; 12];
+ data[0] = b'H';
+ data[11] = 1; // no zero padding
+
+ let mut view_buffer = [0; 16];
+ view_buffer[0..4].copy_from_slice(&1u32.to_le_bytes());
+ view_buffer[4..].copy_from_slice(&data);
+
+ let view = ByteView::from(u128::from_le_bytes(view_buffer));
+ let views = ScalarBuffer::from(vec![view.into()]);
+ let buffers = vec![];
+ StringViewArray::new(views, buffers, None);
+ }
+
+ #[test]
+ #[should_panic(expected = "Mismatch between embedded prefix and data")]
+ fn test_mismatch_between_embedded_prefix_and_data() {
+ let input_str_1 = "Hello, Rustaceans!";
+ let input_str_2 = "Hallo, Rustaceans!";
+ let length = input_str_1.len() as u32;
+ assert!(input_str_1.len() > 12);
+
+ let mut view_buffer = [0; 16];
+ view_buffer[0..4].copy_from_slice(&length.to_le_bytes());
+ view_buffer[4..8].copy_from_slice(&input_str_1.as_bytes()[0..4]);
+ view_buffer[8..12].copy_from_slice(&0u32.to_le_bytes());
+ view_buffer[12..].copy_from_slice(&0u32.to_le_bytes());
+ let view = ByteView::from(u128::from_le_bytes(view_buffer));
+ let views = ScalarBuffer::from(vec![view.into()]);
+ let buffers = vec![Buffer::from_slice_ref(input_str_2.as_bytes())];
+
+ StringViewArray::new(views, buffers, None);
+ }
+}
diff --git a/arrow-array/src/array/mod.rs b/arrow-array/src/array/mod.rs
index 7aa3f92bfbd2..b115ff9c14cc 100644
--- a/arrow-array/src/array/mod.rs
+++ b/arrow-array/src/array/mod.rs
@@ -65,8 +65,13 @@ mod union_array;
pub use union_array::*;
mod run_array;
+
pub use run_array::*;
+mod byte_view_array;
+
+pub use byte_view_array::*;
+
/// An array in the [arrow columnar format](https://arrow.apache.org/docs/format/Columnar.html)
pub trait Array: std::fmt::Debug + Send + Sync {
/// Returns the array as [`Any`] so that it can be
@@ -596,8 +601,10 @@ pub fn make_array(data: ArrayData) -> ArrayRef {
DataType::Binary => Arc::new(BinaryArray::from(data)) as ArrayRef,
DataType::LargeBinary => Arc::new(LargeBinaryArray::from(data)) as ArrayRef,
DataType::FixedSizeBinary(_) => Arc::new(FixedSizeBinaryArray::from(data)) as ArrayRef,
+ DataType::BinaryView => Arc::new(BinaryViewArray::from(data)) as ArrayRef,
DataType::Utf8 => Arc::new(StringArray::from(data)) as ArrayRef,
DataType::LargeUtf8 => Arc::new(LargeStringArray::from(data)) as ArrayRef,
+ DataType::Utf8View => Arc::new(StringViewArray::from(data)) as ArrayRef,
DataType::List(_) => Arc::new(ListArray::from(data)) as ArrayRef,
DataType::LargeList(_) => Arc::new(LargeListArray::from(data)) as ArrayRef,
DataType::Struct(_) => Arc::new(StructArray::from(data)) as ArrayRef,
diff --git a/arrow-array/src/builder/generic_bytes_view_builder.rs b/arrow-array/src/builder/generic_bytes_view_builder.rs
new file mode 100644
index 000000000000..29de7feb0ec1
--- /dev/null
+++ b/arrow-array/src/builder/generic_bytes_view_builder.rs
@@ -0,0 +1,215 @@
+// 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.
+
+use crate::builder::ArrayBuilder;
+use crate::types::{BinaryViewType, ByteViewType, StringViewType};
+use crate::{ArrayRef, GenericByteViewArray};
+use arrow_buffer::{Buffer, BufferBuilder, NullBufferBuilder, ScalarBuffer};
+use arrow_data::ByteView;
+use std::any::Any;
+use std::marker::PhantomData;
+use std::sync::Arc;
+
+const DEFAULT_BLOCK_SIZE: u32 = 8 * 1024;
+
+/// A builder for [`GenericByteViewArray`]
+///
+/// See [`Self::append_value`] for the allocation strategy
+pub struct GenericByteViewBuilder<T: ByteViewType + ?Sized> {
+ views_builder: BufferBuilder<u128>,
+ null_buffer_builder: NullBufferBuilder,
+ completed: Vec<Buffer>,
+ in_progress: Vec<u8>,
+ block_size: u32,
+ phantom: PhantomData<T>,
+}
+
+impl<T: ByteViewType + ?Sized> GenericByteViewBuilder<T> {
+ /// Creates a new [`GenericByteViewBuilder`].
+ pub fn new() -> Self {
+ Self::with_capacity(1024)
+ }
+
+ /// Creates a new [`GenericByteViewBuilder`] with space for `capacity` string values.
+ pub fn with_capacity(capacity: usize) -> Self {
+ Self {
+ views_builder: BufferBuilder::new(capacity),
+ null_buffer_builder: NullBufferBuilder::new(capacity),
+ completed: vec![],
+ in_progress: vec![],
+ block_size: DEFAULT_BLOCK_SIZE,
+ phantom: Default::default(),
+ }
+ }
+
+ /// Override the size of buffers to allocate for holding string data
+ pub fn with_block_size(self, block_size: u32) -> Self {
+ Self { block_size, ..self }
+ }
+
+ /// Appends a value into the builder
+ ///
+ /// # Panics
+ ///
+ /// Panics if
+ /// - String buffer count exceeds `u32::MAX`
+ /// - String length exceeds `u32::MAX`
+ #[inline]
+ pub fn append_value(&mut self, value: impl AsRef<T::Native>) {
+ let v: &[u8] = value.as_ref().as_ref();
+ let length: u32 = v.len().try_into().unwrap();
+ if length <= 12 {
+ let mut view_buffer = [0; 16];
+ view_buffer[0..4].copy_from_slice(&length.to_le_bytes());
+ view_buffer[4..4 + v.len()].copy_from_slice(v);
+ self.views_builder.append(u128::from_le_bytes(view_buffer));
+ self.null_buffer_builder.append_non_null();
+ return;
+ }
+
+ let required_cap = self.in_progress.len() + v.len();
+ if self.in_progress.capacity() < required_cap {
+ let in_progress = Vec::with_capacity(v.len().max(self.block_size as usize));
+ let flushed = std::mem::replace(&mut self.in_progress, in_progress);
+ if !flushed.is_empty() {
+ assert!(self.completed.len() < u32::MAX as usize);
+ self.completed.push(flushed.into());
+ }
+ };
+ let offset = self.in_progress.len() as u32;
+ self.in_progress.extend_from_slice(v);
+
+ let view = ByteView {
+ length,
+ prefix: u32::from_le_bytes(v[0..4].try_into().unwrap()),
+ buffer_index: self.completed.len() as u32,
+ offset,
+ };
+ self.views_builder.append(view.into());
+ self.null_buffer_builder.append_non_null();
+ }
+
+ /// Append an `Option` value into the builder
+ #[inline]
+ pub fn append_option(&mut self, value: Option<impl AsRef<T::Native>>) {
+ match value {
+ None => self.append_null(),
+ Some(v) => self.append_value(v),
+ };
+ }
+
+ /// Append a null value into the builder
+ #[inline]
+ pub fn append_null(&mut self) {
+ self.null_buffer_builder.append_null();
+ self.views_builder.append(0);
+ }
+
+ /// Builds the [`GenericByteViewArray`] and reset this builder
+ pub fn finish(&mut self) -> GenericByteViewArray<T> {
+ let mut completed = std::mem::take(&mut self.completed);
+ if !self.in_progress.is_empty() {
+ completed.push(std::mem::take(&mut self.in_progress).into());
+ }
+ let len = self.views_builder.len();
+ let views = ScalarBuffer::new(self.views_builder.finish(), 0, len);
+ let nulls = self.null_buffer_builder.finish();
+ // SAFETY: valid by construction
+ unsafe { GenericByteViewArray::new_unchecked(views, completed, nulls) }
+ }
+
+ /// Builds the [`GenericByteViewArray`] without resetting the builder
+ pub fn finish_cloned(&self) -> GenericByteViewArray<T> {
+ let mut completed = self.completed.clone();
+ if !self.in_progress.is_empty() {
+ completed.push(Buffer::from_slice_ref(&self.in_progress));
+ }
+ let len = self.views_builder.len();
+ let views = Buffer::from_slice_ref(self.views_builder.as_slice());
+ let views = ScalarBuffer::new(views, 0, len);
+ let nulls = self.null_buffer_builder.finish_cloned();
+ // SAFETY: valid by construction
+ unsafe { GenericByteViewArray::new_unchecked(views, completed, nulls) }
+ }
+}
+
+impl<T: ByteViewType + ?Sized> Default for GenericByteViewBuilder<T> {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl<T: ByteViewType + ?Sized> std::fmt::Debug for GenericByteViewBuilder<T> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}ViewBuilder", T::PREFIX)?;
+ f.debug_struct("")
+ .field("views_builder", &self.views_builder)
+ .field("in_progress", &self.in_progress)
+ .field("completed", &self.completed)
+ .field("null_buffer_builder", &self.null_buffer_builder)
+ .finish()
+ }
+}
+
+impl<T: ByteViewType + ?Sized> ArrayBuilder for GenericByteViewBuilder<T> {
+ fn len(&self) -> usize {
+ self.null_buffer_builder.len()
+ }
+
+ fn finish(&mut self) -> ArrayRef {
+ Arc::new(self.finish())
+ }
+
+ fn finish_cloned(&self) -> ArrayRef {
+ Arc::new(self.finish_cloned())
+ }
+
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn as_any_mut(&mut self) -> &mut dyn Any {
+ self
+ }
+
+ fn into_box_any(self: Box<Self>) -> Box<dyn Any> {
+ self
+ }
+}
+
+impl<T: ByteViewType + ?Sized, V: AsRef<T::Native>> Extend<Option<V>>
+ for GenericByteViewBuilder<T>
+{
+ #[inline]
+ fn extend<I: IntoIterator<Item = Option<V>>>(&mut self, iter: I) {
+ for v in iter {
+ self.append_option(v)
+ }
+ }
+}
+
+/// Array builder for [`StringViewArray`][crate::StringViewArray]
+///
+/// Values can be appended using [`GenericByteViewBuilder::append_value`], and nulls with
+/// [`GenericByteViewBuilder::append_null`] as normal.
+pub type StringViewBuilder = GenericByteViewBuilder<StringViewType>;
+
+/// Array builder for [`BinaryViewArray`][crate::BinaryViewArray]
+///
+/// Values can be appended using [`GenericByteViewBuilder::append_value`], and nulls with
+/// [`GenericByteViewBuilder::append_null`] as normal.
+pub type BinaryViewBuilder = GenericByteViewBuilder<BinaryViewType>;
diff --git a/arrow-array/src/builder/mod.rs b/arrow-array/src/builder/mod.rs
index d33e565a868b..e4ab7ae4ba23 100644
--- a/arrow-array/src/builder/mod.rs
+++ b/arrow-array/src/builder/mod.rs
@@ -178,7 +178,10 @@ mod generic_bytes_dictionary_builder;
pub use generic_bytes_dictionary_builder::*;
mod generic_byte_run_builder;
pub use generic_byte_run_builder::*;
+mod generic_bytes_view_builder;
+pub use generic_bytes_view_builder::*;
mod union_builder;
+
pub use union_builder::*;
use crate::ArrayRef;
diff --git a/arrow-array/src/record_batch.rs b/arrow-array/src/record_batch.rs
index 314445bba617..c56b1fd308cf 100644
--- a/arrow-array/src/record_batch.rs
+++ b/arrow-array/src/record_batch.rs
@@ -626,7 +626,9 @@ mod tests {
use std::collections::HashMap;
use super::*;
- use crate::{BooleanArray, Int32Array, Int64Array, Int8Array, ListArray, StringArray};
+ use crate::{
+ BooleanArray, Int32Array, Int64Array, Int8Array, ListArray, StringArray, StringViewArray,
+ };
use arrow_buffer::{Buffer, ToByteSlice};
use arrow_data::{ArrayData, ArrayDataBuilder};
use arrow_schema::Fields;
@@ -646,6 +648,30 @@ mod tests {
check_batch(record_batch, 5)
}
+ #[test]
+ fn create_string_view_record_batch() {
+ let schema = Schema::new(vec![
+ Field::new("a", DataType::Int32, false),
+ Field::new("b", DataType::Utf8View, false),
+ ]);
+
+ let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
+ let b = StringViewArray::from(vec!["a", "b", "c", "d", "e"]);
+
+ let record_batch =
+ RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a), Arc::new(b)]).unwrap();
+
+ assert_eq!(5, record_batch.num_rows());
+ assert_eq!(2, record_batch.num_columns());
+ assert_eq!(&DataType::Int32, record_batch.schema().field(0).data_type());
+ assert_eq!(
+ &DataType::Utf8View,
+ record_batch.schema().field(1).data_type()
+ );
+ assert_eq!(5, record_batch.column(0).len());
+ assert_eq!(5, record_batch.column(1).len());
+ }
+
#[test]
fn byte_size_should_not_regress() {
let schema = Schema::new(vec![
diff --git a/arrow-array/src/types.rs b/arrow-array/src/types.rs
index 83a229c1da0d..e33f7bde7cba 100644
--- a/arrow-array/src/types.rs
+++ b/arrow-array/src/types.rs
@@ -25,12 +25,14 @@ use crate::timezone::Tz;
use crate::{ArrowNativeTypeOp, OffsetSizeTrait};
use arrow_buffer::{i256, Buffer, OffsetBuffer};
use arrow_data::decimal::{validate_decimal256_precision, validate_decimal_precision};
+use arrow_data::{validate_binary_view, validate_string_view};
use arrow_schema::{
ArrowError, DataType, IntervalUnit, TimeUnit, DECIMAL128_MAX_PRECISION, DECIMAL128_MAX_SCALE,
DECIMAL256_MAX_PRECISION, DECIMAL256_MAX_SCALE, DECIMAL_DEFAULT_SCALE,
};
use chrono::{Duration, NaiveDate, NaiveDateTime};
use half::f16;
+use std::fmt::Debug;
use std::marker::PhantomData;
use std::ops::{Add, Sub};
@@ -1544,6 +1546,72 @@ pub type BinaryType = GenericBinaryType<i32>;
/// An arrow binary array with i64 offsets
pub type LargeBinaryType = GenericBinaryType<i64>;
+mod byte_view {
+ use crate::types::{BinaryViewType, StringViewType};
+
+ pub trait Sealed: Send + Sync {}
+ impl Sealed for StringViewType {}
+ impl Sealed for BinaryViewType {}
+}
+
+/// A trait over the variable length bytes view array types
+pub trait ByteViewType: byte_view::Sealed + 'static + PartialEq + Send + Sync {
+ /// If element in array is utf8 encoded string.
+ const IS_UTF8: bool;
+
+ /// Datatype of array elements
+ const DATA_TYPE: DataType = if Self::IS_UTF8 {
+ DataType::Utf8View
+ } else {
+ DataType::BinaryView
+ };
+
+ /// "Binary" or "String", for use in displayed or error messages
+ const PREFIX: &'static str;
+
+ /// Type for representing its equivalent rust type i.e
+ /// Utf8Array will have native type has &str
+ /// BinaryArray will have type as [u8]
+ type Native: bytes::ByteArrayNativeType + AsRef<Self::Native> + AsRef<[u8]> + ?Sized;
+
+ /// Type for owned corresponding to `Native`
+ type Owned: Debug + Clone + Sync + Send + AsRef<Self::Native>;
+
+ /// Verifies that the provided buffers are valid for this array type
+ fn validate(views: &[u128], buffers: &[Buffer]) -> Result<(), ArrowError>;
+}
+
+/// [`ByteViewType`] for string arrays
+#[derive(PartialEq)]
+pub struct StringViewType {}
+
+impl ByteViewType for StringViewType {
+ const IS_UTF8: bool = true;
+ const PREFIX: &'static str = "String";
+
+ type Native = str;
+ type Owned = String;
+
+ fn validate(views: &[u128], buffers: &[Buffer]) -> Result<(), ArrowError> {
+ validate_string_view(views, buffers)
+ }
+}
+
+/// [`BinaryViewType`] for string arrays
+#[derive(PartialEq)]
+pub struct BinaryViewType {}
+
+impl ByteViewType for BinaryViewType {
+ const IS_UTF8: bool = false;
+ const PREFIX: &'static str = "Binary";
+ type Native = [u8];
+ type Owned = Vec<u8>;
+
+ fn validate(views: &[u128], buffers: &[Buffer]) -> Result<(), ArrowError> {
+ validate_binary_view(views, buffers)
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/arrow-buffer/src/native.rs b/arrow-buffer/src/native.rs
index 38074a8dc26c..5184d60ac1fd 100644
--- a/arrow-buffer/src/native.rs
+++ b/arrow-buffer/src/native.rs
@@ -149,6 +149,7 @@ native_integer!(u8);
native_integer!(u16);
native_integer!(u32);
native_integer!(u64);
+native_integer!(u128);
macro_rules! native_float {
($t:ty, $s:ident, $as_usize: expr, $i:ident, $usize_as: expr) => {
diff --git a/arrow-data/src/byte_view.rs b/arrow-data/src/byte_view.rs
new file mode 100644
index 000000000000..b8b1731ac60b
--- /dev/null
+++ b/arrow-data/src/byte_view.rs
@@ -0,0 +1,123 @@
+// 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.
+
+use arrow_buffer::Buffer;
+use arrow_schema::ArrowError;
+
+#[derive(Debug, Copy, Clone, Default)]
+#[repr(C)]
+pub struct ByteView {
+ /// The length of the string/bytes.
+ pub length: u32,
+ /// First 4 bytes of string/bytes data.
+ pub prefix: u32,
+ /// The buffer index.
+ pub buffer_index: u32,
+ /// The offset into the buffer.
+ pub offset: u32,
+}
+
+impl ByteView {
+ #[inline(always)]
+ pub fn as_u128(self) -> u128 {
+ (self.length as u128)
+ | ((self.prefix as u128) << 32)
+ | ((self.buffer_index as u128) << 64)
+ | ((self.offset as u128) << 96)
+ }
+}
+
+impl From<u128> for ByteView {
+ #[inline]
+ fn from(value: u128) -> Self {
+ Self {
+ length: value as u32,
+ prefix: (value >> 32) as u32,
+ buffer_index: (value >> 64) as u32,
+ offset: (value >> 96) as u32,
+ }
+ }
+}
+
+impl From<ByteView> for u128 {
+ #[inline]
+ fn from(value: ByteView) -> Self {
+ value.as_u128()
+ }
+}
+
+/// Validates the combination of `views` and `buffers` is a valid BinaryView
+pub fn validate_binary_view(views: &[u128], buffers: &[Buffer]) -> Result<(), ArrowError> {
+ validate_view_impl(views, buffers, |_, _| Ok(()))
+}
+
+/// Validates the combination of `views` and `buffers` is a valid StringView
+pub fn validate_string_view(views: &[u128], buffers: &[Buffer]) -> Result<(), ArrowError> {
+ validate_view_impl(views, buffers, |idx, b| {
+ std::str::from_utf8(b).map_err(|e| {
+ ArrowError::InvalidArgumentError(format!(
+ "Encountered non-UTF-8 data at index {idx}: {e}"
+ ))
+ })?;
+ Ok(())
+ })
+}
+
+fn validate_view_impl<F>(views: &[u128], buffers: &[Buffer], f: F) -> Result<(), ArrowError>
+where
+ F: Fn(usize, &[u8]) -> Result<(), ArrowError>,
+{
+ for (idx, v) in views.iter().enumerate() {
+ let len = *v as u32;
+ if len <= 12 {
+ if len < 12 && (v >> (32 + len * 8)) != 0 {
+ return Err(ArrowError::InvalidArgumentError(format!(
+ "View at index {idx} contained non-zero padding for string of length {len}",
+ )));
+ }
+ f(idx, &v.to_le_bytes()[4..4 + len as usize])?;
+ } else {
+ let view = ByteView::from(*v);
+ let data = buffers.get(view.buffer_index as usize).ok_or_else(|| {
+ ArrowError::InvalidArgumentError(format!(
+ "Invalid buffer index at {idx}: got index {} but only has {} buffers",
+ view.buffer_index,
+ buffers.len()
+ ))
+ })?;
+
+ let start = view.offset as usize;
+ let end = start + len as usize;
+ let b = data.get(start..end).ok_or_else(|| {
+ ArrowError::InvalidArgumentError(format!(
+ "Invalid buffer slice at {idx}: got {start}..{end} but buffer {} has length {}",
+ view.buffer_index,
+ data.len()
+ ))
+ })?;
+
+ if !b.starts_with(&view.prefix.to_le_bytes()) {
+ return Err(ArrowError::InvalidArgumentError(
+ "Mismatch between embedded prefix and data".to_string(),
+ ));
+ }
+
+ f(idx, b)?;
+ }
+ }
+ Ok(())
+}
diff --git a/arrow-data/src/data.rs b/arrow-data/src/data.rs
index 16637570f520..e227b168eee5 100644
--- a/arrow-data/src/data.rs
+++ b/arrow-data/src/data.rs
@@ -26,7 +26,7 @@ use std::mem;
use std::ops::Range;
use std::sync::Arc;
-use crate::equal;
+use crate::{equal, validate_binary_view, validate_string_view};
/// A collection of [`Buffer`]
#[doc(hidden)]
@@ -159,29 +159,6 @@ pub(crate) fn new_buffers(data_type: &DataType, capacity: usize) -> [MutableBuff
}
}
-/// Maps 2 [`MutableBuffer`]s into a vector of [Buffer]s whose size depends on `data_type`.
-#[inline]
-pub(crate) fn into_buffers(
- data_type: &DataType,
- buffer1: MutableBuffer,
- buffer2: MutableBuffer,
-) -> Vec<Buffer> {
- match data_type {
- DataType::Null | DataType::Struct(_) | DataType::FixedSizeList(_, _) => vec![],
- DataType::Utf8 | DataType::Binary | DataType::LargeUtf8 | DataType::LargeBinary => {
- vec![buffer1.into(), buffer2.into()]
- }
- DataType::Union(_, mode) => {
- match mode {
- // Based on Union's DataTypeLayout
- UnionMode::Sparse => vec![buffer1.into()],
- UnionMode::Dense => vec![buffer1.into(), buffer2.into()],
- }
- }
- _ => vec![buffer1.into()],
- }
-}
-
/// A generic representation of Arrow array data which encapsulates common attributes and
/// operations for Arrow array. Specific operations for different arrays types (e.g.,
/// primitive, list, struct) are implemented in `Array`.
@@ -745,7 +722,10 @@ impl ArrayData {
)));
}
- if self.buffers.len() != layout.buffers.len() {
+ // Check data buffers length for view types and other types
+ if self.buffers.len() < layout.buffers.len()
+ || (!layout.variadic && self.buffers.len() != layout.buffers.len())
+ {
return Err(ArrowError::InvalidArgumentError(format!(
"Expected {} buffers in array of type {:?}, got {}",
layout.buffers.len(),
@@ -1240,6 +1220,14 @@ impl ArrayData {
DataType::LargeUtf8 => self.validate_utf8::<i64>(),
DataType::Binary => self.validate_offsets_full::<i32>(self.buffers[1].len()),
DataType::LargeBinary => self.validate_offsets_full::<i64>(self.buffers[1].len()),
+ DataType::BinaryView => {
+ let views = self.typed_buffer::<u128>(0, self.len)?;
+ validate_binary_view(views, &self.buffers[1..])
+ }
+ DataType::Utf8View => {
+ let views = self.typed_buffer::<u128>(0, self.len)?;
+ validate_string_view(views, &self.buffers[1..])
+ }
DataType::List(_) | DataType::Map(_, _) => {
let child = &self.child_data[0];
self.validate_offsets_full::<i32>(child.len)
@@ -1511,10 +1499,12 @@ pub fn layout(data_type: &DataType) -> DataTypeLayout {
DataType::Null => DataTypeLayout {
buffers: vec![],
can_contain_null_mask: false,
+ variadic: false,
},
DataType::Boolean => DataTypeLayout {
buffers: vec![BufferSpec::BitMap],
can_contain_null_mask: true,
+ variadic: false,
},
DataType::Int8 => DataTypeLayout::new_fixed_width::<i8>(),
DataType::Int16 => DataTypeLayout::new_fixed_width::<i16>(),
@@ -1546,15 +1536,14 @@ pub fn layout(data_type: &DataType) -> DataTypeLayout {
DataTypeLayout {
buffers: vec![spec],
can_contain_null_mask: true,
+ variadic: false,
}
}
DataType::Binary => DataTypeLayout::new_binary::<i32>(),
DataType::LargeBinary => DataTypeLayout::new_binary::<i64>(),
DataType::Utf8 => DataTypeLayout::new_binary::<i32>(),
DataType::LargeUtf8 => DataTypeLayout::new_binary::<i64>(),
- DataType::BinaryView | DataType::Utf8View => {
- unimplemented!("BinaryView/Utf8View not implemented")
- }
+ DataType::BinaryView | DataType::Utf8View => DataTypeLayout::new_view(),
DataType::FixedSizeList(_, _) => DataTypeLayout::new_empty(), // all in child data
DataType::List(_) => DataTypeLayout::new_fixed_width::<i32>(),
DataType::ListView(_) | DataType::LargeListView(_) => {
@@ -1586,6 +1575,7 @@ pub fn layout(data_type: &DataType) -> DataTypeLayout {
}
},
can_contain_null_mask: false,
+ variadic: false,
}
}
DataType::Dictionary(key_type, _value_type) => layout(key_type),
@@ -1601,6 +1591,11 @@ pub struct DataTypeLayout {
/// Can contain a null bitmask
pub can_contain_null_mask: bool,
+
+ /// This field only applies to the view type [`DataType::BinaryView`] and [`DataType::Utf8View`]
+ /// If `variadic` is true, the number of buffers expected is only lower-bounded by
+ /// buffers.len(). Buffers that exceed the lower bound are legal.
+ pub variadic: bool,
}
impl DataTypeLayout {
@@ -1612,6 +1607,7 @@ impl DataTypeLayout {
alignment: mem::align_of::<T>(),
}],
can_contain_null_mask: true,
+ variadic: false,
}
}
@@ -1622,6 +1618,7 @@ impl DataTypeLayout {
Self {
buffers: vec![],
can_contain_null_mask: true,
+ variadic: false,
}
}
@@ -1640,6 +1637,19 @@ impl DataTypeLayout {
BufferSpec::VariableWidth,
],
can_contain_null_mask: true,
+ variadic: false,
+ }
+ }
+
+ /// Describes a view type
+ pub fn new_view() -> Self {
+ Self {
+ buffers: vec![BufferSpec::FixedWidth {
+ byte_width: mem::size_of::<u128>(),
+ alignment: mem::align_of::<u128>(),
+ }],
+ can_contain_null_mask: true,
+ variadic: true,
}
}
}
@@ -1845,7 +1855,7 @@ impl From<ArrayData> for ArrayDataBuilder {
#[cfg(test)]
mod tests {
use super::*;
- use arrow_schema::{Field, UnionFields};
+ use arrow_schema::Field;
// See arrow/tests/array_data_validation.rs for test of array validation
@@ -2093,23 +2103,6 @@ mod tests {
assert!(!contains_nulls(Some(&buffer), 0, 0));
}
- #[test]
- fn test_into_buffers() {
- let data_types = vec![
- DataType::Union(UnionFields::empty(), UnionMode::Dense),
- DataType::Union(UnionFields::empty(), UnionMode::Sparse),
- ];
-
- for data_type in data_types {
- let buffers = new_buffers(&data_type, 0);
- let [buffer1, buffer2] = buffers;
- let buffers = into_buffers(&data_type, buffer1, buffer2);
-
- let layout = layout(&data_type);
- assert_eq!(buffers.len(), layout.buffers.len());
- }
- }
-
#[test]
fn test_alignment() {
let buffer = Buffer::from_vec(vec![1_i32, 2_i32, 3_i32]);
diff --git a/arrow-data/src/equal/byte_view.rs b/arrow-data/src/equal/byte_view.rs
new file mode 100644
index 000000000000..def395125366
--- /dev/null
+++ b/arrow-data/src/equal/byte_view.rs
@@ -0,0 +1,74 @@
+// 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.
+
+use crate::{ArrayData, ByteView};
+
+pub(super) fn byte_view_equal(
+ lhs: &ArrayData,
+ rhs: &ArrayData,
+ lhs_start: usize,
+ rhs_start: usize,
+ len: usize,
+) -> bool {
+ let lhs_views = &lhs.buffer::<u128>(0)[lhs_start..lhs_start + len];
+ let lhs_buffers = &lhs.buffers()[1..];
+ let rhs_views = &rhs.buffer::<u128>(0)[rhs_start..rhs_start + len];
+ let rhs_buffers = &rhs.buffers()[1..];
+
+ for (idx, (l, r)) in lhs_views.iter().zip(rhs_views).enumerate() {
+ // Only checking one null mask here because by the time the control flow reaches
+ // this point, the equality of the two masks would have already been verified.
+ if lhs.is_null(idx) {
+ continue;
+ }
+
+ let l_len_prefix = *l as u64;
+ let r_len_prefix = *r as u64;
+ // short-circuit, check length and prefix
+ if l_len_prefix != r_len_prefix {
+ return false;
+ }
+
+ let len = l_len_prefix as u32;
+ // for inline storage, only need check view
+ if len <= 12 {
+ if l != r {
+ return false;
+ }
+ continue;
+ }
+
+ // check buffers
+ let l_view = ByteView::from(*l);
+ let r_view = ByteView::from(*r);
+
+ let l_buffer = &lhs_buffers[l_view.buffer_index as usize];
+ let r_buffer = &rhs_buffers[r_view.buffer_index as usize];
+
+ // prefixes are already known to be equal; skip checking them
+ let len = len as usize - 4;
+ let l_offset = l_view.offset as usize + 4;
+ let r_offset = r_view.offset as usize + 4;
+ if l_buffer[l_offset..l_offset + len] != r_buffer[r_offset..r_offset + len] {
+ return false;
+ }
+ }
+ true
+}
+
+#[cfg(test)]
+mod tests {}
diff --git a/arrow-data/src/equal/mod.rs b/arrow-data/src/equal/mod.rs
index 0987fd4c5637..dba6a0186a56 100644
--- a/arrow-data/src/equal/mod.rs
+++ b/arrow-data/src/equal/mod.rs
@@ -25,6 +25,7 @@ use arrow_schema::{DataType, IntervalUnit};
use half::f16;
mod boolean;
+mod byte_view;
mod dictionary;
mod fixed_binary;
mod fixed_list;
@@ -41,6 +42,7 @@ mod variable_size;
// For this reason, they are not exposed and are instead used
// to build the generic functions below (`equal_range` and `equal`).
use boolean::boolean_equal;
+use byte_view::byte_view_equal;
use dictionary::dictionary_equal;
use fixed_binary::fixed_binary_equal;
use fixed_list::fixed_list_equal;
@@ -97,7 +99,7 @@ fn equal_values(
}
DataType::FixedSizeBinary(_) => fixed_binary_equal(lhs, rhs, lhs_start, rhs_start, len),
DataType::BinaryView | DataType::Utf8View => {
- unimplemented!("BinaryView/Utf8View not yet implemented")
+ byte_view_equal(lhs, rhs, lhs_start, rhs_start, len)
}
DataType::List(_) => list_equal::<i32>(lhs, rhs, lhs_start, rhs_start, len),
DataType::ListView(_) | DataType::LargeListView(_) => {
diff --git a/arrow-data/src/lib.rs b/arrow-data/src/lib.rs
index cfa0dba66c35..59a049fe96cf 100644
--- a/arrow-data/src/lib.rs
+++ b/arrow-data/src/lib.rs
@@ -30,3 +30,6 @@ pub mod decimal;
#[cfg(feature = "ffi")]
pub mod ffi;
+
+mod byte_view;
+pub use byte_view::*;
diff --git a/arrow-data/src/transform/mod.rs b/arrow-data/src/transform/mod.rs
index b14f6e771033..b0d9475afcd6 100644
--- a/arrow-data/src/transform/mod.rs
+++ b/arrow-data/src/transform/mod.rs
@@ -15,13 +15,10 @@
// specific language governing permissions and limitations
// under the License.
-use super::{
- data::{into_buffers, new_buffers},
- ArrayData, ArrayDataBuilder,
-};
+use super::{data::new_buffers, ArrayData, ArrayDataBuilder, ByteView};
use crate::bit_mask::set_bits;
use arrow_buffer::buffer::{BooleanBuffer, NullBuffer};
-use arrow_buffer::{bit_util, i256, ArrowNativeType, MutableBuffer};
+use arrow_buffer::{bit_util, i256, ArrowNativeType, Buffer, MutableBuffer};
use arrow_schema::{ArrowError, DataType, IntervalUnit, UnionMode};
use half::f16;
use num::Integer;
@@ -68,36 +65,6 @@ impl<'a> _MutableArrayData<'a> {
.as_mut()
.expect("MutableArrayData not nullable")
}
-
- fn freeze(self, dictionary: Option<ArrayData>) -> ArrayDataBuilder {
- let buffers = into_buffers(&self.data_type, self.buffer1, self.buffer2);
-
- let child_data = match self.data_type {
- DataType::Dictionary(_, _) => vec![dictionary.unwrap()],
- _ => {
- let mut child_data = Vec::with_capacity(self.child_data.len());
- for child in self.child_data {
- child_data.push(child.freeze());
- }
- child_data
- }
- };
-
- let nulls = self
- .null_buffer
- .map(|nulls| {
- let bools = BooleanBuffer::new(nulls.into(), 0, self.len);
- unsafe { NullBuffer::new_unchecked(bools, self.null_count) }
- })
- .filter(|n| n.null_count() > 0);
-
- ArrayDataBuilder::new(self.data_type)
- .offset(0)
- .len(self.len)
- .nulls(nulls)
- .buffers(buffers)
- .child_data(child_data)
- }
}
fn build_extend_null_bits(array: &ArrayData, use_nulls: bool) -> ExtendNullBits {
@@ -138,26 +105,32 @@ fn build_extend_null_bits(array: &ArrayData, use_nulls: bool) -> ExtendNullBits
pub struct MutableArrayData<'a> {
#[allow(dead_code)]
arrays: Vec<&'a ArrayData>,
- // The attributes in [_MutableArrayData] cannot be in [MutableArrayData] due to
- // mutability invariants (interior mutability):
- // [MutableArrayData] contains a function that can only mutate [_MutableArrayData], not
- // [MutableArrayData] itself
+ /// The attributes in [_MutableArrayData] cannot be in [MutableArrayData] due to
+ /// mutability invariants (interior mutability):
+ /// [MutableArrayData] contains a function that can only mutate [_MutableArrayData], not
+ /// [MutableArrayData] itself
data: _MutableArrayData<'a>,
- // the child data of the `Array` in Dictionary arrays.
- // This is not stored in `MutableArrayData` because these values constant and only needed
- // at the end, when freezing [_MutableArrayData].
+ /// the child data of the `Array` in Dictionary arrays.
+ /// This is not stored in `MutableArrayData` because these values constant and only needed
+ /// at the end, when freezing [_MutableArrayData].
dictionary: Option<ArrayData>,
- // function used to extend values from arrays. This function's lifetime is bound to the array
- // because it reads values from it.
+ /// Variadic data buffers referenced by views
+ /// This is not stored in `MutableArrayData` because these values constant and only needed
+ /// at the end, when freezing [_MutableArrayData]
+ variadic_data_buffers: Vec<Buffer>,
+
+ /// function used to extend values from arrays. This function's lifetime is bound to the array
+ /// because it reads values from it.
extend_values: Vec<Extend<'a>>,
- // function used to extend nulls from arrays. This function's lifetime is bound to the array
- // because it reads nulls from it.
+
+ /// function used to extend nulls from arrays. This function's lifetime is bound to the array
+ /// because it reads nulls from it.
extend_null_bits: Vec<ExtendNullBits<'a>>,
- // function used to extend nulls.
- // this is independent of the arrays and therefore has no lifetime.
+ /// function used to extend nulls.
+ /// this is independent of the arrays and therefore has no lifetime.
extend_nulls: ExtendNulls,
}
@@ -197,6 +170,26 @@ fn build_extend_dictionary(array: &ArrayData, offset: usize, max: usize) -> Opti
}
}
+/// Builds an extend that adds `buffer_offset` to any buffer indices encountered
+fn build_extend_view(array: &ArrayData, buffer_offset: u32) -> Extend {
+ let views = array.buffer::<u128>(0);
+ Box::new(
+ move |mutable: &mut _MutableArrayData, _, start: usize, len: usize| {
+ mutable
+ .buffer1
+ .extend(views[start..start + len].iter().map(|v| {
+ let len = *v as u32;
+ if len <= 12 {
+ return *v; // Stored inline
+ }
+ let mut view = ByteView::from(*v);
+ view.buffer_index += buffer_offset;
+ view.into()
+ }))
+ },
+ )
+}
+
fn build_extend(array: &ArrayData) -> Extend {
match array.data_type() {
DataType::Null => null::build_extend(array),
@@ -224,9 +217,7 @@ fn build_extend(array: &ArrayData) -> Extend {
DataType::Decimal256(_, _) => primitive::build_extend::<i256>(array),
DataType::Utf8 | DataType::Binary => variable_size::build_extend::<i32>(array),
DataType::LargeUtf8 | DataType::LargeBinary => variable_size::build_extend::<i64>(array),
- DataType::BinaryView | DataType::Utf8View => {
- unimplemented!("BinaryView/Utf8View not implemented")
- }
+ DataType::BinaryView | DataType::Utf8View => unreachable!("should use build_extend_view"),
DataType::Map(_, _) | DataType::List(_) => list::build_extend::<i32>(array),
DataType::ListView(_) | DataType::LargeListView(_) => {
unimplemented!("ListView/LargeListView not implemented")
@@ -272,9 +263,7 @@ fn build_extend_nulls(data_type: &DataType) -> ExtendNulls {
DataType::Decimal256(_, _) => primitive::extend_nulls::<i256>,
DataType::Utf8 | DataType::Binary => variable_size::extend_nulls::<i32>,
DataType::LargeUtf8 | DataType::LargeBinary => variable_size::extend_nulls::<i64>,
- DataType::BinaryView | DataType::Utf8View => {
- unimplemented!("BinaryView/Utf8View not implemented")
- }
+ DataType::BinaryView | DataType::Utf8View => primitive::extend_nulls::<u128>,
DataType::Map(_, _) | DataType::List(_) => list::extend_nulls::<i32>,
DataType::ListView(_) | DataType::LargeListView(_) => {
unimplemented!("ListView/LargeListView not implemented")
@@ -429,11 +418,10 @@ impl<'a> MutableArrayData<'a> {
| DataType::Binary
| DataType::LargeUtf8
| DataType::LargeBinary
+ | DataType::BinaryView
+ | DataType::Utf8View
| DataType::Interval(_)
| DataType::FixedSizeBinary(_) => vec![],
- DataType::BinaryView | DataType::Utf8View => {
- unimplemented!("BinaryView/Utf8View not implemented")
- }
DataType::ListView(_) | DataType::LargeListView(_) => {
unimplemented!("ListView/LargeListView not implemented")
}
@@ -566,6 +554,15 @@ impl<'a> MutableArrayData<'a> {
_ => (None, false),
};
+ let variadic_data_buffers = match &data_type {
+ DataType::BinaryView | DataType::Utf8View => arrays
+ .iter()
+ .flat_map(|x| x.buffers().iter().skip(1))
+ .map(Buffer::clone)
+ .collect(),
+ _ => vec![],
+ };
+
let extend_nulls = build_extend_nulls(data_type);
let extend_null_bits = arrays
@@ -598,6 +595,20 @@ impl<'a> MutableArrayData<'a> {
extend_values.expect("MutableArrayData::new is infallible")
}
+ DataType::BinaryView | DataType::Utf8View => {
+ let mut next_offset = 0u32;
+ arrays
+ .iter()
+ .map(|arr| {
+ let num_data_buffers = (arr.buffers().len() - 1) as u32;
+ let offset = next_offset;
+ next_offset = next_offset
+ .checked_add(num_data_buffers)
+ .expect("view buffer index overflow");
+ build_extend_view(arr, offset)
+ })
+ .collect()
+ }
_ => arrays.iter().map(|array| build_extend(array)).collect(),
};
@@ -614,6 +625,7 @@ impl<'a> MutableArrayData<'a> {
arrays,
data,
dictionary,
+ variadic_data_buffers,
extend_values,
extend_null_bits,
extend_nulls,
@@ -673,13 +685,55 @@ impl<'a> MutableArrayData<'a> {
/// Creates a [ArrayData] from the pushed regions up to this point, consuming `self`.
pub fn freeze(self) -> ArrayData {
- unsafe { self.data.freeze(self.dictionary).build_unchecked() }
+ unsafe { self.into_builder().build_unchecked() }
}
/// Creates a [ArrayDataBuilder] from the pushed regions up to this point, consuming `self`.
/// This is useful for extending the default behavior of MutableArrayData.
pub fn into_builder(self) -> ArrayDataBuilder {
- self.data.freeze(self.dictionary)
+ let data = self.data;
+
+ let buffers = match data.data_type {
+ DataType::Null | DataType::Struct(_) | DataType::FixedSizeList(_, _) => {
+ vec![]
+ }
+ DataType::BinaryView | DataType::Utf8View => {
+ let mut b = self.variadic_data_buffers;
+ b.insert(0, data.buffer1.into());
+ b
+ }
+ DataType::Utf8 | DataType::Binary | DataType::LargeUtf8 | DataType::LargeBinary => {
+ vec![data.buffer1.into(), data.buffer2.into()]
+ }
+ DataType::Union(_, mode) => {
+ match mode {
+ // Based on Union's DataTypeLayout
+ UnionMode::Sparse => vec![data.buffer1.into()],
+ UnionMode::Dense => vec![data.buffer1.into(), data.buffer2.into()],
+ }
+ }
+ _ => vec![data.buffer1.into()],
+ };
+
+ let child_data = match data.data_type {
+ DataType::Dictionary(_, _) => vec![self.dictionary.unwrap()],
+ _ => data.child_data.into_iter().map(|x| x.freeze()).collect(),
+ };
+
+ let nulls = data
+ .null_buffer
+ .map(|nulls| {
+ let bools = BooleanBuffer::new(nulls.into(), 0, data.len);
+ unsafe { NullBuffer::new_unchecked(bools, data.null_count) }
+ })
+ .filter(|n| n.null_count() > 0);
+
+ ArrayDataBuilder::new(data.data_type)
+ .offset(0)
+ .len(data.len)
+ .nulls(nulls)
+ .buffers(buffers)
+ .child_data(child_data)
}
}
|
diff --git a/arrow/tests/array_equal.rs b/arrow/tests/array_equal.rs
index 9bd276428880..15011c547284 100644
--- a/arrow/tests/array_equal.rs
+++ b/arrow/tests/array_equal.rs
@@ -22,8 +22,8 @@ use arrow::array::{
StringArray, StringDictionaryBuilder, StructArray, UnionBuilder,
};
use arrow::datatypes::{Int16Type, Int32Type};
-use arrow_array::builder::{StringBuilder, StructBuilder};
-use arrow_array::{DictionaryArray, FixedSizeListArray};
+use arrow_array::builder::{StringBuilder, StringViewBuilder, StructBuilder};
+use arrow_array::{DictionaryArray, FixedSizeListArray, StringViewArray};
use arrow_buffer::{Buffer, ToByteSlice};
use arrow_data::{ArrayData, ArrayDataBuilder};
use arrow_schema::{DataType, Field, Fields};
@@ -307,6 +307,50 @@ fn test_fixed_size_binary_array() {
test_equal(&a, &b, true);
}
+#[test]
+fn test_string_view_equal() {
+ let a1 = StringViewArray::from(vec!["foo", "very long string over 12 bytes", "bar"]);
+ let a2 = StringViewArray::from(vec![
+ "a very long string over 12 bytes",
+ "foo",
+ "very long string over 12 bytes",
+ "bar",
+ ]);
+ test_equal(&a1, &a2.slice(1, 3), true);
+
+ let a1 = StringViewArray::from(vec!["foo", "very long string over 12 bytes", "bar"]);
+ let a2 = StringViewArray::from(vec!["foo", "very long string over 12 bytes", "bar"]);
+ test_equal(&a1, &a2, true);
+
+ let a1_s = a1.slice(1, 1);
+ let a2_s = a2.slice(1, 1);
+ test_equal(&a1_s, &a2_s, true);
+
+ let a1_s = a1.slice(2, 1);
+ let a2_s = a2.slice(0, 1);
+ test_equal(&a1_s, &a2_s, false);
+
+ // test will null value.
+ let a1 = StringViewArray::from(vec!["foo", "very long string over 12 bytes", "bar"]);
+ let a2 = {
+ let mut builder = StringViewBuilder::new();
+ builder.append_value("foo");
+ builder.append_null();
+ builder.append_option(Some("very long string over 12 bytes"));
+ builder.append_value("bar");
+ builder.finish()
+ };
+ test_equal(&a1, &a2, false);
+
+ let a1_s = a1.slice(1, 2);
+ let a2_s = a2.slice(1, 3);
+ test_equal(&a1_s, &a2_s, false);
+
+ let a1_s = a1.slice(1, 2);
+ let a2_s = a2.slice(2, 2);
+ test_equal(&a1_s, &a2_s, true);
+}
+
#[test]
fn test_string_offset() {
let a = StringArray::from(vec![Some("a"), None, Some("b")]);
diff --git a/arrow/tests/array_transform.rs b/arrow/tests/array_transform.rs
index 5a267c876d6a..83d3003a0586 100644
--- a/arrow/tests/array_transform.rs
+++ b/arrow/tests/array_transform.rs
@@ -22,6 +22,7 @@ use arrow::array::{
UnionArray,
};
use arrow::datatypes::Int16Type;
+use arrow_array::StringViewArray;
use arrow_buffer::Buffer;
use arrow_data::transform::MutableArrayData;
use arrow_data::ArrayData;
@@ -1027,6 +1028,44 @@ fn test_extend_nulls_panic() {
mutable.extend_nulls(2);
}
+#[test]
+fn test_string_view() {
+ let a1 =
+ StringViewArray::from(vec!["foo", "very long string over 12 bytes", "bar"]).into_data();
+ let a2 = StringViewArray::from_iter(vec![
+ Some("bar"),
+ None,
+ Some("long string also over 12 bytes"),
+ ])
+ .into_data();
+
+ a1.validate_full().unwrap();
+ a2.validate_full().unwrap();
+
+ let mut mutable = MutableArrayData::new(vec![&a1, &a2], false, 4);
+ mutable.extend(1, 0, 1);
+ mutable.extend(0, 1, 2);
+ mutable.extend(0, 0, 1);
+ mutable.extend(1, 2, 3);
+
+ let array = StringViewArray::from(mutable.freeze());
+ assert_eq!(array.data_buffers().len(), 2);
+ // Should have reused data buffers
+ assert_eq!(array.data_buffers()[0].as_ptr(), a1.buffers()[1].as_ptr());
+ assert_eq!(array.data_buffers()[1].as_ptr(), a2.buffers()[1].as_ptr());
+
+ let v = array.iter().collect::<Vec<_>>();
+ assert_eq!(
+ v,
+ vec![
+ Some("bar"),
+ Some("very long string over 12 bytes"),
+ Some("foo"),
+ Some("long string also over 12 bytes")
+ ]
+ )
+}
+
#[test]
#[should_panic(expected = "Arrays with inconsistent types passed to MutableArrayData")]
fn test_mixed_types() {
|
Add `StringViewArray` implementation and layout and basic construction + tests
This is part of the larger project to implement `StringViewArray` -- see https://github.com/apache/arrow-rs/issues/5374
After https://github.com/apache/arrow-rs/issues/5468 we will next need to implement `StringViewArray`
For inspiration I think you can look at https://github.com/apache/arrow-rs/pull/4585
(specifically `arrow-array/src/array/byte_view_array.rs` https://github.com/apache/arrow-rs/pull/4585/files#diff-160ecd8082d5d28081f01cdb08a898cb8f49b17149c7118bf96746ddaae24b4f)
Basic tasks:
1. Create`Utf8ViewArray` and implement `Array` for it. This should follow the outline from https://github.com/apache/arrow-rs/pull/4585 and implement a similar API to `StringArray` https://docs.rs/arrow/latest/arrow/array/type.StringArray.html
2. Add documentaton for new array, with documentation
3. Examples of constructing the array in docs
4. Tests for basic creation APIs (like `new()` and `new_unchecked`, `value()`, `is_null()` etc).
Potentially: implement pretty printing for `Utf8ViewArray` via [`ArrayFormatter`](https://docs.rs/arrow/latest/arrow/util/display/struct.ArrayFormatter.html), though this could be done as a separate ticket / PR.
|
Please assign me, thx :)
I plan to merge https://github.com/apache/arrow-rs/pull/5470 later today -- I don't expect substantial changes, so if you would like to start on this issue, you could probably make a branch from https://github.com/apache/arrow-rs/pull/5470 and rebase once we merge that
Noce that https://github.com/apache/arrow-rs/pull/5470 is merged I think this ticket is unblocked and ready to go
Note I think this ticket will be somewhat of a bottleneck. Once it is done I think we can start implementing other features in parallel (like IPC support, cast, filter, etc)
|
2024-03-07T10:10:53Z
|
50.0
|
82fc0df73ab97e239ce5c748a05c57ce582f3d5d
|
apache/arrow-rs
| 5,477
|
apache__arrow-rs-5477
|
[
"5476"
] |
c6ba0f764a9142b74c9070db269de04d2701d112
|
diff --git a/arrow-arith/src/aggregate.rs b/arrow-arith/src/aggregate.rs
index 20ff0711d735..190685ff9df7 100644
--- a/arrow-arith/src/aggregate.rs
+++ b/arrow-arith/src/aggregate.rs
@@ -22,7 +22,6 @@ use arrow_array::iterator::ArrayIter;
use arrow_array::*;
use arrow_buffer::{ArrowNativeType, NullBuffer};
use arrow_data::bit_iterator::try_for_each_valid_idx;
-use arrow_schema::ArrowError;
use arrow_schema::*;
use std::borrow::BorrowMut;
use std::ops::{BitAnd, BitOr, BitXor};
@@ -729,7 +728,6 @@ where
mod tests {
use super::*;
use arrow_array::types::*;
- use arrow_buffer::NullBuffer;
use std::sync::Arc;
#[test]
diff --git a/arrow-array/src/array/dictionary_array.rs b/arrow-array/src/array/dictionary_array.rs
index 1f4d83b1c5d0..abfae2112aac 100644
--- a/arrow-array/src/array/dictionary_array.rs
+++ b/arrow-array/src/array/dictionary_array.rs
@@ -20,8 +20,7 @@ use crate::cast::AsArray;
use crate::iterator::ArrayIter;
use crate::types::*;
use crate::{
- make_array, Array, ArrayAccessor, ArrayRef, ArrowNativeTypeOp, ArrowPrimitiveType,
- PrimitiveArray, StringArray,
+ make_array, Array, ArrayAccessor, ArrayRef, ArrowNativeTypeOp, PrimitiveArray, StringArray,
};
use arrow_buffer::bit_util::set_bit;
use arrow_buffer::buffer::NullBuffer;
@@ -1007,12 +1006,9 @@ impl<K: ArrowDictionaryKeyType> AnyDictionaryArray for DictionaryArray<K> {
#[cfg(test)]
mod tests {
use super::*;
- use crate::builder::PrimitiveDictionaryBuilder;
use crate::cast::as_dictionary_array;
- use crate::types::{Int32Type, Int8Type, UInt32Type, UInt8Type};
use crate::{Int16Array, Int32Array, Int8Array};
use arrow_buffer::{Buffer, ToByteSlice};
- use std::sync::Arc;
#[test]
fn test_dictionary_array() {
diff --git a/arrow-array/src/array/fixed_size_binary_array.rs b/arrow-array/src/array/fixed_size_binary_array.rs
index d89bbd5ad084..49cecb50e2db 100644
--- a/arrow-array/src/array/fixed_size_binary_array.rs
+++ b/arrow-array/src/array/fixed_size_binary_array.rs
@@ -636,7 +636,6 @@ impl<'a> IntoIterator for &'a FixedSizeBinaryArray {
mod tests {
use crate::RecordBatch;
use arrow_schema::{Field, Schema};
- use std::sync::Arc;
use super::*;
diff --git a/arrow-array/src/array/map_array.rs b/arrow-array/src/array/map_array.rs
index bde7fdd5a953..ed22ba1d8a37 100644
--- a/arrow-array/src/array/map_array.rs
+++ b/arrow-array/src/array/map_array.rs
@@ -441,7 +441,6 @@ mod tests {
use crate::types::UInt32Type;
use crate::{Int32Array, UInt32Array};
use arrow_schema::Fields;
- use std::sync::Arc;
use super::*;
diff --git a/arrow-array/src/array/primitive_array.rs b/arrow-array/src/array/primitive_array.rs
index 03a48609fbab..19ae10fdeb7f 100644
--- a/arrow-array/src/array/primitive_array.rs
+++ b/arrow-array/src/array/primitive_array.rs
@@ -1501,9 +1501,8 @@ mod tests {
use super::*;
use crate::builder::{Decimal128Builder, Decimal256Builder};
use crate::cast::downcast_array;
- use crate::{ArrayRef, BooleanArray};
+ use crate::BooleanArray;
use arrow_schema::TimeUnit;
- use std::sync::Arc;
#[test]
fn test_primitive_array_from_vec() {
diff --git a/arrow-array/src/array/run_array.rs b/arrow-array/src/array/run_array.rs
index 4877f9f850a3..aa8bb259a0eb 100644
--- a/arrow-array/src/array/run_array.rs
+++ b/arrow-array/src/array/run_array.rs
@@ -654,8 +654,6 @@ where
#[cfg(test)]
mod tests {
- use std::sync::Arc;
-
use rand::seq::SliceRandom;
use rand::thread_rng;
use rand::Rng;
@@ -663,8 +661,8 @@ mod tests {
use super::*;
use crate::builder::PrimitiveRunBuilder;
use crate::cast::AsArray;
- use crate::types::{Int16Type, Int32Type, Int8Type, UInt32Type};
- use crate::{Array, Int32Array, StringArray};
+ use crate::types::{Int8Type, UInt32Type};
+ use crate::{Int32Array, StringArray};
fn build_input_array(size: usize) -> Vec<Option<i32>> {
// The input array is created by shuffling and repeating
diff --git a/arrow-array/src/array/struct_array.rs b/arrow-array/src/array/struct_array.rs
index 699da28cf7a3..ae292944e37b 100644
--- a/arrow-array/src/array/struct_array.rs
+++ b/arrow-array/src/array/struct_array.rs
@@ -464,7 +464,6 @@ mod tests {
use crate::{BooleanArray, Float32Array, Float64Array, Int32Array, Int64Array, StringArray};
use arrow_buffer::ToByteSlice;
- use std::sync::Arc;
#[test]
fn test_struct_array_builder() {
diff --git a/arrow-array/src/array/union_array.rs b/arrow-array/src/array/union_array.rs
index 63e927fd08ab..e3e637247537 100644
--- a/arrow-array/src/array/union_array.rs
+++ b/arrow-array/src/array/union_array.rs
@@ -511,7 +511,6 @@ mod tests {
use crate::RecordBatch;
use crate::{Float64Array, Int32Array, Int64Array, StringArray};
use arrow_schema::Schema;
- use std::sync::Arc;
#[test]
fn test_dense_i32() {
diff --git a/arrow-array/src/builder/boolean_builder.rs b/arrow-array/src/builder/boolean_builder.rs
index 7e59d940a50e..a4bda89d52e0 100644
--- a/arrow-array/src/builder/boolean_builder.rs
+++ b/arrow-array/src/builder/boolean_builder.rs
@@ -217,7 +217,6 @@ impl Extend<Option<bool>> for BooleanBuilder {
mod tests {
use super::*;
use crate::Array;
- use arrow_buffer::Buffer;
#[test]
fn test_boolean_array_builder() {
diff --git a/arrow-array/src/builder/buffer_builder.rs b/arrow-array/src/builder/buffer_builder.rs
index 2b66a8187fa9..ab67669febb8 100644
--- a/arrow-array/src/builder/buffer_builder.rs
+++ b/arrow-array/src/builder/buffer_builder.rs
@@ -15,7 +15,6 @@
// specific language governing permissions and limitations
// under the License.
-use crate::array::ArrowPrimitiveType;
pub use arrow_buffer::BufferBuilder;
use half::f16;
diff --git a/arrow-array/src/builder/fixed_size_binary_builder.rs b/arrow-array/src/builder/fixed_size_binary_builder.rs
index 0a50eb8a50e9..132c2e1939bb 100644
--- a/arrow-array/src/builder/fixed_size_binary_builder.rs
+++ b/arrow-array/src/builder/fixed_size_binary_builder.rs
@@ -154,8 +154,6 @@ mod tests {
use super::*;
use crate::Array;
- use crate::FixedSizeBinaryArray;
- use arrow_schema::DataType;
#[test]
fn test_fixed_size_binary_builder() {
diff --git a/arrow-array/src/builder/generic_bytes_builder.rs b/arrow-array/src/builder/generic_bytes_builder.rs
index 2c7ee7a3e448..9939a85f9408 100644
--- a/arrow-array/src/builder/generic_bytes_builder.rs
+++ b/arrow-array/src/builder/generic_bytes_builder.rs
@@ -262,7 +262,7 @@ pub type GenericBinaryBuilder<O> = GenericByteBuilder<GenericBinaryType<O>>;
#[cfg(test)]
mod tests {
use super::*;
- use crate::array::{Array, OffsetSizeTrait};
+ use crate::array::Array;
use crate::GenericStringArray;
fn _test_generic_binary_builder<O: OffsetSizeTrait>() {
diff --git a/arrow-array/src/builder/generic_bytes_dictionary_builder.rs b/arrow-array/src/builder/generic_bytes_dictionary_builder.rs
index b0c722ae7cda..198d4fcbeb2f 100644
--- a/arrow-array/src/builder/generic_bytes_dictionary_builder.rs
+++ b/arrow-array/src/builder/generic_bytes_dictionary_builder.rs
@@ -402,7 +402,6 @@ pub type LargeBinaryDictionaryBuilder<K> = GenericByteDictionaryBuilder<K, Gener
mod tests {
use super::*;
- use crate::array::Array;
use crate::array::Int8Array;
use crate::types::{Int16Type, Int32Type, Int8Type, Utf8Type};
use crate::{BinaryArray, StringArray};
diff --git a/arrow-array/src/builder/generic_list_builder.rs b/arrow-array/src/builder/generic_list_builder.rs
index b857224c5da6..25903bcf546b 100644
--- a/arrow-array/src/builder/generic_list_builder.rs
+++ b/arrow-array/src/builder/generic_list_builder.rs
@@ -354,7 +354,7 @@ mod tests {
use crate::builder::{make_builder, Int32Builder, ListBuilder};
use crate::cast::AsArray;
use crate::types::Int32Type;
- use crate::{Array, Int32Array};
+ use crate::Int32Array;
use arrow_schema::DataType;
fn _test_generic_list_array_builder<O: OffsetSizeTrait>() {
diff --git a/arrow-array/src/builder/primitive_builder.rs b/arrow-array/src/builder/primitive_builder.rs
index 0aad2dbfce0e..39b27bfca896 100644
--- a/arrow-array/src/builder/primitive_builder.rs
+++ b/arrow-array/src/builder/primitive_builder.rs
@@ -17,7 +17,7 @@
use crate::builder::{ArrayBuilder, BufferBuilder};
use crate::types::*;
-use crate::{ArrayRef, ArrowPrimitiveType, PrimitiveArray};
+use crate::{ArrayRef, PrimitiveArray};
use arrow_buffer::NullBufferBuilder;
use arrow_buffer::{Buffer, MutableBuffer};
use arrow_data::ArrayData;
@@ -359,7 +359,6 @@ impl<P: ArrowPrimitiveType> Extend<Option<P::Native>> for PrimitiveBuilder<P> {
#[cfg(test)]
mod tests {
use super::*;
- use arrow_buffer::Buffer;
use arrow_schema::TimeUnit;
use crate::array::Array;
@@ -367,7 +366,6 @@ mod tests {
use crate::array::Date32Array;
use crate::array::Int32Array;
use crate::array::TimestampSecondArray;
- use crate::builder::Int32Builder;
#[test]
fn test_primitive_array_builder_i32() {
diff --git a/arrow-array/src/builder/primitive_dictionary_builder.rs b/arrow-array/src/builder/primitive_dictionary_builder.rs
index a47b2d30d4f3..a64ecf0caa13 100644
--- a/arrow-array/src/builder/primitive_dictionary_builder.rs
+++ b/arrow-array/src/builder/primitive_dictionary_builder.rs
@@ -319,7 +319,6 @@ impl<K: ArrowDictionaryKeyType, P: ArrowPrimitiveType> Extend<Option<P::Native>>
mod tests {
use super::*;
- use crate::array::Array;
use crate::array::UInt32Array;
use crate::array::UInt8Array;
use crate::builder::Decimal128Builder;
diff --git a/arrow-array/src/builder/struct_builder.rs b/arrow-array/src/builder/struct_builder.rs
index 917b58522f66..f8bf42b24ee5 100644
--- a/arrow-array/src/builder/struct_builder.rs
+++ b/arrow-array/src/builder/struct_builder.rs
@@ -16,10 +16,9 @@
// under the License.
use crate::builder::*;
-use crate::{ArrayRef, StructArray};
+use crate::StructArray;
use arrow_buffer::NullBufferBuilder;
use arrow_schema::{DataType, Fields, IntervalUnit, SchemaBuilder, TimeUnit};
-use std::any::Any;
use std::sync::Arc;
/// Builder for [`StructArray`]
diff --git a/arrow-array/src/timezone.rs b/arrow-array/src/timezone.rs
index dc91886f34c5..b4df77deb4f5 100644
--- a/arrow-array/src/timezone.rs
+++ b/arrow-array/src/timezone.rs
@@ -235,7 +235,7 @@ mod private {
mod private {
use super::*;
use chrono::offset::TimeZone;
- use chrono::{FixedOffset, LocalResult, NaiveDate, NaiveDateTime, Offset};
+ use chrono::{LocalResult, NaiveDate, NaiveDateTime, Offset};
use std::str::FromStr;
/// An [`Offset`] for [`Tz`]
diff --git a/arrow-buffer/src/bigint/mod.rs b/arrow-buffer/src/bigint/mod.rs
index afbb3a31df12..a8aaff13cd27 100644
--- a/arrow-buffer/src/bigint/mod.rs
+++ b/arrow-buffer/src/bigint/mod.rs
@@ -838,9 +838,8 @@ impl ToPrimitive for i256 {
#[cfg(all(test, not(miri)))] // llvm.x86.subborrow.64 not supported by MIRI
mod tests {
use super::*;
- use num::{BigInt, FromPrimitive, Signed, ToPrimitive};
+ use num::Signed;
use rand::{thread_rng, Rng};
- use std::ops::Neg;
#[test]
fn test_signed_cmp() {
diff --git a/arrow-buffer/src/buffer/immutable.rs b/arrow-buffer/src/buffer/immutable.rs
index 10b62a2ce473..552e3f1615c7 100644
--- a/arrow-buffer/src/buffer/immutable.rs
+++ b/arrow-buffer/src/buffer/immutable.rs
@@ -17,7 +17,6 @@
use std::alloc::Layout;
use std::fmt::Debug;
-use std::iter::FromIterator;
use std::ptr::NonNull;
use std::sync::Arc;
diff --git a/arrow-cast/src/base64.rs b/arrow-cast/src/base64.rs
index e109c8112480..319c76548286 100644
--- a/arrow-cast/src/base64.rs
+++ b/arrow-cast/src/base64.rs
@@ -86,7 +86,6 @@ pub fn b64_decode<E: Engine, O: OffsetSizeTrait>(
mod tests {
use super::*;
use arrow_array::BinaryArray;
- use base64::prelude::{BASE64_STANDARD, BASE64_STANDARD_NO_PAD};
use rand::{thread_rng, Rng};
fn test_engine<E: Engine>(e: &E, a: &BinaryArray) {
diff --git a/arrow-cast/src/parse.rs b/arrow-cast/src/parse.rs
index 6214e6d97371..7f23526142cc 100644
--- a/arrow-cast/src/parse.rs
+++ b/arrow-cast/src/parse.rs
@@ -17,7 +17,7 @@
use arrow_array::timezone::Tz;
use arrow_array::types::*;
-use arrow_array::{ArrowNativeTypeOp, ArrowPrimitiveType};
+use arrow_array::ArrowNativeTypeOp;
use arrow_buffer::ArrowNativeType;
use arrow_schema::ArrowError;
use chrono::prelude::*;
@@ -1222,7 +1222,6 @@ fn parse_interval_components(
mod tests {
use super::*;
use arrow_array::temporal_conversions::date32_to_datetime;
- use arrow_array::timezone::Tz;
use arrow_buffer::i256;
#[test]
diff --git a/arrow-data/src/data.rs b/arrow-data/src/data.rs
index 2ddc2d845b01..bd45c4f8ddda 100644
--- a/arrow-data/src/data.rs
+++ b/arrow-data/src/data.rs
@@ -22,7 +22,6 @@ use crate::bit_iterator::BitSliceIterator;
use arrow_buffer::buffer::{BooleanBuffer, NullBuffer};
use arrow_buffer::{bit_util, i256, ArrowNativeType, Buffer, MutableBuffer};
use arrow_schema::{ArrowError, DataType, UnionMode};
-use std::convert::TryInto;
use std::mem;
use std::ops::Range;
use std::sync::Arc;
diff --git a/arrow-flight/src/decode.rs b/arrow-flight/src/decode.rs
index 95bbe2b46bb2..afbf033eb06d 100644
--- a/arrow-flight/src/decode.rs
+++ b/arrow-flight/src/decode.rs
@@ -21,7 +21,7 @@ use arrow_buffer::Buffer;
use arrow_schema::{Schema, SchemaRef};
use bytes::Bytes;
use futures::{ready, stream::BoxStream, Stream, StreamExt};
-use std::{collections::HashMap, convert::TryFrom, fmt::Debug, pin::Pin, sync::Arc, task::Poll};
+use std::{collections::HashMap, fmt::Debug, pin::Pin, sync::Arc, task::Poll};
use tonic::metadata::MetadataMap;
use crate::error::{FlightError, Result};
diff --git a/arrow-flight/src/lib.rs b/arrow-flight/src/lib.rs
index 434d19ce76fe..a4b4ab7bc316 100644
--- a/arrow-flight/src/lib.rs
+++ b/arrow-flight/src/lib.rs
@@ -46,11 +46,7 @@ use base64::prelude::BASE64_STANDARD;
use base64::Engine;
use bytes::Bytes;
use prost_types::Timestamp;
-use std::{
- convert::{TryFrom, TryInto},
- fmt,
- ops::Deref,
-};
+use std::{fmt, ops::Deref};
type ArrowResult<T> = std::result::Result<T, ArrowError>;
diff --git a/arrow-ipc/src/reader.rs b/arrow-ipc/src/reader.rs
index 361c4f7f67dd..f015674d6813 100644
--- a/arrow-ipc/src/reader.rs
+++ b/arrow-ipc/src/reader.rs
@@ -1190,7 +1190,6 @@ mod tests {
use crate::root_as_message;
use arrow_array::builder::{PrimitiveRunBuilder, UnionBuilder};
use arrow_array::types::*;
- use arrow_buffer::ArrowNativeType;
use arrow_data::ArrayDataBuilder;
fn create_test_projection_schema() -> Schema {
diff --git a/arrow-ipc/src/writer.rs b/arrow-ipc/src/writer.rs
index 99e52e2a7076..4e32b04b0fba 100644
--- a/arrow-ipc/src/writer.rs
+++ b/arrow-ipc/src/writer.rs
@@ -1421,14 +1421,12 @@ fn pad_to_8(len: u32) -> usize {
mod tests {
use std::io::Cursor;
use std::io::Seek;
- use std::sync::Arc;
use arrow_array::builder::GenericListBuilder;
use arrow_array::builder::MapBuilder;
use arrow_array::builder::UnionBuilder;
use arrow_array::builder::{PrimitiveRunBuilder, UInt32Builder};
use arrow_array::types::*;
- use arrow_schema::DataType;
use crate::reader::*;
use crate::MetadataVersion;
diff --git a/arrow-json/src/lib.rs b/arrow-json/src/lib.rs
index e39882e52620..c7839a17150b 100644
--- a/arrow-json/src/lib.rs
+++ b/arrow-json/src/lib.rs
@@ -144,10 +144,7 @@ impl JsonSerializable for f64 {
mod tests {
use super::*;
- use serde_json::{
- Number,
- Value::{Bool, Number as VNumber, String as VString},
- };
+ use serde_json::Value::{Bool, Number as VNumber, String as VString};
#[test]
fn test_arrow_native_type_to_json() {
diff --git a/arrow-json/src/reader/mod.rs b/arrow-json/src/reader/mod.rs
index 5afe0dec279a..99055573345a 100644
--- a/arrow-json/src/reader/mod.rs
+++ b/arrow-json/src/reader/mod.rs
@@ -140,7 +140,6 @@ use chrono::Utc;
use serde::Serialize;
use arrow_array::timezone::Tz;
-use arrow_array::types::Float32Type;
use arrow_array::types::*;
use arrow_array::{downcast_integer, make_array, RecordBatch, RecordBatchReader, StructArray};
use arrow_data::ArrayData;
@@ -713,20 +712,13 @@ mod tests {
use serde_json::json;
use std::fs::File;
use std::io::{BufReader, Cursor, Seek};
- use std::sync::Arc;
use arrow_array::cast::AsArray;
- use arrow_array::types::Int32Type;
- use arrow_array::{
- make_array, Array, BooleanArray, Float64Array, ListArray, StringArray, StructArray,
- };
+ use arrow_array::{Array, BooleanArray, Float64Array, ListArray, StringArray};
use arrow_buffer::{ArrowNativeType, Buffer};
use arrow_cast::display::{ArrayFormatter, FormatOptions};
use arrow_data::ArrayDataBuilder;
- use arrow_schema::{DataType, Field, FieldRef, Schema};
-
- use crate::reader::infer_json_schema;
- use crate::ReaderBuilder;
+ use arrow_schema::Field;
use super::*;
diff --git a/arrow-ord/src/ord.rs b/arrow-ord/src/ord.rs
index f6bd39c9cd5d..e793038de929 100644
--- a/arrow-ord/src/ord.rs
+++ b/arrow-ord/src/ord.rs
@@ -131,10 +131,8 @@ pub fn build_compare(left: &dyn Array, right: &dyn Array) -> Result<DynComparato
#[cfg(test)]
pub mod tests {
use super::*;
- use arrow_array::{FixedSizeBinaryArray, Float64Array, Int32Array};
use arrow_buffer::{i256, OffsetBuffer};
use half::f16;
- use std::cmp::Ordering;
use std::sync::Arc;
#[test]
diff --git a/arrow-ord/src/sort.rs b/arrow-ord/src/sort.rs
index 2c06057a84e0..fe3a1f86ac00 100644
--- a/arrow-ord/src/sort.rs
+++ b/arrow-ord/src/sort.rs
@@ -833,7 +833,6 @@ mod tests {
use half::f16;
use rand::rngs::StdRng;
use rand::{Rng, RngCore, SeedableRng};
- use std::sync::Arc;
fn create_decimal128_array(data: Vec<Option<i128>>) -> Decimal128Array {
data.into_iter()
diff --git a/arrow-row/src/lib.rs b/arrow-row/src/lib.rs
index 6fd92eaf914b..c2f5293f94c8 100644
--- a/arrow-row/src/lib.rs
+++ b/arrow-row/src/lib.rs
@@ -1303,8 +1303,6 @@ unsafe fn decode_column(
#[cfg(test)]
mod tests {
- use std::sync::Arc;
-
use rand::distributions::uniform::SampleUniform;
use rand::distributions::{Distribution, Standard};
use rand::{thread_rng, Rng};
@@ -1315,7 +1313,7 @@ mod tests {
use arrow_buffer::i256;
use arrow_buffer::Buffer;
use arrow_cast::display::array_value_to_string;
- use arrow_ord::sort::{LexicographicalComparator, SortColumn, SortOptions};
+ use arrow_ord::sort::{LexicographicalComparator, SortColumn};
use super::*;
diff --git a/arrow-schema/src/datatype.rs b/arrow-schema/src/datatype.rs
index b3d89b011e66..89c001b0e657 100644
--- a/arrow-schema/src/datatype.rs
+++ b/arrow-schema/src/datatype.rs
@@ -667,7 +667,6 @@ pub const DECIMAL_DEFAULT_SCALE: i8 = 10;
#[cfg(test)]
mod tests {
use super::*;
- use crate::{Field, UnionMode};
#[test]
#[cfg(feature = "serde")]
diff --git a/arrow-schema/src/field.rs b/arrow-schema/src/field.rs
index 70a3e2b21a3c..0770cf41a02d 100644
--- a/arrow-schema/src/field.rs
+++ b/arrow-schema/src/field.rs
@@ -580,10 +580,7 @@ impl std::fmt::Display for Field {
#[cfg(test)]
mod test {
use super::*;
- use crate::Fields;
use std::collections::hash_map::DefaultHasher;
- use std::hash::{Hash, Hasher};
- use std::sync::Arc;
#[test]
fn test_new_with_string() {
diff --git a/arrow-select/src/concat.rs b/arrow-select/src/concat.rs
index 695903195d25..f98e85475a25 100644
--- a/arrow-select/src/concat.rs
+++ b/arrow-select/src/concat.rs
@@ -195,9 +195,7 @@ pub fn concat_batches<'a>(
mod tests {
use super::*;
use arrow_array::builder::StringDictionaryBuilder;
- use arrow_array::cast::AsArray;
use arrow_schema::{Field, Schema};
- use std::sync::Arc;
#[test]
fn test_concat_empty_vec() {
diff --git a/arrow-select/src/interleave.rs b/arrow-select/src/interleave.rs
index 8229a8f3fe09..fccc02ac9391 100644
--- a/arrow-select/src/interleave.rs
+++ b/arrow-select/src/interleave.rs
@@ -267,10 +267,6 @@ fn interleave_fallback(
mod tests {
use super::*;
use arrow_array::builder::{Int32Builder, ListBuilder};
- use arrow_array::cast::AsArray;
- use arrow_array::types::Int32Type;
- use arrow_array::{Int32Array, ListArray, StringArray};
- use arrow_schema::DataType;
#[test]
fn test_primitive() {
diff --git a/arrow-select/src/nullif.rs b/arrow-select/src/nullif.rs
index 4025a5bacf80..a7848c16a8ec 100644
--- a/arrow-select/src/nullif.rs
+++ b/arrow-select/src/nullif.rs
@@ -102,7 +102,7 @@ mod tests {
use arrow_array::types::Int32Type;
use arrow_array::{Int32Array, NullArray, StringArray, StructArray};
use arrow_data::ArrayData;
- use arrow_schema::{DataType, Field, Fields};
+ use arrow_schema::{Field, Fields};
use rand::{thread_rng, Rng};
#[test]
diff --git a/arrow-string/src/concat_elements.rs b/arrow-string/src/concat_elements.rs
index 66ecd34868a5..cb60363d3324 100644
--- a/arrow-string/src/concat_elements.rs
+++ b/arrow-string/src/concat_elements.rs
@@ -207,7 +207,6 @@ pub fn concat_elements_dyn(left: &dyn Array, right: &dyn Array) -> Result<ArrayR
#[cfg(test)]
mod tests {
use super::*;
- use arrow_array::StringArray;
#[test]
fn test_string_concat() {
let left = [Some("foo"), Some("bar"), None]
diff --git a/arrow-string/src/length.rs b/arrow-string/src/length.rs
index 1dd5933ce0e5..79fa46026912 100644
--- a/arrow-string/src/length.rs
+++ b/arrow-string/src/length.rs
@@ -141,8 +141,7 @@ pub fn bit_length(array: &dyn Array) -> Result<ArrayRef, ArrowError> {
#[cfg(test)]
mod tests {
use super::*;
- use arrow_array::cast::AsArray;
- use arrow_buffer::{Buffer, NullBuffer};
+ use arrow_buffer::Buffer;
use arrow_data::ArrayData;
use arrow_schema::Field;
diff --git a/arrow-string/src/regexp.rs b/arrow-string/src/regexp.rs
index 5e539b91b492..f79eff4b6ea8 100644
--- a/arrow-string/src/regexp.rs
+++ b/arrow-string/src/regexp.rs
@@ -404,7 +404,6 @@ pub fn regexp_match(
#[cfg(test)]
mod tests {
use super::*;
- use arrow_array::{ListArray, StringArray};
#[test]
fn match_single_group() {
diff --git a/arrow/benches/array_from_vec.rs b/arrow/benches/array_from_vec.rs
index 5fce3f113e43..fd83ad5c2a10 100644
--- a/arrow/benches/array_from_vec.rs
+++ b/arrow/benches/array_from_vec.rs
@@ -25,7 +25,7 @@ extern crate arrow;
use arrow::array::*;
use arrow_buffer::i256;
use rand::Rng;
-use std::{convert::TryFrom, sync::Arc};
+use std::sync::Arc;
fn array_from_vec(n: usize) {
let v: Vec<i32> = (0..n as i32).collect();
diff --git a/arrow/benches/cast_kernels.rs b/arrow/benches/cast_kernels.rs
index 1877ed0e7899..228408e5711a 100644
--- a/arrow/benches/cast_kernels.rs
+++ b/arrow/benches/cast_kernels.rs
@@ -31,7 +31,6 @@ use arrow::compute::cast;
use arrow::datatypes::*;
use arrow::util::bench_util::*;
use arrow::util::test_util::seedable_rng;
-use arrow_buffer::i256;
fn build_array<T: ArrowPrimitiveType>(size: usize) -> ArrayRef
where
diff --git a/arrow/benches/comparison_kernels.rs b/arrow/benches/comparison_kernels.rs
index 02de70c5d79d..a272144b52e0 100644
--- a/arrow/benches/comparison_kernels.rs
+++ b/arrow/benches/comparison_kernels.rs
@@ -25,7 +25,6 @@ use arrow::compute::kernels::cmp::*;
use arrow::datatypes::IntervalMonthDayNanoType;
use arrow::util::bench_util::*;
use arrow::{array::*, datatypes::Float32Type, datatypes::Int32Type};
-use arrow_array::Scalar;
use arrow_string::like::*;
use arrow_string::regexp::regexp_is_match_utf8_scalar;
diff --git a/arrow/benches/csv_reader.rs b/arrow/benches/csv_reader.rs
index b5afac1f6a46..38e091548be0 100644
--- a/arrow/benches/csv_reader.rs
+++ b/arrow/benches/csv_reader.rs
@@ -27,7 +27,6 @@ use rand::Rng;
use arrow::array::*;
use arrow::csv;
use arrow::datatypes::*;
-use arrow::record_batch::RecordBatch;
use arrow::util::bench_util::{create_primitive_array, create_string_array_with_len};
use arrow::util::test_util::seedable_rng;
diff --git a/arrow/benches/csv_writer.rs b/arrow/benches/csv_writer.rs
index 0c13428c9160..85bd8ca383de 100644
--- a/arrow/benches/csv_writer.rs
+++ b/arrow/benches/csv_writer.rs
@@ -23,7 +23,6 @@ use criterion::*;
use arrow::array::*;
use arrow::csv;
use arrow::datatypes::*;
-use arrow::record_batch::RecordBatch;
use std::env;
use std::fs::File;
use std::sync::Arc;
diff --git a/arrow/benches/filter_kernels.rs b/arrow/benches/filter_kernels.rs
index 65726a271009..50f3cb40094d 100644
--- a/arrow/benches/filter_kernels.rs
+++ b/arrow/benches/filter_kernels.rs
@@ -19,7 +19,6 @@ extern crate arrow;
use std::sync::Arc;
use arrow::compute::{filter_record_batch, FilterBuilder, FilterPredicate};
-use arrow::record_batch::RecordBatch;
use arrow::util::bench_util::*;
use arrow::array::*;
diff --git a/arrow/benches/partition_kernels.rs b/arrow/benches/partition_kernels.rs
index 85cafbe47a11..fce8634a10a0 100644
--- a/arrow/benches/partition_kernels.rs
+++ b/arrow/benches/partition_kernels.rs
@@ -24,7 +24,7 @@ use arrow::compute::kernels::sort::{lexsort, SortColumn};
use arrow::util::bench_util::*;
use arrow::{
array::*,
- datatypes::{ArrowPrimitiveType, Float64Type, UInt8Type},
+ datatypes::{Float64Type, UInt8Type},
};
use arrow_ord::partition::partition;
use rand::distributions::{Distribution, Standard};
diff --git a/arrow/examples/dynamic_types.rs b/arrow/examples/dynamic_types.rs
index 4c01f0ea8c72..b866cb7e6b1a 100644
--- a/arrow/examples/dynamic_types.rs
+++ b/arrow/examples/dynamic_types.rs
@@ -26,7 +26,6 @@ use arrow::error::Result;
#[cfg(feature = "prettyprint")]
use arrow::util::pretty::print_batches;
-use arrow_schema::Fields;
fn main() -> Result<()> {
// define schema
diff --git a/arrow/src/array/ffi.rs b/arrow/src/array/ffi.rs
index d4d95a6e1770..43f54a038421 100644
--- a/arrow/src/array/ffi.rs
+++ b/arrow/src/array/ffi.rs
@@ -17,8 +17,6 @@
//! Contains functionality to load an ArrayData from the C Data Interface
-use std::convert::TryFrom;
-
use crate::{error::Result, ffi};
use super::ArrayRef;
@@ -61,7 +59,6 @@ mod tests {
datatypes::{DataType, Field},
ffi::{from_ffi, FFI_ArrowArray, FFI_ArrowSchema},
};
- use std::convert::TryFrom;
use std::sync::Arc;
fn test_round_trip(expected: &ArrayData) -> Result<()> {
diff --git a/arrow/src/ffi.rs b/arrow/src/ffi.rs
index d867f7c30d1f..fe3f413924b8 100644
--- a/arrow/src/ffi.rs
+++ b/arrow/src/ffi.rs
@@ -461,7 +461,6 @@ impl<'a> ImportedArrowArray<'a> {
#[cfg(test)]
mod tests {
use std::collections::HashMap;
- use std::convert::TryFrom;
use std::mem::ManuallyDrop;
use std::ptr::addr_of_mut;
@@ -470,12 +469,6 @@ mod tests {
use arrow_array::types::{Float64Type, Int32Type};
use arrow_array::*;
- use crate::array::{
- make_array, Array, ArrayData, BooleanArray, DictionaryArray, DurationSecondArray,
- FixedSizeBinaryArray, FixedSizeListArray, GenericBinaryArray, GenericListArray,
- GenericStringArray, Int32Array, MapArray, OffsetSizeTrait, Time32MillisecondArray,
- TimestampMillisecondArray, UInt32Array,
- };
use crate::compute::kernels;
use crate::datatypes::{Field, Int8Type};
diff --git a/arrow/src/ffi_stream.rs b/arrow/src/ffi_stream.rs
index 06128a1c9984..15b88ef32163 100644
--- a/arrow/src/ffi_stream.rs
+++ b/arrow/src/ffi_stream.rs
@@ -58,7 +58,6 @@ use arrow_schema::DataType;
use std::ffi::CStr;
use std::ptr::addr_of;
use std::{
- convert::TryFrom,
ffi::CString,
os::raw::{c_char, c_int, c_void},
sync::Arc,
@@ -392,12 +391,10 @@ pub unsafe fn export_reader_into_raw(
#[cfg(test)]
mod tests {
- use arrow_schema::DataType;
-
use super::*;
use crate::array::Int32Array;
- use crate::datatypes::{Field, Schema};
+ use crate::datatypes::Field;
struct TestRecordBatchReader {
schema: SchemaRef,
diff --git a/arrow/src/tensor.rs b/arrow/src/tensor.rs
index c2a262b399de..f236e6422cdf 100644
--- a/arrow/src/tensor.rs
+++ b/arrow/src/tensor.rs
@@ -308,7 +308,6 @@ mod tests {
use super::*;
use crate::array::*;
- use crate::buffer::Buffer;
#[test]
fn test_compute_row_major_strides() {
diff --git a/arrow/src/util/data_gen.rs b/arrow/src/util/data_gen.rs
index 5733fdf22add..c63aa6bba3e5 100644
--- a/arrow/src/util/data_gen.rs
+++ b/arrow/src/util/data_gen.rs
@@ -17,13 +17,12 @@
//! Utilities to generate random arrays and batches
-use std::{convert::TryFrom, sync::Arc};
+use std::sync::Arc;
use rand::{distributions::uniform::SampleUniform, Rng};
+use crate::array::*;
use crate::error::{ArrowError, Result};
-use crate::record_batch::{RecordBatch, RecordBatchOptions};
-use crate::{array::*, datatypes::SchemaRef};
use crate::{
buffer::{Buffer, MutableBuffer},
datatypes::*,
@@ -244,7 +243,6 @@ fn create_random_null_buffer(size: usize, null_density: f32) -> Buffer {
#[cfg(test)]
mod tests {
use super::*;
- use arrow_schema::Fields;
#[test]
fn test_create_batch() {
diff --git a/parquet/src/arrow/array_reader/mod.rs b/parquet/src/arrow/array_reader/mod.rs
index c4e9fc5fa066..4ae0f5669e87 100644
--- a/parquet/src/arrow/array_reader/mod.rs
+++ b/parquet/src/arrow/array_reader/mod.rs
@@ -47,6 +47,7 @@ mod test_util;
pub use builder::build_array_reader;
pub use byte_array::make_byte_array_reader;
pub use byte_array_dictionary::make_byte_array_dictionary_reader;
+#[allow(unused_imports)] // Only used for benchmarks
pub use fixed_len_byte_array::make_fixed_len_byte_array_reader;
pub use fixed_size_list_array::FixedSizeListArrayReader;
pub use list_array::ListArrayReader;
diff --git a/parquet/src/arrow/arrow_reader/mod.rs b/parquet/src/arrow/arrow_reader/mod.rs
index 7aeb3d127ac3..a34ce77f2778 100644
--- a/parquet/src/arrow/arrow_reader/mod.rs
+++ b/parquet/src/arrow/arrow_reader/mod.rs
@@ -741,7 +741,6 @@ mod tests {
Decimal128Type, Decimal256Type, DecimalType, Float16Type, Float32Type, Float64Type,
};
use arrow_array::*;
- use arrow_array::{RecordBatch, RecordBatchReader};
use arrow_buffer::{i256, ArrowNativeType, Buffer};
use arrow_data::ArrayDataBuilder;
use arrow_schema::{DataType as ArrowDataType, Field, Fields, Schema};
diff --git a/parquet/src/arrow/arrow_writer/levels.rs b/parquet/src/arrow/arrow_writer/levels.rs
index 1f3078224159..955896010b85 100644
--- a/parquet/src/arrow/arrow_writer/levels.rs
+++ b/parquet/src/arrow/arrow_writer/levels.rs
@@ -617,10 +617,7 @@ impl ArrayLevels {
mod tests {
use super::*;
- use std::sync::Arc;
-
use arrow_array::builder::*;
- use arrow_array::cast::AsArray;
use arrow_array::types::Int32Type;
use arrow_array::*;
use arrow_buffer::{Buffer, ToByteSlice};
diff --git a/parquet/src/arrow/arrow_writer/mod.rs b/parquet/src/arrow/arrow_writer/mod.rs
index b677ef354c7f..27f517649099 100644
--- a/parquet/src/arrow/arrow_writer/mod.rs
+++ b/parquet/src/arrow/arrow_writer/mod.rs
@@ -954,18 +954,15 @@ fn get_fsb_array_slice(
mod tests {
use super::*;
- use bytes::Bytes;
use std::fs::File;
- use std::sync::Arc;
use crate::arrow::arrow_reader::{ParquetRecordBatchReader, ParquetRecordBatchReaderBuilder};
use crate::arrow::ARROW_SCHEMA_META_KEY;
use arrow::datatypes::ToByteSlice;
- use arrow::datatypes::{DataType, Field, Schema, UInt32Type, UInt8Type};
+ use arrow::datatypes::{DataType, Schema};
use arrow::error::Result as ArrowResult;
use arrow::util::pretty::pretty_format_batches;
use arrow::{array::*, buffer::Buffer};
- use arrow_array::RecordBatch;
use arrow_buffer::NullBuffer;
use arrow_schema::Fields;
diff --git a/parquet/src/arrow/buffer/dictionary_buffer.rs b/parquet/src/arrow/buffer/dictionary_buffer.rs
index 9e5b2293aa01..59f1cfa056a1 100644
--- a/parquet/src/arrow/buffer/dictionary_buffer.rs
+++ b/parquet/src/arrow/buffer/dictionary_buffer.rs
@@ -208,7 +208,7 @@ impl<K: ArrowNativeType, V: OffsetSizeTrait> ValuesBuffer for DictionaryBuffer<K
mod tests {
use super::*;
use arrow::compute::cast;
- use arrow_array::{Array, StringArray};
+ use arrow_array::StringArray;
#[test]
fn test_dictionary_buffer() {
diff --git a/parquet/src/bloom_filter/mod.rs b/parquet/src/bloom_filter/mod.rs
index 897cce7620aa..d99c7251902e 100644
--- a/parquet/src/bloom_filter/mod.rs
+++ b/parquet/src/bloom_filter/mod.rs
@@ -344,9 +344,6 @@ fn hash_as_bytes<A: AsBytes + ?Sized>(value: &A) -> u64 {
#[cfg(test)]
mod tests {
use super::*;
- use crate::format::{
- BloomFilterAlgorithm, BloomFilterCompression, SplitBlockAlgorithm, Uncompressed, XxHash,
- };
#[test]
fn test_hash_bytes() {
diff --git a/parquet/src/column/writer/mod.rs b/parquet/src/column/writer/mod.rs
index e993cb4c11a8..9ef505cc7cf6 100644
--- a/parquet/src/column/writer/mod.rs
+++ b/parquet/src/column/writer/mod.rs
@@ -1292,9 +1292,7 @@ fn increment_utf8(mut data: Vec<u8>) -> Option<Vec<u8>> {
#[cfg(test)]
mod tests {
- use crate::{file::properties::DEFAULT_COLUMN_INDEX_TRUNCATE_LENGTH, format::BoundaryOrder};
- use bytes::Bytes;
- use half::f16;
+ use crate::file::properties::DEFAULT_COLUMN_INDEX_TRUNCATE_LENGTH;
use rand::distributions::uniform::SampleUniform;
use std::sync::Arc;
@@ -1304,11 +1302,9 @@ mod tests {
};
use crate::file::writer::TrackedWrite;
use crate::file::{
- properties::{ReaderProperties, WriterProperties},
- reader::SerializedPageReader,
- writer::SerializedPageWriter,
+ properties::ReaderProperties, reader::SerializedPageReader, writer::SerializedPageWriter,
};
- use crate::schema::types::{ColumnDescriptor, ColumnPath, Type as SchemaType};
+ use crate::schema::types::{ColumnPath, Type as SchemaType};
use crate::util::test_common::rand_gen::random_numbers_range;
use super::*;
diff --git a/parquet/src/compression.rs b/parquet/src/compression.rs
index a9a1afbbf213..89f4b64d48b5 100644
--- a/parquet/src/compression.rs
+++ b/parquet/src/compression.rs
@@ -144,10 +144,7 @@ pub(crate) trait CompressionLevel<T: std::fmt::Display + std::cmp::PartialOrd> {
/// Given the compression type `codec`, returns a codec used to compress and decompress
/// bytes for the compression type.
/// This returns `None` if the codec type is `UNCOMPRESSED`.
-pub fn create_codec(
- codec: CodecType,
- _options: &CodecOptions,
-) -> Result<Option<Box<dyn Codec>>> {
+pub fn create_codec(codec: CodecType, _options: &CodecOptions) -> Result<Option<Box<dyn Codec>>> {
match codec {
#[cfg(any(feature = "brotli", test))]
CodecType::BROTLI(level) => Ok(Some(Box::new(BrotliCodec::new(level)))),
@@ -260,8 +257,7 @@ mod gzip_codec {
}
fn compress(&mut self, input_buf: &[u8], output_buf: &mut Vec<u8>) -> Result<()> {
- let mut encoder =
- write::GzEncoder::new(output_buf, Compression::new(self.level.0));
+ let mut encoder = write::GzEncoder::new(output_buf, Compression::new(self.level.0));
encoder.write_all(input_buf)?;
encoder.try_finish().map_err(|e| e.into())
}
@@ -441,7 +437,8 @@ mod lz4_codec {
}
}
}
-#[cfg(any(feature = "lz4", test))]
+
+#[cfg(all(feature = "experimental", any(feature = "lz4", test)))]
pub use lz4_codec::*;
#[cfg(any(feature = "zstd", test))]
@@ -619,10 +616,7 @@ mod lz4_hadoop_codec {
/// Adapted from pola-rs [compression.rs:try_decompress_hadoop](https://pola-rs.github.io/polars/src/parquet2/compression.rs.html#225)
/// Translated from the apache arrow c++ function [TryDecompressHadoop](https://github.com/apache/arrow/blob/bf18e6e4b5bb6180706b1ba0d597a65a4ce5ca48/cpp/src/arrow/util/compression_lz4.cc#L474).
/// Returns error if decompression failed.
- fn try_decompress_hadoop(
- input_buf: &[u8],
- output_buf: &mut [u8],
- ) -> io::Result<usize> {
+ fn try_decompress_hadoop(input_buf: &[u8], output_buf: &mut [u8]) -> io::Result<usize> {
// Parquet files written with the Hadoop Lz4Codec use their own framing.
// The input buffer can contain an arbitrary number of "frames", each
// with the following structure:
@@ -660,11 +654,9 @@ mod lz4_hadoop_codec {
"Not enough bytes to hold advertised output",
));
}
- let decompressed_size = lz4_flex::decompress_into(
- &input[..expected_compressed_size as usize],
- output,
- )
- .map_err(|e| ParquetError::External(Box::new(e)))?;
+ let decompressed_size =
+ lz4_flex::decompress_into(&input[..expected_compressed_size as usize], output)
+ .map_err(|e| ParquetError::External(Box::new(e)))?;
if decompressed_size != expected_decompressed_size as usize {
return Err(io::Error::new(
io::ErrorKind::Other,
@@ -712,8 +704,7 @@ mod lz4_hadoop_codec {
Ok(n) => {
if n != required_len {
return Err(ParquetError::General(
- "LZ4HadoopCodec uncompress_size is not the expected one"
- .into(),
+ "LZ4HadoopCodec uncompress_size is not the expected one".into(),
));
}
Ok(n)
@@ -724,20 +715,12 @@ mod lz4_hadoop_codec {
Err(_) => {
// Truncate any inserted element before tryingg next algorithm.
output_buf.truncate(output_len);
- match LZ4Codec::new().decompress(
- input_buf,
- output_buf,
- uncompress_size,
- ) {
+ match LZ4Codec::new().decompress(input_buf, output_buf, uncompress_size) {
Ok(n) => Ok(n),
Err(_) => {
// Truncate any inserted element before tryingg next algorithm.
output_buf.truncate(output_len);
- LZ4RawCodec::new().decompress(
- input_buf,
- output_buf,
- uncompress_size,
- )
+ LZ4RawCodec::new().decompress(input_buf, output_buf, uncompress_size)
}
}
}
@@ -759,8 +742,7 @@ mod lz4_hadoop_codec {
let compressed_size = compressed_size as u32;
let uncompressed_size = input_buf.len() as u32;
output_buf[..SIZE_U32].copy_from_slice(&uncompressed_size.to_be_bytes());
- output_buf[SIZE_U32..PREFIX_LEN]
- .copy_from_slice(&compressed_size.to_be_bytes());
+ output_buf[SIZE_U32..PREFIX_LEN].copy_from_slice(&compressed_size.to_be_bytes());
Ok(())
}
diff --git a/parquet/src/data_type.rs b/parquet/src/data_type.rs
index 86da7a3acee4..5e1d53badba2 100644
--- a/parquet/src/data_type.rs
+++ b/parquet/src/data_type.rs
@@ -587,7 +587,6 @@ pub(crate) mod private {
use crate::util::bit_util::{read_num_bytes, BitReader, BitWriter};
use crate::basic::Type;
- use std::convert::TryInto;
use super::{ParquetError, Result, SliceAsBytes};
diff --git a/parquet/src/file/metadata.rs b/parquet/src/file/metadata.rs
index acd3a9f938c5..c9232d83e80d 100644
--- a/parquet/src/file/metadata.rs
+++ b/parquet/src/file/metadata.rs
@@ -1003,7 +1003,7 @@ impl OffsetIndexBuilder {
#[cfg(test)]
mod tests {
use super::*;
- use crate::basic::{Encoding, PageType};
+ use crate::basic::PageType;
#[test]
fn test_row_group_metadata_thrift_conversion() {
diff --git a/parquet/src/file/page_encoding_stats.rs b/parquet/src/file/page_encoding_stats.rs
index c941d401175c..edb6a8fa9d4c 100644
--- a/parquet/src/file/page_encoding_stats.rs
+++ b/parquet/src/file/page_encoding_stats.rs
@@ -63,7 +63,6 @@ pub fn to_thrift(encoding_stats: &PageEncodingStats) -> TPageEncodingStats {
#[cfg(test)]
mod tests {
use super::*;
- use crate::basic::{Encoding, PageType};
#[test]
fn test_page_encoding_stats_from_thrift() {
diff --git a/parquet/src/file/reader.rs b/parquet/src/file/reader.rs
index dd6a0fdd2312..cff921b20a9f 100644
--- a/parquet/src/file/reader.rs
+++ b/parquet/src/file/reader.rs
@@ -22,7 +22,7 @@
use bytes::{Buf, Bytes};
use std::fs::File;
use std::io::{BufReader, Seek, SeekFrom};
-use std::{boxed::Box, io::Read, sync::Arc};
+use std::{io::Read, sync::Arc};
use crate::bloom_filter::Sbbf;
use crate::column::page::PageIterator;
diff --git a/parquet/src/file/serialized_reader.rs b/parquet/src/file/serialized_reader.rs
index 5c47e5a83cea..ac7d2d287488 100644
--- a/parquet/src/file/serialized_reader.rs
+++ b/parquet/src/file/serialized_reader.rs
@@ -20,7 +20,7 @@
use std::collections::VecDeque;
use std::iter;
-use std::{convert::TryFrom, fs::File, io::Read, path::Path, sync::Arc};
+use std::{fs::File, io::Read, path::Path, sync::Arc};
use crate::basic::{Encoding, Type};
use crate::bloom_filter::Sbbf;
@@ -769,9 +769,6 @@ impl<R: ChunkReader> PageReader for SerializedPageReader<R> {
#[cfg(test)]
mod tests {
- use bytes::Bytes;
- use std::sync::Arc;
-
use crate::format::BoundaryOrder;
use crate::basic::{self, ColumnOrder};
diff --git a/parquet/src/file/writer.rs b/parquet/src/file/writer.rs
index e15a7195028f..a85442da2b49 100644
--- a/parquet/src/file/writer.rs
+++ b/parquet/src/file/writer.rs
@@ -765,7 +765,6 @@ mod tests {
use crate::data_type::{BoolType, Int32Type};
use crate::file::page_index::index::Index;
use crate::file::properties::EnabledStatistics;
- use crate::file::reader::ChunkReader;
use crate::file::serialized_reader::ReadOptionsBuilder;
use crate::file::{
properties::{ReaderProperties, WriterProperties, WriterVersion},
diff --git a/parquet/src/record/reader.rs b/parquet/src/record/reader.rs
index c6bf8f1f93e6..d74dcd276e88 100644
--- a/parquet/src/record/reader.rs
+++ b/parquet/src/record/reader.rs
@@ -804,14 +804,12 @@ mod tests {
use super::*;
use crate::data_type::Int64Type;
- use crate::errors::Result;
- use crate::file::reader::{FileReader, SerializedFileReader};
+ use crate::file::reader::SerializedFileReader;
use crate::file::writer::SerializedFileWriter;
- use crate::record::api::{Field, Row, RowAccessor};
+ use crate::record::api::RowAccessor;
use crate::schema::parser::parse_message_type;
use crate::util::test_common::file_util::{get_test_file, get_test_path};
use bytes::Bytes;
- use std::convert::TryFrom;
// Convenient macros to assemble row, list, map, and group.
diff --git a/parquet/src/schema/printer.rs b/parquet/src/schema/printer.rs
index 2dec8a5be9f7..0bbf2af748fb 100644
--- a/parquet/src/schema/printer.rs
+++ b/parquet/src/schema/printer.rs
@@ -384,9 +384,9 @@ mod tests {
use std::sync::Arc;
- use crate::basic::{LogicalType, Repetition, Type as PhysicalType};
+ use crate::basic::{Repetition, Type as PhysicalType};
use crate::errors::Result;
- use crate::schema::{parser::parse_message_type, types::Type};
+ use crate::schema::parser::parse_message_type;
fn assert_print_parse_message(message: Type) {
let mut s = String::new();
diff --git a/parquet/src/schema/types.rs b/parquet/src/schema/types.rs
index c913f13c174c..dbf6e8dcb3bd 100644
--- a/parquet/src/schema/types.rs
+++ b/parquet/src/schema/types.rs
@@ -17,7 +17,7 @@
//! Contains structs and methods to build Parquet schema and schema descriptors.
-use std::{collections::HashMap, convert::From, fmt, sync::Arc};
+use std::{collections::HashMap, fmt, sync::Arc};
use crate::format::SchemaElement;
diff --git a/parquet_derive/src/parquet_field.rs b/parquet_derive/src/parquet_field.rs
index 8d759d11c4bc..3ab85a8972f5 100644
--- a/parquet_derive/src/parquet_field.rs
+++ b/parquet_derive/src/parquet_field.rs
@@ -801,7 +801,7 @@ impl Type {
#[cfg(test)]
mod test {
use super::*;
- use syn::{self, Data, DataStruct, DeriveInput};
+ use syn::{Data, DataStruct, DeriveInput};
fn extract_fields(input: proc_macro2::TokenStream) -> Vec<syn::Field> {
let input: DeriveInput = syn::parse2(input).unwrap();
|
diff --git a/arrow-integration-test/src/lib.rs b/arrow-integration-test/src/lib.rs
index a312148dc91a..d6e0dda51a81 100644
--- a/arrow-integration-test/src/lib.rs
+++ b/arrow-integration-test/src/lib.rs
@@ -34,9 +34,7 @@ use arrow::buffer::{Buffer, MutableBuffer};
use arrow::compute;
use arrow::datatypes::*;
use arrow::error::{ArrowError, Result};
-use arrow::record_batch::{RecordBatch, RecordBatchReader};
use arrow::util::bit_util;
-use arrow_buffer::i256;
mod datatype;
mod field;
@@ -1011,9 +1009,6 @@ mod tests {
use std::fs::File;
use std::io::Read;
- use std::sync::Arc;
-
- use arrow::buffer::Buffer;
#[test]
fn test_schema_equality() {
diff --git a/arrow-integration-test/src/schema.rs b/arrow-integration-test/src/schema.rs
index b5f6c5e86b38..541a1ec746ac 100644
--- a/arrow-integration-test/src/schema.rs
+++ b/arrow-integration-test/src/schema.rs
@@ -101,7 +101,7 @@ struct MetadataKeyValue {
#[cfg(test)]
mod tests {
use super::*;
- use arrow::datatypes::{DataType, Field, Fields, IntervalUnit, TimeUnit};
+ use arrow::datatypes::{DataType, Field, IntervalUnit, TimeUnit};
use serde_json::Value;
use std::sync::Arc;
diff --git a/arrow-integration-testing/src/flight_server_scenarios/integration_test.rs b/arrow-integration-testing/src/flight_server_scenarios/integration_test.rs
index 623a240348f4..25203ecb7697 100644
--- a/arrow-integration-testing/src/flight_server_scenarios/integration_test.rs
+++ b/arrow-integration-testing/src/flight_server_scenarios/integration_test.rs
@@ -16,7 +16,6 @@
// under the License.
use std::collections::HashMap;
-use std::convert::TryFrom;
use std::pin::Pin;
use std::sync::Arc;
@@ -35,7 +34,6 @@ use arrow_flight::{
PollInfo, PutResult, SchemaAsIpc, SchemaResult, Ticket,
};
use futures::{channel::mpsc, sink::SinkExt, Stream, StreamExt};
-use std::convert::TryInto;
use tokio::sync::Mutex;
use tonic::{transport::Server, Request, Response, Status, Streaming};
diff --git a/arrow/src/util/test_util.rs b/arrow/src/util/test_util.rs
index fd051dea1a8d..2d718d392baf 100644
--- a/arrow/src/util/test_util.rs
+++ b/arrow/src/util/test_util.rs
@@ -203,7 +203,6 @@ impl<T: Clone> Iterator for BadIterator<T> {
#[cfg(test)]
mod tests {
use super::*;
- use std::env;
#[test]
fn test_data_dir() {
|
Unused import in nightly rust
**Describe the bug**
<!--
A clear and concise description of what the bug is.
-->
With this pr been merged to nightly rust: https://github.com/rust-lang/rust/pull/117772
The tracking for unused import has been improved, resulting numerous compiler warnings when building arrow-rs with nightly rust.
**To Reproduce**
<!--
Steps to reproduce the behavior:
-->
```rust
rustup default nightly
cargo check
```
**Expected behavior**
<!--
A clear and concise description of what you expected to happen.
-->
**Additional context**
<!--
Add any other context about the problem here.
-->
|
2024-03-06T16:29:32Z
|
50.0
|
82fc0df73ab97e239ce5c748a05c57ce582f3d5d
|
|
apache/arrow-rs
| 5,474
|
apache__arrow-rs-5474
|
[
"5463"
] |
7eb866dd328ef9daaa8ce93c25163011ce6ff4d7
|
diff --git a/arrow-array/src/record_batch.rs b/arrow-array/src/record_batch.rs
index d89020a65681..314445bba617 100644
--- a/arrow-array/src/record_batch.rs
+++ b/arrow-array/src/record_batch.rs
@@ -236,6 +236,11 @@ impl RecordBatch {
self.schema.clone()
}
+ /// Returns a reference to the [`Schema`] of the record batch.
+ pub fn schema_ref(&self) -> &SchemaRef {
+ &self.schema
+ }
+
/// Projects the schema onto the specified columns
pub fn project(&self, indices: &[usize]) -> Result<RecordBatch, ArrowError> {
let projected_schema = self.schema.project(indices)?;
diff --git a/arrow-flight/examples/flight_sql_server.rs b/arrow-flight/examples/flight_sql_server.rs
index 85f5c7499346..efd8b6dec90f 100644
--- a/arrow-flight/examples/flight_sql_server.rs
+++ b/arrow-flight/examples/flight_sql_server.rs
@@ -193,9 +193,9 @@ impl FlightSqlService for FlightSqlServiceImpl {
) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
self.check_token(&request)?;
let batch = Self::fake_result().map_err(|e| status!("Could not fake a result", e))?;
- let schema = batch.schema();
- let batches = vec![batch];
- let flight_data = batches_to_flight_data(schema.as_ref(), batches)
+ let schema = batch.schema_ref();
+ let batches = vec![batch.clone()];
+ let flight_data = batches_to_flight_data(schema, batches)
.map_err(|e| status!("Could not convert batches", e))?
.into_iter()
.map(Ok);
@@ -641,10 +641,10 @@ impl FlightSqlService for FlightSqlServiceImpl {
request: Request<Action>,
) -> Result<ActionCreatePreparedStatementResult, Status> {
self.check_token(&request)?;
- let schema = Self::fake_result()
- .map_err(|e| status!("Error getting result schema", e))?
- .schema();
- let message = SchemaAsIpc::new(&schema, &IpcWriteOptions::default())
+ let record_batch =
+ Self::fake_result().map_err(|e| status!("Error getting result schema", e))?;
+ let schema = record_batch.schema_ref();
+ let message = SchemaAsIpc::new(schema, &IpcWriteOptions::default())
.try_into()
.map_err(|e| status!("Unable to serialize schema", e))?;
let IpcMessage(schema_bytes) = message;
diff --git a/arrow-flight/src/encode.rs b/arrow-flight/src/encode.rs
index e6ef9994d487..bb0436816209 100644
--- a/arrow-flight/src/encode.rs
+++ b/arrow-flight/src/encode.rs
@@ -320,7 +320,7 @@ impl FlightDataEncoder {
let schema = match &self.schema {
Some(schema) => schema.clone(),
// encode the schema if this is the first time we have seen it
- None => self.encode_schema(&batch.schema()),
+ None => self.encode_schema(batch.schema_ref()),
};
// encode the batch
@@ -565,12 +565,12 @@ mod tests {
let batch = RecordBatch::try_from_iter(vec![("a", Arc::new(c1) as ArrayRef)])
.expect("cannot create record batch");
- let schema = batch.schema();
+ let schema = batch.schema_ref();
let (_, baseline_flight_batch) = make_flight_data(&batch, &options);
let big_batch = batch.slice(0, batch.num_rows() - 1);
- let optimized_big_batch = prepare_batch_for_flight(&big_batch, Arc::clone(&schema), false)
+ let optimized_big_batch = prepare_batch_for_flight(&big_batch, Arc::clone(schema), false)
.expect("failed to optimize");
let (_, optimized_big_flight_batch) = make_flight_data(&optimized_big_batch, &options);
@@ -581,7 +581,7 @@ mod tests {
let small_batch = batch.slice(0, 1);
let optimized_small_batch =
- prepare_batch_for_flight(&small_batch, Arc::clone(&schema), false)
+ prepare_batch_for_flight(&small_batch, Arc::clone(schema), false)
.expect("failed to optimize");
let (_, optimized_small_flight_batch) = make_flight_data(&optimized_small_batch, &options);
diff --git a/arrow-ipc/src/reader.rs b/arrow-ipc/src/reader.rs
index 81b8b530734a..361c4f7f67dd 100644
--- a/arrow-ipc/src/reader.rs
+++ b/arrow-ipc/src/reader.rs
@@ -1429,7 +1429,7 @@ mod tests {
fn roundtrip_ipc(rb: &RecordBatch) -> RecordBatch {
let mut buf = Vec::new();
- let mut writer = crate::writer::FileWriter::try_new(&mut buf, &rb.schema()).unwrap();
+ let mut writer = crate::writer::FileWriter::try_new(&mut buf, rb.schema_ref()).unwrap();
writer.write(rb).unwrap();
writer.finish().unwrap();
drop(writer);
@@ -1440,7 +1440,7 @@ mod tests {
fn roundtrip_ipc_stream(rb: &RecordBatch) -> RecordBatch {
let mut buf = Vec::new();
- let mut writer = crate::writer::StreamWriter::try_new(&mut buf, &rb.schema()).unwrap();
+ let mut writer = crate::writer::StreamWriter::try_new(&mut buf, rb.schema_ref()).unwrap();
writer.write(rb).unwrap();
writer.finish().unwrap();
drop(writer);
@@ -1815,7 +1815,7 @@ mod tests {
let batch = RecordBatch::new_empty(schema);
let mut buf = Vec::new();
- let mut writer = crate::writer::FileWriter::try_new(&mut buf, &batch.schema()).unwrap();
+ let mut writer = crate::writer::FileWriter::try_new(&mut buf, batch.schema_ref()).unwrap();
writer.write(&batch).unwrap();
writer.finish().unwrap();
drop(writer);
@@ -1842,7 +1842,7 @@ mod tests {
let batch = RecordBatch::new_empty(schema);
let mut buf = Vec::new();
- let mut writer = crate::writer::FileWriter::try_new(&mut buf, &batch.schema()).unwrap();
+ let mut writer = crate::writer::FileWriter::try_new(&mut buf, batch.schema_ref()).unwrap();
writer.write(&batch).unwrap();
writer.finish().unwrap();
drop(writer);
diff --git a/arrow-ipc/src/writer.rs b/arrow-ipc/src/writer.rs
index 1f6bf5f6fa85..99e52e2a7076 100644
--- a/arrow-ipc/src/writer.rs
+++ b/arrow-ipc/src/writer.rs
@@ -1436,7 +1436,7 @@ mod tests {
use super::*;
fn serialize_file(rb: &RecordBatch) -> Vec<u8> {
- let mut writer = FileWriter::try_new(vec![], &rb.schema()).unwrap();
+ let mut writer = FileWriter::try_new(vec![], rb.schema_ref()).unwrap();
writer.write(rb).unwrap();
writer.finish().unwrap();
writer.into_inner().unwrap()
@@ -1448,7 +1448,7 @@ mod tests {
}
fn serialize_stream(record: &RecordBatch) -> Vec<u8> {
- let mut stream_writer = StreamWriter::try_new(vec![], &record.schema()).unwrap();
+ let mut stream_writer = StreamWriter::try_new(vec![], record.schema_ref()).unwrap();
stream_writer.write(record).unwrap();
stream_writer.finish().unwrap();
stream_writer.into_inner().unwrap()
@@ -1982,7 +1982,7 @@ mod tests {
)
.expect("new batch");
- let mut writer = StreamWriter::try_new(vec![], &batch.schema()).expect("new writer");
+ let mut writer = StreamWriter::try_new(vec![], batch.schema_ref()).expect("new writer");
writer.write(&batch).expect("write");
let outbuf = writer.into_inner().expect("inner");
diff --git a/parquet/src/arrow/arrow_reader/mod.rs b/parquet/src/arrow/arrow_reader/mod.rs
index 6b6146042051..7aeb3d127ac3 100644
--- a/parquet/src/arrow/arrow_reader/mod.rs
+++ b/parquet/src/arrow/arrow_reader/mod.rs
@@ -3082,7 +3082,7 @@ mod tests {
.unwrap();
let batches = reader.collect::<Result<Vec<_>, _>>().unwrap();
- let actual = concat_batches(&batch.schema(), &batches).unwrap();
+ let actual = concat_batches(batch.schema_ref(), &batches).unwrap();
assert_eq!(actual.num_rows(), selection.row_count());
let mut batch_offset = 0;
|
diff --git a/arrow-flight/tests/encode_decode.rs b/arrow-flight/tests/encode_decode.rs
index 789233b918d0..224b12500a08 100644
--- a/arrow-flight/tests/encode_decode.rs
+++ b/arrow-flight/tests/encode_decode.rs
@@ -465,7 +465,7 @@ async fn roundtrip(input: Vec<RecordBatch>) {
/// When <https://github.com/apache/arrow-rs/issues/3389> is resolved,
/// it should be possible to use `roundtrip`
async fn roundtrip_dictionary(input: Vec<RecordBatch>) {
- let schema = Arc::new(prepare_schema_for_flight(&input[0].schema()));
+ let schema = Arc::new(prepare_schema_for_flight(input[0].schema_ref()));
let expected_output: Vec<_> = input
.iter()
.map(|batch| prepare_batch_for_flight(batch, schema.clone()).unwrap())
diff --git a/arrow-flight/tests/flight_sql_client_cli.rs b/arrow-flight/tests/flight_sql_client_cli.rs
index a28080450bc2..cc270eeb6186 100644
--- a/arrow-flight/tests/flight_sql_client_cli.rs
+++ b/arrow-flight/tests/flight_sql_client_cli.rs
@@ -189,7 +189,7 @@ impl FlightSqlServiceImpl {
let batch = Self::fake_result()?;
Ok(FlightInfo::new()
- .try_with_schema(&batch.schema())
+ .try_with_schema(batch.schema_ref())
.expect("encoding schema")
.with_endpoint(
FlightEndpoint::new().with_ticket(Ticket::new(
@@ -245,9 +245,9 @@ impl FlightSqlService for FlightSqlServiceImpl {
"part_2" => batch.slice(2, 1),
ticket => panic!("Invalid ticket: {ticket:?}"),
};
- let schema = batch.schema();
- let batches = vec![batch];
- let flight_data = batches_to_flight_data(schema.as_ref(), batches)
+ let schema = batch.schema_ref();
+ let batches = vec![batch.clone()];
+ let flight_data = batches_to_flight_data(schema, batches)
.unwrap()
.into_iter()
.map(Ok);
|
[DISCUSSION] Better borrow propagation (e.g. `RecordBatch::schema()` to return `&SchemaRef` vs `SchemaRef`)
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
For reasons I am not sure of (likely historical), certain APIs of `Schema`/`RecordBatch` return owned instances of `SchemaRef`.
So for example
```rust
let schema: SchemaRef = record_batch.schema()
```
There are at least two challenges here:
1. This often requires an extra copy when not needed (though it is an `Arc::clone` which is relatively inexpensive compared to the work done by most Arrow apis)
2. It makes it hard for borrow propagation to work correctly.
An example of challenges with borrow propagation is illustrated on https://github.com/apache/arrow-rs/issues/5342, which observes, we can't change `Schema::try_merge` to take (`&Schema`) even when it doesn't actually need owned ownership of the `Schema` without creating a temporary `Vec<SchemaRef>` or something similiar
```diff
- pub fn try_merge(schemas: impl IntoIterator<Item = Self>) -> Result<Self, ArrowError> {
+ pub fn try_merge<'a>(
+ schemas: impl IntoIterator<Item = &'a Schema>,
+ ) -> Result<Schema, ArrowError> {
```
**Describe the solution you'd like**
I recommend we add *new* functions that return a reference to the `SchemaRef`
So new functions like
```rust
/// Returns a reference to the [`Schema`] of the record batch.
pub fn schema_ref(&self) -> &SchemaRef {
&self.schema
}
```
**Describe alternatives you've considered**
One alternative is to change the existing APIs as proposed in https://github.com/apache/arrow-rs/pull/5448
```rust
/// Returns a reference to the [`Schema`] of the record batch.
pub fn schema(&self) -> &SchemaRef {
&self.schema
}
```
However I think this requires a substantial amount of downstream code change (as explained on https://github.com/apache/arrow-rs/pull/5448#pullrequestreview-1913470338)
**Additional context**
This came up recently on https://github.com/apache/arrow-rs/issues/5342
@tustvold notes we have made similar changes in the past, e.g. https://github.com/apache/arrow-rs/issues/2035 and https://github.com/apache/arrow-rs/issues/313
|
2024-03-05T23:57:29Z
|
50.0
|
82fc0df73ab97e239ce5c748a05c57ce582f3d5d
|
|
apache/arrow-rs
| 5,439
|
apache__arrow-rs-5439
|
[
"5438"
] |
ef5c45cf4186a8124da5a1603ebdbc09ef9928fc
|
diff --git a/arrow-flight/src/error.rs b/arrow-flight/src/error.rs
index e054883e965d..ba979ca9f7a6 100644
--- a/arrow-flight/src/error.rs
+++ b/arrow-flight/src/error.rs
@@ -49,17 +49,24 @@ impl FlightError {
impl std::fmt::Display for FlightError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- // TODO better format / error
- write!(f, "{self:?}")
+ match self {
+ FlightError::Arrow(source) => write!(f, "Arrow error: {}", source),
+ FlightError::NotYetImplemented(desc) => write!(f, "Not yet implemented: {}", desc),
+ FlightError::Tonic(source) => write!(f, "Tonic error: {}", source),
+ FlightError::ProtocolError(desc) => write!(f, "Protocol error: {}", desc),
+ FlightError::DecodeError(desc) => write!(f, "Decode error: {}", desc),
+ FlightError::ExternalError(source) => write!(f, "External error: {}", source),
+ }
}
}
impl Error for FlightError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
- if let Self::ExternalError(e) = self {
- Some(e.as_ref())
- } else {
- None
+ match self {
+ FlightError::Arrow(source) => Some(source),
+ FlightError::Tonic(source) => Some(source),
+ FlightError::ExternalError(source) => Some(source.as_ref()),
+ _ => None,
}
}
}
diff --git a/arrow-schema/src/error.rs b/arrow-schema/src/error.rs
index b7bf8d6e12a6..d9a0f3452c86 100644
--- a/arrow-schema/src/error.rs
+++ b/arrow-schema/src/error.rs
@@ -114,10 +114,10 @@ impl Display for ArrowError {
impl Error for ArrowError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
- if let Self::ExternalError(e) = self {
- Some(e.as_ref())
- } else {
- None
+ match self {
+ ArrowError::ExternalError(source) => Some(source.as_ref()),
+ ArrowError::IoError(_, source) => Some(source),
+ _ => None,
}
}
}
|
diff --git a/arrow-flight/tests/client.rs b/arrow-flight/tests/client.rs
index 9e19bce92338..47565334cb63 100644
--- a/arrow-flight/tests/client.rs
+++ b/arrow-flight/tests/client.rs
@@ -935,7 +935,7 @@ async fn test_cancel_flight_info_error_no_response() {
assert_eq!(
err.to_string(),
- "ProtocolError(\"Received no response for cancel_flight_info call\")"
+ "Protocol error: Received no response for cancel_flight_info call"
);
// server still got the request
let expected_request = Action::new("CancelFlightInfo", request.encode_to_vec());
@@ -985,7 +985,7 @@ async fn test_renew_flight_endpoint_error_no_response() {
assert_eq!(
err.to_string(),
- "ProtocolError(\"Received no response for renew_flight_endpoint call\")"
+ "Protocol error: Received no response for renew_flight_endpoint call"
);
// server still got the request
let expected_request = Action::new("RenewFlightEndpoint", request.encode_to_vec());
diff --git a/arrow-flight/tests/encode_decode.rs b/arrow-flight/tests/encode_decode.rs
index f4741d743e57..789233b918d0 100644
--- a/arrow-flight/tests/encode_decode.rs
+++ b/arrow-flight/tests/encode_decode.rs
@@ -57,7 +57,7 @@ async fn test_error() {
let result: Result<Vec<_>, _> = decode_stream.try_collect().await;
let result = result.unwrap_err();
- assert_eq!(result.to_string(), r#"NotYetImplemented("foo")"#);
+ assert_eq!(result.to_string(), "Not yet implemented: foo");
}
#[tokio::test]
@@ -287,7 +287,7 @@ async fn test_mismatched_record_batch_schema() {
let err = result.unwrap_err();
assert_eq!(
err.to_string(),
- "Arrow(InvalidArgumentError(\"number of columns(1) must match number of fields(2) in schema\"))"
+ "Arrow error: Invalid argument error: number of columns(1) must match number of fields(2) in schema"
);
}
@@ -312,7 +312,7 @@ async fn test_chained_streams_batch_decoder() {
let err = result.unwrap_err();
assert_eq!(
err.to_string(),
- "ProtocolError(\"Unexpectedly saw multiple Schema messages in FlightData stream\")"
+ "Protocol error: Unexpectedly saw multiple Schema messages in FlightData stream"
);
}
|
Refine `Display` implementation for `FlightError`
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
There's a `TODO` for a better `std::fmt::Display` implementation on `FlightError`. Currently it forwards to `std::fmt::Debug`, which does not appear to be a good practice as errors should describe themselves with friendly messages provided by `Display`.
https://github.com/apache/arrow-rs/blob/ef5c45cf4186a8124da5a1603ebdbc09ef9928fc/arrow-flight/src/error.rs#L50-L55
**Describe the solution you'd like**
Match the variants of the error and specify different prompts like what we did for `ArrowError`.
https://github.com/apache/arrow-rs/blob/ef5c45cf4186a8124da5a1603ebdbc09ef9928fc/arrow-schema/src/error.rs#L79-L87
**Describe alternatives you've considered**
Derive the implementation with `thiserror`. The code can be more concise with the cost of introducing a new build-time dependency.
**Additional context**
A better practice to implement `Display` for errors is **NOT** to include the error source. AWS SDK has adopted this as described in https://github.com/awslabs/aws-sdk-rust/issues/657. However, this could be considered as a breaking change as many developers have not realize that one should leverage something like [`std::error::Report`](https://doc.rust-lang.org/stable/std/error/struct.Report.html) to get the error sources printed.
|
2024-02-27T07:27:28Z
|
50.0
|
82fc0df73ab97e239ce5c748a05c57ce582f3d5d
|
|
apache/arrow-rs
| 5,413
|
apache__arrow-rs-5413
|
[
"5367"
] |
5bb226cc791adfd6903497cbb8fcd8285fe6f298
|
diff --git a/arrow-flight/Cargo.toml b/arrow-flight/Cargo.toml
index 81940b7600ee..1e7255baa748 100644
--- a/arrow-flight/Cargo.toml
+++ b/arrow-flight/Cargo.toml
@@ -44,7 +44,9 @@ bytes = { version = "1", default-features = false }
futures = { version = "0.3", default-features = false, features = ["alloc"] }
once_cell = { version = "1", optional = true }
paste = { version = "1.0" }
-prost = { version = "0.12.1", default-features = false, features = ["prost-derive"] }
+prost = { version = "0.12.3", default-features = false, features = ["prost-derive"] }
+# For Timestamp type
+prost-types = { version = "0.12.3", default-features = false }
tokio = { version = "1.0", default-features = false, features = ["macros", "rt", "rt-multi-thread"] }
tonic = { version = "0.11.0", default-features = false, features = ["transport", "codegen", "prost"] }
diff --git a/arrow-flight/examples/flight_sql_server.rs b/arrow-flight/examples/flight_sql_server.rs
index bd94d3c499ca..85f5c7499346 100644
--- a/arrow-flight/examples/flight_sql_server.rs
+++ b/arrow-flight/examples/flight_sql_server.rs
@@ -249,6 +249,8 @@ impl FlightSqlService for FlightSqlServiceImpl {
let endpoint = FlightEndpoint {
ticket: Some(ticket),
location: vec![loc],
+ expiration_time: None,
+ app_metadata: vec![].into(),
};
let info = FlightInfo::new()
.try_with_schema(&schema)
diff --git a/arrow-flight/examples/server.rs b/arrow-flight/examples/server.rs
index 85ac4ca1384c..8c766b075957 100644
--- a/arrow-flight/examples/server.rs
+++ b/arrow-flight/examples/server.rs
@@ -22,7 +22,7 @@ use tonic::{Request, Response, Status, Streaming};
use arrow_flight::{
flight_service_server::FlightService, flight_service_server::FlightServiceServer, Action,
ActionType, Criteria, Empty, FlightData, FlightDescriptor, FlightInfo, HandshakeRequest,
- HandshakeResponse, PutResult, SchemaResult, Ticket,
+ HandshakeResponse, PollInfo, PutResult, SchemaResult, Ticket,
};
#[derive(Clone)]
@@ -59,6 +59,13 @@ impl FlightService for FlightServiceImpl {
Err(Status::unimplemented("Implement get_flight_info"))
}
+ async fn poll_flight_info(
+ &self,
+ _request: Request<FlightDescriptor>,
+ ) -> Result<Response<PollInfo>, Status> {
+ Err(Status::unimplemented("Implement poll_flight_info"))
+ }
+
async fn get_schema(
&self,
_request: Request<FlightDescriptor>,
diff --git a/arrow-flight/src/arrow.flight.protocol.rs b/arrow-flight/src/arrow.flight.protocol.rs
index e76013bd7c5f..67265e781786 100644
--- a/arrow-flight/src/arrow.flight.protocol.rs
+++ b/arrow-flight/src/arrow.flight.protocol.rs
@@ -70,6 +70,26 @@ pub struct Action {
pub body: ::prost::bytes::Bytes,
}
///
+/// The request of the CancelFlightInfo action.
+///
+/// The request should be stored in Action.body.
+#[allow(clippy::derive_partial_eq_without_eq)]
+#[derive(Clone, PartialEq, ::prost::Message)]
+pub struct CancelFlightInfoRequest {
+ #[prost(message, optional, tag = "1")]
+ pub info: ::core::option::Option<FlightInfo>,
+}
+///
+/// The request of the RenewFlightEndpoint action.
+///
+/// The request should be stored in Action.body.
+#[allow(clippy::derive_partial_eq_without_eq)]
+#[derive(Clone, PartialEq, ::prost::Message)]
+pub struct RenewFlightEndpointRequest {
+ #[prost(message, optional, tag = "1")]
+ pub endpoint: ::core::option::Option<FlightEndpoint>,
+}
+///
/// An opaque result returned after executing an action.
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
@@ -78,6 +98,16 @@ pub struct Result {
pub body: ::prost::bytes::Bytes,
}
///
+/// The result of the CancelFlightInfo action.
+///
+/// The result should be stored in Result.body.
+#[allow(clippy::derive_partial_eq_without_eq)]
+#[derive(Clone, PartialEq, ::prost::Message)]
+pub struct CancelFlightInfoResult {
+ #[prost(enumeration = "CancelStatus", tag = "1")]
+ pub status: i32,
+}
+///
/// Wrap the result of a getSchema call
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
@@ -209,6 +239,57 @@ pub struct FlightInfo {
/// FlightEndpoints are in the same order as the data.
#[prost(bool, tag = "6")]
pub ordered: bool,
+ ///
+ /// Application-defined metadata.
+ ///
+ /// There is no inherent or required relationship between this
+ /// and the app_metadata fields in the FlightEndpoints or resulting
+ /// FlightData messages. Since this metadata is application-defined,
+ /// a given application could define there to be a relationship,
+ /// but there is none required by the spec.
+ #[prost(bytes = "bytes", tag = "7")]
+ pub app_metadata: ::prost::bytes::Bytes,
+}
+///
+/// The information to process a long-running query.
+#[allow(clippy::derive_partial_eq_without_eq)]
+#[derive(Clone, PartialEq, ::prost::Message)]
+pub struct PollInfo {
+ ///
+ /// The currently available results.
+ ///
+ /// If "flight_descriptor" is not specified, the query is complete
+ /// and "info" specifies all results. Otherwise, "info" contains
+ /// partial query results.
+ ///
+ /// Note that each PollInfo response contains a complete
+ /// FlightInfo (not just the delta between the previous and current
+ /// FlightInfo).
+ ///
+ /// Subsequent PollInfo responses may only append new endpoints to
+ /// info.
+ ///
+ /// Clients can begin fetching results via DoGet(Ticket) with the
+ /// ticket in the info before the query is
+ /// completed. FlightInfo.ordered is also valid.
+ #[prost(message, optional, tag = "1")]
+ pub info: ::core::option::Option<FlightInfo>,
+ ///
+ /// The descriptor the client should use on the next try.
+ /// If unset, the query is complete.
+ #[prost(message, optional, tag = "2")]
+ pub flight_descriptor: ::core::option::Option<FlightDescriptor>,
+ ///
+ /// Query progress. If known, must be in \[0.0, 1.0\] but need not be
+ /// monotonic or nondecreasing. If unknown, do not set.
+ #[prost(double, optional, tag = "3")]
+ pub progress: ::core::option::Option<f64>,
+ ///
+ /// Expiration time for this request. After this passes, the server
+ /// might not accept the retry descriptor anymore (and the query may
+ /// be cancelled). This may be updated on a call to PollFlightInfo.
+ #[prost(message, optional, tag = "4")]
+ pub expiration_time: ::core::option::Option<::prost_types::Timestamp>,
}
///
/// A particular stream or split associated with a flight.
@@ -236,6 +317,22 @@ pub struct FlightEndpoint {
/// represent redundant and/or load balanced services.
#[prost(message, repeated, tag = "2")]
pub location: ::prost::alloc::vec::Vec<Location>,
+ ///
+ /// Expiration time of this stream. If present, clients may assume
+ /// they can retry DoGet requests. Otherwise, it is
+ /// application-defined whether DoGet requests may be retried.
+ #[prost(message, optional, tag = "3")]
+ pub expiration_time: ::core::option::Option<::prost_types::Timestamp>,
+ ///
+ /// Application-defined metadata.
+ ///
+ /// There is no inherent or required relationship between this
+ /// and the app_metadata fields in the FlightInfo or resulting
+ /// FlightData messages. Since this metadata is application-defined,
+ /// a given application could define there to be a relationship,
+ /// but there is none required by the spec.
+ #[prost(bytes = "bytes", tag = "4")]
+ pub app_metadata: ::prost::bytes::Bytes,
}
///
/// A location where a Flight service will accept retrieval of a particular
@@ -292,6 +389,51 @@ pub struct PutResult {
#[prost(bytes = "bytes", tag = "1")]
pub app_metadata: ::prost::bytes::Bytes,
}
+///
+/// The result of a cancel operation.
+///
+/// This is used by CancelFlightInfoResult.status.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
+#[repr(i32)]
+pub enum CancelStatus {
+ /// The cancellation status is unknown. Servers should avoid using
+ /// this value (send a NOT_FOUND error if the requested query is
+ /// not known). Clients can retry the request.
+ Unspecified = 0,
+ /// The cancellation request is complete. Subsequent requests with
+ /// the same payload may return CANCELLED or a NOT_FOUND error.
+ Cancelled = 1,
+ /// The cancellation request is in progress. The client may retry
+ /// the cancellation request.
+ Cancelling = 2,
+ /// The query is not cancellable. The client should not retry the
+ /// cancellation request.
+ NotCancellable = 3,
+}
+impl CancelStatus {
+ /// String value of the enum field names used in the ProtoBuf definition.
+ ///
+ /// The values are not transformed in any way and thus are considered stable
+ /// (if the ProtoBuf definition does not change) and safe for programmatic use.
+ pub fn as_str_name(&self) -> &'static str {
+ match self {
+ CancelStatus::Unspecified => "CANCEL_STATUS_UNSPECIFIED",
+ CancelStatus::Cancelled => "CANCEL_STATUS_CANCELLED",
+ CancelStatus::Cancelling => "CANCEL_STATUS_CANCELLING",
+ CancelStatus::NotCancellable => "CANCEL_STATUS_NOT_CANCELLABLE",
+ }
+ }
+ /// Creates an enum from field names used in the ProtoBuf definition.
+ pub fn from_str_name(value: &str) -> ::core::option::Option<Self> {
+ match value {
+ "CANCEL_STATUS_UNSPECIFIED" => Some(Self::Unspecified),
+ "CANCEL_STATUS_CANCELLED" => Some(Self::Cancelled),
+ "CANCEL_STATUS_CANCELLING" => Some(Self::Cancelling),
+ "CANCEL_STATUS_NOT_CANCELLABLE" => Some(Self::NotCancellable),
+ _ => None,
+ }
+ }
+}
/// Generated client implementations.
pub mod flight_service_client {
#![allow(unused_variables, dead_code, missing_docs, clippy::let_unit_value)]
@@ -487,6 +629,56 @@ pub mod flight_service_client {
self.inner.unary(req, path, codec).await
}
///
+ /// For a given FlightDescriptor, start a query and get information
+ /// to poll its execution status. This is a useful interface if the
+ /// query may be a long-running query. The first PollFlightInfo call
+ /// should return as quickly as possible. (GetFlightInfo doesn't
+ /// return until the query is complete.)
+ ///
+ /// A client can consume any available results before
+ /// the query is completed. See PollInfo.info for details.
+ ///
+ /// A client can poll the updated query status by calling
+ /// PollFlightInfo() with PollInfo.flight_descriptor. A server
+ /// should not respond until the result would be different from last
+ /// time. That way, the client can "long poll" for updates
+ /// without constantly making requests. Clients can set a short timeout
+ /// to avoid blocking calls if desired.
+ ///
+ /// A client can't use PollInfo.flight_descriptor after
+ /// PollInfo.expiration_time passes. A server might not accept the
+ /// retry descriptor anymore and the query may be cancelled.
+ ///
+ /// A client may use the CancelFlightInfo action with
+ /// PollInfo.info to cancel the running query.
+ pub async fn poll_flight_info(
+ &mut self,
+ request: impl tonic::IntoRequest<super::FlightDescriptor>,
+ ) -> std::result::Result<tonic::Response<super::PollInfo>, tonic::Status> {
+ self.inner
+ .ready()
+ .await
+ .map_err(|e| {
+ tonic::Status::new(
+ tonic::Code::Unknown,
+ format!("Service was not ready: {}", e.into()),
+ )
+ })?;
+ let codec = tonic::codec::ProstCodec::default();
+ let path = http::uri::PathAndQuery::from_static(
+ "/arrow.flight.protocol.FlightService/PollFlightInfo",
+ );
+ let mut req = request.into_request();
+ req.extensions_mut()
+ .insert(
+ GrpcMethod::new(
+ "arrow.flight.protocol.FlightService",
+ "PollFlightInfo",
+ ),
+ );
+ self.inner.unary(req, path, codec).await
+ }
+ ///
/// For a given FlightDescriptor, get the Schema as described in Schema.fbs::Schema
/// This is used when a consumer needs the Schema of flight stream. Similar to
/// GetFlightInfo this interface may generate a new flight that was not previously
@@ -735,6 +927,33 @@ pub mod flight_service_server {
request: tonic::Request<super::FlightDescriptor>,
) -> std::result::Result<tonic::Response<super::FlightInfo>, tonic::Status>;
///
+ /// For a given FlightDescriptor, start a query and get information
+ /// to poll its execution status. This is a useful interface if the
+ /// query may be a long-running query. The first PollFlightInfo call
+ /// should return as quickly as possible. (GetFlightInfo doesn't
+ /// return until the query is complete.)
+ ///
+ /// A client can consume any available results before
+ /// the query is completed. See PollInfo.info for details.
+ ///
+ /// A client can poll the updated query status by calling
+ /// PollFlightInfo() with PollInfo.flight_descriptor. A server
+ /// should not respond until the result would be different from last
+ /// time. That way, the client can "long poll" for updates
+ /// without constantly making requests. Clients can set a short timeout
+ /// to avoid blocking calls if desired.
+ ///
+ /// A client can't use PollInfo.flight_descriptor after
+ /// PollInfo.expiration_time passes. A server might not accept the
+ /// retry descriptor anymore and the query may be cancelled.
+ ///
+ /// A client may use the CancelFlightInfo action with
+ /// PollInfo.info to cancel the running query.
+ async fn poll_flight_info(
+ &self,
+ request: tonic::Request<super::FlightDescriptor>,
+ ) -> std::result::Result<tonic::Response<super::PollInfo>, tonic::Status>;
+ ///
/// For a given FlightDescriptor, get the Schema as described in Schema.fbs::Schema
/// This is used when a consumer needs the Schema of flight stream. Similar to
/// GetFlightInfo this interface may generate a new flight that was not previously
@@ -1052,6 +1271,53 @@ pub mod flight_service_server {
};
Box::pin(fut)
}
+ "/arrow.flight.protocol.FlightService/PollFlightInfo" => {
+ #[allow(non_camel_case_types)]
+ struct PollFlightInfoSvc<T: FlightService>(pub Arc<T>);
+ impl<
+ T: FlightService,
+ > tonic::server::UnaryService<super::FlightDescriptor>
+ for PollFlightInfoSvc<T> {
+ type Response = super::PollInfo;
+ type Future = BoxFuture<
+ tonic::Response<Self::Response>,
+ tonic::Status,
+ >;
+ fn call(
+ &mut self,
+ request: tonic::Request<super::FlightDescriptor>,
+ ) -> Self::Future {
+ let inner = Arc::clone(&self.0);
+ let fut = async move {
+ <T as FlightService>::poll_flight_info(&inner, request)
+ .await
+ };
+ Box::pin(fut)
+ }
+ }
+ let accept_compression_encodings = self.accept_compression_encodings;
+ let send_compression_encodings = self.send_compression_encodings;
+ let max_decoding_message_size = self.max_decoding_message_size;
+ let max_encoding_message_size = self.max_encoding_message_size;
+ let inner = self.inner.clone();
+ let fut = async move {
+ let inner = inner.0;
+ let method = PollFlightInfoSvc(inner);
+ let codec = tonic::codec::ProstCodec::default();
+ let mut grpc = tonic::server::Grpc::new(codec)
+ .apply_compression_config(
+ accept_compression_encodings,
+ send_compression_encodings,
+ )
+ .apply_max_message_size_config(
+ max_decoding_message_size,
+ max_encoding_message_size,
+ );
+ let res = grpc.unary(method, req).await;
+ Ok(res)
+ };
+ Box::pin(fut)
+ }
"/arrow.flight.protocol.FlightService/GetSchema" => {
#[allow(non_camel_case_types)]
struct GetSchemaSvc<T: FlightService>(pub Arc<T>);
diff --git a/arrow-flight/src/client.rs b/arrow-flight/src/client.rs
index a264012c82ec..b2abfb0c17b2 100644
--- a/arrow-flight/src/client.rs
+++ b/arrow-flight/src/client.rs
@@ -18,9 +18,12 @@
use std::task::Poll;
use crate::{
- decode::FlightRecordBatchStream, flight_service_client::FlightServiceClient,
- trailers::extract_lazy_trailers, Action, ActionType, Criteria, Empty, FlightData,
- FlightDescriptor, FlightInfo, HandshakeRequest, PutResult, Ticket,
+ decode::FlightRecordBatchStream,
+ flight_service_client::FlightServiceClient,
+ gen::{CancelFlightInfoRequest, CancelFlightInfoResult, RenewFlightEndpointRequest},
+ trailers::extract_lazy_trailers,
+ Action, ActionType, Criteria, Empty, FlightData, FlightDescriptor, FlightEndpoint, FlightInfo,
+ HandshakeRequest, PollInfo, PutResult, Ticket,
};
use arrow_schema::Schema;
use bytes::Bytes;
@@ -30,6 +33,7 @@ use futures::{
stream::{self, BoxStream},
FutureExt, Stream, StreamExt, TryStreamExt,
};
+use prost::Message;
use tonic::{metadata::MetadataMap, transport::Channel};
use crate::error::{FlightError, Result};
@@ -256,6 +260,64 @@ impl FlightClient {
Ok(response)
}
+ /// Make a `PollFlightInfo` call to the server with the provided
+ /// [`FlightDescriptor`] and return the [`PollInfo`] from the
+ /// server.
+ ///
+ /// The `info` field of the [`PollInfo`] can be used with
+ /// [`Self::do_get`] to retrieve the requested batches.
+ ///
+ /// If the `flight_descriptor` field of the [`PollInfo`] is
+ /// `None` then the `info` field represents the complete results.
+ ///
+ /// If the `flight_descriptor` field is some [`FlightDescriptor`]
+ /// then the `info` field has incomplete results, and the client
+ /// should call this method again with the new `flight_descriptor`
+ /// to get the updated status.
+ ///
+ /// The `expiration_time`, if set, represents the expiration time
+ /// of the `flight_descriptor`, after which the server may not accept
+ /// this retry descriptor and may cancel the query.
+ ///
+ /// # Example:
+ /// ```no_run
+ /// # async fn run() {
+ /// # use arrow_flight::FlightClient;
+ /// # use arrow_flight::FlightDescriptor;
+ /// # let channel: tonic::transport::Channel = unimplemented!();
+ /// let mut client = FlightClient::new(channel);
+ ///
+ /// // Send a 'CMD' request to the server
+ /// let request = FlightDescriptor::new_cmd(b"MOAR DATA".to_vec());
+ /// let poll_info = client
+ /// .poll_flight_info(request)
+ /// .await
+ /// .expect("error handshaking");
+ ///
+ /// // retrieve the first endpoint from the returned poll info
+ /// let ticket = poll_info
+ /// .info
+ /// .expect("expected flight info")
+ /// .endpoint[0]
+ /// // Extract the ticket
+ /// .ticket
+ /// .clone()
+ /// .expect("expected ticket");
+ ///
+ /// // Retrieve the corresponding RecordBatch stream with do_get
+ /// let data = client
+ /// .do_get(ticket)
+ /// .await
+ /// .expect("error fetching data");
+ /// # }
+ /// ```
+ pub async fn poll_flight_info(&mut self, descriptor: FlightDescriptor) -> Result<PollInfo> {
+ let request = self.make_request(descriptor);
+
+ let response = self.inner.poll_flight_info(request).await?.into_inner();
+ Ok(response)
+ }
+
/// Make a `DoPut` call to the server with the provided
/// [`Stream`] of [`FlightData`] and returning a
/// stream of [`PutResult`].
@@ -540,6 +602,82 @@ impl FlightClient {
Ok(result_stream.boxed())
}
+ /// Make a `CancelFlightInfo` call to the server and return
+ /// a [`CancelFlightInfoResult`].
+ ///
+ /// # Example:
+ /// ```no_run
+ /// # async fn run() {
+ /// # use arrow_flight::{CancelFlightInfoRequest, FlightClient, FlightDescriptor};
+ /// # let channel: tonic::transport::Channel = unimplemented!();
+ /// let mut client = FlightClient::new(channel);
+ ///
+ /// // Send a 'CMD' request to the server
+ /// let request = FlightDescriptor::new_cmd(b"MOAR DATA".to_vec());
+ /// let flight_info = client
+ /// .get_flight_info(request)
+ /// .await
+ /// .expect("error handshaking");
+ ///
+ /// // Cancel the query
+ /// let request = CancelFlightInfoRequest::new(flight_info);
+ /// let result = client
+ /// .cancel_flight_info(request)
+ /// .await
+ /// .expect("error cancelling");
+ /// # }
+ /// ```
+ pub async fn cancel_flight_info(
+ &mut self,
+ request: CancelFlightInfoRequest,
+ ) -> Result<CancelFlightInfoResult> {
+ let action = Action::new("CancelFlightInfo", request.encode_to_vec());
+ let response = self.do_action(action).await?.try_next().await?;
+ let response = response.ok_or(FlightError::protocol(
+ "Received no response for cancel_flight_info call",
+ ))?;
+ CancelFlightInfoResult::decode(response)
+ .map_err(|e| FlightError::DecodeError(e.to_string()))
+ }
+
+ /// Make a `RenewFlightEndpoint` call to the server and return
+ /// the renewed [`FlightEndpoint`].
+ ///
+ /// # Example:
+ /// ```no_run
+ /// # async fn run() {
+ /// # use arrow_flight::{FlightClient, FlightDescriptor, RenewFlightEndpointRequest};
+ /// # let channel: tonic::transport::Channel = unimplemented!();
+ /// let mut client = FlightClient::new(channel);
+ ///
+ /// // Send a 'CMD' request to the server
+ /// let request = FlightDescriptor::new_cmd(b"MOAR DATA".to_vec());
+ /// let flight_endpoint = client
+ /// .get_flight_info(request)
+ /// .await
+ /// .expect("error handshaking")
+ /// .endpoint[0];
+ ///
+ /// // Renew the endpoint
+ /// let request = RenewFlightEndpointRequest::new(flight_endpoint);
+ /// let flight_endpoint = client
+ /// .renew_flight_endpoint(request)
+ /// .await
+ /// .expect("error renewing");
+ /// # }
+ /// ```
+ pub async fn renew_flight_endpoint(
+ &mut self,
+ request: RenewFlightEndpointRequest,
+ ) -> Result<FlightEndpoint> {
+ let action = Action::new("RenewFlightEndpoint", request.encode_to_vec());
+ let response = self.do_action(action).await?.try_next().await?;
+ let response = response.ok_or(FlightError::protocol(
+ "Received no response for renew_flight_endpoint call",
+ ))?;
+ FlightEndpoint::decode(response).map_err(|e| FlightError::DecodeError(e.to_string()))
+ }
+
/// return a Request, adding any configured metadata
fn make_request<T>(&self, t: T) -> tonic::Request<T> {
// Pass along metadata
diff --git a/arrow-flight/src/lib.rs b/arrow-flight/src/lib.rs
index 8d05f658703a..434d19ce76fe 100644
--- a/arrow-flight/src/lib.rs
+++ b/arrow-flight/src/lib.rs
@@ -45,6 +45,7 @@ use arrow_ipc::convert::try_schema_from_ipc_buffer;
use base64::prelude::BASE64_STANDARD;
use base64::Engine;
use bytes::Bytes;
+use prost_types::Timestamp;
use std::{
convert::{TryFrom, TryInto},
fmt,
@@ -97,6 +98,9 @@ pub mod error;
pub use gen::Action;
pub use gen::ActionType;
pub use gen::BasicAuth;
+pub use gen::CancelFlightInfoRequest;
+pub use gen::CancelFlightInfoResult;
+pub use gen::CancelStatus;
pub use gen::Criteria;
pub use gen::Empty;
pub use gen::FlightData;
@@ -106,7 +110,9 @@ pub use gen::FlightInfo;
pub use gen::HandshakeRequest;
pub use gen::HandshakeResponse;
pub use gen::Location;
+pub use gen::PollInfo;
pub use gen::PutResult;
+pub use gen::RenewFlightEndpointRequest;
pub use gen::Result;
pub use gen::SchemaResult;
pub use gen::Ticket;
@@ -225,7 +231,7 @@ impl fmt::Display for FlightEndpoint {
write!(f, " ticket: ")?;
match &self.ticket {
Some(value) => write!(f, "{value}"),
- None => write!(f, " none"),
+ None => write!(f, " None"),
}?;
write!(f, ", location: [")?;
let mut sep = "";
@@ -234,6 +240,13 @@ impl fmt::Display for FlightEndpoint {
sep = ", ";
}
write!(f, "]")?;
+ write!(f, ", expiration_time:")?;
+ match &self.expiration_time {
+ Some(value) => write!(f, " {value}"),
+ None => write!(f, " None"),
+ }?;
+ write!(f, ", app_metadata: ")?;
+ limited_fmt(f, &self.app_metadata, 8)?;
write!(f, " }}")
}
}
@@ -257,6 +270,68 @@ impl fmt::Display for FlightInfo {
}
write!(f, "], total_records: {}", self.total_records)?;
write!(f, ", total_bytes: {}", self.total_bytes)?;
+ write!(f, ", ordered: {}", self.ordered)?;
+ write!(f, ", app_metadata: ")?;
+ limited_fmt(f, &self.app_metadata, 8)?;
+ write!(f, " }}")
+ }
+}
+
+impl fmt::Display for PollInfo {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "PollInfo {{")?;
+ write!(f, " info:")?;
+ match &self.info {
+ Some(value) => write!(f, " {value}"),
+ None => write!(f, " None"),
+ }?;
+ write!(f, ", descriptor:")?;
+ match &self.flight_descriptor {
+ Some(d) => write!(f, " {d}"),
+ None => write!(f, " None"),
+ }?;
+ write!(f, ", progress:")?;
+ match &self.progress {
+ Some(value) => write!(f, " {value}"),
+ None => write!(f, " None"),
+ }?;
+ write!(f, ", expiration_time:")?;
+ match &self.expiration_time {
+ Some(value) => write!(f, " {value}"),
+ None => write!(f, " None"),
+ }?;
+ write!(f, " }}")
+ }
+}
+
+impl fmt::Display for CancelFlightInfoRequest {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "CancelFlightInfoRequest {{")?;
+ write!(f, " info: ")?;
+ match &self.info {
+ Some(value) => write!(f, "{value}")?,
+ None => write!(f, "None")?,
+ };
+ write!(f, " }}")
+ }
+}
+
+impl fmt::Display for CancelFlightInfoResult {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "CancelFlightInfoResult {{")?;
+ write!(f, " status: {}", self.status().as_str_name())?;
+ write!(f, " }}")
+ }
+}
+
+impl fmt::Display for RenewFlightEndpointRequest {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "RenewFlightEndpointRequest {{")?;
+ write!(f, " endpoint: ")?;
+ match &self.endpoint {
+ Some(value) => write!(f, "{value}")?,
+ None => write!(f, "None")?,
+ };
write!(f, " }}")
}
}
@@ -472,9 +547,6 @@ impl FlightInfo {
/// // Encode the Arrow schema
/// .try_with_schema(&get_schema())
/// .expect("encoding failed")
- /// .with_descriptor(
- /// FlightDescriptor::new_cmd("a command")
- /// )
/// .with_endpoint(
/// FlightEndpoint::new()
/// .with_ticket(Ticket::new("ticket contents")
@@ -493,6 +565,7 @@ impl FlightInfo {
// https://github.com/apache/arrow-rs/blob/17ca4d51d0490f9c65f5adde144f677dbc8300e7/format/Flight.proto#L287-L289
total_records: -1,
total_bytes: -1,
+ app_metadata: Bytes::new(),
}
}
@@ -546,6 +619,70 @@ impl FlightInfo {
self.ordered = ordered;
self
}
+
+ /// Add optional application specific metadata to the message
+ pub fn with_app_metadata(mut self, app_metadata: impl Into<Bytes>) -> Self {
+ self.app_metadata = app_metadata.into();
+ self
+ }
+}
+
+impl PollInfo {
+ /// Create a new, empty [`PollInfo`], providing information for a long-running query
+ ///
+ /// # Example:
+ /// ```
+ /// # use arrow_flight::{FlightInfo, PollInfo, FlightDescriptor};
+ /// # use prost_types::Timestamp;
+ /// // Create a new PollInfo
+ /// let poll_info = PollInfo::new()
+ /// .with_info(FlightInfo::new())
+ /// .with_descriptor(FlightDescriptor::new_cmd("RUN QUERY"))
+ /// .try_with_progress(0.5)
+ /// .expect("progress should've been valid")
+ /// .with_expiration_time(
+ /// "1970-01-01".parse().expect("invalid timestamp")
+ /// );
+ /// ```
+ pub fn new() -> Self {
+ Self {
+ info: None,
+ flight_descriptor: None,
+ progress: None,
+ expiration_time: None,
+ }
+ }
+
+ /// Add the current available results for the poll call as a [`FlightInfo`]
+ pub fn with_info(mut self, info: FlightInfo) -> Self {
+ self.info = Some(info);
+ self
+ }
+
+ /// Add a [`FlightDescriptor`] that the client should use for the next poll call,
+ /// if the query is not yet complete
+ pub fn with_descriptor(mut self, flight_descriptor: FlightDescriptor) -> Self {
+ self.flight_descriptor = Some(flight_descriptor);
+ self
+ }
+
+ /// Set the query progress if known. Must be in the range [0.0, 1.0] else this will
+ /// return an error
+ pub fn try_with_progress(mut self, progress: f64) -> ArrowResult<Self> {
+ if !(0.0..=1.0).contains(&progress) {
+ return Err(ArrowError::InvalidArgumentError(format!(
+ "PollInfo progress must be in the range [0.0, 1.0], got {progress}"
+ )));
+ }
+ self.progress = Some(progress);
+ Ok(self)
+ }
+
+ /// Specify expiration time for this request
+ pub fn with_expiration_time(mut self, expiration_time: Timestamp) -> Self {
+ self.expiration_time = Some(expiration_time);
+ self
+ }
}
impl<'a> SchemaAsIpc<'a> {
@@ -556,6 +693,33 @@ impl<'a> SchemaAsIpc<'a> {
}
}
+impl CancelFlightInfoRequest {
+ /// Create a new [`CancelFlightInfoRequest`], providing the [`FlightInfo`]
+ /// of the query to cancel.
+ pub fn new(info: FlightInfo) -> Self {
+ Self { info: Some(info) }
+ }
+}
+
+impl CancelFlightInfoResult {
+ /// Create a new [`CancelFlightInfoResult`] from the provided [`CancelStatus`].
+ pub fn new(status: CancelStatus) -> Self {
+ Self {
+ status: status as i32,
+ }
+ }
+}
+
+impl RenewFlightEndpointRequest {
+ /// Create a new [`RenewFlightEndpointRequest`], providing the [`FlightEndpoint`]
+ /// for which is being requested an extension of its expiration.
+ pub fn new(endpoint: FlightEndpoint) -> Self {
+ Self {
+ endpoint: Some(endpoint),
+ }
+ }
+}
+
impl Action {
/// Create a new Action with type and body
pub fn new(action_type: impl Into<String>, body: impl Into<Bytes>) -> Self {
@@ -633,6 +797,18 @@ impl FlightEndpoint {
self.location.push(Location { uri: uri.into() });
self
}
+
+ /// Specify expiration time for this stream
+ pub fn with_expiration_time(mut self, expiration_time: Timestamp) -> Self {
+ self.expiration_time = Some(expiration_time);
+ self
+ }
+
+ /// Add optional application specific metadata to the message
+ pub fn with_app_metadata(mut self, app_metadata: impl Into<Bytes>) -> Self {
+ self.app_metadata = app_metadata.into();
+ self
+ }
}
#[cfg(test)]
diff --git a/arrow-flight/src/sql/arrow.flight.protocol.sql.rs b/arrow-flight/src/sql/arrow.flight.protocol.sql.rs
index c7c23311e61e..2b2f4af7ac90 100644
--- a/arrow-flight/src/sql/arrow.flight.protocol.sql.rs
+++ b/arrow-flight/src/sql/arrow.flight.protocol.sql.rs
@@ -176,7 +176,7 @@ pub struct CommandGetDbSchemas {
/// - ARROW:FLIGHT:SQL:PRECISION - Column precision/size
/// - ARROW:FLIGHT:SQL:SCALE - Column scale/decimal digits if applicable
/// - ARROW:FLIGHT:SQL:IS_AUTO_INCREMENT - "1" indicates if the column is auto incremented, "0" otherwise.
-/// - ARROW:FLIGHT:SQL:IS_CASE_SENSITIVE - "1" indicates if the column is case sensitive, "0" otherwise.
+/// - ARROW:FLIGHT:SQL:IS_CASE_SENSITIVE - "1" indicates if the column is case-sensitive, "0" otherwise.
/// - ARROW:FLIGHT:SQL:IS_READ_ONLY - "1" indicates if the column is read only, "0" otherwise.
/// - ARROW:FLIGHT:SQL:IS_SEARCHABLE - "1" indicates if the column is searchable via WHERE clause, "0" otherwise.
/// The returned data should be ordered by catalog_name, db_schema_name, table_name, then table_type, followed by table_schema if requested.
@@ -485,11 +485,14 @@ pub struct ActionCreatePreparedStatementResult {
#[prost(bytes = "bytes", tag = "1")]
pub prepared_statement_handle: ::prost::bytes::Bytes,
/// If a result set generating query was provided, dataset_schema contains the
- /// schema of the dataset as described in Schema.fbs::Schema, it is serialized as an IPC message.
+ /// schema of the result set. It should be an IPC-encapsulated Schema, as described in Schema.fbs.
+ /// For some queries, the schema of the results may depend on the schema of the parameters. The server
+ /// should provide its best guess as to the schema at this point. Clients must not assume that this
+ /// schema, if provided, will be accurate.
#[prost(bytes = "bytes", tag = "2")]
pub dataset_schema: ::prost::bytes::Bytes,
/// If the query provided contained parameters, parameter_schema contains the
- /// schema of the expected parameters as described in Schema.fbs::Schema, it is serialized as an IPC message.
+ /// schema of the expected parameters. It should be an IPC-encapsulated Schema, as described in Schema.fbs.
#[prost(bytes = "bytes", tag = "3")]
pub parameter_schema: ::prost::bytes::Bytes,
}
@@ -691,7 +694,7 @@ pub mod action_end_savepoint_request {
/// - ARROW:FLIGHT:SQL:PRECISION - Column precision/size
/// - ARROW:FLIGHT:SQL:SCALE - Column scale/decimal digits if applicable
/// - ARROW:FLIGHT:SQL:IS_AUTO_INCREMENT - "1" indicates if the column is auto incremented, "0" otherwise.
-/// - ARROW:FLIGHT:SQL:IS_CASE_SENSITIVE - "1" indicates if the column is case sensitive, "0" otherwise.
+/// - ARROW:FLIGHT:SQL:IS_CASE_SENSITIVE - "1" indicates if the column is case-sensitive, "0" otherwise.
/// - ARROW:FLIGHT:SQL:IS_READ_ONLY - "1" indicates if the column is read only, "0" otherwise.
/// - ARROW:FLIGHT:SQL:IS_SEARCHABLE - "1" indicates if the column is searchable via WHERE clause, "0" otherwise.
/// - GetFlightInfo: execute the query.
@@ -717,7 +720,7 @@ pub struct CommandStatementQuery {
/// - ARROW:FLIGHT:SQL:PRECISION - Column precision/size
/// - ARROW:FLIGHT:SQL:SCALE - Column scale/decimal digits if applicable
/// - ARROW:FLIGHT:SQL:IS_AUTO_INCREMENT - "1" indicates if the column is auto incremented, "0" otherwise.
-/// - ARROW:FLIGHT:SQL:IS_CASE_SENSITIVE - "1" indicates if the column is case sensitive, "0" otherwise.
+/// - ARROW:FLIGHT:SQL:IS_CASE_SENSITIVE - "1" indicates if the column is case-sensitive, "0" otherwise.
/// - ARROW:FLIGHT:SQL:IS_READ_ONLY - "1" indicates if the column is read only, "0" otherwise.
/// - ARROW:FLIGHT:SQL:IS_SEARCHABLE - "1" indicates if the column is searchable via WHERE clause, "0" otherwise.
/// - GetFlightInfo: execute the query.
@@ -754,9 +757,12 @@ pub struct TicketStatementQuery {
/// - ARROW:FLIGHT:SQL:PRECISION - Column precision/size
/// - ARROW:FLIGHT:SQL:SCALE - Column scale/decimal digits if applicable
/// - ARROW:FLIGHT:SQL:IS_AUTO_INCREMENT - "1" indicates if the column is auto incremented, "0" otherwise.
-/// - ARROW:FLIGHT:SQL:IS_CASE_SENSITIVE - "1" indicates if the column is case sensitive, "0" otherwise.
+/// - ARROW:FLIGHT:SQL:IS_CASE_SENSITIVE - "1" indicates if the column is case-sensitive, "0" otherwise.
/// - ARROW:FLIGHT:SQL:IS_READ_ONLY - "1" indicates if the column is read only, "0" otherwise.
/// - ARROW:FLIGHT:SQL:IS_SEARCHABLE - "1" indicates if the column is searchable via WHERE clause, "0" otherwise.
+///
+/// If the schema is retrieved after parameter values have been bound with DoPut, then the server should account
+/// for the parameters when determining the schema.
/// - DoPut: bind parameter values. All of the bound parameter sets will be executed as a single atomic execution.
/// - GetFlightInfo: execute the prepared statement instance.
#[allow(clippy::derive_partial_eq_without_eq)]
@@ -768,7 +774,7 @@ pub struct CommandPreparedStatementQuery {
}
///
/// Represents a SQL update query. Used in the command member of FlightDescriptor
-/// for the the RPC call DoPut to cause the server to execute the included SQL update.
+/// for the RPC call DoPut to cause the server to execute the included SQL update.
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct CommandStatementUpdate {
@@ -781,7 +787,7 @@ pub struct CommandStatementUpdate {
}
///
/// Represents a SQL update query. Used in the command member of FlightDescriptor
-/// for the the RPC call DoPut to cause the server to execute the included
+/// for the RPC call DoPut to cause the server to execute the included
/// prepared statement handle as an update.
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
@@ -815,6 +821,9 @@ pub struct DoPutUpdateResult {
/// data.
///
/// This command is idempotent.
+///
+/// This command is deprecated since 13.0.0. Use the "CancelFlightInfo"
+/// action with DoAction instead.
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ActionCancelQueryRequest {
@@ -829,6 +838,9 @@ pub struct ActionCancelQueryRequest {
/// The result of cancelling a query.
///
/// The result should be wrapped in a google.protobuf.Any message.
+///
+/// This command is deprecated since 13.0.0. Use the "CancelFlightInfo"
+/// action with DoAction instead.
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ActionCancelQueryResult {
@@ -1272,7 +1284,7 @@ pub enum SqlInfo {
SqlMaxCharLiteralLength = 542,
/// Retrieves a int64 value representing the maximum number of characters allowed for a column name.
SqlMaxColumnNameLength = 543,
- /// Retrieves a int64 value representing the the maximum number of columns allowed in a GROUP BY clause.
+ /// Retrieves a int64 value representing the maximum number of columns allowed in a GROUP BY clause.
SqlMaxColumnsInGroupBy = 544,
/// Retrieves a int64 value representing the maximum number of columns allowed in an index.
SqlMaxColumnsInIndex = 545,
@@ -2373,7 +2385,7 @@ impl SqlSupportsConvert {
}
/// *
/// The JDBC/ODBC-defined type of any object.
-/// All the values here are the sames as in the JDBC and ODBC specs.
+/// All the values here are the same as in the JDBC and ODBC specs.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
#[repr(i32)]
pub enum XdbcDataType {
@@ -2621,7 +2633,7 @@ pub enum Nullable {
/// Indicates that the fields allow the use of null values.
NullabilityNullable = 1,
/// *
- /// Indicates that nullability of the fields can not be determined.
+ /// Indicates that nullability of the fields cannot be determined.
NullabilityUnknown = 2,
}
impl Nullable {
@@ -2650,7 +2662,7 @@ impl Nullable {
#[repr(i32)]
pub enum Searchable {
/// *
- /// Indicates that column can not be used in a WHERE clause.
+ /// Indicates that column cannot be used in a WHERE clause.
None = 0,
/// *
/// Indicates that the column can be used in a WHERE clause if it is using a
diff --git a/arrow-flight/src/sql/client.rs b/arrow-flight/src/sql/client.rs
index 6448e69e7f30..a014137f6fa9 100644
--- a/arrow-flight/src/sql/client.rs
+++ b/arrow-flight/src/sql/client.rs
@@ -391,6 +391,7 @@ impl FlightSqlServiceClient<Channel> {
/// Explicitly shut down and clean up the client.
pub async fn close(&mut self) -> Result<(), ArrowError> {
+ // TODO: consume self instead of &mut self to explicitly prevent reuse?
Ok(())
}
diff --git a/arrow-flight/src/sql/server.rs b/arrow-flight/src/sql/server.rs
index f1656aca882a..0431e58111a4 100644
--- a/arrow-flight/src/sql/server.rs
+++ b/arrow-flight/src/sql/server.rs
@@ -36,9 +36,9 @@ use super::{
DoPutUpdateResult, ProstMessageExt, SqlInfo, TicketStatementQuery,
};
use crate::{
- flight_service_server::FlightService, Action, ActionType, Criteria, Empty, FlightData,
- FlightDescriptor, FlightInfo, HandshakeRequest, HandshakeResponse, PutResult, SchemaResult,
- Ticket,
+ flight_service_server::FlightService, gen::PollInfo, Action, ActionType, Criteria, Empty,
+ FlightData, FlightDescriptor, FlightInfo, HandshakeRequest, HandshakeResponse, PutResult,
+ SchemaResult, Ticket,
};
pub(crate) static CREATE_PREPARED_STATEMENT: &str = "CreatePreparedStatement";
@@ -632,6 +632,13 @@ where
}
}
+ async fn poll_flight_info(
+ &self,
+ _request: Request<FlightDescriptor>,
+ ) -> Result<Response<PollInfo>, Status> {
+ Err(Status::unimplemented("Not yet implemented"))
+ }
+
async fn get_schema(
&self,
_request: Request<FlightDescriptor>,
diff --git a/format/Flight.proto b/format/Flight.proto
index 9b44331a5765..653b983ef2c7 100644
--- a/format/Flight.proto
+++ b/format/Flight.proto
@@ -17,9 +17,10 @@
*/
syntax = "proto3";
+ import "google/protobuf/timestamp.proto";
option java_package = "org.apache.arrow.flight.impl";
- option go_package = "github.com/apache/arrow/go/arrow/flight/internal/flight";
+ option go_package = "github.com/apache/arrow/go/arrow/flight/gen/flight";
option csharp_namespace = "Apache.Arrow.Flight.Protocol";
package arrow.flight.protocol;
@@ -64,6 +65,32 @@
*/
rpc GetFlightInfo(FlightDescriptor) returns (FlightInfo) {}
+ /*
+ * For a given FlightDescriptor, start a query and get information
+ * to poll its execution status. This is a useful interface if the
+ * query may be a long-running query. The first PollFlightInfo call
+ * should return as quickly as possible. (GetFlightInfo doesn't
+ * return until the query is complete.)
+ *
+ * A client can consume any available results before
+ * the query is completed. See PollInfo.info for details.
+ *
+ * A client can poll the updated query status by calling
+ * PollFlightInfo() with PollInfo.flight_descriptor. A server
+ * should not respond until the result would be different from last
+ * time. That way, the client can "long poll" for updates
+ * without constantly making requests. Clients can set a short timeout
+ * to avoid blocking calls if desired.
+ *
+ * A client can't use PollInfo.flight_descriptor after
+ * PollInfo.expiration_time passes. A server might not accept the
+ * retry descriptor anymore and the query may be cancelled.
+ *
+ * A client may use the CancelFlightInfo action with
+ * PollInfo.info to cancel the running query.
+ */
+ rpc PollFlightInfo(FlightDescriptor) returns (PollInfo) {}
+
/*
* For a given FlightDescriptor, get the Schema as described in Schema.fbs::Schema
* This is used when a consumer needs the Schema of flight stream. Similar to
@@ -182,6 +209,24 @@
bytes body = 2;
}
+ /*
+ * The request of the CancelFlightInfo action.
+ *
+ * The request should be stored in Action.body.
+ */
+ message CancelFlightInfoRequest {
+ FlightInfo info = 1;
+ }
+
+ /*
+ * The request of the RenewFlightEndpoint action.
+ *
+ * The request should be stored in Action.body.
+ */
+ message RenewFlightEndpointRequest {
+ FlightEndpoint endpoint = 1;
+ }
+
/*
* An opaque result returned after executing an action.
*/
@@ -189,6 +234,36 @@
bytes body = 1;
}
+ /*
+ * The result of a cancel operation.
+ *
+ * This is used by CancelFlightInfoResult.status.
+ */
+ enum CancelStatus {
+ // The cancellation status is unknown. Servers should avoid using
+ // this value (send a NOT_FOUND error if the requested query is
+ // not known). Clients can retry the request.
+ CANCEL_STATUS_UNSPECIFIED = 0;
+ // The cancellation request is complete. Subsequent requests with
+ // the same payload may return CANCELLED or a NOT_FOUND error.
+ CANCEL_STATUS_CANCELLED = 1;
+ // The cancellation request is in progress. The client may retry
+ // the cancellation request.
+ CANCEL_STATUS_CANCELLING = 2;
+ // The query is not cancellable. The client should not retry the
+ // cancellation request.
+ CANCEL_STATUS_NOT_CANCELLABLE = 3;
+ }
+
+ /*
+ * The result of the CancelFlightInfo action.
+ *
+ * The result should be stored in Result.body.
+ */
+ message CancelFlightInfoResult {
+ CancelStatus status = 1;
+ }
+
/*
* Wrap the result of a getSchema call
*/
@@ -292,6 +367,61 @@
* FlightEndpoints are in the same order as the data.
*/
bool ordered = 6;
+
+ /*
+ * Application-defined metadata.
+ *
+ * There is no inherent or required relationship between this
+ * and the app_metadata fields in the FlightEndpoints or resulting
+ * FlightData messages. Since this metadata is application-defined,
+ * a given application could define there to be a relationship,
+ * but there is none required by the spec.
+ */
+ bytes app_metadata = 7;
+ }
+
+ /*
+ * The information to process a long-running query.
+ */
+ message PollInfo {
+ /*
+ * The currently available results.
+ *
+ * If "flight_descriptor" is not specified, the query is complete
+ * and "info" specifies all results. Otherwise, "info" contains
+ * partial query results.
+ *
+ * Note that each PollInfo response contains a complete
+ * FlightInfo (not just the delta between the previous and current
+ * FlightInfo).
+ *
+ * Subsequent PollInfo responses may only append new endpoints to
+ * info.
+ *
+ * Clients can begin fetching results via DoGet(Ticket) with the
+ * ticket in the info before the query is
+ * completed. FlightInfo.ordered is also valid.
+ */
+ FlightInfo info = 1;
+
+ /*
+ * The descriptor the client should use on the next try.
+ * If unset, the query is complete.
+ */
+ FlightDescriptor flight_descriptor = 2;
+
+ /*
+ * Query progress. If known, must be in [0.0, 1.0] but need not be
+ * monotonic or nondecreasing. If unknown, do not set.
+ */
+ optional double progress = 3;
+
+ /*
+ * Expiration time for this request. After this passes, the server
+ * might not accept the retry descriptor anymore (and the query may
+ * be cancelled). This may be updated on a call to PollFlightInfo.
+ */
+ google.protobuf.Timestamp expiration_time = 4;
}
/*
@@ -321,6 +451,24 @@
* represent redundant and/or load balanced services.
*/
repeated Location location = 2;
+
+ /*
+ * Expiration time of this stream. If present, clients may assume
+ * they can retry DoGet requests. Otherwise, it is
+ * application-defined whether DoGet requests may be retried.
+ */
+ google.protobuf.Timestamp expiration_time = 3;
+
+ /*
+ * Application-defined metadata.
+ *
+ * There is no inherent or required relationship between this
+ * and the app_metadata fields in the FlightInfo or resulting
+ * FlightData messages. Since this metadata is application-defined,
+ * a given application could define there to be a relationship,
+ * but there is none required by the spec.
+ */
+ bytes app_metadata = 4;
}
/*
@@ -377,4 +525,4 @@
*/
message PutResult {
bytes app_metadata = 1;
- }
\ No newline at end of file
+ }
diff --git a/format/FlightSql.proto b/format/FlightSql.proto
index 0acf647e1045..f78e77e23278 100644
--- a/format/FlightSql.proto
+++ b/format/FlightSql.proto
@@ -20,7 +20,7 @@
import "google/protobuf/descriptor.proto";
option java_package = "org.apache.arrow.flight.sql.impl";
- option go_package = "github.com/apache/arrow/go/arrow/flight/internal/flight";
+ option go_package = "github.com/apache/arrow/go/arrow/flight/gen/flight";
package arrow.flight.protocol.sql;
/*
@@ -551,7 +551,7 @@
// Retrieves a int64 value representing the maximum number of characters allowed for a column name.
SQL_MAX_COLUMN_NAME_LENGTH = 543;
- // Retrieves a int64 value representing the the maximum number of columns allowed in a GROUP BY clause.
+ // Retrieves a int64 value representing the maximum number of columns allowed in a GROUP BY clause.
SQL_MAX_COLUMNS_IN_GROUP_BY = 544;
// Retrieves a int64 value representing the maximum number of columns allowed in an index.
@@ -943,7 +943,7 @@
/**
* The JDBC/ODBC-defined type of any object.
- * All the values here are the sames as in the JDBC and ODBC specs.
+ * All the values here are the same as in the JDBC and ODBC specs.
*/
enum XdbcDataType {
XDBC_UNKNOWN_TYPE = 0;
@@ -1023,14 +1023,14 @@
NULLABILITY_NULLABLE = 1;
/**
- * Indicates that nullability of the fields can not be determined.
+ * Indicates that nullability of the fields cannot be determined.
*/
NULLABILITY_UNKNOWN = 2;
}
enum Searchable {
/**
- * Indicates that column can not be used in a WHERE clause.
+ * Indicates that column cannot be used in a WHERE clause.
*/
SEARCHABLE_NONE = 0;
@@ -1196,7 +1196,7 @@
* - ARROW:FLIGHT:SQL:PRECISION - Column precision/size
* - ARROW:FLIGHT:SQL:SCALE - Column scale/decimal digits if applicable
* - ARROW:FLIGHT:SQL:IS_AUTO_INCREMENT - "1" indicates if the column is auto incremented, "0" otherwise.
- * - ARROW:FLIGHT:SQL:IS_CASE_SENSITIVE - "1" indicates if the column is case sensitive, "0" otherwise.
+ * - ARROW:FLIGHT:SQL:IS_CASE_SENSITIVE - "1" indicates if the column is case-sensitive, "0" otherwise.
* - ARROW:FLIGHT:SQL:IS_READ_ONLY - "1" indicates if the column is read only, "0" otherwise.
* - ARROW:FLIGHT:SQL:IS_SEARCHABLE - "1" indicates if the column is searchable via WHERE clause, "0" otherwise.
* The returned data should be ordered by catalog_name, db_schema_name, table_name, then table_type, followed by table_schema if requested.
@@ -1537,11 +1537,14 @@
bytes prepared_statement_handle = 1;
// If a result set generating query was provided, dataset_schema contains the
- // schema of the dataset as described in Schema.fbs::Schema, it is serialized as an IPC message.
+ // schema of the result set. It should be an IPC-encapsulated Schema, as described in Schema.fbs.
+ // For some queries, the schema of the results may depend on the schema of the parameters. The server
+ // should provide its best guess as to the schema at this point. Clients must not assume that this
+ // schema, if provided, will be accurate.
bytes dataset_schema = 2;
// If the query provided contained parameters, parameter_schema contains the
- // schema of the expected parameters as described in Schema.fbs::Schema, it is serialized as an IPC message.
+ // schema of the expected parameters. It should be an IPC-encapsulated Schema, as described in Schema.fbs.
bytes parameter_schema = 3;
}
@@ -1676,7 +1679,7 @@
* - ARROW:FLIGHT:SQL:PRECISION - Column precision/size
* - ARROW:FLIGHT:SQL:SCALE - Column scale/decimal digits if applicable
* - ARROW:FLIGHT:SQL:IS_AUTO_INCREMENT - "1" indicates if the column is auto incremented, "0" otherwise.
- * - ARROW:FLIGHT:SQL:IS_CASE_SENSITIVE - "1" indicates if the column is case sensitive, "0" otherwise.
+ * - ARROW:FLIGHT:SQL:IS_CASE_SENSITIVE - "1" indicates if the column is case-sensitive, "0" otherwise.
* - ARROW:FLIGHT:SQL:IS_READ_ONLY - "1" indicates if the column is read only, "0" otherwise.
* - ARROW:FLIGHT:SQL:IS_SEARCHABLE - "1" indicates if the column is searchable via WHERE clause, "0" otherwise.
* - GetFlightInfo: execute the query.
@@ -1702,7 +1705,7 @@
* - ARROW:FLIGHT:SQL:PRECISION - Column precision/size
* - ARROW:FLIGHT:SQL:SCALE - Column scale/decimal digits if applicable
* - ARROW:FLIGHT:SQL:IS_AUTO_INCREMENT - "1" indicates if the column is auto incremented, "0" otherwise.
- * - ARROW:FLIGHT:SQL:IS_CASE_SENSITIVE - "1" indicates if the column is case sensitive, "0" otherwise.
+ * - ARROW:FLIGHT:SQL:IS_CASE_SENSITIVE - "1" indicates if the column is case-sensitive, "0" otherwise.
* - ARROW:FLIGHT:SQL:IS_READ_ONLY - "1" indicates if the column is read only, "0" otherwise.
* - ARROW:FLIGHT:SQL:IS_SEARCHABLE - "1" indicates if the column is searchable via WHERE clause, "0" otherwise.
* - GetFlightInfo: execute the query.
@@ -1740,9 +1743,12 @@
* - ARROW:FLIGHT:SQL:PRECISION - Column precision/size
* - ARROW:FLIGHT:SQL:SCALE - Column scale/decimal digits if applicable
* - ARROW:FLIGHT:SQL:IS_AUTO_INCREMENT - "1" indicates if the column is auto incremented, "0" otherwise.
- * - ARROW:FLIGHT:SQL:IS_CASE_SENSITIVE - "1" indicates if the column is case sensitive, "0" otherwise.
+ * - ARROW:FLIGHT:SQL:IS_CASE_SENSITIVE - "1" indicates if the column is case-sensitive, "0" otherwise.
* - ARROW:FLIGHT:SQL:IS_READ_ONLY - "1" indicates if the column is read only, "0" otherwise.
* - ARROW:FLIGHT:SQL:IS_SEARCHABLE - "1" indicates if the column is searchable via WHERE clause, "0" otherwise.
+ *
+ * If the schema is retrieved after parameter values have been bound with DoPut, then the server should account
+ * for the parameters when determining the schema.
* - DoPut: bind parameter values. All of the bound parameter sets will be executed as a single atomic execution.
* - GetFlightInfo: execute the prepared statement instance.
*/
@@ -1755,7 +1761,7 @@
/*
* Represents a SQL update query. Used in the command member of FlightDescriptor
- * for the the RPC call DoPut to cause the server to execute the included SQL update.
+ * for the RPC call DoPut to cause the server to execute the included SQL update.
*/
message CommandStatementUpdate {
option (experimental) = true;
@@ -1768,7 +1774,7 @@
/*
* Represents a SQL update query. Used in the command member of FlightDescriptor
- * for the the RPC call DoPut to cause the server to execute the included
+ * for the RPC call DoPut to cause the server to execute the included
* prepared statement handle as an update.
*/
message CommandPreparedStatementUpdate {
@@ -1804,8 +1810,12 @@
* data.
*
* This command is idempotent.
+ *
+ * This command is deprecated since 13.0.0. Use the "CancelFlightInfo"
+ * action with DoAction instead.
*/
message ActionCancelQueryRequest {
+ option deprecated = true;
option (experimental) = true;
// The result of the GetFlightInfo RPC that initiated the query.
@@ -1819,8 +1829,12 @@
* The result of cancelling a query.
*
* The result should be wrapped in a google.protobuf.Any message.
+ *
+ * This command is deprecated since 13.0.0. Use the "CancelFlightInfo"
+ * action with DoAction instead.
*/
message ActionCancelQueryResult {
+ option deprecated = true;
option (experimental) = true;
enum CancelResult {
@@ -1844,4 +1858,4 @@
extend google.protobuf.MessageOptions {
bool experimental = 1000;
- }
\ No newline at end of file
+ }
|
diff --git a/arrow-flight/tests/client.rs b/arrow-flight/tests/client.rs
index 3ad9ee7a45ca..9e19bce92338 100644
--- a/arrow-flight/tests/client.rs
+++ b/arrow-flight/tests/client.rs
@@ -24,13 +24,15 @@ mod common {
use arrow_array::{RecordBatch, UInt64Array};
use arrow_flight::{
decode::FlightRecordBatchStream, encode::FlightDataEncoderBuilder, error::FlightError, Action,
- ActionType, Criteria, Empty, FlightClient, FlightData, FlightDescriptor, FlightInfo,
- HandshakeRequest, HandshakeResponse, PutResult, Ticket,
+ ActionType, CancelFlightInfoRequest, CancelFlightInfoResult, CancelStatus, Criteria, Empty,
+ FlightClient, FlightData, FlightDescriptor, FlightEndpoint, FlightInfo, HandshakeRequest,
+ HandshakeResponse, PollInfo, PutResult, RenewFlightEndpointRequest, Ticket,
};
use arrow_schema::{DataType, Field, Schema};
use bytes::Bytes;
use common::{server::TestFlightServer, trailers_layer::TrailersLayer};
use futures::{Future, StreamExt, TryStreamExt};
+use prost::Message;
use tokio::{net::TcpListener, task::JoinHandle};
use tonic::{
transport::{Channel, Uri},
@@ -106,6 +108,7 @@ fn test_flight_info(request: &FlightDescriptor) -> FlightInfo {
total_bytes: 123,
total_records: 456,
ordered: false,
+ app_metadata: Bytes::new(),
}
}
@@ -141,6 +144,47 @@ async fn test_get_flight_info_error() {
.await;
}
+fn test_poll_info(request: &FlightDescriptor) -> PollInfo {
+ PollInfo {
+ info: Some(test_flight_info(request)),
+ flight_descriptor: None,
+ progress: Some(1.0),
+ expiration_time: None,
+ }
+}
+
+#[tokio::test]
+async fn test_poll_flight_info() {
+ do_test(|test_server, mut client| async move {
+ client.add_header("foo-header", "bar-header-value").unwrap();
+ let request = FlightDescriptor::new_cmd(b"My Command".to_vec());
+
+ let expected_response = test_poll_info(&request);
+ test_server.set_poll_flight_info_response(Ok(expected_response.clone()));
+
+ let response = client.poll_flight_info(request.clone()).await.unwrap();
+
+ assert_eq!(response, expected_response);
+ assert_eq!(test_server.take_poll_flight_info_request(), Some(request));
+ ensure_metadata(&client, &test_server);
+ })
+ .await;
+}
+
+#[tokio::test]
+async fn test_poll_flight_info_error() {
+ do_test(|test_server, mut client| async move {
+ let request = FlightDescriptor::new_cmd(b"My Command".to_vec());
+
+ let e = Status::unauthenticated("DENIED");
+ test_server.set_poll_flight_info_response(Err(e.clone()));
+
+ let response = client.poll_flight_info(request.clone()).await.unwrap_err();
+ expect_status(response, e);
+ })
+ .await;
+}
+
// TODO more negative tests (like if there are endpoints defined, etc)
#[tokio::test]
@@ -852,6 +896,105 @@ async fn test_do_action_error_in_stream() {
.await;
}
+#[tokio::test]
+async fn test_cancel_flight_info() {
+ do_test(|test_server, mut client| async move {
+ client.add_header("foo-header", "bar-header-value").unwrap();
+
+ let expected_response = CancelFlightInfoResult::new(CancelStatus::Cancelled);
+ let response = expected_response.encode_to_vec();
+ let response = Ok(arrow_flight::Result::new(response));
+ test_server.set_do_action_response(vec![response]);
+
+ let request = CancelFlightInfoRequest::new(FlightInfo::new());
+ let actual_response = client
+ .cancel_flight_info(request.clone())
+ .await
+ .expect("error making request");
+
+ let expected_request = Action::new("CancelFlightInfo", request.encode_to_vec());
+ assert_eq!(actual_response, expected_response);
+ assert_eq!(test_server.take_do_action_request(), Some(expected_request));
+ ensure_metadata(&client, &test_server);
+ })
+ .await;
+}
+
+#[tokio::test]
+async fn test_cancel_flight_info_error_no_response() {
+ do_test(|test_server, mut client| async move {
+ client.add_header("foo-header", "bar-header-value").unwrap();
+
+ test_server.set_do_action_response(vec![]);
+
+ let request = CancelFlightInfoRequest::new(FlightInfo::new());
+ let err = client
+ .cancel_flight_info(request.clone())
+ .await
+ .unwrap_err();
+
+ assert_eq!(
+ err.to_string(),
+ "ProtocolError(\"Received no response for cancel_flight_info call\")"
+ );
+ // server still got the request
+ let expected_request = Action::new("CancelFlightInfo", request.encode_to_vec());
+ assert_eq!(test_server.take_do_action_request(), Some(expected_request));
+ ensure_metadata(&client, &test_server);
+ })
+ .await;
+}
+
+#[tokio::test]
+async fn test_renew_flight_endpoint() {
+ do_test(|test_server, mut client| async move {
+ client.add_header("foo-header", "bar-header-value").unwrap();
+
+ let expected_response = FlightEndpoint::new().with_app_metadata(vec![1]);
+ let response = expected_response.encode_to_vec();
+ let response = Ok(arrow_flight::Result::new(response));
+ test_server.set_do_action_response(vec![response]);
+
+ let request =
+ RenewFlightEndpointRequest::new(FlightEndpoint::new().with_app_metadata(vec![0]));
+ let actual_response = client
+ .renew_flight_endpoint(request.clone())
+ .await
+ .expect("error making request");
+
+ let expected_request = Action::new("RenewFlightEndpoint", request.encode_to_vec());
+ assert_eq!(actual_response, expected_response);
+ assert_eq!(test_server.take_do_action_request(), Some(expected_request));
+ ensure_metadata(&client, &test_server);
+ })
+ .await;
+}
+
+#[tokio::test]
+async fn test_renew_flight_endpoint_error_no_response() {
+ do_test(|test_server, mut client| async move {
+ client.add_header("foo-header", "bar-header-value").unwrap();
+
+ test_server.set_do_action_response(vec![]);
+
+ let request = RenewFlightEndpointRequest::new(FlightEndpoint::new());
+ let err = client
+ .renew_flight_endpoint(request.clone())
+ .await
+ .unwrap_err();
+
+ assert_eq!(
+ err.to_string(),
+ "ProtocolError(\"Received no response for renew_flight_endpoint call\")"
+ );
+ // server still got the request
+ let expected_request = Action::new("RenewFlightEndpoint", request.encode_to_vec());
+ assert_eq!(test_server.take_do_action_request(), Some(expected_request));
+ ensure_metadata(&client, &test_server);
+ })
+ .await;
+}
+
async fn test_flight_data() -> Vec<FlightData> {
let batch = RecordBatch::try_from_iter(vec![(
"col",
diff --git a/arrow-flight/tests/common/server.rs b/arrow-flight/tests/common/server.rs
index 8b162d398c4b..a75590a13334 100644
--- a/arrow-flight/tests/common/server.rs
+++ b/arrow-flight/tests/common/server.rs
@@ -26,7 +26,7 @@ use arrow_flight::{
encode::FlightDataEncoderBuilder,
flight_service_server::{FlightService, FlightServiceServer},
Action, ActionType, Criteria, Empty, FlightData, FlightDescriptor, FlightInfo,
- HandshakeRequest, HandshakeResponse, PutResult, SchemaAsIpc, SchemaResult, Ticket,
+ HandshakeRequest, HandshakeResponse, PollInfo, PutResult, SchemaAsIpc, SchemaResult, Ticket,
};
#[derive(Debug, Clone)]
@@ -54,11 +54,10 @@ impl TestFlightServer {
/// Specify the response returned from the next call to handshake
pub fn set_handshake_response(&self, response: Result<HandshakeResponse, Status>) {
let mut state = self.state.lock().expect("mutex not poisoned");
-
state.handshake_response.replace(response);
}
- /// Take and return last handshake request send to the server,
+ /// Take and return last handshake request sent to the server,
pub fn take_handshake_request(&self) -> Option<HandshakeRequest> {
self.state
.lock()
@@ -67,14 +66,13 @@ impl TestFlightServer {
.take()
}
- /// Specify the response returned from the next call to handshake
+ /// Specify the response returned from the next call to get_flight_info
pub fn set_get_flight_info_response(&self, response: Result<FlightInfo, Status>) {
let mut state = self.state.lock().expect("mutex not poisoned");
-
state.get_flight_info_response.replace(response);
}
- /// Take and return last get_flight_info request send to the server,
+ /// Take and return last get_flight_info request sent to the server,
pub fn take_get_flight_info_request(&self) -> Option<FlightDescriptor> {
self.state
.lock()
@@ -83,6 +81,21 @@ impl TestFlightServer {
.take()
}
+ /// Specify the response returned from the next call to poll_flight_info
+ pub fn set_poll_flight_info_response(&self, response: Result<PollInfo, Status>) {
+ let mut state = self.state.lock().expect("mutex not poisoned");
+ state.poll_flight_info_response.replace(response);
+ }
+
+ /// Take and return last poll_flight_info request sent to the server,
+ pub fn take_poll_flight_info_request(&self) -> Option<FlightDescriptor> {
+ self.state
+ .lock()
+ .expect("mutex not poisoned")
+ .poll_flight_info_request
+ .take()
+ }
+
/// Specify the response returned from the next call to `do_get`
pub fn set_do_get_response(&self, response: Vec<Result<RecordBatch, Status>>) {
let mut state = self.state.lock().expect("mutex not poisoned");
@@ -104,7 +117,7 @@ impl TestFlightServer {
state.do_put_response.replace(response);
}
- /// Take and return last do_put request send to the server,
+ /// Take and return last do_put request sent to the server,
pub fn take_do_put_request(&self) -> Option<Vec<FlightData>> {
self.state
.lock()
@@ -214,8 +227,12 @@ struct State {
pub handshake_response: Option<Result<HandshakeResponse, Status>>,
/// The last `get_flight_info` request received
pub get_flight_info_request: Option<FlightDescriptor>,
- /// the next response to return from `get_flight_info`
+ /// The next response to return from `get_flight_info`
pub get_flight_info_response: Option<Result<FlightInfo, Status>>,
+ /// The last `poll_flight_info` request received
+ pub poll_flight_info_request: Option<FlightDescriptor>,
+ /// The next response to return from `poll_flight_info`
+ pub poll_flight_info_response: Option<Result<PollInfo, Status>>,
/// The last do_get request received
pub do_get_request: Option<Ticket>,
/// The next response returned from `do_get`
@@ -318,6 +335,20 @@ impl FlightService for TestFlightServer {
Ok(Response::new(response))
}
+ async fn poll_flight_info(
+ &self,
+ request: Request<FlightDescriptor>,
+ ) -> Result<Response<PollInfo>, Status> {
+ self.save_metadata(&request);
+ let mut state = self.state.lock().expect("mutex not poisoned");
+ state.poll_flight_info_request = Some(request.into_inner());
+ let response = state
+ .poll_flight_info_response
+ .take()
+ .unwrap_or_else(|| Err(Status::internal("No poll_flight_info response configured")))?;
+ Ok(Response::new(response))
+ }
+
async fn get_schema(
&self,
request: Request<FlightDescriptor>,
diff --git a/arrow-integration-testing/src/flight_server_scenarios.rs b/arrow-integration-testing/src/flight_server_scenarios.rs
index 9034776c68d4..48d4e6045684 100644
--- a/arrow-integration-testing/src/flight_server_scenarios.rs
+++ b/arrow-integration-testing/src/flight_server_scenarios.rs
@@ -44,5 +44,7 @@ pub fn endpoint(ticket: &str, location_uri: impl Into<String>) -> FlightEndpoint
location: vec![Location {
uri: location_uri.into(),
}],
+ expiration_time: None,
+ app_metadata: vec![].into(),
}
}
diff --git a/arrow-integration-testing/src/flight_server_scenarios/auth_basic_proto.rs b/arrow-integration-testing/src/flight_server_scenarios/auth_basic_proto.rs
index ff4fc12f2523..20d868953664 100644
--- a/arrow-integration-testing/src/flight_server_scenarios/auth_basic_proto.rs
+++ b/arrow-integration-testing/src/flight_server_scenarios/auth_basic_proto.rs
@@ -21,7 +21,7 @@ use std::sync::Arc;
use arrow_flight::{
flight_service_server::FlightService, flight_service_server::FlightServiceServer, Action,
ActionType, BasicAuth, Criteria, Empty, FlightData, FlightDescriptor, FlightInfo,
- HandshakeRequest, HandshakeResponse, PutResult, SchemaResult, Ticket,
+ HandshakeRequest, HandshakeResponse, PollInfo, PutResult, SchemaResult, Ticket,
};
use futures::{channel::mpsc, sink::SinkExt, Stream, StreamExt};
use tokio::sync::Mutex;
@@ -178,6 +178,14 @@ impl FlightService for AuthBasicProtoScenarioImpl {
Err(Status::unimplemented("Not yet implemented"))
}
+ async fn poll_flight_info(
+ &self,
+ request: Request<FlightDescriptor>,
+ ) -> Result<Response<PollInfo>, Status> {
+ self.check_auth(request.metadata()).await?;
+ Err(Status::unimplemented("Not yet implemented"))
+ }
+
async fn do_put(
&self,
request: Request<Streaming<FlightData>>,
diff --git a/arrow-integration-testing/src/flight_server_scenarios/integration_test.rs b/arrow-integration-testing/src/flight_server_scenarios/integration_test.rs
index 2011031e921a..623a240348f4 100644
--- a/arrow-integration-testing/src/flight_server_scenarios/integration_test.rs
+++ b/arrow-integration-testing/src/flight_server_scenarios/integration_test.rs
@@ -32,7 +32,7 @@ use arrow_flight::{
flight_descriptor::DescriptorType, flight_service_server::FlightService,
flight_service_server::FlightServiceServer, Action, ActionType, Criteria, Empty, FlightData,
FlightDescriptor, FlightEndpoint, FlightInfo, HandshakeRequest, HandshakeResponse, IpcMessage,
- PutResult, SchemaAsIpc, SchemaResult, Ticket,
+ PollInfo, PutResult, SchemaAsIpc, SchemaResult, Ticket,
};
use futures::{channel::mpsc, sink::SinkExt, Stream, StreamExt};
use std::convert::TryInto;
@@ -196,6 +196,7 @@ impl FlightService for FlightServiceImpl {
total_records: total_records as i64,
total_bytes: -1,
ordered: false,
+ app_metadata: vec![].into(),
};
Ok(Response::new(info))
@@ -204,6 +205,13 @@ impl FlightService for FlightServiceImpl {
}
}
+ async fn poll_flight_info(
+ &self,
+ _request: Request<FlightDescriptor>,
+ ) -> Result<Response<PollInfo>, Status> {
+ Err(Status::unimplemented("Not yet implemented"))
+ }
+
async fn do_put(
&self,
request: Request<Streaming<FlightData>>,
diff --git a/arrow-integration-testing/src/flight_server_scenarios/middleware.rs b/arrow-integration-testing/src/flight_server_scenarios/middleware.rs
index 68d871b528a6..e8d9c521bb99 100644
--- a/arrow-integration-testing/src/flight_server_scenarios/middleware.rs
+++ b/arrow-integration-testing/src/flight_server_scenarios/middleware.rs
@@ -20,8 +20,8 @@ use std::pin::Pin;
use arrow_flight::{
flight_descriptor::DescriptorType, flight_service_server::FlightService,
flight_service_server::FlightServiceServer, Action, ActionType, Criteria, Empty, FlightData,
- FlightDescriptor, FlightInfo, HandshakeRequest, HandshakeResponse, PutResult, SchemaResult,
- Ticket,
+ FlightDescriptor, FlightInfo, HandshakeRequest, HandshakeResponse, PollInfo, PutResult,
+ SchemaResult, Ticket,
};
use futures::Stream;
use tonic::{transport::Server, Request, Response, Status, Streaming};
@@ -120,6 +120,13 @@ impl FlightService for MiddlewareScenarioImpl {
Err(status)
}
+ async fn poll_flight_info(
+ &self,
+ _request: Request<FlightDescriptor>,
+ ) -> Result<Response<PollInfo>, Status> {
+ Err(Status::unimplemented("Not yet implemented"))
+ }
+
async fn do_put(
&self,
_request: Request<Streaming<FlightData>>,
|
Update Flight proto
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
<!--
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
(This section helps Arrow developers understand the context and *why* for this feature, in addition to the *what*)
-->
From mailing list: https://lists.apache.org/thread/4t664cj5z52brmbshjb6gknfq30ckhcn
> Now, here lies the issue: neither FlightEndpoint nor the FlightInfo message in the arrow.flight.protocol.rs file of arrow-rs includes an 'app_metadata' field (It seems outdated). Consequently, I am currently facing a roadblock.
Is there a plan to update the flight implementation of arrow-rs?
Need to update the Flight & FlightSql proto as they are outdated.
See arrow source:
- https://github.com/apache/arrow/blob/0993b369c4b91d81a17166d1427e7c26cd9beee4/format/Flight.proto
- https://github.com/apache/arrow/blob/0993b369c4b91d81a17166d1427e7c26cd9beee4/format/FlightSql.proto
**Describe the solution you'd like**
<!--
A clear and concise description of what you want to happen.
-->
Update format files and generated code (and interop code, refer to PR below for previous example)
**Describe alternatives you've considered**
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
For reference, last update PR: https://github.com/apache/arrow-rs/pull/4250
|
I can take a stab at this next week or so, unless someone else is interested in picking this up :eyes:
|
2024-02-20T11:54:36Z
|
50.0
|
82fc0df73ab97e239ce5c748a05c57ce582f3d5d
|
apache/arrow-rs
| 5,355
|
apache__arrow-rs-5355
|
[
"5354"
] |
31cf5ce23febf076104f064358a24fe8af09ee4b
|
diff --git a/arrow/src/pyarrow.rs b/arrow/src/pyarrow.rs
index 9a13cfa493e9..39702ce01aea 100644
--- a/arrow/src/pyarrow.rs
+++ b/arrow/src/pyarrow.rs
@@ -355,7 +355,16 @@ impl FromPyArrow for RecordBatch {
));
}
let array = StructArray::from(array_data);
- return Ok(array.into());
+ // StructArray does not embed metadata from schema. We need to override
+ // the output schema with the schema from the capsule.
+ let schema = Arc::new(Schema::try_from(schema_ptr).map_err(to_py_err)?);
+ let (_fields, columns, nulls) = array.into_parts();
+ assert_eq!(
+ nulls.map(|n| n.null_count()).unwrap_or_default(),
+ 0,
+ "Cannot convert nullable StructArray to RecordBatch, see StructArray documentation"
+ );
+ return RecordBatch::try_new(schema, columns).map_err(to_py_err);
}
validate_class("RecordBatch", value)?;
|
diff --git a/arrow-pyarrow-integration-testing/tests/test_sql.py b/arrow-pyarrow-integration-testing/tests/test_sql.py
index 16d4e0f12f88..5320d0a5343e 100644
--- a/arrow-pyarrow-integration-testing/tests/test_sql.py
+++ b/arrow-pyarrow-integration-testing/tests/test_sql.py
@@ -199,9 +199,10 @@ def test_field_metadata_roundtrip():
def test_schema_roundtrip():
pyarrow_fields = zip(string.ascii_lowercase, _supported_pyarrow_types)
- pyarrow_schema = pa.schema(pyarrow_fields)
+ pyarrow_schema = pa.schema(pyarrow_fields, metadata = {b'key1': b'value1'})
schema = rust.round_trip_schema(pyarrow_schema)
assert schema == pyarrow_schema
+ assert schema.metadata == pyarrow_schema.metadata
def test_primitive_python():
@@ -467,9 +468,11 @@ def test_tensor_array():
b = rust.round_trip_array(f32_array)
assert b == f32_array.storage
- batch = pa.record_batch([f32_array], ["tensor"])
+ batch = pa.record_batch([f32_array], ["tensor"], metadata={b'key1': b'value1'})
b = rust.round_trip_record_batch(batch)
assert b == batch
+ assert b.schema == batch.schema
+ assert b.schema.metadata == batch.schema.metadata
del b
@@ -486,6 +489,7 @@ def test_record_batch_reader():
b = rust.round_trip_record_batch_reader(a)
assert b.schema == schema
+ assert b.schema.metadata == schema.metadata
got_batches = list(b)
assert got_batches == batches
@@ -493,6 +497,7 @@ def test_record_batch_reader():
a = pa.RecordBatchReader.from_batches(schema, batches)
b = rust.boxed_reader_roundtrip(a)
assert b.schema == schema
+ assert b.schema.metadata == schema.metadata
got_batches = list(b)
assert got_batches == batches
@@ -511,6 +516,7 @@ def test_record_batch_reader_pycapsule():
b = rust.round_trip_record_batch_reader(wrapped)
assert b.schema == schema
+ assert b.schema.metadata == schema.metadata
got_batches = list(b)
assert got_batches == batches
@@ -519,6 +525,7 @@ def test_record_batch_reader_pycapsule():
wrapped = StreamWrapper(a)
b = rust.boxed_reader_roundtrip(wrapped)
assert b.schema == schema
+ assert b.schema.metadata == schema.metadata
got_batches = list(b)
assert got_batches == batches
|
RecordBatch conversion from pyarrow loses Schema's metadata
**Describe the bug**
When importing a pyarrow RecordBatch, we instantiate a `StructArray`, then convert it to a `RecordBatch`.
This loses the metadata from the original schema. This is not seen in the current tests, because pyarrow's
tests for equality on schemas ignores metadata.
https://github.com/apache/arrow-rs/blob/31cf5ce23febf076104f064358a24fe8af09ee4b/arrow/src/pyarrow.rs#L357-L358
**To Reproduce**
```python
# In arrow-pyarrow-integration-testing/tests/test_sql.py:470
batch = pa.record_batch([f32_array], ["tensor"], metadata={b'key1': b'value1'})
b = rust.round_trip_record_batch(batch)
assert b == batch # OK
assert b.schema == batch.schema # OK
assert b.schema.metadata == batch.schema.metadata # Fails
```
**Expected behavior**
Imported RecordBatch's schema should keep its metadata.
|
2024-01-31T10:19:29Z
|
50.0
|
82fc0df73ab97e239ce5c748a05c57ce582f3d5d
|
|
apache/arrow-rs
| 5,319
|
apache__arrow-rs-5319
|
[
"5266"
] |
b03613eb002302a85f5761f2b16753d4777552e5
|
diff --git a/arrow-arith/src/temporal.rs b/arrow-arith/src/temporal.rs
index a9c3de5401c1..a386559e30ba 100644
--- a/arrow-arith/src/temporal.rs
+++ b/arrow-arith/src/temporal.rs
@@ -19,105 +19,302 @@
use std::sync::Arc;
-use chrono::{DateTime, Datelike, NaiveDateTime, NaiveTime, Offset, Timelike};
-
-use arrow_array::builder::*;
-use arrow_array::iterator::ArrayIter;
-use arrow_array::temporal_conversions::{as_datetime, as_datetime_with_timezone, as_time};
+use arrow_array::cast::AsArray;
+use chrono::{Datelike, NaiveDateTime, Offset, TimeZone, Timelike, Utc};
+
+use arrow_array::temporal_conversions::{
+ date32_to_datetime, date64_to_datetime, time32ms_to_time, time32s_to_time, time64ns_to_time,
+ time64us_to_time, timestamp_ms_to_datetime, timestamp_ns_to_datetime, timestamp_s_to_datetime,
+ timestamp_us_to_datetime,
+};
use arrow_array::timezone::Tz;
use arrow_array::types::*;
use arrow_array::*;
use arrow_buffer::ArrowNativeType;
use arrow_schema::{ArrowError, DataType};
-/// This function takes an `ArrayIter` of input array and an extractor `op` which takes
-/// an input `NaiveTime` and returns time component (e.g. hour) as `i32` value.
-/// The extracted values are built by the given `builder` to be an `Int32Array`.
-fn as_time_with_op<A: ArrayAccessor<Item = T::Native>, T: ArrowTemporalType, F>(
- iter: ArrayIter<A>,
- mut builder: PrimitiveBuilder<Int32Type>,
- op: F,
-) -> Int32Array
+/// Valid parts to extract from date/time/timestamp arrays.
+///
+/// See [`date_part`].
+///
+/// Marked as non-exhaustive as may expand to support more types of
+/// date parts in the future.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[non_exhaustive]
+pub enum DatePart {
+ /// Quarter of the year, in range `1..=4`
+ Quarter,
+ /// Calendar year
+ Year,
+ /// Month in the year, in range `1..=12`
+ Month,
+ /// ISO week of the year, in range `1..=53`
+ Week,
+ /// Day of the month, in range `1..=31`
+ Day,
+ /// Day of the week, in range `0..=6`, where Sunday is `0`
+ DayOfWeekSunday0,
+ /// Day of the week, in range `0..=6`, where Monday is `0`
+ DayOfWeekMonday0,
+ /// Day of year, in range `1..=366`
+ DayOfYear,
+ /// Hour of the day, in range `0..=23`
+ Hour,
+ /// Minute of the hour, in range `0..=59`
+ Minute,
+ /// Second of the minute, in range `0..=59`
+ Second,
+ /// Millisecond of the second
+ Millisecond,
+ /// Microsecond of the second
+ Microsecond,
+ /// Nanosecond of the second
+ Nanosecond,
+}
+
+impl std::fmt::Display for DatePart {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{:?}", self)
+ }
+}
+
+/// Returns function to extract relevant [`DatePart`] from types like a
+/// [`NaiveDateTime`] or [`DateTime`].
+///
+/// [`DateTime`]: chrono::DateTime
+fn get_date_time_part_extract_fn<T>(part: DatePart) -> fn(T) -> i32
where
- F: Fn(NaiveTime) -> i32,
- i64: From<T::Native>,
+ T: ChronoDateExt + Datelike + Timelike,
{
- iter.into_iter().for_each(|value| {
- if let Some(value) = value {
- match as_time::<T>(i64::from(value)) {
- Some(dt) => builder.append_value(op(dt)),
- None => builder.append_null(),
- }
- } else {
- builder.append_null();
+ match part {
+ DatePart::Quarter => |d| d.quarter() as i32,
+ DatePart::Year => |d| d.year(),
+ DatePart::Month => |d| d.month() as i32,
+ DatePart::Week => |d| d.iso_week().week() as i32,
+ DatePart::Day => |d| d.day() as i32,
+ DatePart::DayOfWeekSunday0 => |d| d.num_days_from_sunday(),
+ DatePart::DayOfWeekMonday0 => |d| d.num_days_from_monday(),
+ DatePart::DayOfYear => |d| d.ordinal() as i32,
+ DatePart::Hour => |d| d.hour() as i32,
+ DatePart::Minute => |d| d.minute() as i32,
+ DatePart::Second => |d| d.second() as i32,
+ DatePart::Millisecond => |d| (d.nanosecond() / 1_000_000) as i32,
+ DatePart::Microsecond => |d| (d.nanosecond() / 1_000) as i32,
+ DatePart::Nanosecond => |d| (d.nanosecond()) as i32,
+ }
+}
+
+/// Given an array, return a new array with the extracted [`DatePart`] as signed 32-bit
+/// integer values.
+///
+/// Currently only supports temporal types:
+/// - Date32/Date64
+/// - Time32/Time64 (Limited support)
+/// - Timestamp
+///
+/// Returns an [`Int32Array`] unless input was a dictionary type, in which case returns
+/// the dictionary but with this function applied onto its values.
+///
+/// If array passed in is not of the above listed types (or is a dictionary array where the
+/// values array isn't of the above listed types), then this function will return an error.
+///
+/// # Examples
+///
+/// ```
+/// # use arrow_array::{Int32Array, TimestampMicrosecondArray};
+/// # use arrow_arith::temporal::{DatePart, date_part};
+/// let input: TimestampMicrosecondArray =
+/// vec![Some(1612025847000000), None, Some(1722015847000000)].into();
+///
+/// let actual = date_part(&input, DatePart::Week).unwrap();
+/// let expected: Int32Array = vec![Some(4), None, Some(30)].into();
+/// assert_eq!(actual.as_ref(), &expected);
+/// ```
+pub fn date_part(array: &dyn Array, part: DatePart) -> Result<ArrayRef, ArrowError> {
+ downcast_temporal_array!(
+ array => {
+ let array = array.date_part(part)?;
+ let array = Arc::new(array) as ArrayRef;
+ Ok(array)
+ }
+ // TODO: support interval
+ // DataType::Interval(_) => {
+ // todo!();
+ // }
+ DataType::Dictionary(_, _) => {
+ let array = array.as_any_dictionary();
+ let values = date_part(array.values(), part)?;
+ let values = Arc::new(values) as ArrayRef;
+ let new_array = array.with_values(values);
+ Ok(new_array)
}
- });
+ t => return_compute_error_with!(format!("{part} does not support"), t),
+ )
+}
- builder.finish()
+/// Used to integrate new [`date_part()`] method with deprecated shims such as
+/// [`hour()`] and [`week()`].
+fn date_part_primitive<T: ArrowTemporalType>(
+ array: &PrimitiveArray<T>,
+ part: DatePart,
+) -> Result<Int32Array, ArrowError> {
+ let array = date_part(array, part)?;
+ Ok(array.as_primitive::<Int32Type>().to_owned())
}
-/// This function takes an `ArrayIter` of input array and an extractor `op` which takes
-/// an input `NaiveDateTime` and returns data time component (e.g. hour) as `i32` value.
-/// The extracted values are built by the given `builder` to be an `Int32Array`.
-fn as_datetime_with_op<A: ArrayAccessor<Item = T::Native>, T: ArrowTemporalType, F>(
- iter: ArrayIter<A>,
- mut builder: PrimitiveBuilder<Int32Type>,
- op: F,
-) -> Int32Array
-where
- F: Fn(NaiveDateTime) -> i32,
- i64: From<T::Native>,
-{
- iter.into_iter().for_each(|value| {
- if let Some(value) = value {
- match as_datetime::<T>(i64::from(value)) {
- Some(dt) => builder.append_value(op(dt)),
- None => builder.append_null(),
- }
- } else {
- builder.append_null();
+/// Extract optional [`Tz`] from timestamp data types, returning error
+/// if called with a non-timestamp type.
+fn get_tz(dt: &DataType) -> Result<Option<Tz>, ArrowError> {
+ match dt {
+ DataType::Timestamp(_, Some(tz)) => Ok(Some(tz.parse::<Tz>()?)),
+ DataType::Timestamp(_, None) => Ok(None),
+ _ => Err(ArrowError::CastError(format!("Not a timestamp type: {dt}"))),
+ }
+}
+
+/// Implement the specialized functions for extracting date part from temporal arrays.
+trait ExtractDatePartExt {
+ fn date_part(&self, part: DatePart) -> Result<Int32Array, ArrowError>;
+}
+
+impl ExtractDatePartExt for PrimitiveArray<Time32SecondType> {
+ fn date_part(&self, part: DatePart) -> Result<Int32Array, ArrowError> {
+ match part {
+ DatePart::Hour => Ok(self.unary_opt(|d| time32s_to_time(d).map(|c| c.hour() as i32))),
+ // TODO expand support for Time types, see: https://github.com/apache/arrow-rs/issues/5261
+ _ => return_compute_error_with!(format!("{part} does not support"), self.data_type()),
+ }
+ }
+}
+
+impl ExtractDatePartExt for PrimitiveArray<Time32MillisecondType> {
+ fn date_part(&self, part: DatePart) -> Result<Int32Array, ArrowError> {
+ match part {
+ DatePart::Hour => Ok(self.unary_opt(|d| time32ms_to_time(d).map(|c| c.hour() as i32))),
+ // TODO expand support for Time types, see: https://github.com/apache/arrow-rs/issues/5261
+ _ => return_compute_error_with!(format!("{part} does not support"), self.data_type()),
}
- });
+ }
+}
- builder.finish()
+impl ExtractDatePartExt for PrimitiveArray<Time64MicrosecondType> {
+ fn date_part(&self, part: DatePart) -> Result<Int32Array, ArrowError> {
+ match part {
+ DatePart::Hour => Ok(self.unary_opt(|d| time64us_to_time(d).map(|c| c.hour() as i32))),
+ // TODO expand support for Time types, see: https://github.com/apache/arrow-rs/issues/5261
+ _ => return_compute_error_with!(format!("{part} does not support"), self.data_type()),
+ }
+ }
}
-/// This function extracts date time component (e.g. hour) from an array of datatime.
-/// `iter` is the `ArrayIter` of input datatime array. `builder` is used to build the
-/// returned `Int32Array` containing the extracted components. `tz` is timezone string
-/// which will be added to datetime values in the input array. `parsed` is a `Parsed`
-/// object used to parse timezone string. `op` is the extractor closure which takes
-/// data time object of `NaiveDateTime` type and returns `i32` value of extracted
-/// component.
-fn extract_component_from_datetime_array<
- A: ArrayAccessor<Item = T::Native>,
- T: ArrowTemporalType,
- F,
->(
- iter: ArrayIter<A>,
- mut builder: PrimitiveBuilder<Int32Type>,
- tz: &str,
- op: F,
-) -> Result<Int32Array, ArrowError>
-where
- F: Fn(DateTime<Tz>) -> i32,
- i64: From<T::Native>,
-{
- let tz: Tz = tz.parse()?;
- for value in iter {
- match value {
- Some(value) => match as_datetime_with_timezone::<T>(value.into(), tz) {
- Some(time) => builder.append_value(op(time)),
- _ => {
- return Err(ArrowError::ComputeError(
- "Unable to read value as datetime".to_string(),
- ))
- }
- },
- None => builder.append_null(),
+impl ExtractDatePartExt for PrimitiveArray<Time64NanosecondType> {
+ fn date_part(&self, part: DatePart) -> Result<Int32Array, ArrowError> {
+ match part {
+ DatePart::Hour => Ok(self.unary_opt(|d| time64ns_to_time(d).map(|c| c.hour() as i32))),
+ // TODO expand support for Time types, see: https://github.com/apache/arrow-rs/issues/5261
+ _ => return_compute_error_with!(format!("{part} does not support"), self.data_type()),
}
}
- Ok(builder.finish())
+}
+
+impl ExtractDatePartExt for PrimitiveArray<Date32Type> {
+ fn date_part(&self, part: DatePart) -> Result<Int32Array, ArrowError> {
+ // Date32 only encodes number of days, so these will always be 0
+ if let DatePart::Hour
+ | DatePart::Minute
+ | DatePart::Second
+ | DatePart::Millisecond
+ | DatePart::Microsecond
+ | DatePart::Nanosecond = part
+ {
+ Ok(Int32Array::new(
+ vec![0; self.len()].into(),
+ self.nulls().cloned(),
+ ))
+ } else {
+ let map_func = get_date_time_part_extract_fn(part);
+ Ok(self.unary_opt(|d| date32_to_datetime(d).map(map_func)))
+ }
+ }
+}
+
+impl ExtractDatePartExt for PrimitiveArray<Date64Type> {
+ fn date_part(&self, part: DatePart) -> Result<Int32Array, ArrowError> {
+ let map_func = get_date_time_part_extract_fn(part);
+ Ok(self.unary_opt(|d| date64_to_datetime(d).map(map_func)))
+ }
+}
+
+impl ExtractDatePartExt for PrimitiveArray<TimestampSecondType> {
+ fn date_part(&self, part: DatePart) -> Result<Int32Array, ArrowError> {
+ // TimestampSecond only encodes number of seconds, so these will always be 0
+ let array =
+ if let DatePart::Millisecond | DatePart::Microsecond | DatePart::Nanosecond = part {
+ Int32Array::new(vec![0; self.len()].into(), self.nulls().cloned())
+ } else if let Some(tz) = get_tz(self.data_type())? {
+ let map_func = get_date_time_part_extract_fn(part);
+ self.unary_opt(|d| {
+ timestamp_s_to_datetime(d)
+ .map(|c| Utc.from_utc_datetime(&c).with_timezone(&tz))
+ .map(map_func)
+ })
+ } else {
+ let map_func = get_date_time_part_extract_fn(part);
+ self.unary_opt(|d| timestamp_s_to_datetime(d).map(map_func))
+ };
+ Ok(array)
+ }
+}
+
+impl ExtractDatePartExt for PrimitiveArray<TimestampMillisecondType> {
+ fn date_part(&self, part: DatePart) -> Result<Int32Array, ArrowError> {
+ let array = if let Some(tz) = get_tz(self.data_type())? {
+ let map_func = get_date_time_part_extract_fn(part);
+ self.unary_opt(|d| {
+ timestamp_ms_to_datetime(d)
+ .map(|c| Utc.from_utc_datetime(&c).with_timezone(&tz))
+ .map(map_func)
+ })
+ } else {
+ let map_func = get_date_time_part_extract_fn(part);
+ self.unary_opt(|d| timestamp_ms_to_datetime(d).map(map_func))
+ };
+ Ok(array)
+ }
+}
+
+impl ExtractDatePartExt for PrimitiveArray<TimestampMicrosecondType> {
+ fn date_part(&self, part: DatePart) -> Result<Int32Array, ArrowError> {
+ let array = if let Some(tz) = get_tz(self.data_type())? {
+ let map_func = get_date_time_part_extract_fn(part);
+ self.unary_opt(|d| {
+ timestamp_us_to_datetime(d)
+ .map(|c| Utc.from_utc_datetime(&c).with_timezone(&tz))
+ .map(map_func)
+ })
+ } else {
+ let map_func = get_date_time_part_extract_fn(part);
+ self.unary_opt(|d| timestamp_us_to_datetime(d).map(map_func))
+ };
+ Ok(array)
+ }
+}
+
+impl ExtractDatePartExt for PrimitiveArray<TimestampNanosecondType> {
+ fn date_part(&self, part: DatePart) -> Result<Int32Array, ArrowError> {
+ let array = if let Some(tz) = get_tz(self.data_type())? {
+ let map_func = get_date_time_part_extract_fn(part);
+ self.unary_opt(|d| {
+ timestamp_ns_to_datetime(d)
+ .map(|c| Utc.from_utc_datetime(&c).with_timezone(&tz))
+ .map(map_func)
+ })
+ } else {
+ let map_func = get_date_time_part_extract_fn(part);
+ self.unary_opt(|d| timestamp_ns_to_datetime(d).map(map_func))
+ };
+ Ok(array)
+ }
}
macro_rules! return_compute_error_with {
@@ -170,7 +367,6 @@ pub fn using_chrono_tz_and_utc_naive_date_time(
tz: &str,
utc: NaiveDateTime,
) -> Option<chrono::offset::FixedOffset> {
- use chrono::TimeZone;
let tz: Tz = tz.parse().ok()?;
Some(tz.offset_from_utc_datetime(&utc).fix())
}
@@ -178,91 +374,76 @@ pub fn using_chrono_tz_and_utc_naive_date_time(
/// Extracts the hours of a given array as an array of integers within
/// the range of [0, 23]. If the given array isn't temporal primitive or dictionary array,
/// an `Err` will be returned.
+#[deprecated(since = "51.0.0", note = "Use `date_part` instead")]
pub fn hour_dyn(array: &dyn Array) -> Result<ArrayRef, ArrowError> {
- time_fraction_dyn(array, "hour", |t| t.hour() as i32)
+ date_part(array, DatePart::Hour)
}
/// Extracts the hours of a given temporal primitive array as an array of integers within
/// the range of [0, 23].
+#[deprecated(since = "51.0.0", note = "Use `date_part` instead")]
pub fn hour<T>(array: &PrimitiveArray<T>) -> Result<Int32Array, ArrowError>
where
T: ArrowTemporalType + ArrowNumericType,
i64: From<T::Native>,
{
- let b = Int32Builder::with_capacity(array.len());
- match array.data_type() {
- DataType::Time32(_) | DataType::Time64(_) => {
- let iter = ArrayIter::new(array);
- Ok(as_time_with_op::<&PrimitiveArray<T>, T, _>(iter, b, |t| {
- t.hour() as i32
- }))
- }
- DataType::Date32 | DataType::Date64 | DataType::Timestamp(_, None) => {
- let iter = ArrayIter::new(array);
- Ok(as_datetime_with_op::<&PrimitiveArray<T>, T, _>(
- iter,
- b,
- |t| t.hour() as i32,
- ))
- }
- DataType::Timestamp(_, Some(tz)) => {
- let iter = ArrayIter::new(array);
- extract_component_from_datetime_array::<&PrimitiveArray<T>, T, _>(iter, b, tz, |t| {
- t.hour() as i32
- })
- }
- _ => return_compute_error_with!("hour does not support", array.data_type()),
- }
+ date_part_primitive(array, DatePart::Hour)
}
/// Extracts the years of a given temporal array as an array of integers.
/// If the given array isn't temporal primitive or dictionary array,
/// an `Err` will be returned.
+#[deprecated(since = "51.0.0", note = "Use `date_part` instead")]
pub fn year_dyn(array: &dyn Array) -> Result<ArrayRef, ArrowError> {
- time_fraction_dyn(array, "year", |t| t.year())
+ date_part(array, DatePart::Year)
}
/// Extracts the years of a given temporal primitive array as an array of integers
+#[deprecated(since = "51.0.0", note = "Use `date_part` instead")]
pub fn year<T>(array: &PrimitiveArray<T>) -> Result<Int32Array, ArrowError>
where
T: ArrowTemporalType + ArrowNumericType,
i64: From<T::Native>,
{
- time_fraction_internal(array, "year", |t| t.year())
+ date_part_primitive(array, DatePart::Year)
}
/// Extracts the quarter of a given temporal array as an array of integersa within
/// the range of [1, 4]. If the given array isn't temporal primitive or dictionary array,
/// an `Err` will be returned.
+#[deprecated(since = "51.0.0", note = "Use `date_part` instead")]
pub fn quarter_dyn(array: &dyn Array) -> Result<ArrayRef, ArrowError> {
- time_fraction_dyn(array, "quarter", |t| t.quarter() as i32)
+ date_part(array, DatePart::Quarter)
}
/// Extracts the quarter of a given temporal primitive array as an array of integers within
/// the range of [1, 4].
+#[deprecated(since = "51.0.0", note = "Use `date_part` instead")]
pub fn quarter<T>(array: &PrimitiveArray<T>) -> Result<Int32Array, ArrowError>
where
T: ArrowTemporalType + ArrowNumericType,
i64: From<T::Native>,
{
- time_fraction_internal(array, "quarter", |t| t.quarter() as i32)
+ date_part_primitive(array, DatePart::Quarter)
}
/// Extracts the month of a given temporal array as an array of integers.
/// If the given array isn't temporal primitive or dictionary array,
/// an `Err` will be returned.
+#[deprecated(since = "51.0.0", note = "Use `date_part` instead")]
pub fn month_dyn(array: &dyn Array) -> Result<ArrayRef, ArrowError> {
- time_fraction_dyn(array, "month", |t| t.month() as i32)
+ date_part(array, DatePart::Month)
}
/// Extracts the month of a given temporal primitive array as an array of integers within
/// the range of [1, 12].
+#[deprecated(since = "51.0.0", note = "Use `date_part` instead")]
pub fn month<T>(array: &PrimitiveArray<T>) -> Result<Int32Array, ArrowError>
where
T: ArrowTemporalType + ArrowNumericType,
i64: From<T::Native>,
{
- time_fraction_internal(array, "month", |t| t.month() as i32)
+ date_part_primitive(array, DatePart::Month)
}
/// Extracts the day of week of a given temporal array as an array of
@@ -274,8 +455,9 @@ where
///
/// If the given array isn't temporal primitive or dictionary array,
/// an `Err` will be returned.
+#[deprecated(since = "51.0.0", note = "Use `date_part` instead")]
pub fn num_days_from_monday_dyn(array: &dyn Array) -> Result<ArrayRef, ArrowError> {
- time_fraction_dyn(array, "num_days_from_monday", |t| t.num_days_from_monday())
+ date_part(array, DatePart::DayOfWeekMonday0)
}
/// Extracts the day of week of a given temporal primitive array as an array of
@@ -284,12 +466,13 @@ pub fn num_days_from_monday_dyn(array: &dyn Array) -> Result<ArrayRef, ArrowErro
/// Monday is encoded as `0`, Tuesday as `1`, etc.
///
/// See also [`num_days_from_sunday`] which starts at Sunday.
+#[deprecated(since = "51.0.0", note = "Use `date_part` instead")]
pub fn num_days_from_monday<T>(array: &PrimitiveArray<T>) -> Result<Int32Array, ArrowError>
where
T: ArrowTemporalType + ArrowNumericType,
i64: From<T::Native>,
{
- time_fraction_internal(array, "num_days_from_monday", |t| t.num_days_from_monday())
+ date_part_primitive(array, DatePart::DayOfWeekMonday0)
}
/// Extracts the day of week of a given temporal array as an array of
@@ -301,8 +484,9 @@ where
///
/// If the given array isn't temporal primitive or dictionary array,
/// an `Err` will be returned.
+#[deprecated(since = "51.0.0", note = "Use `date_part` instead")]
pub fn num_days_from_sunday_dyn(array: &dyn Array) -> Result<ArrayRef, ArrowError> {
- time_fraction_dyn(array, "num_days_from_sunday", |t| t.num_days_from_sunday())
+ date_part(array, DatePart::DayOfWeekSunday0)
}
/// Extracts the day of week of a given temporal primitive array as an array of
@@ -311,201 +495,164 @@ pub fn num_days_from_sunday_dyn(array: &dyn Array) -> Result<ArrayRef, ArrowErro
/// Sunday is encoded as `0`, Monday as `1`, etc.
///
/// See also [`num_days_from_monday`] which starts at Monday.
+#[deprecated(since = "51.0.0", note = "Use `date_part` instead")]
pub fn num_days_from_sunday<T>(array: &PrimitiveArray<T>) -> Result<Int32Array, ArrowError>
where
T: ArrowTemporalType + ArrowNumericType,
i64: From<T::Native>,
{
- time_fraction_internal(array, "num_days_from_sunday", |t| t.num_days_from_sunday())
+ date_part_primitive(array, DatePart::DayOfWeekSunday0)
}
/// Extracts the day of a given temporal array as an array of integers.
/// If the given array isn't temporal primitive or dictionary array,
/// an `Err` will be returned.
+#[deprecated(since = "51.0.0", note = "Use `date_part` instead")]
pub fn day_dyn(array: &dyn Array) -> Result<ArrayRef, ArrowError> {
- time_fraction_dyn(array, "day", |t| t.day() as i32)
+ date_part(array, DatePart::Day)
}
/// Extracts the day of a given temporal primitive array as an array of integers
+#[deprecated(since = "51.0.0", note = "Use `date_part` instead")]
pub fn day<T>(array: &PrimitiveArray<T>) -> Result<Int32Array, ArrowError>
where
T: ArrowTemporalType + ArrowNumericType,
i64: From<T::Native>,
{
- time_fraction_internal(array, "day", |t| t.day() as i32)
+ date_part_primitive(array, DatePart::Day)
}
/// Extracts the day of year of a given temporal array as an array of integers
/// The day of year that ranges from 1 to 366.
/// If the given array isn't temporal primitive or dictionary array,
/// an `Err` will be returned.
+#[deprecated(since = "51.0.0", note = "Use `date_part` instead")]
pub fn doy_dyn(array: &dyn Array) -> Result<ArrayRef, ArrowError> {
- time_fraction_dyn(array, "doy", |t| t.ordinal() as i32)
+ date_part(array, DatePart::DayOfYear)
}
/// Extracts the day of year of a given temporal primitive array as an array of integers
/// The day of year that ranges from 1 to 366
+#[deprecated(since = "51.0.0", note = "Use `date_part` instead")]
pub fn doy<T>(array: &PrimitiveArray<T>) -> Result<Int32Array, ArrowError>
where
T: ArrowTemporalType + ArrowNumericType,
T::Native: ArrowNativeType,
i64: From<T::Native>,
{
- time_fraction_internal(array, "doy", |t| t.ordinal() as i32)
+ date_part_primitive(array, DatePart::DayOfYear)
}
/// Extracts the minutes of a given temporal primitive array as an array of integers
+#[deprecated(since = "51.0.0", note = "Use `date_part` instead")]
pub fn minute<T>(array: &PrimitiveArray<T>) -> Result<Int32Array, ArrowError>
where
T: ArrowTemporalType + ArrowNumericType,
i64: From<T::Native>,
{
- time_fraction_internal(array, "minute", |t| t.minute() as i32)
+ date_part_primitive(array, DatePart::Minute)
}
/// Extracts the week of a given temporal array as an array of integers.
/// If the given array isn't temporal primitive or dictionary array,
/// an `Err` will be returned.
+#[deprecated(since = "51.0.0", note = "Use `date_part` instead")]
pub fn week_dyn(array: &dyn Array) -> Result<ArrayRef, ArrowError> {
- time_fraction_dyn(array, "week", |t| t.iso_week().week() as i32)
+ date_part(array, DatePart::Week)
}
/// Extracts the week of a given temporal primitive array as an array of integers
+#[deprecated(since = "51.0.0", note = "Use `date_part` instead")]
pub fn week<T>(array: &PrimitiveArray<T>) -> Result<Int32Array, ArrowError>
where
T: ArrowTemporalType + ArrowNumericType,
i64: From<T::Native>,
{
- time_fraction_internal(array, "week", |t| t.iso_week().week() as i32)
+ date_part_primitive(array, DatePart::Week)
}
/// Extracts the seconds of a given temporal primitive array as an array of integers
+#[deprecated(since = "51.0.0", note = "Use `date_part` instead")]
pub fn second<T>(array: &PrimitiveArray<T>) -> Result<Int32Array, ArrowError>
where
T: ArrowTemporalType + ArrowNumericType,
i64: From<T::Native>,
{
- time_fraction_internal(array, "second", |t| t.second() as i32)
+ date_part_primitive(array, DatePart::Second)
}
/// Extracts the nanoseconds of a given temporal primitive array as an array of integers
+#[deprecated(since = "51.0.0", note = "Use `date_part` instead")]
pub fn nanosecond<T>(array: &PrimitiveArray<T>) -> Result<Int32Array, ArrowError>
where
T: ArrowTemporalType + ArrowNumericType,
i64: From<T::Native>,
{
- time_fraction_internal(array, "nanosecond", |t| t.nanosecond() as i32)
+ date_part_primitive(array, DatePart::Nanosecond)
}
/// Extracts the nanoseconds of a given temporal primitive array as an array of integers.
/// If the given array isn't temporal primitive or dictionary array,
/// an `Err` will be returned.
+#[deprecated(since = "51.0.0", note = "Use `date_part` instead")]
pub fn nanosecond_dyn(array: &dyn Array) -> Result<ArrayRef, ArrowError> {
- time_fraction_dyn(array, "nanosecond", |t| t.nanosecond() as i32)
+ date_part(array, DatePart::Nanosecond)
}
/// Extracts the microseconds of a given temporal primitive array as an array of integers
+#[deprecated(since = "51.0.0", note = "Use `date_part` instead")]
pub fn microsecond<T>(array: &PrimitiveArray<T>) -> Result<Int32Array, ArrowError>
where
T: ArrowTemporalType + ArrowNumericType,
i64: From<T::Native>,
{
- time_fraction_internal(array, "microsecond", |t| (t.nanosecond() / 1_000) as i32)
+ date_part_primitive(array, DatePart::Microsecond)
}
/// Extracts the microseconds of a given temporal primitive array as an array of integers.
/// If the given array isn't temporal primitive or dictionary array,
/// an `Err` will be returned.
+#[deprecated(since = "51.0.0", note = "Use `date_part` instead")]
pub fn microsecond_dyn(array: &dyn Array) -> Result<ArrayRef, ArrowError> {
- time_fraction_dyn(array, "microsecond", |t| (t.nanosecond() / 1_000) as i32)
+ date_part(array, DatePart::Microsecond)
}
/// Extracts the milliseconds of a given temporal primitive array as an array of integers
+#[deprecated(since = "51.0.0", note = "Use `date_part` instead")]
pub fn millisecond<T>(array: &PrimitiveArray<T>) -> Result<Int32Array, ArrowError>
where
T: ArrowTemporalType + ArrowNumericType,
i64: From<T::Native>,
{
- time_fraction_internal(array, "millisecond", |t| {
- (t.nanosecond() / 1_000_000) as i32
- })
+ date_part_primitive(array, DatePart::Millisecond)
}
+
/// Extracts the milliseconds of a given temporal primitive array as an array of integers.
/// If the given array isn't temporal primitive or dictionary array,
/// an `Err` will be returned.
+#[deprecated(since = "51.0.0", note = "Use `date_part` instead")]
pub fn millisecond_dyn(array: &dyn Array) -> Result<ArrayRef, ArrowError> {
- time_fraction_dyn(array, "millisecond", |t| {
- (t.nanosecond() / 1_000_000) as i32
- })
-}
-
-/// Extracts the time fraction of a given temporal array as an array of integers
-fn time_fraction_dyn<F>(array: &dyn Array, name: &str, op: F) -> Result<ArrayRef, ArrowError>
-where
- F: Fn(NaiveDateTime) -> i32,
-{
- match array.data_type().clone() {
- DataType::Dictionary(_, _) => {
- downcast_dictionary_array!(
- array => {
- let values = time_fraction_dyn(array.values(), name, op)?;
- Ok(Arc::new(array.with_values(values)))
- }
- dt => return_compute_error_with!(format!("{name} does not support"), dt),
- )
- }
- _ => {
- downcast_temporal_array!(
- array => {
- time_fraction_internal(array, name, op)
- .map(|a| Arc::new(a) as ArrayRef)
- }
- dt => return_compute_error_with!(format!("{name} does not support"), dt),
- )
- }
- }
-}
-
-/// Extracts the time fraction of a given temporal array as an array of integers
-fn time_fraction_internal<T, F>(
- array: &PrimitiveArray<T>,
- name: &str,
- op: F,
-) -> Result<Int32Array, ArrowError>
-where
- F: Fn(NaiveDateTime) -> i32,
- T: ArrowTemporalType + ArrowNumericType,
- i64: From<T::Native>,
-{
- let b = Int32Builder::with_capacity(array.len());
- match array.data_type() {
- DataType::Date32 | DataType::Date64 | DataType::Timestamp(_, None) => {
- let iter = ArrayIter::new(array);
- Ok(as_datetime_with_op::<_, T, _>(iter, b, op))
- }
- DataType::Timestamp(_, Some(tz)) => {
- let iter = ArrayIter::new(array);
- extract_component_from_datetime_array::<_, T, _>(iter, b, tz, |t| op(t.naive_local()))
- }
- _ => return_compute_error_with!(format!("{name} does not support"), array.data_type()),
- }
+ date_part(array, DatePart::Millisecond)
}
/// Extracts the minutes of a given temporal array as an array of integers.
/// If the given array isn't temporal primitive or dictionary array,
/// an `Err` will be returned.
+#[deprecated(since = "51.0.0", note = "Use `date_part` instead")]
pub fn minute_dyn(array: &dyn Array) -> Result<ArrayRef, ArrowError> {
- time_fraction_dyn(array, "minute", |t| t.minute() as i32)
+ date_part(array, DatePart::Minute)
}
/// Extracts the seconds of a given temporal array as an array of integers.
/// If the given array isn't temporal primitive or dictionary array,
/// an `Err` will be returned.
+#[deprecated(since = "51.0.0", note = "Use `date_part` instead")]
pub fn second_dyn(array: &dyn Array) -> Result<ArrayRef, ArrowError> {
- time_fraction_dyn(array, "second", |t| t.second() as i32)
+ date_part(array, DatePart::Second)
}
#[cfg(test)]
+#[allow(deprecated)]
mod tests {
use super::*;
@@ -932,7 +1079,7 @@ mod tests {
let expected = Arc::new(expected_dict) as ArrayRef;
assert_eq!(&expected, &b);
- let b = time_fraction_dyn(&dict, "minute", |t| t.minute() as i32).unwrap();
+ let b = date_part(&dict, DatePart::Minute).unwrap();
let b_old = minute_dyn(&dict).unwrap();
@@ -942,7 +1089,7 @@ mod tests {
assert_eq!(&expected, &b);
assert_eq!(&expected, &b_old);
- let b = time_fraction_dyn(&dict, "second", |t| t.second() as i32).unwrap();
+ let b = date_part(&dict, DatePart::Second).unwrap();
let b_old = second_dyn(&dict).unwrap();
@@ -952,7 +1099,7 @@ mod tests {
assert_eq!(&expected, &b);
assert_eq!(&expected, &b_old);
- let b = time_fraction_dyn(&dict, "nanosecond", |t| t.nanosecond() as i32).unwrap();
+ let b = date_part(&dict, DatePart::Nanosecond).unwrap();
let expected_dict =
DictionaryArray::new(keys, Arc::new(Int32Array::from(vec![0, 0, 0, 0, 0])));
|
diff --git a/arrow/tests/arithmetic.rs b/arrow/tests/arithmetic.rs
index 81a19d4b5e20..59a162ef6dc0 100644
--- a/arrow/tests/arithmetic.rs
+++ b/arrow/tests/arithmetic.rs
@@ -16,7 +16,7 @@
// under the License.
use arrow_arith::numeric::{add, sub};
-use arrow_arith::temporal::hour;
+use arrow_arith::temporal::{date_part, DatePart};
use arrow_array::cast::AsArray;
use arrow_array::temporal_conversions::as_datetime_with_timezone;
use arrow_array::timezone::Tz;
@@ -28,7 +28,8 @@ use chrono::{DateTime, TimeZone};
fn test_temporal_array_timestamp_hour_with_timezone_using_chrono_tz() {
let a =
TimestampSecondArray::from(vec![60 * 60 * 10]).with_timezone("Asia/Kolkata".to_string());
- let b = hour(&a).unwrap();
+ let b = date_part(&a, DatePart::Hour).unwrap();
+ let b = b.as_primitive::<Int32Type>();
assert_eq!(15, b.value(0));
}
@@ -41,7 +42,8 @@ fn test_temporal_array_timestamp_hour_with_dst_timezone_using_chrono_tz() {
let a = TimestampMillisecondArray::from(vec![Some(1635577147000)])
.with_timezone("Australia/Sydney".to_string());
- let b = hour(&a).unwrap();
+ let b = date_part(&a, DatePart::Hour).unwrap();
+ let b = b.as_primitive::<Int32Type>();
assert_eq!(17, b.value(0));
}
|
Temporal Extract/Date Part Kernel
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
<!--
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
(This section helps Arrow developers understand the context and *why* for this feature, in addition to the *what*)
-->
Currently we provide a mix of kernels for extracting portions of temporal types, https://docs.rs/arrow-arith/latest/arrow_arith/temporal/index.html
There are a couple of limitations with this implementation:
* The use of generics makes it non-trivial to support types such as Time32/Time64 (#5261) or intervals (#TBD)
* The way the kernels are implemented results in redundant code generation for impossible combinations, e.g. a Date32Array with a DataType of Timestamp
* The use of as_datetime and similar to always proxy via chrono is not only very inefficient, but also hard to follow
* They make use of builders instead of the faster (and more concise) `PrimitiveArray::try_unary` methods
* The code in general is quite hard to follow
**Describe the solution you'd like**
<!--
A clear and concise description of what you want to happen.
-->
I would like to take a similar approach to used in #4465, where we have a single method that accepts an operation and array, and then dispatches the operation to the specialized implementation for that particular array type. Aside from simplifying the implementation, we could also expose this publicly to facilitate implementation of the SQL extract/date_part function - https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT.
In particular I would like something akin to
```
pub enum DatePart {
Century,
Year,
...
Minute,
...
DayOfYear,
DayOfWeek,
}
pub fn date_part(array: &dyn Array, part: DatePart) -> Result<Int32Array> {
match array.data_type() {
...
}
}
```
The existing kernels would be deprecated and updated to act as simple shims to this dynamic dispatch logic, as has been done with the previous datum migrations.
**Describe alternatives you've considered**
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
|
This looks quite good, and would've made #5262 a bit easier to implement for sure (and for intervals in the future) :+1:
I wouldn't mind trying to take a shot at implementing this if it's not already on your todo list
|
2024-01-21T03:01:21Z
|
50.0
|
82fc0df73ab97e239ce5c748a05c57ce582f3d5d
|
apache/arrow-rs
| 5,318
|
apache__arrow-rs-5318
|
[
"5314"
] |
a0148ba4cea1756bd22c534dff14e362cb5ee242
|
diff --git a/arrow-json/src/writer.rs b/arrow-json/src/writer.rs
index cabda5e2dca8..dd77328cb7b5 100644
--- a/arrow-json/src/writer.rs
+++ b/arrow-json/src/writer.rs
@@ -20,28 +20,6 @@
//! This JSON writer converts Arrow [`RecordBatch`]es into arrays of
//! JSON objects or JSON formatted byte streams.
//!
-//! ## Writing JSON Objects
-//!
-//! To serialize [`RecordBatch`]es into array of
-//! [JSON](https://docs.serde.rs/serde_json/) objects, use
-//! [`record_batches_to_json_rows`]:
-//!
-//! ```
-//! # use std::sync::Arc;
-//! # use arrow_array::{Int32Array, RecordBatch};
-//! # use arrow_schema::{DataType, Field, Schema};
-//!
-//! let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
-//! let a = Int32Array::from(vec![1, 2, 3]);
-//! let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)]).unwrap();
-//!
-//! let json_rows = arrow_json::writer::record_batches_to_json_rows(&[&batch]).unwrap();
-//! assert_eq!(
-//! serde_json::Value::Object(json_rows[1].clone()),
-//! serde_json::json!({"a": 2}),
-//! );
-//! ```
-//!
//! ## Writing JSON formatted byte streams
//!
//! To serialize [`RecordBatch`]es into line-delimited JSON bytes, use
@@ -97,6 +75,8 @@
//! In order to explicitly write null values for keys, configure a custom [`Writer`] by
//! using a [`WriterBuilder`] to construct a [`Writer`].
+mod encoder;
+
use std::iter;
use std::{fmt::Debug, io::Write};
@@ -109,7 +89,9 @@ use arrow_array::types::*;
use arrow_array::*;
use arrow_schema::*;
+use crate::writer::encoder::EncoderOptions;
use arrow_cast::display::{ArrayFormatter, FormatOptions};
+use encoder::make_encoder;
fn primitive_array_to_json<T>(array: &dyn Array) -> Result<Vec<Value>, ArrowError>
where
@@ -481,6 +463,7 @@ fn set_column_for_json_rows(
/// Converts an arrow [`RecordBatch`] into a `Vec` of Serde JSON
/// [`JsonMap`]s (objects)
+#[deprecated(note = "Use Writer")]
pub fn record_batches_to_json_rows(
batches: &[&RecordBatch],
) -> Result<Vec<JsonMap<String, Value>>, ArrowError> {
@@ -597,11 +580,7 @@ pub type ArrayWriter<W> = Writer<W, JsonArray>;
/// JSON writer builder.
#[derive(Debug, Clone, Default)]
-pub struct WriterBuilder {
- /// Controls whether null values should be written explicitly for keys
- /// in objects, or whether the key should be omitted entirely.
- explicit_nulls: bool,
-}
+pub struct WriterBuilder(EncoderOptions);
impl WriterBuilder {
/// Create a new builder for configuring JSON writing options.
@@ -629,7 +608,7 @@ impl WriterBuilder {
/// Returns `true` if this writer is configured to keep keys with null values.
pub fn explicit_nulls(&self) -> bool {
- self.explicit_nulls
+ self.0.explicit_nulls
}
/// Set whether to keep keys with null values, or to omit writing them.
@@ -654,7 +633,7 @@ impl WriterBuilder {
///
/// Default is to skip nulls (set to `false`).
pub fn with_explicit_nulls(mut self, explicit_nulls: bool) -> Self {
- self.explicit_nulls = explicit_nulls;
+ self.0.explicit_nulls = explicit_nulls;
self
}
@@ -669,7 +648,7 @@ impl WriterBuilder {
started: false,
finished: false,
format: F::default(),
- explicit_nulls: self.explicit_nulls,
+ options: self.0,
}
}
}
@@ -702,8 +681,8 @@ where
/// Determines how the byte stream is formatted
format: F,
- /// Whether keys with null values should be written or skipped
- explicit_nulls: bool,
+ /// Controls how JSON should be encoded, e.g. whether to write explicit nulls or skip them
+ options: EncoderOptions,
}
impl<W, F> Writer<W, F>
@@ -718,11 +697,12 @@ where
started: false,
finished: false,
format: F::default(),
- explicit_nulls: false,
+ options: EncoderOptions::default(),
}
}
/// Write a single JSON row to the output writer
+ #[deprecated(note = "Use Writer::write")]
pub fn write_row(&mut self, row: &Value) -> Result<(), ArrowError> {
let is_first_row = !self.started;
if !self.started {
@@ -738,18 +718,48 @@ where
Ok(())
}
- /// Convert the `RecordBatch` into JSON rows, and write them to the output
+ /// Serialize `batch` to JSON output
pub fn write(&mut self, batch: &RecordBatch) -> Result<(), ArrowError> {
- for row in record_batches_to_json_rows_internal(&[batch], self.explicit_nulls)? {
- self.write_row(&Value::Object(row))?;
+ if batch.num_rows() == 0 {
+ return Ok(());
}
+
+ // BufWriter uses a buffer size of 8KB
+ // We therefore double this and flush once we have more than 8KB
+ let mut buffer = Vec::with_capacity(16 * 1024);
+
+ let mut is_first_row = !self.started;
+ if !self.started {
+ self.format.start_stream(&mut buffer)?;
+ self.started = true;
+ }
+
+ let array = StructArray::from(batch.clone());
+ let mut encoder = make_encoder(&array, &self.options)?;
+
+ for idx in 0..batch.num_rows() {
+ self.format.start_row(&mut buffer, is_first_row)?;
+ is_first_row = false;
+
+ encoder.encode(idx, &mut buffer);
+ if buffer.len() > 8 * 1024 {
+ self.writer.write_all(&buffer)?;
+ buffer.clear();
+ }
+ self.format.end_row(&mut buffer)?;
+ }
+
+ if !buffer.is_empty() {
+ self.writer.write_all(&buffer)?;
+ }
+
Ok(())
}
- /// Convert the [`RecordBatch`] into JSON rows, and write them to the output
+ /// Serialize `batches` to JSON output
pub fn write_batches(&mut self, batches: &[&RecordBatch]) -> Result<(), ArrowError> {
- for row in record_batches_to_json_rows_internal(batches, self.explicit_nulls)? {
- self.write_row(&Value::Object(row))?;
+ for b in batches {
+ self.write(b)?;
}
Ok(())
}
@@ -1453,6 +1463,7 @@ mod tests {
}
#[test]
+ #[allow(deprecated)]
fn json_writer_one_row() {
let mut writer = ArrayWriter::new(vec![] as Vec<u8>);
let v = json!({ "an": "object" });
@@ -1465,6 +1476,7 @@ mod tests {
}
#[test]
+ #[allow(deprecated)]
fn json_writer_two_rows() {
let mut writer = ArrayWriter::new(vec![] as Vec<u8>);
let v = json!({ "an": "object" });
@@ -1564,9 +1576,9 @@ mod tests {
r#"{"a":{"list":[1,2]},"b":{"list":[1,2]}}
{"a":{"list":[null]},"b":{"list":[null]}}
{"a":{"list":[]},"b":{"list":[]}}
-{"a":null,"b":{"list":[3,null]}}
+{"b":{"list":[3,null]}}
{"a":{"list":[4,5]},"b":{"list":[4,5]}}
-{"a":null,"b":{}}
+{"b":{}}
{"a":{},"b":{}}
"#,
);
@@ -1621,7 +1633,7 @@ mod tests {
assert_json_eq(
&buf,
r#"{"map":{"foo":10}}
-{"map":null}
+{}
{"map":{}}
{"map":{"bar":20,"baz":30,"qux":40}}
{"map":{"quux":50}}
diff --git a/arrow-json/src/writer/encoder.rs b/arrow-json/src/writer/encoder.rs
new file mode 100644
index 000000000000..87efcb9f39a0
--- /dev/null
+++ b/arrow-json/src/writer/encoder.rs
@@ -0,0 +1,445 @@
+// 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.
+
+use arrow_array::cast::AsArray;
+use arrow_array::types::*;
+use arrow_array::*;
+use arrow_buffer::{ArrowNativeType, NullBuffer, OffsetBuffer, ScalarBuffer};
+use arrow_cast::display::{ArrayFormatter, FormatOptions};
+use arrow_schema::{ArrowError, DataType, FieldRef};
+use half::f16;
+use lexical_core::FormattedSize;
+use serde::Serializer;
+use std::io::Write;
+
+#[derive(Debug, Clone, Default)]
+pub struct EncoderOptions {
+ pub explicit_nulls: bool,
+}
+
+/// A trait to format array values as JSON values
+///
+/// Nullability is handled by the caller to allow encoding nulls implicitly, i.e. `{}` instead of `{"a": null}`
+pub trait Encoder {
+ /// Encode the non-null value at index `idx` to `out`
+ ///
+ /// The behaviour is unspecified if `idx` corresponds to a null index
+ fn encode(&mut self, idx: usize, out: &mut Vec<u8>);
+}
+
+pub fn make_encoder<'a>(
+ array: &'a dyn Array,
+ options: &EncoderOptions,
+) -> Result<Box<dyn Encoder + 'a>, ArrowError> {
+ let (encoder, nulls) = make_encoder_impl(array, options)?;
+ assert!(nulls.is_none(), "root cannot be nullable");
+ Ok(encoder)
+}
+
+fn make_encoder_impl<'a>(
+ array: &'a dyn Array,
+ options: &EncoderOptions,
+) -> Result<(Box<dyn Encoder + 'a>, Option<NullBuffer>), ArrowError> {
+ macro_rules! primitive_helper {
+ ($t:ty) => {{
+ let array = array.as_primitive::<$t>();
+ let nulls = array.nulls().cloned();
+ (Box::new(PrimitiveEncoder::new(array)) as _, nulls)
+ }};
+ }
+
+ Ok(downcast_integer! {
+ array.data_type() => (primitive_helper),
+ DataType::Float16 => primitive_helper!(Float16Type),
+ DataType::Float32 => primitive_helper!(Float32Type),
+ DataType::Float64 => primitive_helper!(Float64Type),
+ DataType::Boolean => {
+ let array = array.as_boolean();
+ (Box::new(BooleanEncoder(array.clone())), array.nulls().cloned())
+ }
+ DataType::Null => (Box::new(NullEncoder), array.logical_nulls()),
+ DataType::Utf8 => {
+ let array = array.as_string::<i32>();
+ (Box::new(StringEncoder(array.clone())) as _, array.nulls().cloned())
+ }
+ DataType::LargeUtf8 => {
+ let array = array.as_string::<i64>();
+ (Box::new(StringEncoder(array.clone())) as _, array.nulls().cloned())
+ }
+ DataType::List(_) => {
+ let array = array.as_list::<i32>();
+ (Box::new(ListEncoder::try_new(array, options)?) as _, array.nulls().cloned())
+ }
+ DataType::LargeList(_) => {
+ let array = array.as_list::<i64>();
+ (Box::new(ListEncoder::try_new(array, options)?) as _, array.nulls().cloned())
+ }
+
+ DataType::Dictionary(_, _) => downcast_dictionary_array! {
+ array => (Box::new(DictionaryEncoder::try_new(array, options)?) as _, array.logical_nulls()),
+ _ => unreachable!()
+ }
+
+ DataType::Map(_, _) => {
+ let array = array.as_map();
+ (Box::new(MapEncoder::try_new(array, options)?) as _, array.nulls().cloned())
+ }
+
+ DataType::Struct(fields) => {
+ let array = array.as_struct();
+ let encoders = fields.iter().zip(array.columns()).map(|(field, array)| {
+ let (encoder, nulls) = make_encoder_impl(array, options)?;
+ Ok(FieldEncoder{
+ field: field.clone(),
+ encoder, nulls
+ })
+ }).collect::<Result<Vec<_>, ArrowError>>()?;
+
+ let encoder = StructArrayEncoder{
+ encoders,
+ explicit_nulls: options.explicit_nulls,
+ };
+ (Box::new(encoder) as _, array.nulls().cloned())
+ }
+ d => match d.is_temporal() {
+ true => {
+ // Note: the implementation of Encoder for ArrayFormatter assumes it does not produce
+ // characters that would need to be escaped within a JSON string, e.g. `'"'`.
+ // If support for user-provided format specifications is added, this assumption
+ // may need to be revisited
+ let options = FormatOptions::new().with_display_error(true);
+ let formatter = ArrayFormatter::try_new(array, &options)?;
+ (Box::new(formatter) as _, array.nulls().cloned())
+ }
+ false => return Err(ArrowError::InvalidArgumentError(format!("JSON Writer does not support data type: {d}"))),
+ }
+ })
+}
+
+fn encode_string(s: &str, out: &mut Vec<u8>) {
+ let mut serializer = serde_json::Serializer::new(out);
+ serializer.serialize_str(s).unwrap();
+}
+
+struct FieldEncoder<'a> {
+ field: FieldRef,
+ encoder: Box<dyn Encoder + 'a>,
+ nulls: Option<NullBuffer>,
+}
+
+struct StructArrayEncoder<'a> {
+ encoders: Vec<FieldEncoder<'a>>,
+ explicit_nulls: bool,
+}
+
+impl<'a> Encoder for StructArrayEncoder<'a> {
+ fn encode(&mut self, idx: usize, out: &mut Vec<u8>) {
+ out.push(b'{');
+ let mut is_first = true;
+ for field_encoder in &mut self.encoders {
+ let is_null = field_encoder.nulls.as_ref().is_some_and(|n| n.is_null(idx));
+ if is_null && !self.explicit_nulls {
+ continue;
+ }
+
+ if !is_first {
+ out.push(b',');
+ }
+ is_first = false;
+
+ encode_string(field_encoder.field.name(), out);
+ out.push(b':');
+
+ match is_null {
+ true => out.extend_from_slice(b"null"),
+ false => field_encoder.encoder.encode(idx, out),
+ }
+ }
+ out.push(b'}');
+ }
+}
+
+trait PrimitiveEncode: ArrowNativeType {
+ type Buffer;
+
+ // Workaround https://github.com/rust-lang/rust/issues/61415
+ fn init_buffer() -> Self::Buffer;
+
+ /// Encode the primitive value as bytes, returning a reference to that slice.
+ ///
+ /// `buf` is temporary space that may be used
+ fn encode(self, buf: &mut Self::Buffer) -> &[u8];
+}
+
+macro_rules! integer_encode {
+ ($($t:ty),*) => {
+ $(
+ impl PrimitiveEncode for $t {
+ type Buffer = [u8; Self::FORMATTED_SIZE];
+
+ fn init_buffer() -> Self::Buffer {
+ [0; Self::FORMATTED_SIZE]
+ }
+
+ fn encode(self, buf: &mut Self::Buffer) -> &[u8] {
+ lexical_core::write(self, buf)
+ }
+ }
+ )*
+ };
+}
+integer_encode!(i8, i16, i32, i64, u8, u16, u32, u64);
+
+macro_rules! float_encode {
+ ($($t:ty),*) => {
+ $(
+ impl PrimitiveEncode for $t {
+ type Buffer = [u8; Self::FORMATTED_SIZE];
+
+ fn init_buffer() -> Self::Buffer {
+ [0; Self::FORMATTED_SIZE]
+ }
+
+ fn encode(self, buf: &mut Self::Buffer) -> &[u8] {
+ if self.is_infinite() || self.is_nan() {
+ b"null"
+ } else {
+ lexical_core::write(self, buf)
+ }
+ }
+ }
+ )*
+ };
+}
+float_encode!(f32, f64);
+
+impl PrimitiveEncode for f16 {
+ type Buffer = <f32 as PrimitiveEncode>::Buffer;
+
+ fn init_buffer() -> Self::Buffer {
+ f32::init_buffer()
+ }
+
+ fn encode(self, buf: &mut Self::Buffer) -> &[u8] {
+ self.to_f32().encode(buf)
+ }
+}
+
+struct PrimitiveEncoder<N: PrimitiveEncode> {
+ values: ScalarBuffer<N>,
+ buffer: N::Buffer,
+}
+
+impl<N: PrimitiveEncode> PrimitiveEncoder<N> {
+ fn new<P: ArrowPrimitiveType<Native = N>>(array: &PrimitiveArray<P>) -> Self {
+ Self {
+ values: array.values().clone(),
+ buffer: N::init_buffer(),
+ }
+ }
+}
+
+impl<N: PrimitiveEncode> Encoder for PrimitiveEncoder<N> {
+ fn encode(&mut self, idx: usize, out: &mut Vec<u8>) {
+ out.extend_from_slice(self.values[idx].encode(&mut self.buffer));
+ }
+}
+
+struct BooleanEncoder(BooleanArray);
+
+impl Encoder for BooleanEncoder {
+ fn encode(&mut self, idx: usize, out: &mut Vec<u8>) {
+ match self.0.value(idx) {
+ true => out.extend_from_slice(b"true"),
+ false => out.extend_from_slice(b"false"),
+ }
+ }
+}
+
+struct StringEncoder<O: OffsetSizeTrait>(GenericStringArray<O>);
+
+impl<O: OffsetSizeTrait> Encoder for StringEncoder<O> {
+ fn encode(&mut self, idx: usize, out: &mut Vec<u8>) {
+ encode_string(self.0.value(idx), out);
+ }
+}
+
+struct ListEncoder<'a, O: OffsetSizeTrait> {
+ offsets: OffsetBuffer<O>,
+ nulls: Option<NullBuffer>,
+ encoder: Box<dyn Encoder + 'a>,
+}
+
+impl<'a, O: OffsetSizeTrait> ListEncoder<'a, O> {
+ fn try_new(
+ array: &'a GenericListArray<O>,
+ options: &EncoderOptions,
+ ) -> Result<Self, ArrowError> {
+ let (encoder, nulls) = make_encoder_impl(array.values().as_ref(), options)?;
+ Ok(Self {
+ offsets: array.offsets().clone(),
+ encoder,
+ nulls,
+ })
+ }
+}
+
+impl<'a, O: OffsetSizeTrait> Encoder for ListEncoder<'a, O> {
+ fn encode(&mut self, idx: usize, out: &mut Vec<u8>) {
+ let end = self.offsets[idx + 1].as_usize();
+ let start = self.offsets[idx].as_usize();
+ out.push(b'[');
+ match self.nulls.as_ref() {
+ Some(n) => (start..end).for_each(|idx| {
+ if idx != start {
+ out.push(b',')
+ }
+ match n.is_null(idx) {
+ true => out.extend_from_slice(b"null"),
+ false => self.encoder.encode(idx, out),
+ }
+ }),
+ None => (start..end).for_each(|idx| {
+ if idx != start {
+ out.push(b',')
+ }
+ self.encoder.encode(idx, out);
+ }),
+ }
+ out.push(b']');
+ }
+}
+
+struct DictionaryEncoder<'a, K: ArrowDictionaryKeyType> {
+ keys: ScalarBuffer<K::Native>,
+ encoder: Box<dyn Encoder + 'a>,
+}
+
+impl<'a, K: ArrowDictionaryKeyType> DictionaryEncoder<'a, K> {
+ fn try_new(
+ array: &'a DictionaryArray<K>,
+ options: &EncoderOptions,
+ ) -> Result<Self, ArrowError> {
+ let encoder = make_encoder(array.values().as_ref(), options)?;
+
+ Ok(Self {
+ keys: array.keys().values().clone(),
+ encoder,
+ })
+ }
+}
+
+impl<'a, K: ArrowDictionaryKeyType> Encoder for DictionaryEncoder<'a, K> {
+ fn encode(&mut self, idx: usize, out: &mut Vec<u8>) {
+ self.encoder.encode(self.keys[idx].as_usize(), out)
+ }
+}
+
+impl<'a> Encoder for ArrayFormatter<'a> {
+ fn encode(&mut self, idx: usize, out: &mut Vec<u8>) {
+ out.push(b'"');
+ // Should be infallible
+ // Note: We are making an assumption that the formatter does not produce characters that require escaping
+ let _ = write!(out, "{}", self.value(idx));
+ out.push(b'"')
+ }
+}
+
+struct NullEncoder;
+
+impl Encoder for NullEncoder {
+ fn encode(&mut self, _idx: usize, _out: &mut Vec<u8>) {
+ unreachable!()
+ }
+}
+
+struct MapEncoder<'a> {
+ offsets: OffsetBuffer<i32>,
+ keys: Box<dyn Encoder + 'a>,
+ values: Box<dyn Encoder + 'a>,
+ value_nulls: Option<NullBuffer>,
+ explicit_nulls: bool,
+}
+
+impl<'a> MapEncoder<'a> {
+ fn try_new(array: &'a MapArray, options: &EncoderOptions) -> Result<Self, ArrowError> {
+ let values = array.values();
+ let keys = array.keys();
+
+ if !matches!(keys.data_type(), DataType::Utf8 | DataType::LargeUtf8) {
+ return Err(ArrowError::JsonError(format!(
+ "Only UTF8 keys supported by JSON MapArray Writer: got {:?}",
+ keys.data_type()
+ )));
+ }
+
+ let (keys, key_nulls) = make_encoder_impl(keys, options)?;
+ let (values, value_nulls) = make_encoder_impl(values, options)?;
+
+ // We sanity check nulls as these are currently not enforced by MapArray (#1697)
+ if key_nulls.is_some_and(|x| x.null_count() != 0) {
+ return Err(ArrowError::InvalidArgumentError(
+ "Encountered nulls in MapArray keys".to_string(),
+ ));
+ }
+
+ if array.entries().nulls().is_some_and(|x| x.null_count() != 0) {
+ return Err(ArrowError::InvalidArgumentError(
+ "Encountered nulls in MapArray entries".to_string(),
+ ));
+ }
+
+ Ok(Self {
+ offsets: array.offsets().clone(),
+ keys,
+ values,
+ value_nulls,
+ explicit_nulls: options.explicit_nulls,
+ })
+ }
+}
+
+impl<'a> Encoder for MapEncoder<'a> {
+ fn encode(&mut self, idx: usize, out: &mut Vec<u8>) {
+ let end = self.offsets[idx + 1].as_usize();
+ let start = self.offsets[idx].as_usize();
+
+ let mut is_first = true;
+
+ out.push(b'{');
+ for idx in start..end {
+ let is_null = self.value_nulls.as_ref().is_some_and(|n| n.is_null(idx));
+ if is_null && !self.explicit_nulls {
+ continue;
+ }
+
+ if !is_first {
+ out.push(b',');
+ }
+ is_first = false;
+
+ self.keys.encode(idx, out);
+ out.push(b':');
+
+ match is_null {
+ true => out.extend_from_slice(b"null"),
+ false => self.values.encode(idx, out),
+ }
+ }
+ out.push(b'}');
+ }
+}
diff --git a/arrow/benches/json_writer.rs b/arrow/benches/json_writer.rs
index a4c486bac6da..48be0bccb462 100644
--- a/arrow/benches/json_writer.rs
+++ b/arrow/benches/json_writer.rs
@@ -133,7 +133,7 @@ fn bench_string(c: &mut Criterion) {
let batch =
RecordBatch::try_from_iter([("c1", c1 as _), ("c2", c2 as _), ("c3", c3 as _)]).unwrap();
- do_bench(c, "bench_dict_array", &batch)
+ do_bench(c, "bench_string", &batch)
}
fn bench_struct(c: &mut Criterion) {
|
diff --git a/arrow-json/test/data/basic.json b/arrow-json/test/data/basic.json
index a6a8766bf97c..fdcae9e6557e 100644
--- a/arrow-json/test/data/basic.json
+++ b/arrow-json/test/data/basic.json
@@ -1,5 +1,5 @@
-{"a":1, "b":2.0, "c":false, "d":"4", "e":"1970-1-2", "f": "1.02", "g": "2012-04-23T18:25:43.511", "h": 1.1}
-{"a":-10, "b":-3.5, "c":true, "d":"4", "e": "1969-12-31", "f": "-0.3", "g": "2016-04-23T18:25:43.511", "h": 3.141}
+{"a":1, "b":2.0, "c":false, "d":"4", "e":"1970-1-2", "f": "1.02", "g": "2012-04-23T18:25:43.511", "h": 1.125}
+{"a":-10, "b":-3.5, "c":true, "d":"4", "e": "1969-12-31", "f": "-0.3", "g": "2016-04-23T18:25:43.511", "h": 3.5}
{"a":2, "b":0.6, "c":false, "d":"text", "e": "1970-01-02 11:11:11", "f": "1377.223"}
{"a":1, "b":2.0, "c":false, "d":"4", "f": "1337.009"}
{"a":7, "b":-3.5, "c":true, "d":"4", "f": "1"}
|
Raw JSON Writer
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
<!--
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
(This section helps Arrow developers understand the context and *why* for this feature, in addition to the *what*)
-->
Following #3479 we no longer use serde_json to decode JSON, this is not only significantly faster but gives us more control.
I would like to propose doing something similar for the write path, this would not only significantly improve performance but also give us more control over how data is encoded - https://github.com/apache/arrow-rs/pull/5197#discussion_r1421834724
**Describe the solution you'd like**
<!--
A clear and concise description of what you want to happen.
-->
I would like to deprecate the current serde_json based encoding mechanism, and introduce a new encoder that writes directly to a `std::fmt::Write`. Unfortunately the `serde_json` nature leaks out in a couple of places, so we will need to have a gradual deprecation of this functionality much like we did for #3479.
**Describe alternatives you've considered**
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
|
2024-01-20T13:03:28Z
|
50.0
|
82fc0df73ab97e239ce5c748a05c57ce582f3d5d
|
|
apache/arrow-rs
| 5,293
|
apache__arrow-rs-5293
|
[
"4102"
] |
db811083669df66992008c9409b743a2e365adb0
|
diff --git a/parquet/Cargo.toml b/parquet/Cargo.toml
index 4cd03c051e62..fb3b67274ada 100644
--- a/parquet/Cargo.toml
+++ b/parquet/Cargo.toml
@@ -175,6 +175,11 @@ name = "compression"
required-features = ["experimental", "default"]
harness = false
+[[bench]]
+name = "encoding"
+required-features = ["experimental", "default"]
+harness = false
+
[[bench]]
name = "metadata"
diff --git a/parquet/README.md b/parquet/README.md
index 9de7aec4e59a..e5b53050b70c 100644
--- a/parquet/README.md
+++ b/parquet/README.md
@@ -55,7 +55,7 @@ The `parquet` crate provides the following features which may be enabled in your
## Parquet Feature Status
-- [x] All encodings supported, except for BYTE_STREAM_SPLIT ([#4102](https://github.com/apache/arrow-rs/issues/4102))
+- [x] All encodings supported
- [x] All compression codecs supported
- [x] Read support
- [x] Primitive column value readers
diff --git a/parquet/benches/encoding.rs b/parquet/benches/encoding.rs
new file mode 100644
index 000000000000..bdbca3567a2b
--- /dev/null
+++ b/parquet/benches/encoding.rs
@@ -0,0 +1,83 @@
+// 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.
+
+use criterion::*;
+use parquet::basic::Encoding;
+use parquet::data_type::{DataType, DoubleType, FloatType};
+use parquet::decoding::{get_decoder, Decoder};
+use parquet::encoding::get_encoder;
+use parquet::schema::types::{ColumnDescPtr, ColumnDescriptor, ColumnPath, Type};
+use rand::prelude::*;
+use std::sync::Arc;
+
+fn bench_typed<T: DataType>(c: &mut Criterion, values: &[T::T], encoding: Encoding) {
+ let name = format!(
+ "dtype={}, encoding={:?}",
+ std::any::type_name::<T::T>(),
+ encoding
+ );
+ c.bench_function(&format!("encoding: {}", name), |b| {
+ b.iter(|| {
+ let mut encoder = get_encoder::<T>(encoding).unwrap();
+ encoder.put(values).unwrap();
+ encoder.flush_buffer().unwrap();
+ });
+ });
+
+ let mut encoder = get_encoder::<T>(encoding).unwrap();
+ encoder.put(values).unwrap();
+ let encoded = encoder.flush_buffer().unwrap();
+ println!("{} encoded as {} bytes", name, encoded.len(),);
+
+ let mut buffer = vec![T::T::default(); values.len()];
+ let column_desc_ptr = ColumnDescPtr::new(ColumnDescriptor::new(
+ Arc::new(
+ Type::primitive_type_builder("", T::get_physical_type())
+ .build()
+ .unwrap(),
+ ),
+ 0,
+ 0,
+ ColumnPath::new(vec![]),
+ ));
+ c.bench_function(&format!("decoding: {}", name), |b| {
+ b.iter(|| {
+ let mut decoder: Box<dyn Decoder<T>> =
+ get_decoder(column_desc_ptr.clone(), encoding).unwrap();
+ decoder.set_data(encoded.clone(), values.len()).unwrap();
+ decoder.get(&mut buffer).unwrap();
+ });
+ });
+}
+
+fn criterion_benchmark(c: &mut Criterion) {
+ let mut rng = StdRng::seed_from_u64(0);
+ let n = 16 * 1024;
+
+ let mut f32s = Vec::new();
+ let mut f64s = Vec::new();
+ for _ in 0..n {
+ f32s.push(rng.gen::<f32>());
+ f64s.push(rng.gen::<f64>());
+ }
+
+ bench_typed::<FloatType>(c, &f32s, Encoding::BYTE_STREAM_SPLIT);
+ bench_typed::<DoubleType>(c, &f64s, Encoding::BYTE_STREAM_SPLIT);
+}
+
+criterion_group!(benches, criterion_benchmark);
+criterion_main!(benches);
diff --git a/parquet/src/arrow/arrow_reader/mod.rs b/parquet/src/arrow/arrow_reader/mod.rs
index 52d7249a290e..6b6146042051 100644
--- a/parquet/src/arrow/arrow_reader/mod.rs
+++ b/parquet/src/arrow/arrow_reader/mod.rs
@@ -737,7 +737,9 @@ mod tests {
use arrow_array::builder::*;
use arrow_array::cast::AsArray;
- use arrow_array::types::{Decimal128Type, Decimal256Type, DecimalType, Float16Type};
+ use arrow_array::types::{
+ Decimal128Type, Decimal256Type, DecimalType, Float16Type, Float32Type, Float64Type,
+ };
use arrow_array::*;
use arrow_array::{RecordBatch, RecordBatchReader};
use arrow_buffer::{i256, ArrowNativeType, Buffer};
@@ -755,7 +757,7 @@ mod tests {
use crate::column::reader::decoder::REPETITION_LEVELS_BATCH_SIZE;
use crate::data_type::{
BoolType, ByteArray, ByteArrayType, DataType, FixedLenByteArray, FixedLenByteArrayType,
- Int32Type, Int64Type, Int96Type,
+ FloatType, Int32Type, Int64Type, Int96Type,
};
use crate::errors::Result;
use crate::file::properties::{EnabledStatistics, WriterProperties, WriterVersion};
@@ -861,6 +863,13 @@ mod tests {
Encoding::DELTA_BINARY_PACKED,
],
);
+ run_single_column_reader_tests::<FloatType, _, FloatType>(
+ 2,
+ ConvertedType::NONE,
+ None,
+ |vals| Arc::new(Float32Array::from_iter(vals.iter().cloned())),
+ &[Encoding::PLAIN, Encoding::BYTE_STREAM_SPLIT],
+ );
}
#[test]
@@ -1390,6 +1399,35 @@ mod tests {
assert!(col.value(2).is_nan());
}
+ #[test]
+ fn test_read_float32_float64_byte_stream_split() {
+ let path = format!(
+ "{}/byte_stream_split.zstd.parquet",
+ arrow::util::test_util::parquet_test_data(),
+ );
+ let file = File::open(path).unwrap();
+ let record_reader = ParquetRecordBatchReader::try_new(file, 128).unwrap();
+
+ let mut row_count = 0;
+ for batch in record_reader {
+ let batch = batch.unwrap();
+ row_count += batch.num_rows();
+ let f32_col = batch.column(0).as_primitive::<Float32Type>();
+ let f64_col = batch.column(1).as_primitive::<Float64Type>();
+
+ // This file contains floats from a standard normal distribution
+ for &x in f32_col.values() {
+ assert!(x > -10.0);
+ assert!(x < 10.0);
+ }
+ for &x in f64_col.values() {
+ assert!(x > -10.0);
+ assert!(x < 10.0);
+ }
+ }
+ assert_eq!(row_count, 300);
+ }
+
/// Parameters for single_column_reader_test
#[derive(Clone)]
struct TestOptions {
diff --git a/parquet/src/arrow/arrow_writer/mod.rs b/parquet/src/arrow/arrow_writer/mod.rs
index e6e95d50996a..3563348791bc 100644
--- a/parquet/src/arrow/arrow_writer/mod.rs
+++ b/parquet/src/arrow/arrow_writer/mod.rs
@@ -1579,6 +1579,9 @@ mod tests {
| DataType::UInt32
| DataType::UInt16
| DataType::UInt8 => vec![Encoding::PLAIN, Encoding::DELTA_BINARY_PACKED],
+ DataType::Float32 | DataType::Float64 => {
+ vec![Encoding::PLAIN, Encoding::BYTE_STREAM_SPLIT]
+ }
_ => vec![Encoding::PLAIN],
};
diff --git a/parquet/src/encodings/decoding.rs b/parquet/src/encodings/decoding.rs
index 5843acdb6d0f..88bc3920f309 100644
--- a/parquet/src/encodings/decoding.rs
+++ b/parquet/src/encodings/decoding.rs
@@ -31,6 +31,8 @@ use crate::errors::{ParquetError, Result};
use crate::schema::types::ColumnDescPtr;
use crate::util::bit_util::{self, BitReader};
+mod byte_stream_split_decoder;
+
pub(crate) mod private {
use super::*;
@@ -103,8 +105,32 @@ pub(crate) mod private {
}
}
- impl GetDecoder for f32 {}
- impl GetDecoder for f64 {}
+ impl GetDecoder for f32 {
+ fn get_decoder<T: DataType<T = Self>>(
+ descr: ColumnDescPtr,
+ encoding: Encoding,
+ ) -> Result<Box<dyn Decoder<T>>> {
+ match encoding {
+ Encoding::BYTE_STREAM_SPLIT => Ok(Box::new(
+ byte_stream_split_decoder::ByteStreamSplitDecoder::new(),
+ )),
+ _ => get_decoder_default(descr, encoding),
+ }
+ }
+ }
+ impl GetDecoder for f64 {
+ fn get_decoder<T: DataType<T = Self>>(
+ descr: ColumnDescPtr,
+ encoding: Encoding,
+ ) -> Result<Box<dyn Decoder<T>>> {
+ match encoding {
+ Encoding::BYTE_STREAM_SPLIT => Ok(Box::new(
+ byte_stream_split_decoder::ByteStreamSplitDecoder::new(),
+ )),
+ _ => get_decoder_default(descr, encoding),
+ }
+ }
+ }
impl GetDecoder for ByteArray {
fn get_decoder<T: DataType<T = Self>>(
@@ -550,14 +576,12 @@ where
.get_zigzag_vlq_int()
.ok_or_else(|| eof_err!("Not enough data to decode 'min_delta'"))?;
- self.min_delta = T::T::from_i64(min_delta)
- .ok_or_else(|| general_err!("'min_delta' too large"))?;
+ self.min_delta =
+ T::T::from_i64(min_delta).ok_or_else(|| general_err!("'min_delta' too large"))?;
self.mini_block_bit_widths.clear();
- self.bit_reader.get_aligned_bytes(
- &mut self.mini_block_bit_widths,
- self.mini_blocks_per_block,
- );
+ self.bit_reader
+ .get_aligned_bytes(&mut self.mini_block_bit_widths, self.mini_blocks_per_block);
let mut offset = self.bit_reader.get_byte_offset();
let mut remaining = self.values_left;
@@ -634,10 +658,8 @@ where
.get_zigzag_vlq_int()
.ok_or_else(|| eof_err!("Not enough data to decode 'first_value'"))?;
- self.first_value = Some(
- T::T::from_i64(first_value)
- .ok_or_else(|| general_err!("first value too large"))?,
- );
+ self.first_value =
+ Some(T::T::from_i64(first_value).ok_or_else(|| general_err!("first value too large"))?);
if self.block_size % 128 != 0 {
return Err(general_err!(
@@ -649,7 +671,8 @@ where
if self.block_size % self.mini_blocks_per_block != 0 {
return Err(general_err!(
"'block_size' must be a multiple of 'mini_blocks_per_block' got {} and {}",
- self.block_size, self.mini_blocks_per_block
+ self.block_size,
+ self.mini_blocks_per_block
));
}
@@ -994,11 +1017,9 @@ impl<T: DataType> Decoder<T> for DeltaByteArrayDecoder<T> {
self.previous_value.clear();
Ok(())
}
- _ => {
- Err(general_err!(
- "DeltaByteArrayDecoder only supports ByteArrayType and FixedLenByteArrayType"
- ))
- }
+ _ => Err(general_err!(
+ "DeltaByteArrayDecoder only supports ByteArrayType and FixedLenByteArrayType"
+ )),
}
}
@@ -1010,7 +1031,10 @@ impl<T: DataType> Decoder<T> for DeltaByteArrayDecoder<T> {
for item in buffer.iter_mut().take(num_values) {
// Process suffix
// TODO: this is awkward - maybe we should add a non-vectorized API?
- let suffix_decoder = self.suffix_decoder.as_mut().expect("decoder not initialized");
+ let suffix_decoder = self
+ .suffix_decoder
+ .as_mut()
+ .expect("decoder not initialized");
suffix_decoder.get(&mut v[..])?;
let suffix = v[0].data();
@@ -1045,11 +1069,9 @@ impl<T: DataType> Decoder<T> for DeltaByteArrayDecoder<T> {
self.num_values -= num_values;
Ok(num_values)
}
- _ => {
- Err(general_err!(
- "DeltaByteArrayDecoder only supports ByteArrayType and FixedLenByteArrayType"
- ))
- }
+ _ => Err(general_err!(
+ "DeltaByteArrayDecoder only supports ByteArrayType and FixedLenByteArrayType"
+ )),
}
}
@@ -1075,9 +1097,7 @@ mod tests {
use std::f64::consts::PI as PI_f64;
use std::sync::Arc;
- use crate::schema::types::{
- ColumnDescPtr, ColumnDescriptor, ColumnPath, Type as SchemaType,
- };
+ use crate::schema::types::{ColumnDescPtr, ColumnDescriptor, ColumnPath, Type as SchemaType};
use crate::util::test_common::rand_gen::RandGen;
#[test]
@@ -1085,10 +1105,7 @@ mod tests {
// supported encodings
create_and_check_decoder::<Int32Type>(Encoding::PLAIN, None);
create_and_check_decoder::<Int32Type>(Encoding::DELTA_BINARY_PACKED, None);
- create_and_check_decoder::<ByteArrayType>(
- Encoding::DELTA_LENGTH_BYTE_ARRAY,
- None,
- );
+ create_and_check_decoder::<ByteArrayType>(Encoding::DELTA_LENGTH_BYTE_ARRAY, None);
create_and_check_decoder::<ByteArrayType>(Encoding::DELTA_BYTE_ARRAY, None);
create_and_check_decoder::<BoolType>(Encoding::RLE, None);
@@ -1479,8 +1496,8 @@ mod tests {
#[test]
fn test_delta_bit_packed_int32_repeat() {
let block_data = vec![
- 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2,
- 3, 4, 5, 6, 7, 8,
+ 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5,
+ 6, 7, 8,
];
test_delta_bit_packed_decode::<Int32Type>(vec![block_data]);
}
@@ -1488,8 +1505,8 @@ mod tests {
#[test]
fn test_skip_delta_bit_packed_int32_repeat() {
let block_data = vec![
- 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2,
- 3, 4, 5, 6, 7, 8,
+ 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5,
+ 6, 7, 8,
];
test_skip::<Int32Type>(block_data.clone(), Encoding::DELTA_BINARY_PACKED, 10);
test_skip::<Int32Type>(block_data, Encoding::DELTA_BINARY_PACKED, 100);
@@ -1511,14 +1528,13 @@ mod tests {
#[test]
fn test_delta_bit_packed_int32_same_values() {
let block_data = vec![
- 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,
- 127,
+ 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,
];
test_delta_bit_packed_decode::<Int32Type>(vec![block_data]);
let block_data = vec![
- -127, -127, -127, -127, -127, -127, -127, -127, -127, -127, -127, -127, -127,
- -127, -127, -127,
+ -127, -127, -127, -127, -127, -127, -127, -127, -127, -127, -127, -127, -127, -127,
+ -127, -127,
];
test_delta_bit_packed_decode::<Int32Type>(vec![block_data]);
}
@@ -1526,15 +1542,14 @@ mod tests {
#[test]
fn test_skip_delta_bit_packed_int32_same_values() {
let block_data = vec![
- 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,
- 127,
+ 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127,
];
test_skip::<Int32Type>(block_data.clone(), Encoding::DELTA_BINARY_PACKED, 5);
test_skip::<Int32Type>(block_data, Encoding::DELTA_BINARY_PACKED, 100);
let block_data = vec![
- -127, -127, -127, -127, -127, -127, -127, -127, -127, -127, -127, -127, -127,
- -127, -127, -127,
+ -127, -127, -127, -127, -127, -127, -127, -127, -127, -127, -127, -127, -127, -127,
+ -127, -127,
];
test_skip::<Int32Type>(block_data.clone(), Encoding::DELTA_BINARY_PACKED, 5);
test_skip::<Int32Type>(block_data, Encoding::DELTA_BINARY_PACKED, 100);
@@ -1634,8 +1649,8 @@ mod tests {
#[test]
fn test_delta_bit_packed_decoder_sample() {
let data_bytes = vec![
- 128, 1, 4, 3, 58, 28, 6, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 128, 1, 4, 3, 58, 28, 6, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0,
];
let mut decoder: DeltaBitPackDecoder<Int32Type> = DeltaBitPackDecoder::new();
decoder.set_data(data_bytes.into(), 3).unwrap();
@@ -1760,6 +1775,38 @@ mod tests {
test_delta_byte_array_decode(data);
}
+ #[test]
+ fn test_byte_stream_split_multiple_f32() {
+ let data = vec![
+ vec![
+ f32::from_le_bytes([0xAA, 0xBB, 0xCC, 0xDD]),
+ f32::from_le_bytes([0x00, 0x11, 0x22, 0x33]),
+ ],
+ vec![f32::from_le_bytes([0xA3, 0xB4, 0xC5, 0xD6])],
+ ];
+ test_byte_stream_split_decode::<FloatType>(data);
+ }
+
+ #[test]
+ fn test_byte_stream_split_f64() {
+ let data = vec![vec![
+ f64::from_le_bytes([0, 1, 2, 3, 4, 5, 6, 7]),
+ f64::from_le_bytes([8, 9, 10, 11, 12, 13, 14, 15]),
+ ]];
+ test_byte_stream_split_decode::<DoubleType>(data);
+ }
+
+ #[test]
+ fn test_skip_byte_stream_split() {
+ let block_data = vec![0.3, 0.4, 0.1, 4.10];
+ test_skip::<FloatType>(block_data.clone(), Encoding::BYTE_STREAM_SPLIT, 2);
+ test_skip::<DoubleType>(
+ block_data.into_iter().map(|x| x as f64).collect(),
+ Encoding::BYTE_STREAM_SPLIT,
+ 100,
+ );
+ }
+
fn test_rle_value_decode<T: DataType>(data: Vec<Vec<T::T>>) {
test_encode_decode::<T>(data, Encoding::RLE);
}
@@ -1768,6 +1815,10 @@ mod tests {
test_encode_decode::<T>(data, Encoding::DELTA_BINARY_PACKED);
}
+ fn test_byte_stream_split_decode<T: DataType>(data: Vec<Vec<T::T>>) {
+ test_encode_decode::<T>(data, Encoding::BYTE_STREAM_SPLIT);
+ }
+
fn test_delta_byte_array_decode(data: Vec<Vec<ByteArray>>) {
test_encode_decode::<ByteArrayType>(data, Encoding::DELTA_BYTE_ARRAY);
}
@@ -1844,10 +1895,7 @@ mod tests {
}
}
- fn create_and_check_decoder<T: DataType>(
- encoding: Encoding,
- err: Option<ParquetError>,
- ) {
+ fn create_and_check_decoder<T: DataType>(encoding: Encoding, err: Option<ParquetError>) {
let descr = create_test_col_desc_ptr(-1, T::get_physical_type());
let decoder = get_decoder::<T>(descr, encoding);
match err {
diff --git a/parquet/src/encodings/decoding/byte_stream_split_decoder.rs b/parquet/src/encodings/decoding/byte_stream_split_decoder.rs
new file mode 100644
index 000000000000..98841d21ec9e
--- /dev/null
+++ b/parquet/src/encodings/decoding/byte_stream_split_decoder.rs
@@ -0,0 +1,121 @@
+// 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.
+
+use std::marker::PhantomData;
+
+use bytes::Bytes;
+
+use crate::basic::Encoding;
+use crate::data_type::{DataType, SliceAsBytes};
+use crate::errors::{ParquetError, Result};
+
+use super::Decoder;
+
+pub struct ByteStreamSplitDecoder<T: DataType> {
+ _phantom: PhantomData<T>,
+ encoded_bytes: Bytes,
+ total_num_values: usize,
+ values_decoded: usize,
+}
+
+impl<T: DataType> ByteStreamSplitDecoder<T> {
+ pub(crate) fn new() -> Self {
+ Self {
+ _phantom: PhantomData,
+ encoded_bytes: Bytes::new(),
+ total_num_values: 0,
+ values_decoded: 0,
+ }
+ }
+}
+
+// Here we assume src contains the full data (which it must, since we're
+// can only know where to split the streams once all data is collected),
+// but dst can be just a slice starting from the given index.
+// We iterate over the output bytes and fill them in from their strided
+// input byte locations.
+fn join_streams_const<const TYPE_SIZE: usize>(
+ src: &[u8],
+ dst: &mut [u8],
+ stride: usize,
+ values_decoded: usize,
+) {
+ let sub_src = &src[values_decoded..];
+ for i in 0..dst.len() / TYPE_SIZE {
+ for j in 0..TYPE_SIZE {
+ dst[i * TYPE_SIZE + j] = sub_src[i + j * stride];
+ }
+ }
+}
+
+impl<T: DataType> Decoder<T> for ByteStreamSplitDecoder<T> {
+ fn set_data(&mut self, data: Bytes, num_values: usize) -> Result<()> {
+ self.encoded_bytes = data;
+ self.total_num_values = num_values;
+ self.values_decoded = 0;
+
+ Ok(())
+ }
+
+ fn get(&mut self, buffer: &mut [<T as DataType>::T]) -> Result<usize> {
+ let total_remaining_values = self.values_left();
+ let num_values = buffer.len().min(total_remaining_values);
+ let buffer = &mut buffer[..num_values];
+
+ // SAFETY: f32 and f64 has no constraints on their internal representation, so we can modify it as we want
+ let raw_out_bytes = unsafe { <T as DataType>::T::slice_as_bytes_mut(buffer) };
+ let type_size = T::get_type_size();
+ let stride = self.encoded_bytes.len() / type_size;
+ match type_size {
+ 4 => join_streams_const::<4>(
+ &self.encoded_bytes,
+ raw_out_bytes,
+ stride,
+ self.values_decoded,
+ ),
+ 8 => join_streams_const::<8>(
+ &self.encoded_bytes,
+ raw_out_bytes,
+ stride,
+ self.values_decoded,
+ ),
+ _ => {
+ return Err(general_err!(
+ "byte stream split unsupported for data types of size {} bytes",
+ type_size
+ ));
+ }
+ }
+ self.values_decoded += num_values;
+
+ Ok(num_values)
+ }
+
+ fn values_left(&self) -> usize {
+ self.total_num_values - self.values_decoded
+ }
+
+ fn encoding(&self) -> Encoding {
+ Encoding::BYTE_STREAM_SPLIT
+ }
+
+ fn skip(&mut self, num_values: usize) -> Result<usize> {
+ let to_skip = usize::min(self.values_left(), num_values);
+ self.values_decoded += to_skip;
+ Ok(to_skip)
+ }
+}
diff --git a/parquet/src/encodings/encoding/byte_stream_split_encoder.rs b/parquet/src/encodings/encoding/byte_stream_split_encoder.rs
new file mode 100644
index 000000000000..a95487041cee
--- /dev/null
+++ b/parquet/src/encodings/encoding/byte_stream_split_encoder.rs
@@ -0,0 +1,93 @@
+// 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.
+
+use crate::basic::{Encoding, Type};
+use crate::data_type::DataType;
+use crate::data_type::SliceAsBytes;
+
+use crate::errors::{ParquetError, Result};
+
+use super::Encoder;
+
+use bytes::Bytes;
+use std::marker::PhantomData;
+
+pub struct ByteStreamSplitEncoder<T> {
+ buffer: Vec<u8>,
+ _p: PhantomData<T>,
+}
+
+impl<T: DataType> ByteStreamSplitEncoder<T> {
+ pub(crate) fn new() -> Self {
+ Self {
+ buffer: Vec::new(),
+ _p: PhantomData,
+ }
+ }
+}
+
+// Here we assume src contains the full data (which it must, since we're
+// can only know where to split the streams once all data is collected).
+// We iterate over the input bytes and write them to their strided output
+// byte locations.
+fn split_streams_const<const TYPE_SIZE: usize>(src: &[u8], dst: &mut [u8]) {
+ let stride = src.len() / TYPE_SIZE;
+ for i in 0..stride {
+ for j in 0..TYPE_SIZE {
+ dst[i + j * stride] = src[i * TYPE_SIZE + j];
+ }
+ }
+}
+
+impl<T: DataType> Encoder<T> for ByteStreamSplitEncoder<T> {
+ fn put(&mut self, values: &[T::T]) -> Result<()> {
+ self.buffer
+ .extend(<T as DataType>::T::slice_as_bytes(values));
+ ensure_phys_ty!(
+ Type::FLOAT | Type::DOUBLE,
+ "ByteStreamSplitEncoder only supports FloatType or DoubleType"
+ );
+
+ Ok(())
+ }
+
+ fn encoding(&self) -> Encoding {
+ Encoding::BYTE_STREAM_SPLIT
+ }
+
+ fn estimated_data_encoded_size(&self) -> usize {
+ self.buffer.len()
+ }
+
+ fn flush_buffer(&mut self) -> Result<Bytes> {
+ let mut encoded = vec![0; self.buffer.len()];
+ let type_size = T::get_type_size();
+ match type_size {
+ 4 => split_streams_const::<4>(&self.buffer, &mut encoded),
+ 8 => split_streams_const::<8>(&self.buffer, &mut encoded),
+ _ => {
+ return Err(general_err!(
+ "byte stream split unsupported for data types of size {} bytes",
+ type_size
+ ));
+ }
+ }
+
+ self.buffer.clear();
+ Ok(encoded.into())
+ }
+}
diff --git a/parquet/src/encodings/encoding/mod.rs b/parquet/src/encodings/encoding/mod.rs
index 89e61ee226ad..ef49f03e2f4a 100644
--- a/parquet/src/encodings/encoding/mod.rs
+++ b/parquet/src/encodings/encoding/mod.rs
@@ -29,6 +29,7 @@ use crate::util::bit_util::{self, num_required_bits, BitWriter};
use bytes::Bytes;
pub use dict_encoder::DictEncoder;
+mod byte_stream_split_encoder;
mod dict_encoder;
// ----------------------------------------------------------------------
@@ -85,6 +86,9 @@ pub fn get_encoder<T: DataType>(encoding: Encoding) -> Result<Box<dyn Encoder<T>
Encoding::DELTA_BINARY_PACKED => Box::new(DeltaBitPackEncoder::new()),
Encoding::DELTA_LENGTH_BYTE_ARRAY => Box::new(DeltaLengthByteArrayEncoder::new()),
Encoding::DELTA_BYTE_ARRAY => Box::new(DeltaByteArrayEncoder::new()),
+ Encoding::BYTE_STREAM_SPLIT => {
+ Box::new(byte_stream_split_encoder::ByteStreamSplitEncoder::new())
+ }
e => return Err(nyi_err!("Encoding {} is not supported", e)),
};
Ok(encoder)
@@ -376,19 +380,17 @@ impl<T: DataType> DeltaBitPackEncoder<T> {
// Compute the max delta in current mini block
let mut max_delta = i64::MIN;
for j in 0..n {
- max_delta =
- cmp::max(max_delta, self.deltas[i * self.mini_block_size + j]);
+ max_delta = cmp::max(max_delta, self.deltas[i * self.mini_block_size + j]);
}
// Compute bit width to store (max_delta - min_delta)
- let bit_width =
- num_required_bits(self.subtract_u64(max_delta, min_delta)) as usize;
+ let bit_width = num_required_bits(self.subtract_u64(max_delta, min_delta)) as usize;
self.bit_writer.write_at(offset + i, bit_width as u8);
// Encode values in current mini block using min_delta and bit_width
for j in 0..n {
- let packed_value = self
- .subtract_u64(self.deltas[i * self.mini_block_size + j], min_delta);
+ let packed_value =
+ self.subtract_u64(self.deltas[i * self.mini_block_size + j], min_delta);
self.bit_writer.put_value(packed_value, bit_width);
}
@@ -572,8 +574,7 @@ impl<T: DataType> Encoder<T> for DeltaLengthByteArrayEncoder<T> {
.map(|x| x.as_any().downcast_ref::<ByteArray>().unwrap())
};
- let lengths: Vec<i32> =
- val_it().map(|byte_array| byte_array.len() as i32).collect();
+ let lengths: Vec<i32> = val_it().map(|byte_array| byte_array.len() as i32).collect();
self.len_encoder.put(&lengths)?;
for byte_array in val_it() {
self.encoded_size += byte_array.len();
@@ -649,14 +650,15 @@ impl<T: DataType> Encoder<T> for DeltaByteArrayEncoder<T> {
let mut prefix_lengths: Vec<i32> = vec![];
let mut suffixes: Vec<ByteArray> = vec![];
- let values = values.iter()
+ let values = values
+ .iter()
.map(|x| x.as_any())
.map(|x| match T::get_physical_type() {
Type::BYTE_ARRAY => x.downcast_ref::<ByteArray>().unwrap(),
Type::FIXED_LEN_BYTE_ARRAY => x.downcast_ref::<FixedLenByteArray>().unwrap(),
_ => panic!(
"DeltaByteArrayEncoder only supports ByteArrayType and FixedLenByteArrayType"
- )
+ ),
});
for byte_array in values {
@@ -665,8 +667,7 @@ impl<T: DataType> Encoder<T> for DeltaByteArrayEncoder<T> {
// value
let prefix_len = cmp::min(self.previous.len(), current.len());
let mut match_len = 0;
- while match_len < prefix_len && self.previous[match_len] == current[match_len]
- {
+ while match_len < prefix_len && self.previous[match_len] == current[match_len] {
match_len += 1;
}
prefix_lengths.push(match_len as i32);
@@ -724,9 +725,7 @@ mod tests {
use std::sync::Arc;
use crate::encodings::decoding::{get_decoder, Decoder, DictDecoder, PlainDecoder};
- use crate::schema::types::{
- ColumnDescPtr, ColumnDescriptor, ColumnPath, Type as SchemaType,
- };
+ use crate::schema::types::{ColumnDescPtr, ColumnDescriptor, ColumnPath, Type as SchemaType};
use crate::util::test_common::rand_gen::{random_bytes, RandGen};
const TEST_SET_SIZE: usize = 1024;
@@ -792,12 +791,14 @@ mod tests {
fn test_float() {
FloatType::test(Encoding::PLAIN, TEST_SET_SIZE, -1);
FloatType::test(Encoding::PLAIN_DICTIONARY, TEST_SET_SIZE, -1);
+ FloatType::test(Encoding::BYTE_STREAM_SPLIT, TEST_SET_SIZE, -1);
}
#[test]
fn test_double() {
DoubleType::test(Encoding::PLAIN, TEST_SET_SIZE, -1);
DoubleType::test(Encoding::PLAIN_DICTIONARY, TEST_SET_SIZE, -1);
+ DoubleType::test(Encoding::BYTE_STREAM_SPLIT, TEST_SET_SIZE, -1);
}
#[test]
@@ -817,11 +818,7 @@ mod tests {
#[test]
fn test_dict_encoded_size() {
- fn run_test<T: DataType>(
- type_length: i32,
- values: &[T::T],
- expected_size: usize,
- ) {
+ fn run_test<T: DataType>(type_length: i32, values: &[T::T], expected_size: usize) {
let mut encoder = create_test_dict_encoder::<T>(type_length);
assert_eq!(encoder.dict_encoded_size(), 0);
encoder.put(values).unwrap();
@@ -843,11 +840,7 @@ mod tests {
&[Int96::from(vec![1, 2, 3]), Int96::from(vec![2, 3, 4])],
24,
);
- run_test::<ByteArrayType>(
- -1,
- &[ByteArray::from("abcd"), ByteArray::from("efj")],
- 15,
- );
+ run_test::<ByteArrayType>(-1, &[ByteArray::from("abcd"), ByteArray::from("efj")], 15);
run_test::<FixedLenByteArrayType>(
2,
&[ByteArray::from("ab").into(), ByteArray::from("bc").into()],
@@ -916,15 +909,45 @@ mod tests {
3, // only suffix bytes, length encoder is not flushed yet
0,
);
+
+ // BYTE_STREAM_SPLIT
+ run_test::<FloatType>(Encoding::BYTE_STREAM_SPLIT, -1, &[0.1, 0.2], 0, 8, 0);
+ }
+
+ #[test]
+ fn test_byte_stream_split_example_f32() {
+ // Test data from https://github.com/apache/parquet-format/blob/2a481fe1aad64ff770e21734533bb7ef5a057dac/Encodings.md#byte-stream-split-byte_stream_split--9
+ let mut encoder = create_test_encoder::<FloatType>(Encoding::BYTE_STREAM_SPLIT);
+ let mut decoder = create_test_decoder::<FloatType>(0, Encoding::BYTE_STREAM_SPLIT);
+
+ let input = vec![
+ f32::from_le_bytes([0xAA, 0xBB, 0xCC, 0xDD]),
+ f32::from_le_bytes([0x00, 0x11, 0x22, 0x33]),
+ f32::from_le_bytes([0xA3, 0xB4, 0xC5, 0xD6]),
+ ];
+
+ encoder.put(&input).unwrap();
+ let encoded = encoder.flush_buffer().unwrap();
+
+ assert_eq!(
+ encoded,
+ Bytes::from(vec![
+ 0xAA_u8, 0x00, 0xA3, 0xBB, 0x11, 0xB4, 0xCC, 0x22, 0xC5, 0xDD, 0x33, 0xD6
+ ])
+ );
+
+ let mut decoded = vec![0.0; input.len()];
+ decoder.set_data(encoded, input.len()).unwrap();
+ decoder.get(&mut decoded).unwrap();
+
+ assert_eq!(decoded, input);
}
// See: https://github.com/sunchao/parquet-rs/issues/47
#[test]
fn test_issue_47() {
- let mut encoder =
- create_test_encoder::<ByteArrayType>(Encoding::DELTA_BYTE_ARRAY);
- let mut decoder =
- create_test_decoder::<ByteArrayType>(0, Encoding::DELTA_BYTE_ARRAY);
+ let mut encoder = create_test_encoder::<ByteArrayType>(Encoding::DELTA_BYTE_ARRAY);
+ let mut decoder = create_test_decoder::<ByteArrayType>(0, Encoding::DELTA_BYTE_ARRAY);
let input = vec![
ByteArray::from("aa"),
@@ -935,8 +958,7 @@ mod tests {
let mut output = vec![ByteArray::default(); input.len()];
- let mut result =
- put_and_get(&mut encoder, &mut decoder, &input[..2], &mut output[..2]);
+ let mut result = put_and_get(&mut encoder, &mut decoder, &input[..2], &mut output[..2]);
assert!(
result.is_ok(),
"first put_and_get() failed with: {}",
@@ -1072,10 +1094,7 @@ mod tests {
decoder.get(output)
}
- fn create_and_check_encoder<T: DataType>(
- encoding: Encoding,
- err: Option<ParquetError>,
- ) {
+ fn create_and_check_encoder<T: DataType>(encoding: Encoding, err: Option<ParquetError>) {
let encoder = get_encoder::<T>(encoding);
match err {
Some(parquet_error) => {
@@ -1106,10 +1125,7 @@ mod tests {
get_encoder(enc).unwrap()
}
- fn create_test_decoder<T: DataType>(
- type_len: i32,
- enc: Encoding,
- ) -> Box<dyn Decoder<T>> {
+ fn create_test_decoder<T: DataType>(type_len: i32, enc: Encoding) -> Box<dyn Decoder<T>> {
let desc = create_test_col_desc_ptr(type_len, T::get_physical_type());
get_decoder(desc, enc).unwrap()
}
|
diff --git a/parquet-testing b/parquet-testing
index 89b685a64c31..4cb3cff24c96 160000
--- a/parquet-testing
+++ b/parquet-testing
@@ -1,1 +1,1 @@
-Subproject commit 89b685a64c3117b3023d8684af1f41400841db71
+Subproject commit 4cb3cff24c965fb329cdae763eabce47395a68a0
|
Parquet: Support `Encoding::BYTE_STREAM_SPLIT`
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
I would like to evaluate whether using the `BYTE_STREAM_SPLIT` encoding helps a Float64 column compress better. But it seems like it is not supported yet: https://github.com/apache/arrow-rs/blob/93484a10d145617434432d610e241640a06b382f/parquet/src/encodings/encoding/mod.rs#L90
**Describe the solution you'd like**
An implementation of the encoding. Even a naive, non-optimized version would resolve this issue. The implementation can be improved iteratively.
**Describe alternatives you've considered**
`PyArrow` seems to support it, but I would really like to stay within the Rust world.
**Additional context**
- Parquet format description here: https://github.com/apache/parquet-format/blob/master/Encodings.md#byte-stream-split-byte_stream_split--9
- The scalar impl in the C++ library is here: https://github.com/apache/arrow/blob/0bf777a5952be012e41f5b1ad443d4fec38e6f5a/cpp/src/arrow/util/byte_stream_split.h#L579-L602 . They also have SIMD variations, which will be more involved to port.
|
I'll give it a go myself, if possible.
|
2024-01-10T02:39:07Z
|
50.0
|
82fc0df73ab97e239ce5c748a05c57ce582f3d5d
|
apache/arrow-rs
| 5,222
|
apache__arrow-rs-5222
|
[
"4611"
] |
a9470d3eb083303350fc109f94865666fd0f062f
|
diff --git a/object_store/src/azure/client.rs b/object_store/src/azure/client.rs
index 3c71e69da00c..a30dfe8935be 100644
--- a/object_store/src/azure/client.rs
+++ b/object_store/src/azure/client.rs
@@ -25,7 +25,7 @@ use crate::client::retry::RetryExt;
use crate::client::GetOptionsExt;
use crate::multipart::PartId;
use crate::path::DELIMITER;
-use crate::util::deserialize_rfc1123;
+use crate::util::{deserialize_rfc1123, GetRange};
use crate::{
ClientOptions, GetOptions, ListResult, ObjectMeta, Path, PutMode, PutOptions, PutResult,
Result, RetryConfig,
@@ -356,6 +356,14 @@ impl GetClient for AzureClient {
/// <https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob>
/// <https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-properties>
async fn get_request(&self, path: &Path, options: GetOptions) -> Result<Response> {
+ // As of 2024-01-02, Azure does not support suffix requests,
+ // so we should fail fast here rather than sending one
+ if let Some(GetRange::Suffix(_)) = options.range.as_ref() {
+ return Err(crate::Error::NotSupported {
+ source: "Azure does not support suffix range requests".into(),
+ });
+ }
+
let credential = self.get_credential().await?;
let url = self.config.path_url(path);
let method = match options.head {
diff --git a/object_store/src/client/get.rs b/object_store/src/client/get.rs
index b7e7f24b29c2..2e399e523ed4 100644
--- a/object_store/src/client/get.rs
+++ b/object_store/src/client/get.rs
@@ -19,7 +19,7 @@ use std::ops::Range;
use crate::client::header::{header_meta, HeaderConfig};
use crate::path::Path;
-use crate::{Error, GetOptions, GetResult, GetResultPayload, Result};
+use crate::{GetOptions, GetRange, GetResult, GetResultPayload, Result};
use async_trait::async_trait;
use futures::{StreamExt, TryStreamExt};
use hyper::header::CONTENT_RANGE;
@@ -49,6 +49,12 @@ pub trait GetClientExt {
impl<T: GetClient> GetClientExt for T {
async fn get_opts(&self, location: &Path, options: GetOptions) -> Result<GetResult> {
let range = options.range.clone();
+ if let Some(r) = range.as_ref() {
+ r.is_valid().map_err(|e| crate::Error::Generic {
+ store: T::STORE,
+ source: Box::new(e),
+ })?;
+ }
let response = self.get_request(location, options).await?;
get_result::<T>(location, range, response).map_err(|e| crate::Error::Generic {
store: T::STORE,
@@ -94,6 +100,11 @@ enum GetResultError {
source: crate::client::header::Error,
},
+ #[snafu(context(false))]
+ InvalidRangeRequest {
+ source: crate::util::InvalidGetRange,
+ },
+
#[snafu(display("Received non-partial response when range requested"))]
NotPartial,
@@ -115,7 +126,7 @@ enum GetResultError {
fn get_result<T: GetClient>(
location: &Path,
- range: Option<Range<usize>>,
+ range: Option<GetRange>,
response: Response,
) -> Result<GetResult, GetResultError> {
let mut meta = header_meta(location, response.headers(), T::HEADER_CONFIG)?;
@@ -135,13 +146,16 @@ fn get_result<T: GetClient>(
let value = ContentRange::from_str(value).context(ParseContentRangeSnafu { value })?;
let actual = value.range;
+ // Update size to reflect full size of object (#5272)
+ meta.size = value.size;
+
+ let expected = expected.as_range(meta.size)?;
+
ensure!(
actual == expected,
UnexpectedRangeSnafu { expected, actual }
);
- // Update size to reflect full size of object (#5272)
- meta.size = value.size;
actual
} else {
0..meta.size
@@ -149,7 +163,7 @@ fn get_result<T: GetClient>(
let stream = response
.bytes_stream()
- .map_err(|source| Error::Generic {
+ .map_err(|source| crate::Error::Generic {
store: T::STORE,
source: Box::new(source),
})
@@ -220,20 +234,22 @@ mod tests {
let bytes = res.bytes().await.unwrap();
assert_eq!(bytes.len(), 12);
+ let get_range = GetRange::from(2..3);
+
let resp = make_response(
12,
Some(2..3),
StatusCode::PARTIAL_CONTENT,
Some("bytes 2-2/12"),
);
- let res = get_result::<TestClient>(&path, Some(2..3), resp).unwrap();
+ let res = get_result::<TestClient>(&path, Some(get_range.clone()), resp).unwrap();
assert_eq!(res.meta.size, 12);
assert_eq!(res.range, 2..3);
let bytes = res.bytes().await.unwrap();
assert_eq!(bytes.len(), 1);
let resp = make_response(12, Some(2..3), StatusCode::OK, None);
- let err = get_result::<TestClient>(&path, Some(2..3), resp).unwrap_err();
+ let err = get_result::<TestClient>(&path, Some(get_range.clone()), resp).unwrap_err();
assert_eq!(
err.to_string(),
"Received non-partial response when range requested"
@@ -245,7 +261,7 @@ mod tests {
StatusCode::PARTIAL_CONTENT,
Some("bytes 2-3/12"),
);
- let err = get_result::<TestClient>(&path, Some(2..3), resp).unwrap_err();
+ let err = get_result::<TestClient>(&path, Some(get_range.clone()), resp).unwrap_err();
assert_eq!(err.to_string(), "Requested 2..3, got 2..4");
let resp = make_response(
@@ -254,17 +270,50 @@ mod tests {
StatusCode::PARTIAL_CONTENT,
Some("bytes 2-2/*"),
);
- let err = get_result::<TestClient>(&path, Some(2..3), resp).unwrap_err();
+ let err = get_result::<TestClient>(&path, Some(get_range.clone()), resp).unwrap_err();
assert_eq!(
err.to_string(),
"Failed to parse value for CONTENT_RANGE header: \"bytes 2-2/*\""
);
let resp = make_response(12, Some(2..3), StatusCode::PARTIAL_CONTENT, None);
- let err = get_result::<TestClient>(&path, Some(2..3), resp).unwrap_err();
+ let err = get_result::<TestClient>(&path, Some(get_range.clone()), resp).unwrap_err();
assert_eq!(
err.to_string(),
"Content-Range header not present in partial response"
);
+
+ let resp = make_response(
+ 2,
+ Some(2..3),
+ StatusCode::PARTIAL_CONTENT,
+ Some("bytes 2-3/2"),
+ );
+ let err = get_result::<TestClient>(&path, Some(get_range.clone()), resp).unwrap_err();
+ assert_eq!(
+ err.to_string(),
+ "InvalidRangeRequest: Wanted range starting at 2, but object was only 2 bytes long"
+ );
+
+ let resp = make_response(
+ 6,
+ Some(2..6),
+ StatusCode::PARTIAL_CONTENT,
+ Some("bytes 2-5/6"),
+ );
+ let res = get_result::<TestClient>(&path, Some(GetRange::Suffix(4)), resp).unwrap();
+ assert_eq!(res.meta.size, 6);
+ assert_eq!(res.range, 2..6);
+ let bytes = res.bytes().await.unwrap();
+ assert_eq!(bytes.len(), 4);
+
+ let resp = make_response(
+ 6,
+ Some(2..6),
+ StatusCode::PARTIAL_CONTENT,
+ Some("bytes 2-3/6"),
+ );
+ let err = get_result::<TestClient>(&path, Some(GetRange::Suffix(4)), resp).unwrap_err();
+ assert_eq!(err.to_string(), "Requested 2..6, got 2..4");
}
}
diff --git a/object_store/src/client/mod.rs b/object_store/src/client/mod.rs
index 2baf586127c6..4a78927d0988 100644
--- a/object_store/src/client/mod.rs
+++ b/object_store/src/client/mod.rs
@@ -594,8 +594,7 @@ impl GetOptionsExt for RequestBuilder {
use hyper::header::*;
if let Some(range) = options.range {
- let range = format!("bytes={}-{}", range.start, range.end.saturating_sub(1));
- self = self.header(RANGE, range);
+ self = self.header(RANGE, range.to_string());
}
if let Some(tag) = options.if_match {
diff --git a/object_store/src/lib.rs b/object_store/src/lib.rs
index b438254bdd01..2e1e70dc19e3 100644
--- a/object_store/src/lib.rs
+++ b/object_store/src/lib.rs
@@ -499,6 +499,7 @@ mod parse;
mod util;
pub use parse::{parse_url, parse_url_opts};
+pub use util::GetRange;
use crate::path::Path;
#[cfg(not(target_arch = "wasm32"))]
@@ -580,10 +581,12 @@ pub trait ObjectStore: std::fmt::Display + Send + Sync + Debug + 'static {
async fn get_opts(&self, location: &Path, options: GetOptions) -> Result<GetResult>;
/// Return the bytes that are stored at the specified location
- /// in the given byte range
+ /// in the given byte range.
+ ///
+ /// See [`GetRange::Bounded`] for more details on how `range` gets interpreted
async fn get_range(&self, location: &Path, range: Range<usize>) -> Result<Bytes> {
let options = GetOptions {
- range: Some(range.clone()),
+ range: Some(range.into()),
..Default::default()
};
self.get_opts(location, options).await?.bytes().await
@@ -913,7 +916,7 @@ pub struct GetOptions {
/// otherwise returning [`Error::NotModified`]
///
/// <https://datatracker.ietf.org/doc/html/rfc9110#name-range>
- pub range: Option<Range<usize>>,
+ pub range: Option<GetRange>,
/// Request a particular object version
pub version: Option<String>,
/// Request transfer of no content
@@ -1307,7 +1310,7 @@ mod tests {
assert_eq!(bytes, expected_data.slice(range.clone()));
let opts = GetOptions {
- range: Some(2..5),
+ range: Some(GetRange::Bounded(2..5)),
..Default::default()
};
let result = storage.get_opts(&location, opts).await.unwrap();
@@ -1323,6 +1326,62 @@ mod tests {
// Should be a non-fatal error
out_of_range_result.unwrap_err();
+ let opts = GetOptions {
+ range: Some(GetRange::Bounded(2..100)),
+ ..Default::default()
+ };
+ let result = storage.get_opts(&location, opts).await.unwrap();
+ assert_eq!(result.range, 2..14);
+ assert_eq!(result.meta.size, 14);
+ let bytes = result.bytes().await.unwrap();
+ assert_eq!(bytes, b"bitrary data".as_ref());
+
+ let opts = GetOptions {
+ range: Some(GetRange::Suffix(2)),
+ ..Default::default()
+ };
+ match storage.get_opts(&location, opts).await {
+ Ok(result) => {
+ assert_eq!(result.range, 12..14);
+ assert_eq!(result.meta.size, 14);
+ let bytes = result.bytes().await.unwrap();
+ assert_eq!(bytes, b"ta".as_ref());
+ }
+ Err(Error::NotSupported { .. }) => {}
+ Err(e) => panic!("{e}"),
+ }
+
+ let opts = GetOptions {
+ range: Some(GetRange::Suffix(100)),
+ ..Default::default()
+ };
+ match storage.get_opts(&location, opts).await {
+ Ok(result) => {
+ assert_eq!(result.range, 0..14);
+ assert_eq!(result.meta.size, 14);
+ let bytes = result.bytes().await.unwrap();
+ assert_eq!(bytes, b"arbitrary data".as_ref());
+ }
+ Err(Error::NotSupported { .. }) => {}
+ Err(e) => panic!("{e}"),
+ }
+
+ let opts = GetOptions {
+ range: Some(GetRange::Offset(3)),
+ ..Default::default()
+ };
+ let result = storage.get_opts(&location, opts).await.unwrap();
+ assert_eq!(result.range, 3..14);
+ assert_eq!(result.meta.size, 14);
+ let bytes = result.bytes().await.unwrap();
+ assert_eq!(bytes, b"itrary data".as_ref());
+
+ let opts = GetOptions {
+ range: Some(GetRange::Offset(100)),
+ ..Default::default()
+ };
+ storage.get_opts(&location, opts).await.unwrap_err();
+
let ranges = vec![0..1, 2..3, 0..5];
let bytes = storage.get_ranges(&location, &ranges).await.unwrap();
for (range, bytes) in ranges.iter().zip(bytes) {
diff --git a/object_store/src/local.rs b/object_store/src/local.rs
index 71b96f058c79..e985ff070cd4 100644
--- a/object_store/src/local.rs
+++ b/object_store/src/local.rs
@@ -19,6 +19,7 @@
use crate::{
maybe_spawn_blocking,
path::{absolute_path_to_url, Path},
+ util::InvalidGetRange,
GetOptions, GetResult, GetResultPayload, ListResult, MultipartId, ObjectMeta, ObjectStore,
PutMode, PutOptions, PutResult, Result,
};
@@ -111,6 +112,11 @@ pub(crate) enum Error {
actual: usize,
},
+ #[snafu(display("Requested range was invalid"))]
+ InvalidRange {
+ source: InvalidGetRange,
+ },
+
#[snafu(display("Unable to copy file from {} to {}: {}", from.display(), to.display(), source))]
UnableToCopyFile {
from: PathBuf,
@@ -424,9 +430,14 @@ impl ObjectStore for LocalFileSystem {
let meta = convert_metadata(metadata, location)?;
options.check_preconditions(&meta)?;
+ let range = match options.range {
+ Some(r) => r.as_range(meta.size).context(InvalidRangeSnafu)?,
+ None => 0..meta.size,
+ };
+
Ok(GetResult {
payload: GetResultPayload::File(file, path),
- range: options.range.unwrap_or(0..meta.size),
+ range,
meta,
})
})
diff --git a/object_store/src/memory.rs b/object_store/src/memory.rs
index 382300123846..41cfcc490da6 100644
--- a/object_store/src/memory.rs
+++ b/object_store/src/memory.rs
@@ -16,9 +16,10 @@
// under the License.
//! An in-memory object store implementation
+use crate::util::InvalidGetRange;
use crate::{
- path::Path, GetResult, GetResultPayload, ListResult, ObjectMeta, ObjectStore, PutMode,
- PutOptions, PutResult, Result, UpdateVersion,
+ path::Path, GetRange, GetResult, GetResultPayload, ListResult, ObjectMeta, ObjectStore,
+ PutMode, PutOptions, PutResult, Result, UpdateVersion,
};
use crate::{GetOptions, MultipartId};
use async_trait::async_trait;
@@ -26,7 +27,7 @@ use bytes::Bytes;
use chrono::{DateTime, Utc};
use futures::{stream::BoxStream, StreamExt};
use parking_lot::RwLock;
-use snafu::{ensure, OptionExt, Snafu};
+use snafu::{OptionExt, ResultExt, Snafu};
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::io;
@@ -43,13 +44,8 @@ enum Error {
#[snafu(display("No data in memory found. Location: {path}"))]
NoDataInMemory { path: String },
- #[snafu(display(
- "Requested range {}..{} is out of bounds for object with length {}", range.start, range.end, len
- ))]
- OutOfRange { range: Range<usize>, len: usize },
-
- #[snafu(display("Invalid range: {}..{}", range.start, range.end))]
- BadRange { range: Range<usize> },
+ #[snafu(display("Invalid range: {source}"))]
+ Range { source: InvalidGetRange },
#[snafu(display("Object already exists at that location: {path}"))]
AlreadyExists { path: String },
@@ -220,10 +216,8 @@ impl ObjectStore for InMemory {
let (range, data) = match options.range {
Some(range) => {
- let len = entry.data.len();
- ensure!(range.end <= len, OutOfRangeSnafu { range, len });
- ensure!(range.start <= range.end, BadRangeSnafu { range });
- (range.clone(), entry.data.slice(range))
+ let r = range.as_range(entry.data.len()).context(RangeSnafu)?;
+ (r.clone(), entry.data.slice(r))
}
None => (0..entry.data.len(), entry.data),
};
@@ -241,14 +235,11 @@ impl ObjectStore for InMemory {
ranges
.iter()
.map(|range| {
- let range = range.clone();
- let len = entry.data.len();
- ensure!(
- range.end <= entry.data.len(),
- OutOfRangeSnafu { range, len }
- );
- ensure!(range.start <= range.end, BadRangeSnafu { range });
- Ok(entry.data.slice(range))
+ let r = GetRange::Bounded(range.clone())
+ .as_range(entry.data.len())
+ .context(RangeSnafu)?;
+
+ Ok(entry.data.slice(r))
})
.collect()
}
diff --git a/object_store/src/util.rs b/object_store/src/util.rs
index fd86ba7366b0..a19d5aab4b5b 100644
--- a/object_store/src/util.rs
+++ b/object_store/src/util.rs
@@ -16,9 +16,15 @@
// under the License.
//! Common logic for interacting with remote object stores
+use std::{
+ fmt::Display,
+ ops::{Range, RangeBounds},
+};
+
use super::Result;
use bytes::Bytes;
use futures::{stream::StreamExt, Stream, TryStreamExt};
+use snafu::Snafu;
#[cfg(any(feature = "azure", feature = "http"))]
pub static RFC1123_FMT: &str = "%a, %d %h %Y %T GMT";
@@ -98,12 +104,12 @@ pub const OBJECT_STORE_COALESCE_PARALLEL: usize = 10;
/// * Make multiple `fetch` requests in parallel (up to maximum of 10)
///
pub async fn coalesce_ranges<F, E, Fut>(
- ranges: &[std::ops::Range<usize>],
+ ranges: &[Range<usize>],
fetch: F,
coalesce: usize,
) -> Result<Vec<Bytes>, E>
where
- F: Send + FnMut(std::ops::Range<usize>) -> Fut,
+ F: Send + FnMut(Range<usize>) -> Fut,
E: Send,
Fut: std::future::Future<Output = Result<Bytes, E>> + Send,
{
@@ -124,13 +130,13 @@ where
let start = range.start - fetch_range.start;
let end = range.end - fetch_range.start;
- fetch_bytes.slice(start..end)
+ fetch_bytes.slice(start..end.min(fetch_bytes.len()))
})
.collect())
}
/// Returns a sorted list of ranges that cover `ranges`
-fn merge_ranges(ranges: &[std::ops::Range<usize>], coalesce: usize) -> Vec<std::ops::Range<usize>> {
+fn merge_ranges(ranges: &[Range<usize>], coalesce: usize) -> Vec<Range<usize>> {
if ranges.is_empty() {
return vec![];
}
@@ -167,6 +173,119 @@ fn merge_ranges(ranges: &[std::ops::Range<usize>], coalesce: usize) -> Vec<std::
ret
}
+/// Request only a portion of an object's bytes
+///
+/// These can be created from [usize] ranges, like
+///
+/// ```rust
+/// # use object_store::GetRange;
+/// let range1: GetRange = (50..150).into();
+/// let range2: GetRange = (50..=150).into();
+/// let range3: GetRange = (50..).into();
+/// let range4: GetRange = (..150).into();
+/// ```
+///
+/// Implementations may wish to inspect [`GetResult`] for the exact byte
+/// range returned.
+///
+/// [`GetResult`]: crate::GetResult
+#[derive(Debug, PartialEq, Eq, Clone)]
+pub enum GetRange {
+ /// Request a specific range of bytes
+ ///
+ /// If the given range is zero-length or starts after the end of the object,
+ /// an error will be returned. Additionally, if the range ends after the end
+ /// of the object, the entire remainder of the object will be returned.
+ /// Otherwise, the exact requested range will be returned.
+ Bounded(Range<usize>),
+ /// Request all bytes starting from a given byte offset
+ Offset(usize),
+ /// Request up to the last n bytes
+ Suffix(usize),
+}
+
+#[derive(Debug, Snafu)]
+pub(crate) enum InvalidGetRange {
+ #[snafu(display(
+ "Wanted range starting at {requested}, but object was only {length} bytes long"
+ ))]
+ StartTooLarge { requested: usize, length: usize },
+
+ #[snafu(display("Range started at {start} and ended at {end}"))]
+ Inconsistent { start: usize, end: usize },
+}
+
+impl GetRange {
+ pub(crate) fn is_valid(&self) -> Result<(), InvalidGetRange> {
+ match self {
+ Self::Bounded(r) if r.end <= r.start => {
+ return Err(InvalidGetRange::Inconsistent {
+ start: r.start,
+ end: r.end,
+ });
+ }
+ _ => (),
+ };
+ Ok(())
+ }
+
+ /// Convert to a [`Range`] if valid.
+ pub(crate) fn as_range(&self, len: usize) -> Result<Range<usize>, InvalidGetRange> {
+ self.is_valid()?;
+ match self {
+ Self::Bounded(r) => {
+ if r.start >= len {
+ Err(InvalidGetRange::StartTooLarge {
+ requested: r.start,
+ length: len,
+ })
+ } else if r.end > len {
+ Ok(r.start..len)
+ } else {
+ Ok(r.clone())
+ }
+ }
+ Self::Offset(o) => {
+ if *o >= len {
+ Err(InvalidGetRange::StartTooLarge {
+ requested: *o,
+ length: len,
+ })
+ } else {
+ Ok(*o..len)
+ }
+ }
+ Self::Suffix(n) => Ok(len.saturating_sub(*n)..len),
+ }
+ }
+}
+
+impl Display for GetRange {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::Bounded(r) => write!(f, "bytes={}-{}", r.start, r.end - 1),
+ Self::Offset(o) => write!(f, "bytes={o}-"),
+ Self::Suffix(n) => write!(f, "bytes=-{n}"),
+ }
+ }
+}
+
+impl<T: RangeBounds<usize>> From<T> for GetRange {
+ fn from(value: T) -> Self {
+ use std::ops::Bound::*;
+ let first = match value.start_bound() {
+ Included(i) => *i,
+ Excluded(i) => i + 1,
+ Unbounded => 0,
+ };
+ match value.end_bound() {
+ Included(i) => Self::Bounded(first..(i + 1)),
+ Excluded(i) => Self::Bounded(first..*i),
+ Unbounded => Self::Offset(first),
+ }
+ }
+}
+
#[cfg(test)]
mod tests {
use crate::Error;
@@ -269,4 +388,59 @@ mod tests {
}
}
}
+
+ #[test]
+ fn getrange_str() {
+ assert_eq!(GetRange::Offset(0).to_string(), "bytes=0-");
+ assert_eq!(GetRange::Bounded(10..19).to_string(), "bytes=10-18");
+ assert_eq!(GetRange::Suffix(10).to_string(), "bytes=-10");
+ }
+
+ #[test]
+ fn getrange_from() {
+ assert_eq!(Into::<GetRange>::into(10..15), GetRange::Bounded(10..15),);
+ assert_eq!(Into::<GetRange>::into(10..=15), GetRange::Bounded(10..16),);
+ assert_eq!(Into::<GetRange>::into(10..), GetRange::Offset(10),);
+ assert_eq!(Into::<GetRange>::into(..=15), GetRange::Bounded(0..16));
+ }
+
+ #[test]
+ fn test_as_range() {
+ let range = GetRange::Bounded(2..5);
+ assert_eq!(range.as_range(5).unwrap(), 2..5);
+
+ let range = range.as_range(4).unwrap();
+ assert_eq!(range, 2..4);
+
+ let range = GetRange::Bounded(3..3);
+ let err = range.as_range(2).unwrap_err().to_string();
+ assert_eq!(err, "Range started at 3 and ended at 3");
+
+ let range = GetRange::Bounded(2..2);
+ let err = range.as_range(3).unwrap_err().to_string();
+ assert_eq!(err, "Range started at 2 and ended at 2");
+
+ let range = GetRange::Suffix(3);
+ assert_eq!(range.as_range(3).unwrap(), 0..3);
+ assert_eq!(range.as_range(2).unwrap(), 0..2);
+
+ let range = GetRange::Suffix(0);
+ assert_eq!(range.as_range(0).unwrap(), 0..0);
+
+ let range = GetRange::Offset(2);
+ let err = range.as_range(2).unwrap_err().to_string();
+ assert_eq!(
+ err,
+ "Wanted range starting at 2, but object was only 2 bytes long"
+ );
+
+ let err = range.as_range(1).unwrap_err().to_string();
+ assert_eq!(
+ err,
+ "Wanted range starting at 2, but object was only 1 bytes long"
+ );
+
+ let range = GetRange::Offset(1);
+ assert_eq!(range.as_range(2).unwrap(), 1..2);
+ }
}
|
diff --git a/object_store/tests/get_range_file.rs b/object_store/tests/get_range_file.rs
index 85231a5a5b9b..f73d78578f08 100644
--- a/object_store/tests/get_range_file.rs
+++ b/object_store/tests/get_range_file.rs
@@ -93,4 +93,29 @@ async fn test_get_range() {
let data = store.get_range(&path, range.clone()).await.unwrap();
assert_eq!(&data[..], &expected[range])
}
+
+ let over_range = 0..(expected.len() * 2);
+ let data = store.get_range(&path, over_range.clone()).await.unwrap();
+ assert_eq!(&data[..], expected)
+}
+
+/// Test that, when a requesting a range which overhangs the end of the resource,
+/// the resulting [GetResult::range] reports the returned range,
+/// not the requested.
+#[tokio::test]
+async fn test_get_opts_over_range() {
+ let tmp = tempdir().unwrap();
+ let store = MyStore(LocalFileSystem::new_with_prefix(tmp.path()).unwrap());
+ let path = Path::from("foo");
+
+ let expected = Bytes::from_static(b"hello world");
+ store.put(&path, expected.clone()).await.unwrap();
+
+ let opts = GetOptions {
+ range: Some(GetRange::Bounded(0..(expected.len() * 2))),
+ ..Default::default()
+ };
+ let res = store.get_opts(&path, opts).await.unwrap();
+ assert_eq!(res.range, 0..expected.len());
+ assert_eq!(res.bytes().await.unwrap(), expected);
}
|
object_store: range request with suffix
We need to read the last `n` bytes of a file whose size we do not know. This is supported by HTTP range requests, and access to local files (via `Seek`), can `object_store` support it?
`object_store::GetOptions::range` could take, instead of a `core::ops::Range`, something like this: https://github.com/clbarnes/byteranges-rs/blob/0a953e7c580e96b65fe28e61ed460d6e221dcd8d/src/request.rs#L6-L51 . So long as `From<RangeBounds>` is supported this may not have to break any existing code.
The alternative is a HEAD request to find the length and then a range request using the offset from 0, which is twice the round trips.
|
I seem to remember GCS being the only cloud store that supports this, but I could be mistaken. Have you done any research into this?
The S3 docs say they support the Range header, and specifically states that they don't support `multipart/byteranges` responses, but doesn't specifically say they don't support suffixes https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html#API_GetObject_RequestSyntax
Have you tested this, I seem to remember it did not but my memory is hazy
Suffix range requests are supported by all major cloud providers. Here is an example against S3 (proxied via Cloudfront):
```bash
curl -H 'Range: bytes=-524292' https://static.webknossos.org/data/zarr_v3/l4_sample/color/1/c/0/3/3/1 | wc -c
```
I would be happy to review a PR making this change. The use of `From<RangeBounds>` is clever and I like it, although I suspect many use-cases have hard-coded `Range<usize>` which will then require modification to support this.
> Suffix range requests are supported by all major cloud providers
Good to know, I'm not sure where I got the impression otherwise. Ultimately it isn't a massive problem if they don't support them, we just report this as an error to the user.
> we just report this as an error to the user.
Sounds like users might consider that a problem :grin:
Well yes, but if the store itself doesn't support them there isn't really all that much we can do :smile:
It would appear that Azure Blob Storage does not support suffix range headers, although it does support prefix range headers
https://learn.microsoft.com/en-us/rest/api/storageservices/specifying-the-range-header-for-blob-service-operations
I think I'm closing in on an implementation here. Allowing suffixes could mean that some bytes are fetched twice but I don't think that's too much of a problem, as it's on the user to have knowledge of the resource they're looking into. I've been using `HttpRange` as the type name (and in all the functions which use it) - would be nice to have something more terse but it's the best description I think, even for stores which aren't HTTP-backed.
I think that replacing references to `Range<usize>` in the API with `T: Into<HttpRange> + Copy` should make for a seamless upgrade path, but the `range` field on the `GetOptions` struct would need to be deprecated and a different field of type `HttpRange` (called `http_range`?), probably raising an error if both are defined.
What we do with suffixes on azure is another question - probably just a `log_once::warn_once!()` when a suffix is requested, and then a HEAD request to find the length and regular range request.
> In the API with T: Into<HttpRange> + Copy
This would still be a breaking API change, something I am rather hesitant about. It would also not be object safe, which is likely more problematic.
Did you see, it would appear at least one of the major cloud providers do not support this, and I would not be surprised if there are other implementations that do not - https://github.com/apache/arrow-rs/issues/4611#issuecomment-1674965990
> This would still be a breaking API change, something I am rather hesitant about. It would also not be object safe, which is likely more problematic.
Understood. If we added `get_http_range` and `get_http_ranges`, deprecated `get_range` and `get_ranges` and then provided a default impl which used the new methods under the hood (and marked them as deprecated), then 3rd party implementations would need to update but only in an additive way, new implementations wouldn't need to implement the limited methods, and people could continue to use their existing code. In this case it would definitely be nice to use a name more terse than `http_range`, though!
The difficult bit would be getting 3rd party implementations to implement `get` in a way which respects the new `GetOptions::http_range` field. Marking `range` as deprecated would at least give visibility to developers but it could easily be ignored.
> Did you see, it would appear at least one of the major cloud providers do not support this
Yes, tried to address that in my comment above. Sometimes people need the suffix, and on azure, the best those people can do is HEAD and GET range, but logging it so that users can change their access pattern if necessary is probably the right thing to do.
> The difficult bit would be getting 3rd party implementations to implement get in a way which respects the new GetOptions::http_range field. Marking range as deprecated would at least give visibility to developers but it could easily be ignored.
Actually, just noticed we control this too - it's just a case of updating `GetOptionsExt`. We'd need to decide what to do if someone sent *both* a `range` and an `http_range` in their `GetOptions`; choosing the `http_range` and logging a warning is probably best, if not panicking as it's purely a user error that they should be getting a clear deprecation warning about.
Perhaps you could expand upon why you do not know the sizes of the files, I would have expected the files to have been identified by either a catalog or a listing call, both of which could provide this information?
I dunno, generally the approach of this crate is to encourage people towards patterns that behave equally well across all backends, as opposed to ones that will have store-specific performance pitfalls.
Perhaps I am just trying to avoid another breaking API change as they end up taking up an inordinate amount of my and others time, something I am somewhat struggling to justify here...
> it's just a case of updating GetOptionsExt
`GetOptionsExt` is crate private
> Perhaps you could expand upon why you do not know the sizes of the files
I mentioned our use case in another issue; copied below
> As part of the [zarr](https://zarr-specs.readthedocs.io/en/latest/v3/core/v3.0.html) project, we plan to store large tensors on a variety of backends (local/ HTTP/ object store), which are chunked into many separate files/ objects. As part of the [sharding](https://zarr-specs.readthedocs.io/en/latest/v3/codecs/sharding-indexed/v1.0.html) specification, each chunk (=shard) could contain many sub-chunks which are independently encoded and then concatenated. We'd want to read a footer to find the byte addresses of sub-chunks (see https://github.com/apache/arrow-rs/issues/4611 ), and then read (possibly multiple) byte ranges from the shard.
We don't want to list all existing chunks ahead of time as there could easily be many millions, and this could even change under our feet if we're writing the tensor as we go. As chunks may be compressed with arbitrary codecs, we can't predict how many bytes they'll be even if we know how large the chunks are; we just need to read the footer (which indexes sub-chunks) so that we then know which bits of the object to read.
I suppose in this use case we never need to read the suffix at the same time as the rest of the chunk, so we could have a separate method for suffix-getting with a default implementation of using a HEAD then GET which is documented as possibly being slow.
> I dunno, generally the approach of this crate is to encourage people towards patterns that behave equally well across all backends, as opposed to ones that will have store-specific performance pitfalls.
Patterns, yes, but I hope we've demonstrated that sometimes people actually need a suffix. All stores can do it (with 2 requests), some stores can just do it better (with 1) - should we refuse to use optimisations which are only available to certain stores? If people already know the length (from listing or whatever), then they don't need to use the method documented as being possibly slow.
> GetOptionsExt is crate private
Ah, yes, that's unfortunate. So 3rd party stores currently just wrangle their own options?
I think the minimal-impact course is to keep everything as it is and just add something like
```rust
pub trait ObjectStore: std::fmt::Display + Send + Sync + Debug + 'static {
...
/// Get the last `nbytes` of an object.
///
/// If the object size is not known, the default implementation first finds out with a HEAD request.
/// Stores which support suffix requests directly should override this behaviour.
async fn get_suffix(&self, location: &Path, nbytes: usize, object_size: Option<usize>) -> Result<GetResult> {
// if size is None, find out with a head request
// then do self.get_range
}
}
```
Instantly works for everyone, the performance concerns are well-documented, there's an ergonomic path for people who need a suffix and already know the size, and an easy optimisation path for stores which do support it.
|
2023-12-18T15:18:36Z
|
49.0
|
a9470d3eb083303350fc109f94865666fd0f062f
|
apache/arrow-rs
| 5,184
|
apache__arrow-rs-5184
|
[
"5185"
] |
b06ab13fa2681624c7d5094004309607b253773b
|
diff --git a/.github/workflows/arrow.yml b/.github/workflows/arrow.yml
index da56c23b5cd9..d3b2526740fa 100644
--- a/.github/workflows/arrow.yml
+++ b/.github/workflows/arrow.yml
@@ -67,8 +67,8 @@ jobs:
run: cargo test -p arrow-data --all-features
- name: Test arrow-schema with all features
run: cargo test -p arrow-schema --all-features
- - name: Test arrow-array with all features except SIMD
- run: cargo test -p arrow-array
+ - name: Test arrow-array with all features
+ run: cargo test -p arrow-array --all-features
- name: Test arrow-select with all features
run: cargo test -p arrow-select --all-features
- name: Test arrow-cast with all features
@@ -85,15 +85,15 @@ jobs:
run: cargo test -p arrow-string --all-features
- name: Test arrow-ord with all features
run: cargo test -p arrow-ord --all-features
- - name: Test arrow-arith with all features except SIMD
- run: cargo test -p arrow-arith
+ - name: Test arrow-arith with all features
+ run: cargo test -p arrow-arith --all-features
- name: Test arrow-row with all features
run: cargo test -p arrow-row --all-features
- name: Test arrow-integration-test with all features
run: cargo test -p arrow-integration-test --all-features
- name: Test arrow with default features
run: cargo test -p arrow
- - name: Test arrow with all features apart from simd
+ - name: Test arrow with all features except pyarrow
run: cargo test -p arrow --features=force_validate,prettyprint,ipc_compression,ffi,chrono-tz
- name: Run examples
run: |
@@ -132,29 +132,6 @@ jobs:
- name: Check compilation --no-default-features --all-targets --features chrono-tz
run: cargo check -p arrow --no-default-features --all-targets --features chrono-tz
- # test the --features "simd" of the arrow crate. This requires nightly Rust.
- linux-test-simd:
- name: Test SIMD on AMD64 Rust ${{ matrix.rust }}
- runs-on: ubuntu-latest
- container:
- image: amd64/rust
- steps:
- - uses: actions/checkout@v4
- with:
- submodules: true
- - name: Setup Rust toolchain
- uses: ./.github/actions/setup-builder
- with:
- rust-version: nightly
- - name: Test arrow-array with SIMD
- run: cargo test -p arrow-array --features simd
- - name: Test arrow-arith with SIMD
- run: cargo test -p arrow-arith --features simd
- - name: Test arrow with SIMD
- run: cargo test -p arrow --features simd
- - name: Check compilation --features simd --all-targets
- run: cargo check -p arrow --features simd --all-targets
-
# test the arrow crate builds against wasm32 in nightly rust
wasm32-build:
@@ -169,12 +146,11 @@ jobs:
- name: Setup Rust toolchain
uses: ./.github/actions/setup-builder
with:
- rust-version: nightly
target: wasm32-unknown-unknown,wasm32-wasi
- name: Build wasm32-unknown-unknown
- run: cargo build -p arrow --no-default-features --features=json,csv,ipc,simd,ffi --target wasm32-unknown-unknown
+ run: cargo build -p arrow --no-default-features --features=json,csv,ipc,ffi --target wasm32-unknown-unknown
- name: Build wasm32-wasi
- run: cargo build -p arrow --no-default-features --features=json,csv,ipc,simd,ffi --target wasm32-wasi
+ run: cargo build -p arrow --no-default-features --features=json,csv,ipc,ffi --target wasm32-wasi
clippy:
name: Clippy
@@ -193,8 +169,8 @@ jobs:
run: cargo clippy -p arrow-data --all-targets --all-features -- -D warnings
- name: Clippy arrow-schema with all features
run: cargo clippy -p arrow-schema --all-targets --all-features -- -D warnings
- - name: Clippy arrow-array with all features except SIMD
- run: cargo clippy -p arrow-array --all-targets -- -D warnings
+ - name: Clippy arrow-array with all features
+ run: cargo clippy -p arrow-array --all-targets --all-features -- -D warnings
- name: Clippy arrow-select with all features
run: cargo clippy -p arrow-select --all-targets --all-features -- -D warnings
- name: Clippy arrow-cast with all features
@@ -211,12 +187,12 @@ jobs:
run: cargo clippy -p arrow-string --all-targets --all-features -- -D warnings
- name: Clippy arrow-ord with all features
run: cargo clippy -p arrow-ord --all-targets --all-features -- -D warnings
- - name: Clippy arrow-arith with all features except SIMD
- run: cargo clippy -p arrow-arith --all-targets -- -D warnings
+ - name: Clippy arrow-arith with all features
+ run: cargo clippy -p arrow-arith --all-targets --all-features -- -D warnings
- name: Clippy arrow-row with all features
run: cargo clippy -p arrow-row --all-targets --all-features -- -D warnings
- - name: Clippy arrow with all features except SIMD
- run: cargo clippy -p arrow --features=prettyprint,csv,ipc,test_utils,ffi,ipc_compression,chrono-tz --all-targets -- -D warnings
+ - name: Clippy arrow with all features
+ run: cargo clippy -p arrow --all-features --all-targets -- -D warnings
- name: Clippy arrow-integration-test with all features
run: cargo clippy -p arrow-integration-test --all-targets --all-features -- -D warnings
- name: Clippy arrow-integration-testing with all features
diff --git a/.github/workflows/miri.sh b/.github/workflows/miri.sh
index ec8712660c74..5057c876b952 100755
--- a/.github/workflows/miri.sh
+++ b/.github/workflows/miri.sh
@@ -14,5 +14,5 @@ cargo miri test -p arrow-buffer
cargo miri test -p arrow-data --features ffi
cargo miri test -p arrow-schema --features ffi
cargo miri test -p arrow-array
-cargo miri test -p arrow-arith --features simd
+cargo miri test -p arrow-arith
cargo miri test -p arrow-ord
diff --git a/arrow-arith/Cargo.toml b/arrow-arith/Cargo.toml
index 57dc033e9645..d2ee0b9e2c72 100644
--- a/arrow-arith/Cargo.toml
+++ b/arrow-arith/Cargo.toml
@@ -43,6 +43,3 @@ half = { version = "2.1", default-features = false }
num = { version = "0.4", default-features = false, features = ["std"] }
[dev-dependencies]
-
-[features]
-simd = ["arrow-array/simd"]
diff --git a/arrow-array/Cargo.toml b/arrow-array/Cargo.toml
index 4f7ab24f9708..04eec8df6379 100644
--- a/arrow-array/Cargo.toml
+++ b/arrow-array/Cargo.toml
@@ -49,10 +49,6 @@ chrono-tz = { version = "0.8", optional = true }
num = { version = "0.4.1", default-features = false, features = ["std"] }
half = { version = "2.1", default-features = false, features = ["num-traits"] }
hashbrown = { version = "0.14", default-features = false }
-packed_simd = { version = "0.3.9", default-features = false, optional = true }
-
-[features]
-simd = ["packed_simd"]
[dev-dependencies]
rand = { version = "0.8", default-features = false, features = ["std", "std_rng"] }
diff --git a/arrow-array/src/numeric.rs b/arrow-array/src/numeric.rs
index b5e474ba696a..a3cd7bde5d36 100644
--- a/arrow-array/src/numeric.rs
+++ b/arrow-array/src/numeric.rs
@@ -15,621 +15,9 @@
// specific language governing permissions and limitations
// under the License.
-use crate::types::*;
use crate::ArrowPrimitiveType;
-#[cfg(feature = "simd")]
-use packed_simd::*;
-#[cfg(feature = "simd")]
-use std::ops::{Add, BitAnd, BitAndAssign, BitOr, BitOrAssign, Div, Mul, Not, Rem, Sub};
/// A subtype of primitive type that represents numeric values.
-///
-/// SIMD operations are defined in this trait if available on the target system.
-#[cfg(feature = "simd")]
-pub trait ArrowNumericType: ArrowPrimitiveType
-where
- Self::Simd: Add<Output = Self::Simd>
- + Sub<Output = Self::Simd>
- + Mul<Output = Self::Simd>
- + Div<Output = Self::Simd>
- + Rem<Output = Self::Simd>
- + Copy,
- Self::SimdMask: BitAnd<Output = Self::SimdMask>
- + BitOr<Output = Self::SimdMask>
- + BitAndAssign
- + BitOrAssign
- + Not<Output = Self::SimdMask>
- + Copy,
-{
- /// Defines the SIMD type that should be used for this numeric type
- type Simd;
-
- /// Defines the SIMD Mask type that should be used for this numeric type
- type SimdMask;
-
- /// The number of SIMD lanes available
- fn lanes() -> usize;
-
- /// Initializes a SIMD register to a constant value
- fn init(value: Self::Native) -> Self::Simd;
-
- /// Loads a slice into a SIMD register
- fn load(slice: &[Self::Native]) -> Self::Simd;
-
- /// Creates a new SIMD mask for this SIMD type filling it with `value`
- fn mask_init(value: bool) -> Self::SimdMask;
-
- /// Creates a new SIMD mask for this SIMD type from the lower-most bits of the given `mask`.
- /// The number of bits used corresponds to the number of lanes of this type
- fn mask_from_u64(mask: u64) -> Self::SimdMask;
-
- /// Creates a bitmask from the given SIMD mask.
- /// Each bit corresponds to one vector lane, starting with the least-significant bit.
- fn mask_to_u64(mask: &Self::SimdMask) -> u64;
-
- /// Gets the value of a single lane in a SIMD mask
- fn mask_get(mask: &Self::SimdMask, idx: usize) -> bool;
-
- /// Sets the value of a single lane of a SIMD mask
- fn mask_set(mask: Self::SimdMask, idx: usize, value: bool) -> Self::SimdMask;
-
- /// Selects elements of `a` and `b` using `mask`
- fn mask_select(mask: Self::SimdMask, a: Self::Simd, b: Self::Simd) -> Self::Simd;
-
- /// Returns `true` if any of the lanes in the mask are `true`
- fn mask_any(mask: Self::SimdMask) -> bool;
-
- /// Performs a SIMD binary operation
- fn bin_op<F: Fn(Self::Simd, Self::Simd) -> Self::Simd>(
- left: Self::Simd,
- right: Self::Simd,
- op: F,
- ) -> Self::Simd;
-
- /// SIMD version of equal
- fn eq(left: Self::Simd, right: Self::Simd) -> Self::SimdMask;
-
- /// SIMD version of not equal
- fn ne(left: Self::Simd, right: Self::Simd) -> Self::SimdMask;
-
- /// SIMD version of less than
- fn lt(left: Self::Simd, right: Self::Simd) -> Self::SimdMask;
-
- /// SIMD version of less than or equal to
- fn le(left: Self::Simd, right: Self::Simd) -> Self::SimdMask;
-
- /// SIMD version of greater than
- fn gt(left: Self::Simd, right: Self::Simd) -> Self::SimdMask;
-
- /// SIMD version of greater than or equal to
- fn ge(left: Self::Simd, right: Self::Simd) -> Self::SimdMask;
-
- /// Writes a SIMD result back to a slice
- fn write(simd_result: Self::Simd, slice: &mut [Self::Native]);
-
- /// Performs a SIMD unary operation
- fn unary_op<F: Fn(Self::Simd) -> Self::Simd>(a: Self::Simd, op: F) -> Self::Simd;
-}
-
-/// A subtype of primitive type that represents numeric values.
-#[cfg(not(feature = "simd"))]
pub trait ArrowNumericType: ArrowPrimitiveType {}
-macro_rules! make_numeric_type {
- ($impl_ty:ty, $native_ty:ty, $simd_ty:ident, $simd_mask_ty:ident) => {
- #[cfg(feature = "simd")]
- impl ArrowNumericType for $impl_ty {
- type Simd = $simd_ty;
-
- type SimdMask = $simd_mask_ty;
-
- #[inline]
- fn lanes() -> usize {
- Self::Simd::lanes()
- }
-
- #[inline]
- fn init(value: Self::Native) -> Self::Simd {
- Self::Simd::splat(value)
- }
-
- #[inline]
- fn load(slice: &[Self::Native]) -> Self::Simd {
- unsafe { Self::Simd::from_slice_unaligned_unchecked(slice) }
- }
-
- #[inline]
- fn mask_init(value: bool) -> Self::SimdMask {
- Self::SimdMask::splat(value)
- }
-
- #[inline]
- fn mask_from_u64(mask: u64) -> Self::SimdMask {
- // this match will get removed by the compiler since the number of lanes is known at
- // compile-time for each concrete numeric type
- match Self::lanes() {
- 4 => {
- // the bit position in each lane indicates the index of that lane
- let vecidx = i128x4::new(1, 2, 4, 8);
-
- // broadcast the lowermost 8 bits of mask to each lane
- let vecmask = i128x4::splat((mask & 0x0F) as i128);
- // compute whether the bit corresponding to each lanes index is set
- let vecmask = (vecidx & vecmask).eq(vecidx);
-
- // transmute is necessary because the different match arms return different
- // mask types, at runtime only one of those expressions will exist per type,
- // with the type being equal to `SimdMask`.
- unsafe { std::mem::transmute(vecmask) }
- }
- 8 => {
- // the bit position in each lane indicates the index of that lane
- let vecidx = i64x8::new(1, 2, 4, 8, 16, 32, 64, 128);
-
- // broadcast the lowermost 8 bits of mask to each lane
- let vecmask = i64x8::splat((mask & 0xFF) as i64);
- // compute whether the bit corresponding to each lanes index is set
- let vecmask = (vecidx & vecmask).eq(vecidx);
-
- // transmute is necessary because the different match arms return different
- // mask types, at runtime only one of those expressions will exist per type,
- // with the type being equal to `SimdMask`.
- unsafe { std::mem::transmute(vecmask) }
- }
- 16 => {
- // same general logic as for 8 lanes, extended to 16 bits
- let vecidx = i32x16::new(
- 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384,
- 32768,
- );
-
- let vecmask = i32x16::splat((mask & 0xFFFF) as i32);
- let vecmask = (vecidx & vecmask).eq(vecidx);
-
- unsafe { std::mem::transmute(vecmask) }
- }
- 32 => {
- // compute two separate m32x16 vector masks from from the lower-most 32 bits of `mask`
- // and then combine them into one m16x32 vector mask by writing and reading a temporary
- let tmp = &mut [0_i16; 32];
-
- let vecidx = i32x16::new(
- 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384,
- 32768,
- );
-
- let vecmask = i32x16::splat((mask & 0xFFFF) as i32);
- let vecmask = (vecidx & vecmask).eq(vecidx);
-
- i16x16::from_cast(vecmask).write_to_slice_unaligned(&mut tmp[0..16]);
-
- let vecmask = i32x16::splat(((mask >> 16) & 0xFFFF) as i32);
- let vecmask = (vecidx & vecmask).eq(vecidx);
-
- i16x16::from_cast(vecmask).write_to_slice_unaligned(&mut tmp[16..32]);
-
- unsafe { std::mem::transmute(i16x32::from_slice_unaligned(tmp)) }
- }
- 64 => {
- // compute four m32x16 vector masks from from all 64 bits of `mask`
- // and convert them into one m8x64 vector mask by writing and reading a temporary
- let tmp = &mut [0_i8; 64];
-
- let vecidx = i32x16::new(
- 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384,
- 32768,
- );
-
- let vecmask = i32x16::splat((mask & 0xFFFF) as i32);
- let vecmask = (vecidx & vecmask).eq(vecidx);
-
- i8x16::from_cast(vecmask).write_to_slice_unaligned(&mut tmp[0..16]);
-
- let vecmask = i32x16::splat(((mask >> 16) & 0xFFFF) as i32);
- let vecmask = (vecidx & vecmask).eq(vecidx);
-
- i8x16::from_cast(vecmask).write_to_slice_unaligned(&mut tmp[16..32]);
-
- let vecmask = i32x16::splat(((mask >> 32) & 0xFFFF) as i32);
- let vecmask = (vecidx & vecmask).eq(vecidx);
-
- i8x16::from_cast(vecmask).write_to_slice_unaligned(&mut tmp[32..48]);
-
- let vecmask = i32x16::splat(((mask >> 48) & 0xFFFF) as i32);
- let vecmask = (vecidx & vecmask).eq(vecidx);
-
- i8x16::from_cast(vecmask).write_to_slice_unaligned(&mut tmp[48..64]);
-
- unsafe { std::mem::transmute(i8x64::from_slice_unaligned(tmp)) }
- }
- _ => panic!("Invalid number of vector lanes"),
- }
- }
-
- #[inline]
- fn mask_to_u64(mask: &Self::SimdMask) -> u64 {
- mask.bitmask() as u64
- }
-
- #[inline]
- fn mask_get(mask: &Self::SimdMask, idx: usize) -> bool {
- unsafe { mask.extract_unchecked(idx) }
- }
-
- #[inline]
- fn mask_set(mask: Self::SimdMask, idx: usize, value: bool) -> Self::SimdMask {
- unsafe { mask.replace_unchecked(idx, value) }
- }
-
- /// Selects elements of `a` and `b` using `mask`
- #[inline]
- fn mask_select(mask: Self::SimdMask, a: Self::Simd, b: Self::Simd) -> Self::Simd {
- mask.select(a, b)
- }
-
- #[inline]
- fn mask_any(mask: Self::SimdMask) -> bool {
- mask.any()
- }
-
- #[inline]
- fn bin_op<F: Fn(Self::Simd, Self::Simd) -> Self::Simd>(
- left: Self::Simd,
- right: Self::Simd,
- op: F,
- ) -> Self::Simd {
- op(left, right)
- }
-
- #[inline]
- fn eq(left: Self::Simd, right: Self::Simd) -> Self::SimdMask {
- left.eq(right)
- }
-
- #[inline]
- fn ne(left: Self::Simd, right: Self::Simd) -> Self::SimdMask {
- left.ne(right)
- }
-
- #[inline]
- fn lt(left: Self::Simd, right: Self::Simd) -> Self::SimdMask {
- left.lt(right)
- }
-
- #[inline]
- fn le(left: Self::Simd, right: Self::Simd) -> Self::SimdMask {
- left.le(right)
- }
-
- #[inline]
- fn gt(left: Self::Simd, right: Self::Simd) -> Self::SimdMask {
- left.gt(right)
- }
-
- #[inline]
- fn ge(left: Self::Simd, right: Self::Simd) -> Self::SimdMask {
- left.ge(right)
- }
-
- #[inline]
- fn write(simd_result: Self::Simd, slice: &mut [Self::Native]) {
- unsafe { simd_result.write_to_slice_unaligned_unchecked(slice) };
- }
-
- #[inline]
- fn unary_op<F: Fn(Self::Simd) -> Self::Simd>(a: Self::Simd, op: F) -> Self::Simd {
- op(a)
- }
- }
-
- #[cfg(not(feature = "simd"))]
- impl ArrowNumericType for $impl_ty {}
- };
-}
-
-make_numeric_type!(Int8Type, i8, i8x64, m8x64);
-make_numeric_type!(Int16Type, i16, i16x32, m16x32);
-make_numeric_type!(Int32Type, i32, i32x16, m32x16);
-make_numeric_type!(Int64Type, i64, i64x8, m64x8);
-make_numeric_type!(UInt8Type, u8, u8x64, m8x64);
-make_numeric_type!(UInt16Type, u16, u16x32, m16x32);
-make_numeric_type!(UInt32Type, u32, u32x16, m32x16);
-make_numeric_type!(UInt64Type, u64, u64x8, m64x8);
-make_numeric_type!(Float32Type, f32, f32x16, m32x16);
-make_numeric_type!(Float64Type, f64, f64x8, m64x8);
-
-make_numeric_type!(TimestampSecondType, i64, i64x8, m64x8);
-make_numeric_type!(TimestampMillisecondType, i64, i64x8, m64x8);
-make_numeric_type!(TimestampMicrosecondType, i64, i64x8, m64x8);
-make_numeric_type!(TimestampNanosecondType, i64, i64x8, m64x8);
-make_numeric_type!(Date32Type, i32, i32x16, m32x16);
-make_numeric_type!(Date64Type, i64, i64x8, m64x8);
-make_numeric_type!(Time32SecondType, i32, i32x16, m32x16);
-make_numeric_type!(Time32MillisecondType, i32, i32x16, m32x16);
-make_numeric_type!(Time64MicrosecondType, i64, i64x8, m64x8);
-make_numeric_type!(Time64NanosecondType, i64, i64x8, m64x8);
-make_numeric_type!(IntervalYearMonthType, i32, i32x16, m32x16);
-make_numeric_type!(IntervalDayTimeType, i64, i64x8, m64x8);
-make_numeric_type!(IntervalMonthDayNanoType, i128, i128x4, m128x4);
-make_numeric_type!(DurationSecondType, i64, i64x8, m64x8);
-make_numeric_type!(DurationMillisecondType, i64, i64x8, m64x8);
-make_numeric_type!(DurationMicrosecondType, i64, i64x8, m64x8);
-make_numeric_type!(DurationNanosecondType, i64, i64x8, m64x8);
-make_numeric_type!(Decimal128Type, i128, i128x4, m128x4);
-
-#[cfg(not(feature = "simd"))]
-impl ArrowNumericType for Float16Type {}
-
-#[cfg(feature = "simd")]
-impl ArrowNumericType for Float16Type {
- type Simd = <Float32Type as ArrowNumericType>::Simd;
- type SimdMask = <Float32Type as ArrowNumericType>::SimdMask;
-
- fn lanes() -> usize {
- Float32Type::lanes()
- }
-
- fn init(value: Self::Native) -> Self::Simd {
- Float32Type::init(value.to_f32())
- }
-
- fn load(slice: &[Self::Native]) -> Self::Simd {
- let mut s = [0_f32; Self::Simd::lanes()];
- s.iter_mut().zip(slice).for_each(|(o, a)| *o = a.to_f32());
- Float32Type::load(&s)
- }
-
- fn mask_init(value: bool) -> Self::SimdMask {
- Float32Type::mask_init(value)
- }
-
- fn mask_from_u64(mask: u64) -> Self::SimdMask {
- Float32Type::mask_from_u64(mask)
- }
-
- fn mask_to_u64(mask: &Self::SimdMask) -> u64 {
- Float32Type::mask_to_u64(mask)
- }
-
- fn mask_get(mask: &Self::SimdMask, idx: usize) -> bool {
- Float32Type::mask_get(mask, idx)
- }
-
- fn mask_set(mask: Self::SimdMask, idx: usize, value: bool) -> Self::SimdMask {
- Float32Type::mask_set(mask, idx, value)
- }
-
- fn mask_select(mask: Self::SimdMask, a: Self::Simd, b: Self::Simd) -> Self::Simd {
- Float32Type::mask_select(mask, a, b)
- }
-
- fn mask_any(mask: Self::SimdMask) -> bool {
- Float32Type::mask_any(mask)
- }
-
- fn bin_op<F: Fn(Self::Simd, Self::Simd) -> Self::Simd>(
- left: Self::Simd,
- right: Self::Simd,
- op: F,
- ) -> Self::Simd {
- op(left, right)
- }
-
- fn eq(left: Self::Simd, right: Self::Simd) -> Self::SimdMask {
- Float32Type::eq(left, right)
- }
-
- fn ne(left: Self::Simd, right: Self::Simd) -> Self::SimdMask {
- Float32Type::ne(left, right)
- }
-
- fn lt(left: Self::Simd, right: Self::Simd) -> Self::SimdMask {
- Float32Type::lt(left, right)
- }
-
- fn le(left: Self::Simd, right: Self::Simd) -> Self::SimdMask {
- Float32Type::le(left, right)
- }
-
- fn gt(left: Self::Simd, right: Self::Simd) -> Self::SimdMask {
- Float32Type::gt(left, right)
- }
-
- fn ge(left: Self::Simd, right: Self::Simd) -> Self::SimdMask {
- Float32Type::ge(left, right)
- }
-
- fn write(simd_result: Self::Simd, slice: &mut [Self::Native]) {
- let mut s = [0_f32; Self::Simd::lanes()];
- Float32Type::write(simd_result, &mut s);
- slice
- .iter_mut()
- .zip(s)
- .for_each(|(o, i)| *o = half::f16::from_f32(i))
- }
-
- fn unary_op<F: Fn(Self::Simd) -> Self::Simd>(a: Self::Simd, op: F) -> Self::Simd {
- Float32Type::unary_op(a, op)
- }
-}
-
-#[cfg(not(feature = "simd"))]
-impl ArrowNumericType for Decimal256Type {}
-
-#[cfg(feature = "simd")]
-impl ArrowNumericType for Decimal256Type {
- type Simd = arrow_buffer::i256;
- type SimdMask = bool;
-
- fn lanes() -> usize {
- 1
- }
-
- fn init(value: Self::Native) -> Self::Simd {
- value
- }
-
- fn load(slice: &[Self::Native]) -> Self::Simd {
- slice[0]
- }
-
- fn mask_init(value: bool) -> Self::SimdMask {
- value
- }
-
- fn mask_from_u64(mask: u64) -> Self::SimdMask {
- mask != 0
- }
-
- fn mask_to_u64(mask: &Self::SimdMask) -> u64 {
- *mask as u64
- }
-
- fn mask_get(mask: &Self::SimdMask, _idx: usize) -> bool {
- *mask
- }
-
- fn mask_set(_mask: Self::SimdMask, _idx: usize, value: bool) -> Self::SimdMask {
- value
- }
-
- fn mask_select(mask: Self::SimdMask, a: Self::Simd, b: Self::Simd) -> Self::Simd {
- match mask {
- true => a,
- false => b,
- }
- }
-
- fn mask_any(mask: Self::SimdMask) -> bool {
- mask
- }
-
- fn bin_op<F: Fn(Self::Simd, Self::Simd) -> Self::Simd>(
- left: Self::Simd,
- right: Self::Simd,
- op: F,
- ) -> Self::Simd {
- op(left, right)
- }
-
- fn eq(left: Self::Simd, right: Self::Simd) -> Self::SimdMask {
- left.eq(&right)
- }
-
- fn ne(left: Self::Simd, right: Self::Simd) -> Self::SimdMask {
- left.ne(&right)
- }
-
- fn lt(left: Self::Simd, right: Self::Simd) -> Self::SimdMask {
- left.lt(&right)
- }
-
- fn le(left: Self::Simd, right: Self::Simd) -> Self::SimdMask {
- left.le(&right)
- }
-
- fn gt(left: Self::Simd, right: Self::Simd) -> Self::SimdMask {
- left.gt(&right)
- }
-
- fn ge(left: Self::Simd, right: Self::Simd) -> Self::SimdMask {
- left.ge(&right)
- }
-
- fn write(simd_result: Self::Simd, slice: &mut [Self::Native]) {
- slice[0] = simd_result
- }
-
- fn unary_op<F: Fn(Self::Simd) -> Self::Simd>(a: Self::Simd, op: F) -> Self::Simd {
- op(a)
- }
-}
-
-#[cfg(all(test, feature = "simd"))]
-mod tests {
- use super::*;
- use FromCast;
-
- /// calculate the expected mask by iterating over all bits
- macro_rules! expected_mask {
- ($T:ty, $MASK:expr) => {{
- let mask = $MASK;
- // simd width of all types is currently 64 bytes -> 512 bits
- let lanes = 64 / std::mem::size_of::<$T>();
- // translate each set bit into a value of all ones (-1) of the correct type
- (0..lanes)
- .map(|i| (if (mask & (1 << i)) != 0 { -1 } else { 0 }))
- .collect::<Vec<$T>>()
- }};
- }
-
- #[test]
- fn test_mask_i128() {
- let mask = 0b1101;
- let actual = IntervalMonthDayNanoType::mask_from_u64(mask);
- let expected = expected_mask!(i128, mask);
- let expected = m128x4::from_cast(i128x4::from_slice_unaligned(expected.as_slice()));
-
- assert_eq!(expected, actual);
- }
-
- #[test]
- fn test_mask_f64() {
- let mask = 0b10101010;
- let actual = Float64Type::mask_from_u64(mask);
- let expected = expected_mask!(i64, mask);
- let expected = m64x8::from_cast(i64x8::from_slice_unaligned(expected.as_slice()));
-
- assert_eq!(expected, actual);
- }
-
- #[test]
- fn test_mask_u64() {
- let mask = 0b01010101;
- let actual = Int64Type::mask_from_u64(mask);
- let expected = expected_mask!(i64, mask);
- let expected = m64x8::from_cast(i64x8::from_slice_unaligned(expected.as_slice()));
-
- assert_eq!(expected, actual);
- }
-
- #[test]
- fn test_mask_f32() {
- let mask = 0b10101010_10101010;
- let actual = Float32Type::mask_from_u64(mask);
- let expected = expected_mask!(i32, mask);
- let expected = m32x16::from_cast(i32x16::from_slice_unaligned(expected.as_slice()));
-
- assert_eq!(expected, actual);
- }
-
- #[test]
- fn test_mask_i32() {
- let mask = 0b01010101_01010101;
- let actual = Int32Type::mask_from_u64(mask);
- let expected = expected_mask!(i32, mask);
- let expected = m32x16::from_cast(i32x16::from_slice_unaligned(expected.as_slice()));
-
- assert_eq!(expected, actual);
- }
-
- #[test]
- fn test_mask_u16() {
- let mask = 0b01010101_01010101_10101010_10101010;
- let actual = UInt16Type::mask_from_u64(mask);
- let expected = expected_mask!(i16, mask);
- let expected = m16x32::from_cast(i16x32::from_slice_unaligned(expected.as_slice()));
-
- assert_eq!(expected, actual);
- }
-
- #[test]
- fn test_mask_i8() {
- let mask = 0b01010101_01010101_10101010_10101010_01010101_01010101_10101010_10101010;
- let actual = Int8Type::mask_from_u64(mask);
- let expected = expected_mask!(i8, mask);
- let expected = m8x64::from_cast(i8x64::from_slice_unaligned(expected.as_slice()));
-
- assert_eq!(expected, actual);
- }
-}
+impl<T: ArrowPrimitiveType> ArrowNumericType for T {}
diff --git a/arrow-buffer/src/util/bit_util.rs b/arrow-buffer/src/util/bit_util.rs
index b27931f4cc85..d2dbf3c84882 100644
--- a/arrow-buffer/src/util/bit_util.rs
+++ b/arrow-buffer/src/util/bit_util.rs
@@ -17,9 +17,6 @@
//! Utils for working with bits
-#[cfg(feature = "simd")]
-use packed_simd::u8x64;
-
const BIT_MASK: [u8; 8] = [1, 2, 4, 8, 16, 32, 64, 128];
const UNSET_BIT_MASK: [u8; 8] = [
255 - 1,
@@ -104,31 +101,13 @@ pub fn ceil(value: usize, divisor: usize) -> usize {
value / divisor + (0 != value % divisor) as usize
}
-/// Performs SIMD bitwise binary operations.
-///
-/// # Safety
-///
-/// Note that each slice should be 64 bytes and it is the callers responsibility to ensure
-/// that this is the case. If passed slices larger than 64 bytes the operation will only
-/// be performed on the first 64 bytes. Slices less than 64 bytes will panic.
-#[cfg(feature = "simd")]
-pub unsafe fn bitwise_bin_op_simd<F>(left: &[u8], right: &[u8], result: &mut [u8], op: F)
-where
- F: Fn(u8x64, u8x64) -> u8x64,
-{
- let left_simd = u8x64::from_slice_unaligned_unchecked(left);
- let right_simd = u8x64::from_slice_unaligned_unchecked(right);
- let simd_result = op(left_simd, right_simd);
- simd_result.write_to_slice_unaligned_unchecked(result);
-}
-
-#[cfg(all(test, feature = "test_utils"))]
+#[cfg(test)]
mod tests {
use std::collections::HashSet;
use super::*;
- use crate::util::test_util::seedable_rng;
- use rand::Rng;
+ use rand::rngs::StdRng;
+ use rand::{Rng, SeedableRng};
#[test]
fn test_round_upto_multiple_of_64() {
@@ -167,10 +146,14 @@ mod tests {
assert!(!get_bit(&[0b01001001, 0b01010010], 15));
}
+ pub fn seedable_rng() -> StdRng {
+ StdRng::seed_from_u64(42)
+ }
+
#[test]
fn test_get_bit_raw() {
const NUM_BYTE: usize = 10;
- let mut buf = vec![0; NUM_BYTE];
+ let mut buf = [0; NUM_BYTE];
let mut expected = vec![];
let mut rng = seedable_rng();
for i in 0..8 * NUM_BYTE {
@@ -278,7 +261,6 @@ mod tests {
}
#[test]
- #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn test_ceil() {
assert_eq!(ceil(0, 1), 0);
assert_eq!(ceil(1, 1), 1);
@@ -292,28 +274,4 @@ mod tests {
assert_eq!(ceil(10, 10000000000), 1);
assert_eq!(ceil(10000000000, 1000000000), 10);
}
-
- #[test]
- #[cfg(feature = "simd")]
- fn test_bitwise_and_simd() {
- let buf1 = [0b00110011u8; 64];
- let buf2 = [0b11110000u8; 64];
- let mut buf3 = [0b00000000; 64];
- unsafe { bitwise_bin_op_simd(&buf1, &buf2, &mut buf3, |a, b| a & b) };
- for i in buf3.iter() {
- assert_eq!(&0b00110000u8, i);
- }
- }
-
- #[test]
- #[cfg(feature = "simd")]
- fn test_bitwise_or_simd() {
- let buf1 = [0b00110011u8; 64];
- let buf2 = [0b11110000u8; 64];
- let mut buf3 = [0b00000000; 64];
- unsafe { bitwise_bin_op_simd(&buf1, &buf2, &mut buf3, |a, b| a | b) };
- for i in buf3.iter() {
- assert_eq!(&0b11110011u8, i);
- }
- }
}
diff --git a/arrow-ord/src/comparison.rs b/arrow-ord/src/comparison.rs
index 021ecdf0e658..4dbb395192e1 100644
--- a/arrow-ord/src/comparison.rs
+++ b/arrow-ord/src/comparison.rs
@@ -243,64 +243,6 @@ fn make_utf8_scalar(d: &DataType, scalar: &str) -> Result<ArrayRef, ArrowError>
}
}
-/// Helper function to perform boolean lambda function on values from two array accessors, this
-/// version does not attempt to use SIMD.
-fn compare_op<T: ArrayAccessor, S: ArrayAccessor, F>(
- left: T,
- right: S,
- op: F,
-) -> Result<BooleanArray, ArrowError>
-where
- F: Fn(T::Item, S::Item) -> bool,
-{
- if left.len() != right.len() {
- return Err(ArrowError::ComputeError(
- "Cannot perform comparison operation on arrays of different length".to_string(),
- ));
- }
-
- Ok(BooleanArray::from_binary(left, right, op))
-}
-
-/// Helper function to perform boolean lambda function on values from array accessor, this
-/// version does not attempt to use SIMD.
-fn compare_op_scalar<T: ArrayAccessor, F>(left: T, op: F) -> Result<BooleanArray, ArrowError>
-where
- F: Fn(T::Item) -> bool,
-{
- Ok(BooleanArray::from_unary(left, op))
-}
-
-/// Evaluate `op(left, right)` for [`PrimitiveArray`]s using a specified
-/// comparison function.
-#[deprecated(note = "Use BooleanArray::from_binary")]
-pub fn no_simd_compare_op<T, F>(
- left: &PrimitiveArray<T>,
- right: &PrimitiveArray<T>,
- op: F,
-) -> Result<BooleanArray, ArrowError>
-where
- T: ArrowPrimitiveType,
- F: Fn(T::Native, T::Native) -> bool,
-{
- compare_op(left, right, op)
-}
-
-/// Evaluate `op(left, right)` for [`PrimitiveArray`] and scalar using
-/// a specified comparison function.
-#[deprecated(note = "Use BooleanArray::from_unary")]
-pub fn no_simd_compare_op_scalar<T, F>(
- left: &PrimitiveArray<T>,
- right: T::Native,
- op: F,
-) -> Result<BooleanArray, ArrowError>
-where
- T: ArrowPrimitiveType,
- F: Fn(T::Native, T::Native) -> bool,
-{
- compare_op_scalar(left, |l| op(l, right))
-}
-
/// Perform `left == right` operation on [`StringArray`] / [`LargeStringArray`].
#[deprecated(note = "Use arrow_ord::cmp::eq")]
pub fn eq_utf8<OffsetSize: OffsetSizeTrait>(
@@ -610,7 +552,6 @@ pub fn gt_eq_utf8_scalar<OffsetSize: OffsetSizeTrait>(
/// Perform `left == right` operation on an array and a numeric scalar
/// value. Supports PrimitiveArrays, and DictionaryArrays that have primitive values.
///
-/// If `simd` feature flag is not enabled:
/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
/// Note that totalOrder treats positive and negative zeros are different. If it is necessary
@@ -628,7 +569,6 @@ where
/// Perform `left < right` operation on an array and a numeric scalar
/// value. Supports PrimitiveArrays, and DictionaryArrays that have primitive values.
///
-/// If `simd` feature flag is not enabled:
/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
/// Note that totalOrder treats positive and negative zeros are different. If it is necessary
@@ -646,7 +586,6 @@ where
/// Perform `left <= right` operation on an array and a numeric scalar
/// value. Supports PrimitiveArrays, and DictionaryArrays that have primitive values.
///
-/// If `simd` feature flag is not enabled:
/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
/// Note that totalOrder treats positive and negative zeros are different. If it is necessary
@@ -664,7 +603,6 @@ where
/// Perform `left > right` operation on an array and a numeric scalar
/// value. Supports PrimitiveArrays, and DictionaryArrays that have primitive values.
///
-/// If `simd` feature flag is not enabled:
/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
/// Note that totalOrder treats positive and negative zeros are different. If it is necessary
@@ -682,7 +620,6 @@ where
/// Perform `left >= right` operation on an array and a numeric scalar
/// value. Supports PrimitiveArrays, and DictionaryArrays that have primitive values.
///
-/// If `simd` feature flag is not enabled:
/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
/// Note that totalOrder treats positive and negative zeros are different. If it is necessary
@@ -700,7 +637,6 @@ where
/// Perform `left != right` operation on an array and a numeric scalar
/// value. Supports PrimitiveArrays, and DictionaryArrays that have primitive values.
///
-/// If `simd` feature flag is not enabled:
/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
/// Note that totalOrder treats positive and negative zeros are different. If it is necessary
@@ -1015,7 +951,6 @@ pub fn gt_eq_dyn(left: &dyn Array, right: &dyn Array) -> Result<BooleanArray, Ar
/// Perform `left == right` operation on two [`PrimitiveArray`]s.
///
-/// If `simd` feature flag is not enabled:
/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
/// Note that totalOrder treats positive and negative zeros are different. If it is necessary
@@ -1051,17 +986,17 @@ where
}
/// Applies an unary and infallible comparison function to a primitive array.
+#[deprecated(note = "Use BooleanArray::from_unary")]
pub fn unary_cmp<T, F>(left: &PrimitiveArray<T>, op: F) -> Result<BooleanArray, ArrowError>
where
T: ArrowNumericType,
F: Fn(T::Native) -> bool,
{
- compare_op_scalar(left, op)
+ Ok(BooleanArray::from_unary(left, op))
}
/// Perform `left != right` operation on two [`PrimitiveArray`]s.
///
-/// If `simd` feature flag is not enabled:
/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
/// Note that totalOrder treats positive and negative zeros are different. If it is necessary
@@ -1081,7 +1016,6 @@ where
/// Perform `left != right` operation on a [`PrimitiveArray`] and a scalar value.
///
-/// If `simd` feature flag is not enabled:
/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
/// Note that totalOrder treats positive and negative zeros are different. If it is necessary
@@ -1100,7 +1034,6 @@ where
/// Perform `left < right` operation on two [`PrimitiveArray`]s. Null values are less than non-null
/// values.
///
-/// If `simd` feature flag is not enabled:
/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
/// Note that totalOrder treats positive and negative zeros are different. If it is necessary
@@ -1121,7 +1054,6 @@ where
/// Perform `left < right` operation on a [`PrimitiveArray`] and a scalar value.
/// Null values are less than non-null values.
///
-/// If `simd` feature flag is not enabled:
/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
/// Note that totalOrder treats positive and negative zeros are different. If it is necessary
@@ -1140,7 +1072,6 @@ where
/// Perform `left <= right` operation on two [`PrimitiveArray`]s. Null values are less than non-null
/// values.
///
-/// If `simd` feature flag is not enabled:
/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
/// Note that totalOrder treats positive and negative zeros are different. If it is necessary
@@ -1161,7 +1092,6 @@ where
/// Perform `left <= right` operation on a [`PrimitiveArray`] and a scalar value.
/// Null values are less than non-null values.
///
-/// If `simd` feature flag is not enabled:
/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
/// Note that totalOrder treats positive and negative zeros are different. If it is necessary
@@ -1183,7 +1113,6 @@ where
/// Perform `left > right` operation on two [`PrimitiveArray`]s. Non-null values are greater than null
/// values.
///
-/// If `simd` feature flag is not enabled:
/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
/// Note that totalOrder treats positive and negative zeros are different. If it is necessary
@@ -1204,7 +1133,6 @@ where
/// Perform `left > right` operation on a [`PrimitiveArray`] and a scalar value.
/// Non-null values are greater than null values.
///
-/// If `simd` feature flag is not enabled:
/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
/// Note that totalOrder treats positive and negative zeros are different. If it is necessary
@@ -1223,7 +1151,6 @@ where
/// Perform `left >= right` operation on two [`PrimitiveArray`]s. Non-null values are greater than null
/// values.
///
-/// If `simd` feature flag is not enabled:
/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
/// Note that totalOrder treats positive and negative zeros are different. If it is necessary
@@ -1244,7 +1171,6 @@ where
/// Perform `left >= right` operation on a [`PrimitiveArray`] and a scalar value.
/// Non-null values are greater than null values.
///
-/// If `simd` feature flag is not enabled:
/// For floating values like f32 and f64, this comparison produces an ordering in accordance to
/// the totalOrder predicate as defined in the IEEE 754 (2008 revision) floating point standard.
/// Note that totalOrder treats positive and negative zeros are different. If it is necessary
diff --git a/arrow/CONTRIBUTING.md b/arrow/CONTRIBUTING.md
index 5b84bc2d3bdb..0c795d6b9cbd 100644
--- a/arrow/CONTRIBUTING.md
+++ b/arrow/CONTRIBUTING.md
@@ -67,18 +67,6 @@ the impossibility of the compiler to derive the invariants (such as lifetime, nu
The arrow format declares a IPC protocol, which this crate supports. IPC is equivalent to a FFI in that the rust compiler can't reason about the contract's invariants.
-#### SIMD
-
-The API provided by the [packed_simd_2](https://docs.rs/packed_simd_2/latest/packed_simd_2/) crate is currently `unsafe`. However,
-SIMD offers a significant performance improvement over non-SIMD operations. A related crate in development is
-[portable-simd](https://rust-lang.github.io/portable-simd/core_simd/) which has a nice
-[beginners guide](https://github.com/rust-lang/portable-simd/blob/master/beginners-guide.md). These crates provide the ability
-for code on x86 and ARM architectures to use some of the available parallel register operations. As an example if two arrays
-of numbers are added, [1,2,3,4] + [5,6,7,8], rather than using four instructions to add each of the elements of the arrays,
-one instruction can be used to all all four elements at the same time, which leads to improved time to solution. SIMD instructions
-are typically most effective when data is aligned to allow a single load instruction to bring multiple consecutive data elements
-to the registers, before use of a SIMD instruction.
-
#### Performance
Some operations are significantly faster when `unsafe` is used.
diff --git a/arrow/Cargo.toml b/arrow/Cargo.toml
index 6ca218f5f658..a6b4ddf51dfb 100644
--- a/arrow/Cargo.toml
+++ b/arrow/Cargo.toml
@@ -65,7 +65,6 @@ ipc_compression = ["ipc", "arrow-ipc/lz4", "arrow-ipc/zstd"]
csv = ["arrow-csv"]
ipc = ["arrow-ipc"]
json = ["arrow-json"]
-simd = ["arrow-array/simd", "arrow-arith/simd"]
prettyprint = ["arrow-cast/prettyprint"]
# The test utils feature enables code used in benchmarks and tests but
# not the core arrow code itself. Be aware that `rand` must be kept as
diff --git a/arrow/README.md b/arrow/README.md
index 6a91bc951cc1..bc95b91a9a4a 100644
--- a/arrow/README.md
+++ b/arrow/README.md
@@ -48,9 +48,7 @@ The `arrow` crate provides the following features which may be enabled in your `
- `ipc` (default) - support for reading [Arrow IPC Format](https://arrow.apache.org/docs/format/Columnar.html#serialization-and-interprocess-communication-ipc), also used as the wire protocol in [arrow-flight](https://crates.io/crates/arrow-flight)
- `ipc_compression` - Enables reading and writing compressed IPC streams (also enables `ipc`)
- `prettyprint` - support for formatting record batches as textual columns
-- `simd` - (_Requires Nightly Rust_) Use alternate hand optimized
implementations of some [compute](https://github.com/apache/arrow-rs/tree/master/arrow/src/compute/kernels)
- kernels using explicit SIMD instructions via [packed_simd_2](https://docs.rs/packed_simd_2/latest/packed_simd_2/).
- `chrono-tz` - support of parsing timezone using [chrono-tz](https://docs.rs/chrono-tz/0.6.0/chrono_tz/)
- `ffi` - bindings for the Arrow C [C Data Interface](https://arrow.apache.org/docs/format/CDataInterface.html)
- `pyarrow` - bindings for pyo3 to call arrow-rs from python
@@ -75,7 +73,6 @@ In particular there are a number of scenarios where `unsafe` is largely unavoida
- Invariants that cannot be statically verified by the compiler and unlock non-trivial performance wins, e.g. values in a StringArray are UTF-8, [TrustedLen](https://doc.rust-lang.org/std/iter/trait.TrustedLen.html) iterators, etc...
- FFI
-- SIMD
Additionally, this crate exposes a number of `unsafe` APIs, allowing downstream crates to explicitly opt-out of potentially expensive invariant checking where appropriate.
@@ -95,7 +92,7 @@ In order to compile Arrow for `wasm32-unknown-unknown` you will need to disable
```toml
[dependencies]
-arrow = { version = "5.0", default-features = false, features = ["csv", "ipc", "simd"] }
+arrow = { version = "5.0", default-features = false, features = ["csv", "ipc"] }
```
## Examples
diff --git a/arrow/src/ffi.rs b/arrow/src/ffi.rs
index b49f56c91574..d867f7c30d1f 100644
--- a/arrow/src/ffi.rs
+++ b/arrow/src/ffi.rs
@@ -468,13 +468,13 @@ mod tests {
use arrow_array::builder::UnionBuilder;
use arrow_array::cast::AsArray;
use arrow_array::types::{Float64Type, Int32Type};
- use arrow_array::{StructArray, UnionArray};
+ use arrow_array::*;
use crate::array::{
- make_array, Array, ArrayData, BooleanArray, Decimal128Array, DictionaryArray,
- DurationSecondArray, FixedSizeBinaryArray, FixedSizeListArray, GenericBinaryArray,
- GenericListArray, GenericStringArray, Int32Array, MapArray, OffsetSizeTrait,
- Time32MillisecondArray, TimestampMillisecondArray, UInt32Array,
+ make_array, Array, ArrayData, BooleanArray, DictionaryArray, DurationSecondArray,
+ FixedSizeBinaryArray, FixedSizeListArray, GenericBinaryArray, GenericListArray,
+ GenericStringArray, Int32Array, MapArray, OffsetSizeTrait, Time32MillisecondArray,
+ TimestampMillisecondArray, UInt32Array,
};
use crate::compute::kernels;
use crate::datatypes::{Field, Int8Type};
diff --git a/arrow/src/pyarrow.rs b/arrow/src/pyarrow.rs
index 8302f8741b60..9a13cfa493e9 100644
--- a/arrow/src/pyarrow.rs
+++ b/arrow/src/pyarrow.rs
@@ -71,7 +71,7 @@ use crate::datatypes::{DataType, Field, Schema};
use crate::error::ArrowError;
use crate::ffi;
use crate::ffi::{FFI_ArrowArray, FFI_ArrowSchema};
-use crate::ffi_stream::{export_reader_into_raw, ArrowArrayStreamReader, FFI_ArrowArrayStream};
+use crate::ffi_stream::{ArrowArrayStreamReader, FFI_ArrowArrayStream};
use crate::record_batch::RecordBatch;
import_exception!(pyarrow, ArrowException);
@@ -377,7 +377,7 @@ impl FromPyArrow for RecordBatch {
impl ToPyArrow for RecordBatch {
fn to_pyarrow(&self, py: Python) -> PyResult<PyObject> {
// Workaround apache/arrow#37669 by returning RecordBatchIterator
- let reader = RecordBatchIterator::new(vec![Ok(self.clone())], self.schema().clone());
+ let reader = RecordBatchIterator::new(vec![Ok(self.clone())], self.schema());
let reader: Box<dyn RecordBatchReader + Send> = Box::new(reader);
let py_reader = reader.into_pyarrow(py)?;
py_reader.call_method0(py, "read_next_batch")
|
diff --git a/arrow/tests/array_transform.rs b/arrow/tests/array_transform.rs
index 74e2a212736a..6f5b245b8e3b 100644
--- a/arrow/tests/array_transform.rs
+++ b/arrow/tests/array_transform.rs
@@ -28,6 +28,7 @@ use arrow_data::ArrayData;
use arrow_schema::{DataType, Field, Fields};
use std::sync::Arc;
+#[allow(unused)]
fn create_decimal_array(array: Vec<Option<i128>>, precision: u8, scale: i8) -> Decimal128Array {
array
.into_iter()
|
Remove nightly-only simd feature and related code in ArrowNumericType
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
<!--
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
(This section helps Arrow developers understand the context and *why* for this feature, in addition to the *what*)
-->
With the merge of #5100 all users of the feature-gated methods in `ArrowNumericType` should be gone and those functions can be removed.
**Describe the solution you'd like**
- Remove simd related functions from `ArrowNumericType` trait
- Remove `bit_util::bitwise_bin_op_simd` which seems to be unused
- Remove `simd` feature and `packed_simd` dependency
<!--
A clear and concise description of what you want to happen.
-->
**Describe alternatives you've considered**
The `ArrowNumericType` seems a little bit redundant with `ArrowNativeTypeOp`, but removing it completely would involve a lot of little api changes, so it's probably better to keep it as an empty marker trait.
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
|
2023-12-07T16:39:44Z
|
49.0
|
a9470d3eb083303350fc109f94865666fd0f062f
|
|
apache/arrow-rs
| 5,092
|
apache__arrow-rs-5092
|
[
"5091"
] |
481652a4f8d972b633063158903dbdb0adcf094d
|
diff --git a/arrow-data/src/transform/mod.rs b/arrow-data/src/transform/mod.rs
index af25e9c7e3dc..268cf10f2326 100644
--- a/arrow-data/src/transform/mod.rs
+++ b/arrow-data/src/transform/mod.rs
@@ -354,6 +354,14 @@ impl<'a> MutableArrayData<'a> {
) -> Self {
let data_type = arrays[0].data_type();
+ for a in arrays.iter().skip(1) {
+ assert_eq!(
+ data_type,
+ a.data_type(),
+ "Arrays with inconsistent types passed to MutableArrayData"
+ )
+ }
+
// if any of the arrays has nulls, insertions from any array requires setting bits
// as there is at least one array with nulls.
let use_nulls = use_nulls | arrays.iter().any(|array| array.null_count() > 0);
|
diff --git a/arrow/tests/array_transform.rs b/arrow/tests/array_transform.rs
index ccf66e1c30ad..74e2a212736a 100644
--- a/arrow/tests/array_transform.rs
+++ b/arrow/tests/array_transform.rs
@@ -975,6 +975,14 @@ fn test_extend_nulls_panic() {
mutable.extend_nulls(2);
}
+#[test]
+#[should_panic(expected = "Arrays with inconsistent types passed to MutableArrayData")]
+fn test_mixed_types() {
+ let a = StringArray::from(vec!["abc", "def"]).to_data();
+ let b = Int32Array::from(vec![1, 2, 3]).to_data();
+ MutableArrayData::new(vec![&a, &b], false, 4);
+}
+
/*
// this is an old test used on a meanwhile removed dead code
// that is still useful when `MutableArrayData` supports fixed-size lists.
|
Unsound MutableArrayData Constructor
**Describe the bug**
<!--
A clear and concise description of what the bug is.
-->
I want to use `MutableArrayData` to construct an array, but if the input array sequence is different, the output will be different.
This is because `MutableArrayData::new_with_capacities` will use the first array's data type.
https://github.com/apache/arrow-rs/blob/master/arrow-data/src/transform/mod.rs#L350-L356
**To Reproduce**
<!--
Steps to reproduce the behavior:
-->
Such as
```rust
use arrow::array::{ArrayRef, Int64Array, MutableArrayData, NullArray, Capacities};
use std::sync::Arc;
fn main() {
let x = Arc::new(Int64Array::from(vec![1, 2, 3])) as ArrayRef;
let x_data = x.to_data();
let y = Arc::new(NullArray::new(3)) as ArrayRef;
let y_data = y.to_data();
let arr1 = vec![&x_data, &y_data];
let mut m1 = MutableArrayData::new(arr1, true, 1000);
m1.extend(0, 0, 3);
let ret = Int64Array::from(m1.freeze()); // works just fine
let arr2 = vec![&y_data, &x_data];
let mut m2 = MutableArrayData::new(arr2, true, 100);
m2.extend(1, 0, 3);
let ret = Int64Array::from(m2.freeze()); // This will panic because ArrayData data type is null
}
```
**Expected behavior**
<!--
A clear and concise description of what you expected to happen.
-->
maybe we need a method to specify the ArrayData DataType, so whatever sequence of arrays we put in, we can get the excepted result.
maybe we can have a method like
```
pub fn with_capacities(
arrays: Vec<&'a ArrayData>,
use_nulls: bool,
capacities: Capacities,
data_type: DataType
) -> Self {
```
@tustvold @alamb how do you think?
**Additional context**
<!--
Add any other context about the problem here.
-->
|
I think it is probably a bug that MutableArrayData lets you extend with a mixture of types, this is not what it is intended to do and is highly unlikely to behave correctly... I was sure it checked this
Edit: it would appear this does is not only incorrect but is unsound, will prioritize fixing this
Thanks for your answer!
I'm refactoring `array_array` in `arrow-datafusion`, and I want to simplify macro by using `MutableArrayData`. So I use it like
https://github.com/apache/arrow-datafusion/pull/8252/files#diff-48cc9cf1bfdb0214a9f625b384d1c4fd5967a9da61e8f22a5dc1c4c5800563b4R395-R403
it can handle `make_array(1, NULL, 2)` but when it comes `make_array(NULL, 1)`, this will be failed to construct. Because in the later case, this first array is `NullArray`
> it can handle make_array(1, NULL, 2) but when it comes make_array(NULL, 1), this will be failed to construct. Because in the later case, this first array is NullArray
It is only handling this by accident and incorrectly. You need to coerce the types passed to make_array to a consistent type signature
|
2023-11-17T15:11:14Z
|
49.0
|
a9470d3eb083303350fc109f94865666fd0f062f
|
apache/arrow-rs
| 5,080
|
apache__arrow-rs-5080
|
[
"4867"
] |
4d141a34cb2ab53c07cfd2255351348a830b0224
|
diff --git a/arrow-data/src/ffi.rs b/arrow-data/src/ffi.rs
index 2b4d52601286..589f7dac6d19 100644
--- a/arrow-data/src/ffi.rs
+++ b/arrow-data/src/ffi.rs
@@ -168,6 +168,12 @@ impl FFI_ArrowArray {
.collect::<Box<_>>();
let n_children = children.len() as i64;
+ // As in the IPC format, emit null_count = length for Null type
+ let null_count = match data.data_type() {
+ DataType::Null => data.len(),
+ _ => data.null_count(),
+ };
+
// create the private data owning everything.
// any other data must be added here, e.g. via a struct, to track lifetime.
let mut private_data = Box::new(ArrayPrivateData {
@@ -179,7 +185,7 @@ impl FFI_ArrowArray {
Self {
length: data.len() as i64,
- null_count: data.null_count() as i64,
+ null_count: null_count as i64,
offset: data.offset() as i64,
n_buffers,
n_children,
diff --git a/arrow-schema/src/error.rs b/arrow-schema/src/error.rs
index 8ea533db89af..b7bf8d6e12a6 100644
--- a/arrow-schema/src/error.rs
+++ b/arrow-schema/src/error.rs
@@ -58,6 +58,12 @@ impl From<std::io::Error> for ArrowError {
}
}
+impl From<std::str::Utf8Error> for ArrowError {
+ fn from(error: std::str::Utf8Error) -> Self {
+ ArrowError::ParseError(error.to_string())
+ }
+}
+
impl From<std::string::FromUtf8Error> for ArrowError {
fn from(error: std::string::FromUtf8Error) -> Self {
ArrowError::ParseError(error.to_string())
diff --git a/arrow-schema/src/ffi.rs b/arrow-schema/src/ffi.rs
index b4d10b814a5d..8a18c77ea291 100644
--- a/arrow-schema/src/ffi.rs
+++ b/arrow-schema/src/ffi.rs
@@ -34,7 +34,9 @@
//! assert_eq!(schema, back);
//! ```
-use crate::{ArrowError, DataType, Field, FieldRef, Schema, TimeUnit, UnionFields, UnionMode};
+use crate::{
+ ArrowError, DataType, Field, FieldRef, IntervalUnit, Schema, TimeUnit, UnionFields, UnionMode,
+};
use std::sync::Arc;
use std::{
collections::HashMap,
@@ -402,6 +404,9 @@ impl TryFrom<&FFI_ArrowSchema> for DataType {
"tDm" => DataType::Duration(TimeUnit::Millisecond),
"tDu" => DataType::Duration(TimeUnit::Microsecond),
"tDn" => DataType::Duration(TimeUnit::Nanosecond),
+ "tiM" => DataType::Interval(IntervalUnit::YearMonth),
+ "tiD" => DataType::Interval(IntervalUnit::DayTime),
+ "tin" => DataType::Interval(IntervalUnit::MonthDayNano),
"+l" => {
let c_child = c_schema.child(0);
DataType::List(Arc::new(Field::try_from(c_child)?))
@@ -669,6 +674,9 @@ fn get_format_string(dtype: &DataType) -> Result<String, ArrowError> {
DataType::Duration(TimeUnit::Millisecond) => Ok("tDm".to_string()),
DataType::Duration(TimeUnit::Microsecond) => Ok("tDu".to_string()),
DataType::Duration(TimeUnit::Nanosecond) => Ok("tDn".to_string()),
+ DataType::Interval(IntervalUnit::YearMonth) => Ok("tiM".to_string()),
+ DataType::Interval(IntervalUnit::DayTime) => Ok("tiD".to_string()),
+ DataType::Interval(IntervalUnit::MonthDayNano) => Ok("tin".to_string()),
DataType::List(_) => Ok("+l".to_string()),
DataType::LargeList(_) => Ok("+L".to_string()),
DataType::Struct(_) => Ok("+s".to_string()),
diff --git a/arrow/src/array/ffi.rs b/arrow/src/array/ffi.rs
index e05c256d0128..d4d95a6e1770 100644
--- a/arrow/src/array/ffi.rs
+++ b/arrow/src/array/ffi.rs
@@ -70,7 +70,7 @@ mod tests {
let schema = FFI_ArrowSchema::try_from(expected.data_type())?;
// simulate an external consumer by being the consumer
- let result = &from_ffi(array, &schema)?;
+ let result = &unsafe { from_ffi(array, &schema) }?;
assert_eq!(result, expected);
Ok(())
diff --git a/arrow/src/ffi.rs b/arrow/src/ffi.rs
index c13d4c6e5dff..31388bf99358 100644
--- a/arrow/src/ffi.rs
+++ b/arrow/src/ffi.rs
@@ -43,7 +43,7 @@
//! let (out_array, out_schema) = to_ffi(&data)?;
//!
//! // import it
-//! let data = from_ffi(out_array, &out_schema)?;
+//! let data = unsafe { from_ffi(out_array, &out_schema) }?;
//! let array = Int32Array::from(data);
//!
//! // perform some operation
@@ -80,7 +80,7 @@
//! let mut schema = FFI_ArrowSchema::empty();
//! let mut array = FFI_ArrowArray::empty();
//! foreign.export_to_c(addr_of_mut!(array), addr_of_mut!(schema));
-//! Ok(make_array(from_ffi(array, &schema)?))
+//! Ok(make_array(unsafe { from_ffi(array, &schema) }?))
//! }
//! ```
@@ -108,6 +108,7 @@ use std::{mem::size_of, ptr::NonNull, sync::Arc};
pub use arrow_data::ffi::FFI_ArrowArray;
pub use arrow_schema::ffi::{FFI_ArrowSchema, Flags};
+
use arrow_schema::UnionMode;
use crate::array::{layout, ArrayData};
@@ -233,32 +234,53 @@ pub fn to_ffi(data: &ArrayData) -> Result<(FFI_ArrowArray, FFI_ArrowSchema)> {
/// # Safety
///
/// This struct assumes that the incoming data agrees with the C data interface.
-pub fn from_ffi(array: FFI_ArrowArray, schema: &FFI_ArrowSchema) -> Result<ArrayData> {
+pub unsafe fn from_ffi(array: FFI_ArrowArray, schema: &FFI_ArrowSchema) -> Result<ArrayData> {
+ let dt = DataType::try_from(schema)?;
let array = Arc::new(array);
- let tmp = ArrowArray {
+ let tmp = ImportedArrowArray {
array: &array,
- schema,
+ data_type: dt,
+ owner: &array,
+ };
+ tmp.consume()
+}
+
+/// Import [ArrayData] from the C Data Interface
+///
+/// # Safety
+///
+/// This struct assumes that the incoming data agrees with the C data interface.
+pub unsafe fn from_ffi_and_data_type(
+ array: FFI_ArrowArray,
+ data_type: DataType,
+) -> Result<ArrayData> {
+ let array = Arc::new(array);
+ let tmp = ImportedArrowArray {
+ array: &array,
+ data_type,
owner: &array,
};
tmp.consume()
}
#[derive(Debug)]
-struct ArrowArray<'a> {
+struct ImportedArrowArray<'a> {
array: &'a FFI_ArrowArray,
- schema: &'a FFI_ArrowSchema,
+ data_type: DataType,
owner: &'a Arc<FFI_ArrowArray>,
}
-impl<'a> ArrowArray<'a> {
+impl<'a> ImportedArrowArray<'a> {
fn consume(self) -> Result<ArrayData> {
- let dt = DataType::try_from(self.schema)?;
let len = self.array.len();
let offset = self.array.offset();
- let null_count = self.array.null_count();
+ let null_count = match &self.data_type {
+ DataType::Null => 0,
+ _ => self.array.null_count(),
+ };
- let data_layout = layout(&dt);
- let buffers = self.buffers(data_layout.can_contain_null_mask, &dt)?;
+ let data_layout = layout(&self.data_type);
+ let buffers = self.buffers(data_layout.can_contain_null_mask)?;
let null_bit_buffer = if data_layout.can_contain_null_mask {
self.null_bit_buffer()
@@ -266,14 +288,9 @@ impl<'a> ArrowArray<'a> {
None
};
- let mut child_data = (0..self.array.num_children())
- .map(|i| {
- let child = self.child(i);
- child.consume()
- })
- .collect::<Result<Vec<_>>>()?;
+ let mut child_data = self.consume_children()?;
- if let Some(d) = self.dictionary() {
+ if let Some(d) = self.dictionary()? {
// For dictionary type there should only be a single child, so we don't need to worry if
// there are other children added above.
assert!(child_data.is_empty());
@@ -283,7 +300,7 @@ impl<'a> ArrowArray<'a> {
// Should FFI be checking validity?
Ok(unsafe {
ArrayData::new_unchecked(
- dt,
+ self.data_type,
len,
Some(null_count),
null_bit_buffer,
@@ -294,14 +311,49 @@ impl<'a> ArrowArray<'a> {
})
}
+ fn consume_children(&self) -> Result<Vec<ArrayData>> {
+ match &self.data_type {
+ DataType::List(field)
+ | DataType::FixedSizeList(field, _)
+ | DataType::LargeList(field)
+ | DataType::Map(field, _) => Ok([self.consume_child(0, field.data_type())?].to_vec()),
+ DataType::Struct(fields) => {
+ assert!(fields.len() == self.array.num_children());
+ fields
+ .iter()
+ .enumerate()
+ .map(|(i, field)| self.consume_child(i, field.data_type()))
+ .collect::<Result<Vec<_>>>()
+ }
+ DataType::Union(union_fields, _) => {
+ assert!(union_fields.len() == self.array.num_children());
+ union_fields
+ .iter()
+ .enumerate()
+ .map(|(i, (_, field))| self.consume_child(i, field.data_type()))
+ .collect::<Result<Vec<_>>>()
+ }
+ _ => Ok(Vec::new()),
+ }
+ }
+
+ fn consume_child(&self, index: usize, child_type: &DataType) -> Result<ArrayData> {
+ ImportedArrowArray {
+ array: self.array.child(index),
+ data_type: child_type.clone(),
+ owner: self.owner,
+ }
+ .consume()
+ }
+
/// returns all buffers, as organized by Rust (i.e. null buffer is skipped if it's present
/// in the spec of the type)
- fn buffers(&self, can_contain_null_mask: bool, dt: &DataType) -> Result<Vec<Buffer>> {
+ fn buffers(&self, can_contain_null_mask: bool) -> Result<Vec<Buffer>> {
// + 1: skip null buffer
let buffer_begin = can_contain_null_mask as usize;
(buffer_begin..self.array.num_buffers())
.map(|index| {
- let len = self.buffer_len(index, dt)?;
+ let len = self.buffer_len(index, &self.data_type)?;
match unsafe { create_buffer(self.owner.clone(), self.array, index, len) } {
Some(buf) => Ok(buf),
@@ -388,25 +440,20 @@ impl<'a> ArrowArray<'a> {
unsafe { create_buffer(self.owner.clone(), self.array, 0, buffer_len) }
}
- fn child(&self, index: usize) -> ArrowArray {
- ArrowArray {
- array: self.array.child(index),
- schema: self.schema.child(index),
- owner: self.owner,
- }
- }
-
- fn dictionary(&self) -> Option<ArrowArray> {
- match (self.array.dictionary(), self.schema.dictionary()) {
- (Some(array), Some(schema)) => Some(ArrowArray {
+ fn dictionary(&self) -> Result<Option<ImportedArrowArray>> {
+ match (self.array.dictionary(), &self.data_type) {
+ (Some(array), DataType::Dictionary(_, value_type)) => Ok(Some(ImportedArrowArray {
array,
- schema,
+ data_type: value_type.as_ref().clone(),
owner: self.owner,
- }),
- (None, None) => None,
- _ => panic!(
- "Dictionary should both be set or not set in FFI_ArrowArray and FFI_ArrowSchema"
- ),
+ })),
+ (Some(_), _) => Err(ArrowError::CDataInterface(
+ "Got dictionary in FFI_ArrowArray for non-dictionary data type".to_string(),
+ )),
+ (None, DataType::Dictionary(_, _)) => Err(ArrowError::CDataInterface(
+ "Missing dictionary in FFI_ArrowArray for dictionary data type".to_string(),
+ )),
+ (_, _) => Ok(None),
}
}
}
@@ -443,7 +490,7 @@ mod tests {
let (array, schema) = to_ffi(&array.into_data()).unwrap();
// (simulate consumer) import it
- let array = Int32Array::from(from_ffi(array, &schema).unwrap());
+ let array = Int32Array::from(unsafe { from_ffi(array, &schema) }.unwrap());
let array = kernels::numeric::add(&array, &array).unwrap();
// verify
@@ -487,7 +534,7 @@ mod tests {
let (array, schema) = to_ffi(&array.to_data())?;
// (simulate consumer) import it
- let data = from_ffi(array, &schema)?;
+ let data = unsafe { from_ffi(array, &schema) }?;
let array = make_array(data);
// perform some operation
@@ -517,7 +564,7 @@ mod tests {
let (array, schema) = to_ffi(&original_array.to_data())?;
// (simulate consumer) import it
- let data = from_ffi(array, &schema)?;
+ let data = unsafe { from_ffi(array, &schema) }?;
let array = make_array(data);
// perform some operation
@@ -539,7 +586,7 @@ mod tests {
let (array, schema) = to_ffi(&array.to_data())?;
// (simulate consumer) import it
- let data = from_ffi(array, &schema)?;
+ let data = unsafe { from_ffi(array, &schema) }?;
let array = make_array(data);
// perform some operation
@@ -608,7 +655,7 @@ mod tests {
let (array, schema) = to_ffi(&array.to_data())?;
// (simulate consumer) import it
- let data = from_ffi(array, &schema)?;
+ let data = unsafe { from_ffi(array, &schema) }?;
let array = make_array(data);
// downcast
@@ -648,7 +695,7 @@ mod tests {
let (array, schema) = to_ffi(&array.to_data())?;
// (simulate consumer) import it
- let data = from_ffi(array, &schema)?;
+ let data = unsafe { from_ffi(array, &schema) }?;
let array = make_array(data);
// perform some operation
@@ -693,7 +740,7 @@ mod tests {
let (array, schema) = to_ffi(&array.to_data())?;
// (simulate consumer) import it
- let data = from_ffi(array, &schema)?;
+ let data = unsafe { from_ffi(array, &schema) }?;
let array = make_array(data);
// perform some operation
@@ -719,7 +766,7 @@ mod tests {
let (array, schema) = to_ffi(&array.to_data())?;
// (simulate consumer) import it
- let data = from_ffi(array, &schema)?;
+ let data = unsafe { from_ffi(array, &schema) }?;
let array = make_array(data);
// perform some operation
@@ -748,7 +795,7 @@ mod tests {
let (array, schema) = to_ffi(&array.to_data())?;
// (simulate consumer) import it
- let data = from_ffi(array, &schema)?;
+ let data = unsafe { from_ffi(array, &schema) }?;
let array = make_array(data);
// perform some operation
@@ -784,7 +831,7 @@ mod tests {
let (array, schema) = to_ffi(&array.to_data())?;
// (simulate consumer) import it
- let data = from_ffi(array, &schema)?;
+ let data = unsafe { from_ffi(array, &schema) }?;
let array = make_array(data);
// perform some operation
@@ -845,7 +892,7 @@ mod tests {
let (array, schema) = to_ffi(&list_data)?;
// (simulate consumer) import it
- let data = from_ffi(array, &schema)?;
+ let data = unsafe { from_ffi(array, &schema) }?;
let array = make_array(data);
// perform some operation
@@ -890,7 +937,7 @@ mod tests {
let (array, schema) = to_ffi(&dict_array.to_data())?;
// (simulate consumer) import it
- let data = from_ffi(array, &schema)?;
+ let data = unsafe { from_ffi(array, &schema) }?;
let array = make_array(data);
// perform some operation
@@ -928,7 +975,7 @@ mod tests {
}
// (simulate consumer) import it
- let data = from_ffi(out_array, &out_schema)?;
+ let data = unsafe { from_ffi(out_array, &out_schema) }?;
let array = make_array(data);
// perform some operation
@@ -949,7 +996,7 @@ mod tests {
let (array, schema) = to_ffi(&array.to_data())?;
// (simulate consumer) import it
- let data = from_ffi(array, &schema)?;
+ let data = unsafe { from_ffi(array, &schema) }?;
let array = make_array(data);
// perform some operation
@@ -986,7 +1033,7 @@ mod tests {
let (array, schema) = to_ffi(&map_array.to_data())?;
// (simulate consumer) import it
- let data = from_ffi(array, &schema)?;
+ let data = unsafe { from_ffi(array, &schema) }?;
let array = make_array(data);
// perform some operation
@@ -1009,7 +1056,7 @@ mod tests {
let (array, schema) = to_ffi(&struct_array.to_data())?;
// (simulate consumer) import it
- let data = from_ffi(array, &schema)?;
+ let data = unsafe { from_ffi(array, &schema) }?;
let array = make_array(data);
// perform some operation
@@ -1033,7 +1080,7 @@ mod tests {
let (array, schema) = to_ffi(&union.to_data())?;
// (simulate consumer) import it
- let data = from_ffi(array, &schema)?;
+ let data = unsafe { from_ffi(array, &schema) }?;
let array = make_array(data);
let array = array.as_any().downcast_ref::<UnionArray>().unwrap();
@@ -1094,7 +1141,7 @@ mod tests {
let (array, schema) = to_ffi(&union.to_data())?;
// (simulate consumer) import it
- let data = from_ffi(array, &schema)?;
+ let data = unsafe { from_ffi(array, &schema) }?;
let array = UnionArray::from(data);
let expected_type_ids = vec![0_i8, 0, 1, 0];
diff --git a/arrow/src/ffi_stream.rs b/arrow/src/ffi_stream.rs
index 123669aa61be..bbec71e8837e 100644
--- a/arrow/src/ffi_stream.rs
+++ b/arrow/src/ffi_stream.rs
@@ -357,9 +357,11 @@ impl Iterator for ArrowArrayStreamReader {
}
let schema_ref = self.schema();
+ // NOTE: this parses the FFI_ArrowSchema again on each iterator call;
+ // should probably use from_ffi_and_data_type() instead.
let schema = FFI_ArrowSchema::try_from(schema_ref.as_ref()).ok()?;
- let data = from_ffi(array, &schema).ok()?;
+ let data = unsafe { from_ffi(array, &schema) }.ok()?;
let record_batch = RecordBatch::from(StructArray::from(data));
@@ -464,7 +466,7 @@ mod tests {
break;
}
- let array = from_ffi(ffi_array, &ffi_schema).unwrap();
+ let array = unsafe { from_ffi(ffi_array, &ffi_schema) }.unwrap();
let record_batch = RecordBatch::from(StructArray::from(array));
produced_batches.push(record_batch);
diff --git a/arrow/src/pyarrow.rs b/arrow/src/pyarrow.rs
index 2ac550ad0456..8302f8741b60 100644
--- a/arrow/src/pyarrow.rs
+++ b/arrow/src/pyarrow.rs
@@ -267,7 +267,7 @@ impl FromPyArrow for ArrayData {
let schema_ptr = unsafe { schema_capsule.reference::<FFI_ArrowSchema>() };
let array = unsafe { FFI_ArrowArray::from_raw(array_capsule.pointer() as _) };
- return ffi::from_ffi(array, schema_ptr).map_err(to_py_err);
+ return unsafe { ffi::from_ffi(array, schema_ptr) }.map_err(to_py_err);
}
validate_class("Array", value)?;
@@ -287,7 +287,7 @@ impl FromPyArrow for ArrayData {
),
)?;
- ffi::from_ffi(array, &schema).map_err(to_py_err)
+ unsafe { ffi::from_ffi(array, &schema) }.map_err(to_py_err)
}
}
@@ -348,7 +348,7 @@ impl FromPyArrow for RecordBatch {
let schema_ptr = unsafe { schema_capsule.reference::<FFI_ArrowSchema>() };
let ffi_array = unsafe { FFI_ArrowArray::from_raw(array_capsule.pointer() as _) };
- let array_data = ffi::from_ffi(ffi_array, schema_ptr).map_err(to_py_err)?;
+ let array_data = unsafe { ffi::from_ffi(ffi_array, schema_ptr) }.map_err(to_py_err)?;
if !matches!(array_data.data_type(), DataType::Struct(_)) {
return Err(PyTypeError::new_err(
"Expected Struct type from __arrow_c_array.",
|
diff --git a/arrow-integration-testing/Cargo.toml b/arrow-integration-testing/Cargo.toml
index 86c2cb27d297..c29860f09d64 100644
--- a/arrow-integration-testing/Cargo.toml
+++ b/arrow-integration-testing/Cargo.toml
@@ -27,11 +27,14 @@ edition = { workspace = true }
publish = false
rust-version = { workspace = true }
+[lib]
+crate-type = ["lib", "cdylib"]
+
[features]
logging = ["tracing-subscriber"]
[dependencies]
-arrow = { path = "../arrow", default-features = false, features = ["test_utils", "ipc", "ipc_compression", "json"] }
+arrow = { path = "../arrow", default-features = false, features = ["test_utils", "ipc", "ipc_compression", "json", "ffi"] }
arrow-flight = { path = "../arrow-flight", default-features = false }
arrow-buffer = { path = "../arrow-buffer", default-features = false }
arrow-integration-test = { path = "../arrow-integration-test", default-features = false }
diff --git a/arrow-integration-testing/README.md b/arrow-integration-testing/README.md
index e82591e6b139..dcf39c27fbc5 100644
--- a/arrow-integration-testing/README.md
+++ b/arrow-integration-testing/README.md
@@ -48,7 +48,7 @@ ln -s <path_to_arrow_rs> arrow/rust
```shell
cd arrow
-pip install -e dev/archery[docker]
+pip install -e dev/archery[integration]
```
### Build the C++ binaries:
diff --git a/arrow-integration-testing/src/bin/arrow-json-integration-test.rs b/arrow-integration-testing/src/bin/arrow-json-integration-test.rs
index 187d987a5a0a..9f1abb16a668 100644
--- a/arrow-integration-testing/src/bin/arrow-json-integration-test.rs
+++ b/arrow-integration-testing/src/bin/arrow-json-integration-test.rs
@@ -15,16 +15,13 @@
// specific language governing permissions and limitations
// under the License.
-use arrow::datatypes::{DataType, Field};
-use arrow::datatypes::{Fields, Schema};
use arrow::error::{ArrowError, Result};
use arrow::ipc::reader::FileReader;
use arrow::ipc::writer::FileWriter;
use arrow_integration_test::*;
-use arrow_integration_testing::read_json_file;
+use arrow_integration_testing::{canonicalize_schema, open_json_file};
use clap::Parser;
use std::fs::File;
-use std::sync::Arc;
#[derive(clap::ValueEnum, Debug, Clone)]
#[clap(rename_all = "SCREAMING_SNAKE_CASE")]
@@ -66,12 +63,12 @@ fn json_to_arrow(json_name: &str, arrow_name: &str, verbose: bool) -> Result<()>
eprintln!("Converting {json_name} to {arrow_name}");
}
- let json_file = read_json_file(json_name)?;
+ let json_file = open_json_file(json_name)?;
let arrow_file = File::create(arrow_name)?;
let mut writer = FileWriter::try_new(arrow_file, &json_file.schema)?;
- for b in json_file.batches {
+ for b in json_file.read_batches()? {
writer.write(&b)?;
}
@@ -113,49 +110,13 @@ fn arrow_to_json(arrow_name: &str, json_name: &str, verbose: bool) -> Result<()>
Ok(())
}
-fn canonicalize_schema(schema: &Schema) -> Schema {
- let fields = schema
- .fields()
- .iter()
- .map(|field| match field.data_type() {
- DataType::Map(child_field, sorted) => match child_field.data_type() {
- DataType::Struct(fields) if fields.len() == 2 => {
- let first_field = fields.get(0).unwrap();
- let key_field =
- Arc::new(Field::new("key", first_field.data_type().clone(), false));
- let second_field = fields.get(1).unwrap();
- let value_field = Arc::new(Field::new(
- "value",
- second_field.data_type().clone(),
- second_field.is_nullable(),
- ));
-
- let fields = Fields::from([key_field, value_field]);
- let struct_type = DataType::Struct(fields);
- let child_field = Field::new("entries", struct_type, false);
-
- Arc::new(Field::new(
- field.name().as_str(),
- DataType::Map(Arc::new(child_field), *sorted),
- field.is_nullable(),
- ))
- }
- _ => panic!("The child field of Map type should be Struct type with 2 fields."),
- },
- _ => field.clone(),
- })
- .collect::<Fields>();
-
- Schema::new(fields).with_metadata(schema.metadata().clone())
-}
-
fn validate(arrow_name: &str, json_name: &str, verbose: bool) -> Result<()> {
if verbose {
eprintln!("Validating {arrow_name} and {json_name}");
}
// open JSON file
- let json_file = read_json_file(json_name)?;
+ let json_file = open_json_file(json_name)?;
// open Arrow file
let arrow_file = File::open(arrow_name)?;
@@ -170,7 +131,7 @@ fn validate(arrow_name: &str, json_name: &str, verbose: bool) -> Result<()> {
)));
}
- let json_batches = &json_file.batches;
+ let json_batches = json_file.read_batches()?;
// compare number of batches
assert!(
diff --git a/arrow-integration-testing/src/flight_client_scenarios/integration_test.rs b/arrow-integration-testing/src/flight_client_scenarios/integration_test.rs
index 81cc4bbe8ed2..c6b5a72ca6e2 100644
--- a/arrow-integration-testing/src/flight_client_scenarios/integration_test.rs
+++ b/arrow-integration-testing/src/flight_client_scenarios/integration_test.rs
@@ -15,7 +15,7 @@
// specific language governing permissions and limitations
// under the License.
-use crate::{read_json_file, ArrowFile};
+use crate::open_json_file;
use std::collections::HashMap;
use arrow::{
@@ -45,23 +45,16 @@ pub async fn run_scenario(host: &str, port: u16, path: &str) -> Result {
let client = FlightServiceClient::connect(url).await?;
- let ArrowFile {
- schema, batches, ..
- } = read_json_file(path)?;
+ let json_file = open_json_file(path)?;
- let schema = Arc::new(schema);
+ let batches = json_file.read_batches()?;
+ let schema = Arc::new(json_file.schema);
let mut descriptor = FlightDescriptor::default();
descriptor.set_type(DescriptorType::Path);
descriptor.path = vec![path.to_string()];
- upload_data(
- client.clone(),
- schema.clone(),
- descriptor.clone(),
- batches.clone(),
- )
- .await?;
+ upload_data(client.clone(), schema, descriptor.clone(), batches.clone()).await?;
verify_data(client, descriptor, &batches).await?;
Ok(())
diff --git a/arrow-integration-testing/src/lib.rs b/arrow-integration-testing/src/lib.rs
index 2d76be3495c8..553e69b0a1a0 100644
--- a/arrow-integration-testing/src/lib.rs
+++ b/arrow-integration-testing/src/lib.rs
@@ -19,14 +19,20 @@
use serde_json::Value;
-use arrow::datatypes::Schema;
-use arrow::error::Result;
+use arrow::array::{Array, StructArray};
+use arrow::datatypes::{DataType, Field, Fields, Schema};
+use arrow::error::{ArrowError, Result};
+use arrow::ffi::{from_ffi_and_data_type, FFI_ArrowArray, FFI_ArrowSchema};
use arrow::record_batch::RecordBatch;
use arrow::util::test_util::arrow_test_data;
use arrow_integration_test::*;
use std::collections::HashMap;
+use std::ffi::{c_int, CStr, CString};
use std::fs::File;
use std::io::BufReader;
+use std::iter::zip;
+use std::ptr;
+use std::sync::Arc;
/// The expected username for the basic auth integration test.
pub const AUTH_USERNAME: &str = "arrow";
@@ -40,11 +46,68 @@ pub struct ArrowFile {
pub schema: Schema,
// we can evolve this into a concrete Arrow type
// this is temporarily not being read from
- pub _dictionaries: HashMap<i64, ArrowJsonDictionaryBatch>,
- pub batches: Vec<RecordBatch>,
+ dictionaries: HashMap<i64, ArrowJsonDictionaryBatch>,
+ arrow_json: Value,
}
-pub fn read_json_file(json_name: &str) -> Result<ArrowFile> {
+impl ArrowFile {
+ pub fn read_batch(&self, batch_num: usize) -> Result<RecordBatch> {
+ let b = self.arrow_json["batches"].get(batch_num).unwrap();
+ let json_batch: ArrowJsonBatch = serde_json::from_value(b.clone()).unwrap();
+ record_batch_from_json(&self.schema, json_batch, Some(&self.dictionaries))
+ }
+
+ pub fn read_batches(&self) -> Result<Vec<RecordBatch>> {
+ self.arrow_json["batches"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|b| {
+ let json_batch: ArrowJsonBatch = serde_json::from_value(b.clone()).unwrap();
+ record_batch_from_json(&self.schema, json_batch, Some(&self.dictionaries))
+ })
+ .collect()
+ }
+}
+
+// Canonicalize the names of map fields in a schema
+pub fn canonicalize_schema(schema: &Schema) -> Schema {
+ let fields = schema
+ .fields()
+ .iter()
+ .map(|field| match field.data_type() {
+ DataType::Map(child_field, sorted) => match child_field.data_type() {
+ DataType::Struct(fields) if fields.len() == 2 => {
+ let first_field = fields.get(0).unwrap();
+ let key_field =
+ Arc::new(Field::new("key", first_field.data_type().clone(), false));
+ let second_field = fields.get(1).unwrap();
+ let value_field = Arc::new(Field::new(
+ "value",
+ second_field.data_type().clone(),
+ second_field.is_nullable(),
+ ));
+
+ let fields = Fields::from([key_field, value_field]);
+ let struct_type = DataType::Struct(fields);
+ let child_field = Field::new("entries", struct_type, false);
+
+ Arc::new(Field::new(
+ field.name().as_str(),
+ DataType::Map(Arc::new(child_field), *sorted),
+ field.is_nullable(),
+ ))
+ }
+ _ => panic!("The child field of Map type should be Struct type with 2 fields."),
+ },
+ _ => field.clone(),
+ })
+ .collect::<Fields>();
+
+ Schema::new(fields).with_metadata(schema.metadata().clone())
+}
+
+pub fn open_json_file(json_name: &str) -> Result<ArrowFile> {
let json_file = File::open(json_name)?;
let reader = BufReader::new(json_file);
let arrow_json: Value = serde_json::from_reader(reader).unwrap();
@@ -62,17 +125,10 @@ pub fn read_json_file(json_name: &str) -> Result<ArrowFile> {
dictionaries.insert(json_dict.id, json_dict);
}
}
-
- let mut batches = vec![];
- for b in arrow_json["batches"].as_array().unwrap() {
- let json_batch: ArrowJsonBatch = serde_json::from_value(b.clone()).unwrap();
- let batch = record_batch_from_json(&schema, json_batch, Some(&dictionaries))?;
- batches.push(batch);
- }
Ok(ArrowFile {
schema,
- _dictionaries: dictionaries,
- batches,
+ dictionaries,
+ arrow_json,
})
}
@@ -100,3 +156,147 @@ pub fn read_gzip_json(version: &str, path: &str) -> ArrowJson {
let arrow_json: ArrowJson = serde_json::from_str(&s).unwrap();
arrow_json
}
+
+//
+// C Data Integration entrypoints
+//
+
+fn cdata_integration_export_schema_from_json(
+ c_json_name: *const i8,
+ out: *mut FFI_ArrowSchema,
+) -> Result<()> {
+ let json_name = unsafe { CStr::from_ptr(c_json_name) };
+ let f = open_json_file(json_name.to_str()?)?;
+ let c_schema = FFI_ArrowSchema::try_from(&f.schema)?;
+ // Move exported schema into output struct
+ unsafe { ptr::write(out, c_schema) };
+ Ok(())
+}
+
+fn cdata_integration_export_batch_from_json(
+ c_json_name: *const i8,
+ batch_num: c_int,
+ out: *mut FFI_ArrowArray,
+) -> Result<()> {
+ let json_name = unsafe { CStr::from_ptr(c_json_name) };
+ let b = open_json_file(json_name.to_str()?)?.read_batch(batch_num.try_into().unwrap())?;
+ let a = StructArray::from(b).into_data();
+ let c_array = FFI_ArrowArray::new(&a);
+ // Move exported array into output struct
+ unsafe { ptr::write(out, c_array) };
+ Ok(())
+}
+
+fn cdata_integration_import_schema_and_compare_to_json(
+ c_json_name: *const i8,
+ c_schema: *mut FFI_ArrowSchema,
+) -> Result<()> {
+ let json_name = unsafe { CStr::from_ptr(c_json_name) };
+ let json_schema = open_json_file(json_name.to_str()?)?.schema;
+
+ // The source ArrowSchema will be released when this is dropped
+ let imported_schema = unsafe { FFI_ArrowSchema::from_raw(c_schema) };
+ let imported_schema = Schema::try_from(&imported_schema)?;
+
+ // compare schemas
+ if canonicalize_schema(&json_schema) != canonicalize_schema(&imported_schema) {
+ return Err(ArrowError::ComputeError(format!(
+ "Schemas do not match.\n- JSON: {:?}\n- Imported: {:?}",
+ json_schema, imported_schema
+ )));
+ }
+ Ok(())
+}
+
+fn compare_batches(a: &RecordBatch, b: &RecordBatch) -> Result<()> {
+ if a.num_columns() != b.num_columns() {
+ return Err(ArrowError::InvalidArgumentError(
+ "batches do not have the same number of columns".to_string(),
+ ));
+ }
+ for (a_column, b_column) in zip(a.columns(), b.columns()) {
+ if a_column != b_column {
+ return Err(ArrowError::InvalidArgumentError(
+ "batch columns are not the same".to_string(),
+ ));
+ }
+ }
+ Ok(())
+}
+
+fn cdata_integration_import_batch_and_compare_to_json(
+ c_json_name: *const i8,
+ batch_num: c_int,
+ c_array: *mut FFI_ArrowArray,
+) -> Result<()> {
+ let json_name = unsafe { CStr::from_ptr(c_json_name) };
+ let json_batch =
+ open_json_file(json_name.to_str()?)?.read_batch(batch_num.try_into().unwrap())?;
+ let schema = json_batch.schema();
+
+ let data_type_for_import = DataType::Struct(schema.fields.clone());
+ let imported_array = unsafe { FFI_ArrowArray::from_raw(c_array) };
+ let imported_array = unsafe { from_ffi_and_data_type(imported_array, data_type_for_import) }?;
+ imported_array.validate_full()?;
+ let imported_batch = RecordBatch::from(StructArray::from(imported_array));
+
+ compare_batches(&json_batch, &imported_batch)
+}
+
+// If Result is an error, then export a const char* to its string display, otherwise NULL
+fn result_to_c_error<T, E: std::fmt::Display>(result: &std::result::Result<T, E>) -> *mut i8 {
+ match result {
+ Ok(_) => ptr::null_mut(),
+ Err(e) => CString::new(format!("{}", e)).unwrap().into_raw(),
+ }
+}
+
+/// Release a const char* exported by result_to_c_error()
+///
+/// # Safety
+///
+/// The pointer is assumed to have been obtained using CString::into_raw.
+#[no_mangle]
+pub unsafe extern "C" fn arrow_rs_free_error(c_error: *mut i8) {
+ if !c_error.is_null() {
+ drop(unsafe { CString::from_raw(c_error) });
+ }
+}
+
+#[no_mangle]
+pub extern "C" fn arrow_rs_cdata_integration_export_schema_from_json(
+ c_json_name: *const i8,
+ out: *mut FFI_ArrowSchema,
+) -> *mut i8 {
+ let r = cdata_integration_export_schema_from_json(c_json_name, out);
+ result_to_c_error(&r)
+}
+
+#[no_mangle]
+pub extern "C" fn arrow_rs_cdata_integration_import_schema_and_compare_to_json(
+ c_json_name: *const i8,
+ c_schema: *mut FFI_ArrowSchema,
+) -> *mut i8 {
+ let r = cdata_integration_import_schema_and_compare_to_json(c_json_name, c_schema);
+ result_to_c_error(&r)
+}
+
+#[no_mangle]
+pub extern "C" fn arrow_rs_cdata_integration_export_batch_from_json(
+ c_json_name: *const i8,
+ batch_num: c_int,
+ out: *mut FFI_ArrowArray,
+) -> *mut i8 {
+ let r = cdata_integration_export_batch_from_json(c_json_name, batch_num, out);
+ result_to_c_error(&r)
+}
+
+#[no_mangle]
+pub extern "C" fn arrow_rs_cdata_integration_import_batch_and_compare_to_json(
+ c_json_name: *const i8,
+ batch_num: c_int,
+ c_array: *mut FFI_ArrowArray,
+) -> *mut i8 {
+ let r = cdata_integration_import_batch_and_compare_to_json(c_json_name, batch_num, c_array);
+ result_to_c_error(&r)
+}
|
Enable C Data Integration Tests
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
<!--
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
(This section helps Arrow developers understand the context and *why* for this feature, in addition to the *what*)
-->
https://github.com/apache/arrow-rs/pull/4862#issuecomment-1735712205
**Describe the solution you'd like**
<!--
A clear and concise description of what you want to happen.
-->
Integration test the C Data interface against other implementations
**Describe alternatives you've considered**
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
|
I'm not a Rust developer, but feel free to ping me for any guidance or early PR comments.
The logs also appear to contain
```
Rust does not support IPC
Rust does not support Flight
```
Which would appear to suggest there may be additional test coverage that isn't enabled properly
Which logs exactly?
For example https://github.com/apache/arrow-rs/actions/runs/6637236852/job/18031126773?pr=4988
I also see messages such as "Skipping test because producer Java does not support IPC", which is clearly wrong.
Oh, actually, the messages are confusing, but they simply correspond to the registered skips:
https://github.com/apache/arrow/blob/25e5d19b98511310e617c8b6e3c6ce6af39dfcde/dev/archery/archery/integration/datagen.py#L1787-L1870
and
https://github.com/apache/arrow/blob/25e5d19b98511310e617c8b6e3c6ce6af39dfcde/dev/archery/archery/integration/runner.py#L151-L162
|
2023-11-15T22:59:32Z
|
49.0
|
a9470d3eb083303350fc109f94865666fd0f062f
|
apache/arrow-rs
| 5,076
|
apache__arrow-rs-5076
|
[
"5037"
] |
7ba36b012322e08b06184c806f8ba339181cebc1
|
diff --git a/parquet/src/column/writer/mod.rs b/parquet/src/column/writer/mod.rs
index a917c4864988..11c39685911c 100644
--- a/parquet/src/column/writer/mod.rs
+++ b/parquet/src/column/writer/mod.rs
@@ -636,8 +636,16 @@ impl<'a, E: ColumnValueEncoder> GenericColumnWriter<'a, E> {
Type::BYTE_ARRAY | Type::FIXED_LEN_BYTE_ARRAY => {
self.column_index_builder.append(
null_page,
- self.truncate_min_value(stat.min_bytes()),
- self.truncate_max_value(stat.max_bytes()),
+ self.truncate_min_value(
+ self.props.column_index_truncate_length(),
+ stat.min_bytes(),
+ )
+ .0,
+ self.truncate_max_value(
+ self.props.column_index_truncate_length(),
+ stat.max_bytes(),
+ )
+ .0,
self.page_metrics.num_page_nulls as i64,
);
}
@@ -658,26 +666,26 @@ impl<'a, E: ColumnValueEncoder> GenericColumnWriter<'a, E> {
.append_row_count(self.page_metrics.num_buffered_rows as i64);
}
- fn truncate_min_value(&self, data: &[u8]) -> Vec<u8> {
- self.props
- .column_index_truncate_length()
+ fn truncate_min_value(&self, truncation_length: Option<usize>, data: &[u8]) -> (Vec<u8>, bool) {
+ truncation_length
.filter(|l| data.len() > *l)
.and_then(|l| match str::from_utf8(data) {
Ok(str_data) => truncate_utf8(str_data, l),
Err(_) => Some(data[..l].to_vec()),
})
- .unwrap_or_else(|| data.to_vec())
+ .map(|truncated| (truncated, true))
+ .unwrap_or_else(|| (data.to_vec(), false))
}
- fn truncate_max_value(&self, data: &[u8]) -> Vec<u8> {
- self.props
- .column_index_truncate_length()
+ fn truncate_max_value(&self, truncation_length: Option<usize>, data: &[u8]) -> (Vec<u8>, bool) {
+ truncation_length
.filter(|l| data.len() > *l)
.and_then(|l| match str::from_utf8(data) {
Ok(str_data) => truncate_utf8(str_data, l).and_then(increment_utf8),
Err(_) => increment(data[..l].to_vec()),
})
- .unwrap_or_else(|| data.to_vec())
+ .map(|truncated| (truncated, true))
+ .unwrap_or_else(|| (data.to_vec(), false))
}
/// Adds data page.
@@ -856,20 +864,64 @@ impl<'a, E: ColumnValueEncoder> GenericColumnWriter<'a, E> {
.set_dictionary_page_offset(dict_page_offset);
if self.statistics_enabled != EnabledStatistics::None {
+ let backwards_compatible_min_max = self.descr.sort_order().is_signed();
+
let statistics = ValueStatistics::<E::T>::new(
self.column_metrics.min_column_value.clone(),
self.column_metrics.max_column_value.clone(),
self.column_metrics.column_distinct_count,
self.column_metrics.num_column_nulls,
false,
- );
+ )
+ .with_backwards_compatible_min_max(backwards_compatible_min_max)
+ .into();
+
+ let statistics = match statistics {
+ Statistics::ByteArray(stats) if stats.has_min_max_set() => {
+ let (min, did_truncate_min) = self.truncate_min_value(
+ self.props.statistics_truncate_length(),
+ stats.min_bytes(),
+ );
+ let (max, did_truncate_max) = self.truncate_max_value(
+ self.props.statistics_truncate_length(),
+ stats.max_bytes(),
+ );
+ Statistics::ByteArray(
+ ValueStatistics::new(
+ Some(min.into()),
+ Some(max.into()),
+ stats.distinct_count(),
+ stats.null_count(),
+ backwards_compatible_min_max,
+ )
+ .with_max_is_exact(!did_truncate_max)
+ .with_min_is_exact(!did_truncate_min),
+ )
+ }
+ Statistics::FixedLenByteArray(stats) if stats.has_min_max_set() => {
+ let (min, did_truncate_min) = self.truncate_min_value(
+ self.props.statistics_truncate_length(),
+ stats.min_bytes(),
+ );
+ let (max, did_truncate_max) = self.truncate_max_value(
+ self.props.statistics_truncate_length(),
+ stats.max_bytes(),
+ );
+ Statistics::FixedLenByteArray(
+ ValueStatistics::new(
+ Some(min.into()),
+ Some(max.into()),
+ stats.distinct_count(),
+ stats.null_count(),
+ backwards_compatible_min_max,
+ )
+ .with_max_is_exact(!did_truncate_max)
+ .with_min_is_exact(!did_truncate_min),
+ )
+ }
+ stats => stats,
+ };
- // Some common readers only support the deprecated statistics
- // format so we also write them out if possible
- // See https://github.com/apache/arrow-rs/issues/799
- let statistics = statistics
- .with_backwards_compatible_min_max(self.descr.sort_order().is_signed())
- .into();
builder = builder.set_statistics(statistics);
}
@@ -2612,6 +2664,148 @@ mod tests {
}
}
+ #[test]
+ fn test_statistics_truncating_byte_array() {
+ let page_writer = get_test_page_writer();
+
+ const TEST_TRUNCATE_LENGTH: usize = 1;
+
+ // Truncate values at 1 byte
+ let builder =
+ WriterProperties::builder().set_statistics_truncate_length(Some(TEST_TRUNCATE_LENGTH));
+ let props = Arc::new(builder.build());
+ let mut writer = get_test_column_writer::<ByteArrayType>(page_writer, 0, 0, props);
+
+ let mut data = vec![ByteArray::default(); 1];
+ // This is the expected min value
+ data[0].set_data(Bytes::from(String::from("Blart Versenwald III")));
+
+ writer.write_batch(&data, None, None).unwrap();
+
+ writer.flush_data_pages().unwrap();
+
+ let r = writer.close().unwrap();
+
+ assert_eq!(1, r.rows_written);
+
+ let stats = r.metadata.statistics().expect("statistics");
+ assert!(stats.has_min_max_set());
+ assert_eq!(stats.null_count(), 0);
+ assert_eq!(stats.distinct_count(), None);
+ if let Statistics::ByteArray(_stats) = stats {
+ let min_value = _stats.min();
+ let max_value = _stats.max();
+
+ assert!(!_stats.min_is_exact());
+ assert!(!_stats.max_is_exact());
+
+ assert_eq!(min_value.len(), TEST_TRUNCATE_LENGTH);
+ assert_eq!(max_value.len(), TEST_TRUNCATE_LENGTH);
+
+ assert_eq!("B".as_bytes(), min_value.as_bytes());
+ assert_eq!("C".as_bytes(), max_value.as_bytes());
+ } else {
+ panic!("expecting Statistics::ByteArray");
+ }
+ }
+
+ #[test]
+ fn test_statistics_truncating_fixed_len_byte_array() {
+ let page_writer = get_test_page_writer();
+
+ const TEST_TRUNCATE_LENGTH: usize = 1;
+
+ // Truncate values at 1 byte
+ let builder =
+ WriterProperties::builder().set_statistics_truncate_length(Some(TEST_TRUNCATE_LENGTH));
+ let props = Arc::new(builder.build());
+ let mut writer = get_test_column_writer::<FixedLenByteArrayType>(page_writer, 0, 0, props);
+
+ let mut data = vec![FixedLenByteArray::default(); 1];
+
+ const PSEUDO_DECIMAL_VALUE: i128 = 6541894651216648486512564456564654;
+ const PSEUDO_DECIMAL_BYTES: [u8; 16] = PSEUDO_DECIMAL_VALUE.to_be_bytes();
+
+ const EXPECTED_MIN: [u8; TEST_TRUNCATE_LENGTH] = [PSEUDO_DECIMAL_BYTES[0]]; // parquet specifies big-endian order for decimals
+ const EXPECTED_MAX: [u8; TEST_TRUNCATE_LENGTH] =
+ [PSEUDO_DECIMAL_BYTES[0].overflowing_add(1).0];
+
+ // This is the expected min value
+ data[0].set_data(Bytes::from(PSEUDO_DECIMAL_BYTES.as_slice()));
+
+ writer.write_batch(&data, None, None).unwrap();
+
+ writer.flush_data_pages().unwrap();
+
+ let r = writer.close().unwrap();
+
+ assert_eq!(1, r.rows_written);
+
+ let stats = r.metadata.statistics().expect("statistics");
+ assert!(stats.has_min_max_set());
+ assert_eq!(stats.null_count(), 0);
+ assert_eq!(stats.distinct_count(), None);
+ if let Statistics::FixedLenByteArray(_stats) = stats {
+ let min_value = _stats.min();
+ let max_value = _stats.max();
+
+ assert!(!_stats.min_is_exact());
+ assert!(!_stats.max_is_exact());
+
+ assert_eq!(min_value.len(), TEST_TRUNCATE_LENGTH);
+ assert_eq!(max_value.len(), TEST_TRUNCATE_LENGTH);
+
+ assert_eq!(EXPECTED_MIN.as_slice(), min_value.as_bytes());
+ assert_eq!(EXPECTED_MAX.as_slice(), max_value.as_bytes());
+
+ let reconstructed_min = i128::from_be_bytes([
+ min_value.as_bytes()[0],
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ ]);
+
+ let reconstructed_max = i128::from_be_bytes([
+ max_value.as_bytes()[0],
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ ]);
+
+ // check that the inner value is correctly bounded by the min/max
+ println!("min: {reconstructed_min} {PSEUDO_DECIMAL_VALUE}");
+ assert!(reconstructed_min <= PSEUDO_DECIMAL_VALUE);
+ println!("max {reconstructed_max} {PSEUDO_DECIMAL_VALUE}");
+ assert!(reconstructed_max >= PSEUDO_DECIMAL_VALUE);
+ } else {
+ panic!("expecting Statistics::FixedLenByteArray");
+ }
+ }
+
#[test]
fn test_send() {
fn test<T: Send>() {}
diff --git a/parquet/src/file/properties.rs b/parquet/src/file/properties.rs
index ea71763a0101..287e73c9906a 100644
--- a/parquet/src/file/properties.rs
+++ b/parquet/src/file/properties.rs
@@ -51,6 +51,8 @@ pub const DEFAULT_COLUMN_INDEX_TRUNCATE_LENGTH: Option<usize> = Some(64);
pub const DEFAULT_BLOOM_FILTER_FPP: f64 = 0.05;
/// Default value for [`BloomFilterProperties::ndv`]
pub const DEFAULT_BLOOM_FILTER_NDV: u64 = 1_000_000_u64;
+/// Default values for [`WriterProperties::statistics_truncate_length`]
+pub const DEFAULT_STATISTICS_TRUNCATE_LENGTH: Option<usize> = None;
/// Parquet writer version.
///
@@ -136,6 +138,7 @@ pub struct WriterProperties {
column_properties: HashMap<ColumnPath, ColumnProperties>,
sorting_columns: Option<Vec<SortingColumn>>,
column_index_truncate_length: Option<usize>,
+ statistics_truncate_length: Option<usize>,
}
impl Default for WriterProperties {
@@ -241,6 +244,13 @@ impl WriterProperties {
self.column_index_truncate_length
}
+ /// Returns the maximum length of truncated min/max values in statistics.
+ ///
+ /// `None` if truncation is disabled, must be greater than 0 otherwise.
+ pub fn statistics_truncate_length(&self) -> Option<usize> {
+ self.statistics_truncate_length
+ }
+
/// Returns encoding for a data page, when dictionary encoding is enabled.
/// This is not configurable.
#[inline]
@@ -334,6 +344,7 @@ pub struct WriterPropertiesBuilder {
column_properties: HashMap<ColumnPath, ColumnProperties>,
sorting_columns: Option<Vec<SortingColumn>>,
column_index_truncate_length: Option<usize>,
+ statistics_truncate_length: Option<usize>,
}
impl WriterPropertiesBuilder {
@@ -352,6 +363,7 @@ impl WriterPropertiesBuilder {
column_properties: HashMap::new(),
sorting_columns: None,
column_index_truncate_length: DEFAULT_COLUMN_INDEX_TRUNCATE_LENGTH,
+ statistics_truncate_length: DEFAULT_STATISTICS_TRUNCATE_LENGTH,
}
}
@@ -370,6 +382,7 @@ impl WriterPropertiesBuilder {
column_properties: self.column_properties,
sorting_columns: self.sorting_columns,
column_index_truncate_length: self.column_index_truncate_length,
+ statistics_truncate_length: self.statistics_truncate_length,
}
}
@@ -643,6 +656,17 @@ impl WriterPropertiesBuilder {
self.column_index_truncate_length = max_length;
self
}
+
+ /// Sets the max length of min/max value fields in statistics. Must be greater than 0.
+ /// If set to `None` - there's no effective limit.
+ pub fn set_statistics_truncate_length(mut self, max_length: Option<usize>) -> Self {
+ if let Some(value) = max_length {
+ assert!(value > 0, "Cannot have a 0 statistics truncate length. If you wish to disable min/max value truncation, set it to `None`.");
+ }
+
+ self.statistics_truncate_length = max_length;
+ self
+ }
}
/// Controls the level of statistics to be computed by the writer
diff --git a/parquet/src/file/statistics.rs b/parquet/src/file/statistics.rs
index 345fe7dd2615..1bc003d48854 100644
--- a/parquet/src/file/statistics.rs
+++ b/parquet/src/file/statistics.rs
@@ -27,6 +27,8 @@
//! assert_eq!(stats.null_count(), 3);
//! assert!(stats.has_min_max_set());
//! assert!(stats.is_min_max_deprecated());
+//! assert!(stats.min_is_exact());
+//! assert!(stats.max_is_exact());
//!
//! match stats {
//! Statistics::Int32(ref typed) => {
@@ -206,19 +208,27 @@ pub fn from_thrift(
null_count,
old_format,
),
- Type::BYTE_ARRAY => Statistics::byte_array(
- min.map(ByteArray::from),
- max.map(ByteArray::from),
- distinct_count,
- null_count,
- old_format,
+ Type::BYTE_ARRAY => Statistics::ByteArray(
+ ValueStatistics::new(
+ min.map(ByteArray::from),
+ max.map(ByteArray::from),
+ distinct_count,
+ null_count,
+ old_format,
+ )
+ .with_max_is_exact(stats.is_max_value_exact.unwrap_or(false))
+ .with_min_is_exact(stats.is_min_value_exact.unwrap_or(false)),
),
- Type::FIXED_LEN_BYTE_ARRAY => Statistics::fixed_len_byte_array(
- min.map(ByteArray::from).map(FixedLenByteArray::from),
- max.map(ByteArray::from).map(FixedLenByteArray::from),
- distinct_count,
- null_count,
- old_format,
+ Type::FIXED_LEN_BYTE_ARRAY => Statistics::FixedLenByteArray(
+ ValueStatistics::new(
+ min.map(ByteArray::from).map(FixedLenByteArray::from),
+ max.map(ByteArray::from).map(FixedLenByteArray::from),
+ distinct_count,
+ null_count,
+ old_format,
+ )
+ .with_max_is_exact(stats.is_max_value_exact.unwrap_or(false))
+ .with_min_is_exact(stats.is_min_value_exact.unwrap_or(false)),
),
};
@@ -248,13 +258,15 @@ pub fn to_thrift(stats: Option<&Statistics>) -> Option<TStatistics> {
};
// Get min/max if set.
- let (min, max) = if stats.has_min_max_set() {
+ let (min, max, min_exact, max_exact) = if stats.has_min_max_set() {
(
Some(stats.min_bytes().to_vec()),
Some(stats.max_bytes().to_vec()),
+ Some(stats.min_is_exact()),
+ Some(stats.max_is_exact()),
)
} else {
- (None, None)
+ (None, None, None, None)
};
if stats.is_min_max_backwards_compatible() {
@@ -268,6 +280,9 @@ pub fn to_thrift(stats: Option<&Statistics>) -> Option<TStatistics> {
thrift_stats.max_value = max;
}
+ thrift_stats.is_min_value_exact = min_exact;
+ thrift_stats.is_max_value_exact = max_exact;
+
Some(thrift_stats)
}
@@ -374,6 +389,16 @@ impl Statistics {
statistics_enum_func![self, has_min_max_set]
}
+ /// Returns `true` if the min value is set, and is an exact min value.
+ pub fn min_is_exact(&self) -> bool {
+ statistics_enum_func![self, min_is_exact]
+ }
+
+ /// Returns `true` if the max value is set, and is an exact max value.
+ pub fn max_is_exact(&self) -> bool {
+ statistics_enum_func![self, max_is_exact]
+ }
+
/// Returns slice of bytes that represent min value.
/// Panics if min value is not set.
pub fn min_bytes(&self) -> &[u8] {
@@ -428,6 +453,10 @@ pub struct ValueStatistics<T> {
distinct_count: Option<u64>,
null_count: u64,
+ // Whether or not the min or max values are exact, or truncated.
+ is_max_value_exact: bool,
+ is_min_value_exact: bool,
+
/// If `true` populate the deprecated `min` and `max` fields instead of
/// `min_value` and `max_value`
is_min_max_deprecated: bool,
@@ -447,6 +476,8 @@ impl<T: ParquetValueType> ValueStatistics<T> {
is_min_max_deprecated: bool,
) -> Self {
Self {
+ is_max_value_exact: max.is_some(),
+ is_min_value_exact: min.is_some(),
min,
max,
distinct_count,
@@ -456,6 +487,28 @@ impl<T: ParquetValueType> ValueStatistics<T> {
}
}
+ /// Set whether the stored `min` field represents the exact
+ /// minimum, or just a bound on the minimum value.
+ ///
+ /// see [`Self::min_is_exact`]
+ pub fn with_min_is_exact(self, is_min_value_exact: bool) -> Self {
+ Self {
+ is_min_value_exact,
+ ..self
+ }
+ }
+
+ /// Set whether the stored `max` field represents the exact
+ /// maximum, or just a bound on the maximum value.
+ ///
+ /// see [`Self::max_is_exact`]
+ pub fn with_max_is_exact(self, is_max_value_exact: bool) -> Self {
+ Self {
+ is_max_value_exact,
+ ..self
+ }
+ }
+
/// Set whether to write the deprecated `min` and `max` fields
/// for compatibility with older parquet writers
///
@@ -506,13 +559,23 @@ impl<T: ParquetValueType> ValueStatistics<T> {
self.min.is_some() && self.max.is_some()
}
+ /// Whether or not max value is set, and is an exact value.
+ pub fn max_is_exact(&self) -> bool {
+ self.max.is_some() && self.is_max_value_exact
+ }
+
+ /// Whether or not min value is set, and is an exact value.
+ pub fn min_is_exact(&self) -> bool {
+ self.min.is_some() && self.is_min_value_exact
+ }
+
/// Returns optional value of number of distinct values occurring.
- fn distinct_count(&self) -> Option<u64> {
+ pub fn distinct_count(&self) -> Option<u64> {
self.distinct_count
}
/// Returns null count.
- fn null_count(&self) -> u64 {
+ pub fn null_count(&self) -> u64 {
self.null_count
}
@@ -556,6 +619,8 @@ impl<T: ParquetValueType> fmt::Display for ValueStatistics<T> {
}
write!(f, ", null_count: {}", self.null_count)?;
write!(f, ", min_max_deprecated: {}", self.is_min_max_deprecated)?;
+ write!(f, ", max_value_exact: {}", self.is_max_value_exact)?;
+ write!(f, ", min_value_exact: {}", self.is_min_value_exact)?;
write!(f, "}}")
}
}
@@ -565,13 +630,15 @@ impl<T: ParquetValueType> fmt::Debug for ValueStatistics<T> {
write!(
f,
"{{min: {:?}, max: {:?}, distinct_count: {:?}, null_count: {}, \
- min_max_deprecated: {}, min_max_backwards_compatible: {}}}",
+ min_max_deprecated: {}, min_max_backwards_compatible: {}, max_value_exact: {}, min_value_exact: {}}}",
self.min,
self.max,
self.distinct_count,
self.null_count,
self.is_min_max_deprecated,
- self.is_min_max_backwards_compatible
+ self.is_min_max_backwards_compatible,
+ self.is_max_value_exact,
+ self.is_min_value_exact
)
}
}
@@ -628,14 +695,14 @@ mod tests {
assert_eq!(
format!("{stats:?}"),
"Int32({min: Some(1), max: Some(12), distinct_count: None, null_count: 12, \
- min_max_deprecated: true, min_max_backwards_compatible: true})"
+ min_max_deprecated: true, min_max_backwards_compatible: true, max_value_exact: true, min_value_exact: true})"
);
let stats = Statistics::int32(None, None, None, 7, false);
assert_eq!(
format!("{stats:?}"),
"Int32({min: None, max: None, distinct_count: None, null_count: 7, \
- min_max_deprecated: false, min_max_backwards_compatible: false})"
+ min_max_deprecated: false, min_max_backwards_compatible: false, max_value_exact: false, min_value_exact: false})"
)
}
@@ -644,14 +711,14 @@ mod tests {
let stats = Statistics::int32(Some(1), Some(12), None, 12, true);
assert_eq!(
format!("{stats}"),
- "{min: 1, max: 12, distinct_count: N/A, null_count: 12, min_max_deprecated: true}"
+ "{min: 1, max: 12, distinct_count: N/A, null_count: 12, min_max_deprecated: true, max_value_exact: true, min_value_exact: true}"
);
let stats = Statistics::int64(None, None, None, 7, false);
assert_eq!(
format!("{stats}"),
"{min: N/A, max: N/A, distinct_count: N/A, null_count: 7, min_max_deprecated: \
- false}"
+ false, max_value_exact: false, min_value_exact: false}"
);
let stats = Statistics::int96(
@@ -664,19 +731,23 @@ mod tests {
assert_eq!(
format!("{stats}"),
"{min: [1, 0, 0], max: [2, 3, 4], distinct_count: N/A, null_count: 3, \
- min_max_deprecated: true}"
+ min_max_deprecated: true, max_value_exact: true, min_value_exact: true}"
);
- let stats = Statistics::byte_array(
- Some(ByteArray::from(vec![1u8])),
- Some(ByteArray::from(vec![2u8])),
- Some(5),
- 7,
- false,
+ let stats = Statistics::ByteArray(
+ ValueStatistics::new(
+ Some(ByteArray::from(vec![1u8])),
+ Some(ByteArray::from(vec![2u8])),
+ Some(5),
+ 7,
+ false,
+ )
+ .with_max_is_exact(false)
+ .with_min_is_exact(false),
);
assert_eq!(
format!("{stats}"),
- "{min: [1], max: [2], distinct_count: 5, null_count: 7, min_max_deprecated: false}"
+ "{min: [1], max: [2], distinct_count: 5, null_count: 7, min_max_deprecated: false, max_value_exact: false, min_value_exact: false}"
);
}
@@ -712,7 +783,45 @@ mod tests {
Some(ByteArray::from(vec![1, 2, 3]).into()),
None,
0,
- true
+ true,
+ )
+ );
+
+ assert!(
+ Statistics::byte_array(
+ Some(ByteArray::from(vec![1, 2, 3])),
+ Some(ByteArray::from(vec![1, 2, 3])),
+ None,
+ 0,
+ true,
+ ) != Statistics::ByteArray(
+ ValueStatistics::new(
+ Some(ByteArray::from(vec![1, 2, 3])),
+ Some(ByteArray::from(vec![1, 2, 3])),
+ None,
+ 0,
+ true,
+ )
+ .with_max_is_exact(false)
+ )
+ );
+
+ assert!(
+ Statistics::fixed_len_byte_array(
+ Some(FixedLenByteArray::from(vec![1, 2, 3])),
+ Some(FixedLenByteArray::from(vec![1, 2, 3])),
+ None,
+ 0,
+ true,
+ ) != Statistics::FixedLenByteArray(
+ ValueStatistics::new(
+ Some(FixedLenByteArray::from(vec![1, 2, 3])),
+ Some(FixedLenByteArray::from(vec![1, 2, 3])),
+ None,
+ 0,
+ true,
+ )
+ .with_min_is_exact(false)
)
);
}
|
diff --git a/parquet/tests/arrow_writer_layout.rs b/parquet/tests/arrow_writer_layout.rs
index fab87f32f5c4..cd124031cfdc 100644
--- a/parquet/tests/arrow_writer_layout.rs
+++ b/parquet/tests/arrow_writer_layout.rs
@@ -185,7 +185,7 @@ fn test_primitive() {
pages: (0..8)
.map(|_| Page {
rows: 250,
- page_header_size: 34,
+ page_header_size: 36,
compressed_size: 1000,
encoding: Encoding::PLAIN,
page_type: PageType::DATA_PAGE,
@@ -214,14 +214,14 @@ fn test_primitive() {
pages: vec![
Page {
rows: 250,
- page_header_size: 34,
+ page_header_size: 36,
compressed_size: 258,
encoding: Encoding::RLE_DICTIONARY,
page_type: PageType::DATA_PAGE,
},
Page {
rows: 1750,
- page_header_size: 34,
+ page_header_size: 36,
compressed_size: 7000,
encoding: Encoding::PLAIN,
page_type: PageType::DATA_PAGE,
@@ -229,7 +229,7 @@ fn test_primitive() {
],
dictionary_page: Some(Page {
rows: 250,
- page_header_size: 34,
+ page_header_size: 36,
compressed_size: 1000,
encoding: Encoding::PLAIN,
page_type: PageType::DICTIONARY_PAGE,
@@ -256,42 +256,42 @@ fn test_primitive() {
pages: vec![
Page {
rows: 400,
- page_header_size: 34,
+ page_header_size: 36,
compressed_size: 452,
encoding: Encoding::RLE_DICTIONARY,
page_type: PageType::DATA_PAGE,
},
Page {
rows: 370,
- page_header_size: 34,
+ page_header_size: 36,
compressed_size: 472,
encoding: Encoding::RLE_DICTIONARY,
page_type: PageType::DATA_PAGE,
},
Page {
rows: 330,
- page_header_size: 34,
+ page_header_size: 36,
compressed_size: 464,
encoding: Encoding::RLE_DICTIONARY,
page_type: PageType::DATA_PAGE,
},
Page {
rows: 330,
- page_header_size: 34,
+ page_header_size: 36,
compressed_size: 464,
encoding: Encoding::RLE_DICTIONARY,
page_type: PageType::DATA_PAGE,
},
Page {
rows: 330,
- page_header_size: 34,
+ page_header_size: 36,
compressed_size: 464,
encoding: Encoding::RLE_DICTIONARY,
page_type: PageType::DATA_PAGE,
},
Page {
rows: 240,
- page_header_size: 34,
+ page_header_size: 36,
compressed_size: 332,
encoding: Encoding::RLE_DICTIONARY,
page_type: PageType::DATA_PAGE,
@@ -299,7 +299,7 @@ fn test_primitive() {
],
dictionary_page: Some(Page {
rows: 2000,
- page_header_size: 34,
+ page_header_size: 36,
compressed_size: 8000,
encoding: Encoding::PLAIN,
page_type: PageType::DICTIONARY_PAGE,
@@ -325,7 +325,7 @@ fn test_primitive() {
pages: (0..20)
.map(|_| Page {
rows: 100,
- page_header_size: 34,
+ page_header_size: 36,
compressed_size: 400,
encoding: Encoding::PLAIN,
page_type: PageType::DATA_PAGE,
@@ -360,14 +360,14 @@ fn test_string() {
pages: (0..15)
.map(|_| Page {
rows: 130,
- page_header_size: 34,
+ page_header_size: 36,
compressed_size: 1040,
encoding: Encoding::PLAIN,
page_type: PageType::DATA_PAGE,
})
.chain(std::iter::once(Page {
rows: 50,
- page_header_size: 33,
+ page_header_size: 35,
compressed_size: 400,
encoding: Encoding::PLAIN,
page_type: PageType::DATA_PAGE,
@@ -396,21 +396,21 @@ fn test_string() {
pages: vec![
Page {
rows: 130,
- page_header_size: 34,
+ page_header_size: 36,
compressed_size: 138,
encoding: Encoding::RLE_DICTIONARY,
page_type: PageType::DATA_PAGE,
},
Page {
rows: 1250,
- page_header_size: 36,
+ page_header_size: 38,
compressed_size: 10000,
encoding: Encoding::PLAIN,
page_type: PageType::DATA_PAGE,
},
Page {
rows: 620,
- page_header_size: 34,
+ page_header_size: 36,
compressed_size: 4960,
encoding: Encoding::PLAIN,
page_type: PageType::DATA_PAGE,
@@ -418,7 +418,7 @@ fn test_string() {
],
dictionary_page: Some(Page {
rows: 130,
- page_header_size: 34,
+ page_header_size: 36,
compressed_size: 1040,
encoding: Encoding::PLAIN,
page_type: PageType::DICTIONARY_PAGE,
@@ -445,42 +445,42 @@ fn test_string() {
pages: vec![
Page {
rows: 400,
- page_header_size: 34,
+ page_header_size: 36,
compressed_size: 452,
encoding: Encoding::RLE_DICTIONARY,
page_type: PageType::DATA_PAGE,
},
Page {
rows: 370,
- page_header_size: 34,
+ page_header_size: 36,
compressed_size: 472,
encoding: Encoding::RLE_DICTIONARY,
page_type: PageType::DATA_PAGE,
},
Page {
rows: 330,
- page_header_size: 34,
+ page_header_size: 36,
compressed_size: 464,
encoding: Encoding::RLE_DICTIONARY,
page_type: PageType::DATA_PAGE,
},
Page {
rows: 330,
- page_header_size: 34,
+ page_header_size: 36,
compressed_size: 464,
encoding: Encoding::RLE_DICTIONARY,
page_type: PageType::DATA_PAGE,
},
Page {
rows: 330,
- page_header_size: 34,
+ page_header_size: 36,
compressed_size: 464,
encoding: Encoding::RLE_DICTIONARY,
page_type: PageType::DATA_PAGE,
},
Page {
rows: 240,
- page_header_size: 34,
+ page_header_size: 36,
compressed_size: 332,
encoding: Encoding::RLE_DICTIONARY,
page_type: PageType::DATA_PAGE,
@@ -488,7 +488,7 @@ fn test_string() {
],
dictionary_page: Some(Page {
rows: 2000,
- page_header_size: 34,
+ page_header_size: 36,
compressed_size: 16000,
encoding: Encoding::PLAIN,
page_type: PageType::DICTIONARY_PAGE,
@@ -528,7 +528,7 @@ fn test_list() {
pages: (0..10)
.map(|_| Page {
rows: 20,
- page_header_size: 34,
+ page_header_size: 36,
compressed_size: 672,
encoding: Encoding::PLAIN,
page_type: PageType::DATA_PAGE,
|
Binary columns do not receive truncated statistics
**Describe the bug**
#4389 introduced truncation on column indices for binary columns, where the min/max values for a binary column may be arbitrarily large. As noted, this matches the behaviour in parquet-mr for shortening columns.
However, the value in the statistics is written un-truncated. This differs from the behaviour of parquet-mr where the statistics are truncated too: https://github.com/apache/parquet-mr/blob/master/parquet-hadoop/src/main/java/org/apache/parquet/format/converter/ParquetMetadataConverter.java#L715
**To Reproduce**
There is a test in https://github.com/delta-io/delta-rs/issues/1805 which demonstrates this, but in general write a parquet file with a long binary column and observe that the stats for that column are not truncated.
**Expected behavior**
Matching parquet-mr, the statistics should be truncated as well.
**Additional context**
Found this when looking into https://github.com/delta-io/delta-rs/issues/1805. delta-rs uses the column stats to serialize into the delta log, which leads to very bloated entries.
I think it is sufficient to just call truncate_min_value/truncate_max_value when creating the column metadata here: https://github.com/apache/arrow-rs/blob/master/parquet/src/column/writer/mod.rs#L858-L859 but I don't know enough about the internals of arrow to know if that change is correct.
|
Support for this was only added to the parquet standard 3 weeks ago - https://github.com/apache/parquet-format/pull/216
TBC this will be a breaking API change, as it will break workloads expecting the statistics to not be truncated
Got it. It looks like the change to enable statistics truncation was done to parquet-mr in 2019, but without the flag: https://github.com/apache/parquet-mr/pull/696
So in principle, you couldn’t trust the completeness of binary column stats before then as there was no indication as to whether truncation had occurred or not.
Hmm... I also note that it is disabled by default, is this still the case?
Regardless I think we should probably only perform this in the context of https://github.com/apache/parquet-format/pull/216 as whilst parquet-mr would appear to be configurable to perform binary truncation, I'm fairly confident there are applications that have implicit assumptions that this would break.
FYI @alamb my memory is hazy as to what forms of aggregate pushdown DF performs, and if we might need to introduce some notion of inexact statistics (if it doesn't already exist).
I'm happy to work up a PR that implements this in the same way, also disabled by default, for parquet-rs.
Thank you, that would be great
> FYI @alamb my memory is hazy as to what forms of aggregate pushdown DF performs, and if we might need to introduce some notion of inexact statistics (if it doesn't already exist).
I think the recent work by @berkaysynnada to add https://github.com/apache/arrow-datafusion/blob/e95e3f89c97ae27149c1dd8093f91a5574210fe6/datafusion/common/src/stats.rs#L29-L36 might be relevant
However, I think it is likely we will/should eventually add another variant like
```
enum Precision {
// The value is known to be within the range (it is at at most this large for Max, or at least this large for Min)
// but the actual values may be lower/higher.
Bounded(ScalarValue)
}
```
I believe we have a similar usecase in IOx for when we want to ensure the bound includes the actual range, but could be larger (cc @NGA-TRAN )
> > FYI @alamb my memory is hazy as to what forms of aggregate pushdown DF performs, and if we might need to introduce some notion of inexact statistics (if it doesn't already exist).
>
> I think the recent work by @berkaysynnada to add https://github.com/apache/arrow-datafusion/blob/e95e3f89c97ae27149c1dd8093f91a5574210fe6/datafusion/common/src/stats.rs#L29-L36 might be relevant
>
> However, I think it is likely we will/should eventually add another variant like
>
> ```
> enum Precision {
> // The value is known to be within the range (it is at at most this large for Max, or at least this large for Min)
> // but the actual values may be lower/higher.
> Bounded(ScalarValue)
> }
> ```
>
> I believe we have a similar usecase in IOx for when we want to ensure the bound includes the actual range, but could be larger (cc @NGA-TRAN )
I think so too, adding a range-specifying variant will pave the way for many things. While I have other high-priority tasks to address shortly, I'm always available to offer support if someone wishes to take this on. The variant I have in mind is as follows:
```
enum Precision {
...
InBetween(Interval)
}
```
It will also be easier to use after updating intervals (planning to open the related PR in a few days).
I filed https://github.com/apache/arrow-datafusion/issues/8078 with a proposal of a more precise way to represent inexact statistics
|
2023-11-14T13:24:14Z
|
49.0
|
a9470d3eb083303350fc109f94865666fd0f062f
|
apache/arrow-rs
| 5,065
|
apache__arrow-rs-5065
|
[
"3774"
] |
4d141a34cb2ab53c07cfd2255351348a830b0224
|
diff --git a/arrow-array/src/numeric.rs b/arrow-array/src/numeric.rs
index ad7b3eca1dbc..b5e474ba696a 100644
--- a/arrow-array/src/numeric.rs
+++ b/arrow-array/src/numeric.rs
@@ -618,7 +618,6 @@ mod tests {
let mask = 0b01010101_01010101_10101010_10101010;
let actual = UInt16Type::mask_from_u64(mask);
let expected = expected_mask!(i16, mask);
- dbg!(&expected);
let expected = m16x32::from_cast(i16x32::from_slice_unaligned(expected.as_slice()));
assert_eq!(expected, actual);
diff --git a/arrow-json/src/lib.rs b/arrow-json/src/lib.rs
index e69eaaba3ef8..e39882e52620 100644
--- a/arrow-json/src/lib.rs
+++ b/arrow-json/src/lib.rs
@@ -82,7 +82,7 @@ pub type RawReader<R> = Reader<R>;
pub type RawReaderBuilder = ReaderBuilder;
pub use self::reader::{Reader, ReaderBuilder};
-pub use self::writer::{ArrayWriter, LineDelimitedWriter, Writer};
+pub use self::writer::{ArrayWriter, LineDelimitedWriter, Writer, WriterBuilder};
use half::f16;
use serde_json::{Number, Value};
diff --git a/arrow-json/src/writer.rs b/arrow-json/src/writer.rs
index 5ecfc932364b..4f74817ca1e3 100644
--- a/arrow-json/src/writer.rs
+++ b/arrow-json/src/writer.rs
@@ -92,6 +92,10 @@
//! let buf = writer.into_inner();
//! assert_eq!(r#"[{"a":1},{"a":2},{"a":3}]"#, String::from_utf8(buf).unwrap())
//! ```
+//!
+//! [`LineDelimitedWriter`] and [`ArrayWriter`] will omit writing keys with null values.
+//! In order to explicitly write null values for keys, configure a custom [`Writer`] by
+//! using a [`WriterBuilder`] to construct a [`Writer`].
use std::iter;
use std::{fmt::Debug, io::Write};
@@ -124,6 +128,7 @@ where
fn struct_array_to_jsonmap_array(
array: &StructArray,
+ explicit_nulls: bool,
) -> Result<Vec<JsonMap<String, Value>>, ArrowError> {
let inner_col_names = array.column_names();
@@ -132,13 +137,26 @@ fn struct_array_to_jsonmap_array(
.collect::<Vec<JsonMap<String, Value>>>();
for (j, struct_col) in array.columns().iter().enumerate() {
- set_column_for_json_rows(&mut inner_objs, struct_col, inner_col_names[j])?
+ set_column_for_json_rows(
+ &mut inner_objs,
+ struct_col,
+ inner_col_names[j],
+ explicit_nulls,
+ )?
}
Ok(inner_objs)
}
/// Converts an arrow [`Array`] into a `Vec` of Serde JSON [`serde_json::Value`]'s
pub fn array_to_json_array(array: &dyn Array) -> Result<Vec<Value>, ArrowError> {
+ // For backwards compatibility, default to skip nulls
+ array_to_json_array_internal(array, false)
+}
+
+fn array_to_json_array_internal(
+ array: &dyn Array,
+ explicit_nulls: bool,
+) -> Result<Vec<Value>, ArrowError> {
match array.data_type() {
DataType::Null => Ok(iter::repeat(Value::Null).take(array.len()).collect()),
DataType::Boolean => Ok(array
@@ -180,32 +198,44 @@ pub fn array_to_json_array(array: &dyn Array) -> Result<Vec<Value>, ArrowError>
DataType::List(_) => as_list_array(array)
.iter()
.map(|maybe_value| match maybe_value {
- Some(v) => Ok(Value::Array(array_to_json_array(&v)?)),
+ Some(v) => Ok(Value::Array(array_to_json_array_internal(
+ &v,
+ explicit_nulls,
+ )?)),
None => Ok(Value::Null),
})
.collect(),
DataType::LargeList(_) => as_large_list_array(array)
.iter()
.map(|maybe_value| match maybe_value {
- Some(v) => Ok(Value::Array(array_to_json_array(&v)?)),
+ Some(v) => Ok(Value::Array(array_to_json_array_internal(
+ &v,
+ explicit_nulls,
+ )?)),
None => Ok(Value::Null),
})
.collect(),
DataType::FixedSizeList(_, _) => as_fixed_size_list_array(array)
.iter()
.map(|maybe_value| match maybe_value {
- Some(v) => Ok(Value::Array(array_to_json_array(&v)?)),
+ Some(v) => Ok(Value::Array(array_to_json_array_internal(
+ &v,
+ explicit_nulls,
+ )?)),
None => Ok(Value::Null),
})
.collect(),
DataType::Struct(_) => {
- let jsonmaps = struct_array_to_jsonmap_array(array.as_struct())?;
+ let jsonmaps = struct_array_to_jsonmap_array(array.as_struct(), explicit_nulls)?;
Ok(jsonmaps.into_iter().map(Value::Object).collect())
}
DataType::Map(_, _) => as_map_array(array)
.iter()
.map(|maybe_value| match maybe_value {
- Some(v) => Ok(Value::Array(array_to_json_array(&v)?)),
+ Some(v) => Ok(Value::Array(array_to_json_array_internal(
+ &v,
+ explicit_nulls,
+ )?)),
None => Ok(Value::Null),
})
.collect(),
@@ -216,14 +246,16 @@ pub fn array_to_json_array(array: &dyn Array) -> Result<Vec<Value>, ArrowError>
}
macro_rules! set_column_by_array_type {
- ($cast_fn:ident, $col_name:ident, $rows:ident, $array:ident) => {
+ ($cast_fn:ident, $col_name:ident, $rows:ident, $array:ident, $explicit_nulls:ident) => {
let arr = $cast_fn($array);
$rows
.iter_mut()
.zip(arr.iter())
.for_each(|(row, maybe_value)| {
- if let Some(v) = maybe_value {
- row.insert($col_name.to_string(), v.into());
+ if let Some(j) = maybe_value.map(Into::into) {
+ row.insert($col_name.to_string(), j);
+ } else if $explicit_nulls {
+ row.insert($col_name.to_string(), Value::Null);
}
});
};
@@ -233,6 +265,7 @@ fn set_column_by_primitive_type<T>(
rows: &mut [JsonMap<String, Value>],
array: &ArrayRef,
col_name: &str,
+ explicit_nulls: bool,
) where
T: ArrowPrimitiveType,
T::Native: JsonSerializable,
@@ -242,9 +275,10 @@ fn set_column_by_primitive_type<T>(
rows.iter_mut()
.zip(primitive_arr.iter())
.for_each(|(row, maybe_value)| {
- // when value is null, we simply skip setting the key
if let Some(j) = maybe_value.and_then(|v| v.into_json_value()) {
row.insert(col_name.to_string(), j);
+ } else if explicit_nulls {
+ row.insert(col_name.to_string(), Value::Null);
}
});
}
@@ -253,52 +287,57 @@ fn set_column_for_json_rows(
rows: &mut [JsonMap<String, Value>],
array: &ArrayRef,
col_name: &str,
+ explicit_nulls: bool,
) -> Result<(), ArrowError> {
match array.data_type() {
DataType::Int8 => {
- set_column_by_primitive_type::<Int8Type>(rows, array, col_name);
+ set_column_by_primitive_type::<Int8Type>(rows, array, col_name, explicit_nulls);
}
DataType::Int16 => {
- set_column_by_primitive_type::<Int16Type>(rows, array, col_name);
+ set_column_by_primitive_type::<Int16Type>(rows, array, col_name, explicit_nulls);
}
DataType::Int32 => {
- set_column_by_primitive_type::<Int32Type>(rows, array, col_name);
+ set_column_by_primitive_type::<Int32Type>(rows, array, col_name, explicit_nulls);
}
DataType::Int64 => {
- set_column_by_primitive_type::<Int64Type>(rows, array, col_name);
+ set_column_by_primitive_type::<Int64Type>(rows, array, col_name, explicit_nulls);
}
DataType::UInt8 => {
- set_column_by_primitive_type::<UInt8Type>(rows, array, col_name);
+ set_column_by_primitive_type::<UInt8Type>(rows, array, col_name, explicit_nulls);
}
DataType::UInt16 => {
- set_column_by_primitive_type::<UInt16Type>(rows, array, col_name);
+ set_column_by_primitive_type::<UInt16Type>(rows, array, col_name, explicit_nulls);
}
DataType::UInt32 => {
- set_column_by_primitive_type::<UInt32Type>(rows, array, col_name);
+ set_column_by_primitive_type::<UInt32Type>(rows, array, col_name, explicit_nulls);
}
DataType::UInt64 => {
- set_column_by_primitive_type::<UInt64Type>(rows, array, col_name);
+ set_column_by_primitive_type::<UInt64Type>(rows, array, col_name, explicit_nulls);
}
DataType::Float16 => {
- set_column_by_primitive_type::<Float16Type>(rows, array, col_name);
+ set_column_by_primitive_type::<Float16Type>(rows, array, col_name, explicit_nulls);
}
DataType::Float32 => {
- set_column_by_primitive_type::<Float32Type>(rows, array, col_name);
+ set_column_by_primitive_type::<Float32Type>(rows, array, col_name, explicit_nulls);
}
DataType::Float64 => {
- set_column_by_primitive_type::<Float64Type>(rows, array, col_name);
+ set_column_by_primitive_type::<Float64Type>(rows, array, col_name, explicit_nulls);
}
DataType::Null => {
- // when value is null, we simply skip setting the key
+ if explicit_nulls {
+ rows.iter_mut().for_each(|row| {
+ row.insert(col_name.to_string(), Value::Null);
+ });
+ }
}
DataType::Boolean => {
- set_column_by_array_type!(as_boolean_array, col_name, rows, array);
+ set_column_by_array_type!(as_boolean_array, col_name, rows, array, explicit_nulls);
}
DataType::Utf8 => {
- set_column_by_array_type!(as_string_array, col_name, rows, array);
+ set_column_by_array_type!(as_string_array, col_name, rows, array, explicit_nulls);
}
DataType::LargeUtf8 => {
- set_column_by_array_type!(as_largestring_array, col_name, rows, array);
+ set_column_by_array_type!(as_largestring_array, col_name, rows, array, explicit_nulls);
}
DataType::Date32
| DataType::Date64
@@ -310,16 +349,19 @@ fn set_column_for_json_rows(
let formatter = ArrayFormatter::try_new(array.as_ref(), &options)?;
let nulls = array.nulls();
rows.iter_mut().enumerate().for_each(|(idx, row)| {
- if nulls.map(|x| x.is_valid(idx)).unwrap_or(true) {
- row.insert(
- col_name.to_string(),
- formatter.value(idx).to_string().into(),
- );
- }
+ let maybe_value = nulls
+ .map(|x| x.is_valid(idx))
+ .unwrap_or(true)
+ .then(|| formatter.value(idx).to_string().into());
+ if let Some(j) = maybe_value {
+ row.insert(col_name.to_string(), j);
+ } else if explicit_nulls {
+ row.insert(col_name.to_string(), Value::Null);
+ };
});
}
DataType::Struct(_) => {
- let inner_objs = struct_array_to_jsonmap_array(array.as_struct())?;
+ let inner_objs = struct_array_to_jsonmap_array(array.as_struct(), explicit_nulls)?;
rows.iter_mut().zip(inner_objs).for_each(|(row, obj)| {
row.insert(col_name.to_string(), Value::Object(obj));
});
@@ -328,8 +370,13 @@ fn set_column_for_json_rows(
let listarr = as_list_array(array);
rows.iter_mut().zip(listarr.iter()).try_for_each(
|(row, maybe_value)| -> Result<(), ArrowError> {
- if let Some(v) = maybe_value {
- row.insert(col_name.to_string(), Value::Array(array_to_json_array(&v)?));
+ let maybe_value = maybe_value
+ .map(|v| array_to_json_array_internal(&v, explicit_nulls).map(Value::Array))
+ .transpose()?;
+ if let Some(j) = maybe_value {
+ row.insert(col_name.to_string(), j);
+ } else if explicit_nulls {
+ row.insert(col_name.to_string(), Value::Null);
}
Ok(())
},
@@ -339,9 +386,13 @@ fn set_column_for_json_rows(
let listarr = as_large_list_array(array);
rows.iter_mut().zip(listarr.iter()).try_for_each(
|(row, maybe_value)| -> Result<(), ArrowError> {
- if let Some(v) = maybe_value {
- let val = array_to_json_array(&v)?;
- row.insert(col_name.to_string(), Value::Array(val));
+ let maybe_value = maybe_value
+ .map(|v| array_to_json_array_internal(&v, explicit_nulls).map(Value::Array))
+ .transpose()?;
+ if let Some(j) = maybe_value {
+ row.insert(col_name.to_string(), j);
+ } else if explicit_nulls {
+ row.insert(col_name.to_string(), Value::Null);
}
Ok(())
},
@@ -350,7 +401,7 @@ fn set_column_for_json_rows(
DataType::Dictionary(_, value_type) => {
let hydrated = arrow_cast::cast::cast(&array, value_type)
.expect("cannot cast dictionary to underlying values");
- set_column_for_json_rows(rows, &hydrated, col_name)?;
+ set_column_for_json_rows(rows, &hydrated, col_name, explicit_nulls)?;
}
DataType::Map(_, _) => {
let maparr = as_map_array(array);
@@ -367,7 +418,7 @@ fn set_column_for_json_rows(
}
let keys = keys.as_string::<i32>();
- let values = array_to_json_array(values)?;
+ let values = array_to_json_array_internal(values, explicit_nulls)?;
let mut kv = keys.iter().zip(values);
@@ -401,6 +452,14 @@ fn set_column_for_json_rows(
/// [`JsonMap`]s (objects)
pub fn record_batches_to_json_rows(
batches: &[&RecordBatch],
+) -> Result<Vec<JsonMap<String, Value>>, ArrowError> {
+ // For backwards compatibility, default to skip nulls
+ record_batches_to_json_rows_internal(batches, false)
+}
+
+fn record_batches_to_json_rows_internal(
+ batches: &[&RecordBatch],
+ explicit_nulls: bool,
) -> Result<Vec<JsonMap<String, Value>>, ArrowError> {
let mut rows: Vec<JsonMap<String, Value>> = iter::repeat(JsonMap::new())
.take(batches.iter().map(|b| b.num_rows()).sum())
@@ -414,7 +473,7 @@ pub fn record_batches_to_json_rows(
let row_slice = &mut rows[base..base + batch.num_rows()];
for (j, col) in batch.columns().iter().enumerate() {
let col_name = schema.field(j).name();
- set_column_for_json_rows(row_slice, col, col_name)?
+ set_column_for_json_rows(row_slice, col, col_name, explicit_nulls)?
}
base += row_count;
}
@@ -450,7 +509,9 @@ pub trait JsonFormat: Debug + Default {
}
}
-/// Produces JSON output with one record per line. For example
+/// Produces JSON output with one record per line.
+///
+/// For example:
///
/// ```json
/// {"foo":1}
@@ -467,7 +528,9 @@ impl JsonFormat for LineDelimited {
}
}
-/// Produces JSON output as a single JSON array. For example
+/// Produces JSON output as a single JSON array.
+///
+/// For example:
///
/// ```json
/// [{"foo":1},{"bar":1}]
@@ -494,16 +557,101 @@ impl JsonFormat for JsonArray {
}
}
-/// A JSON writer which serializes [`RecordBatch`]es to newline delimited JSON objects
+/// A JSON writer which serializes [`RecordBatch`]es to newline delimited JSON objects.
pub type LineDelimitedWriter<W> = Writer<W, LineDelimited>;
-/// A JSON writer which serializes [`RecordBatch`]es to JSON arrays
+/// A JSON writer which serializes [`RecordBatch`]es to JSON arrays.
pub type ArrayWriter<W> = Writer<W, JsonArray>;
+/// JSON writer builder.
+#[derive(Debug, Clone, Default)]
+pub struct WriterBuilder {
+ /// Controls whether null values should be written explicitly for keys
+ /// in objects, or whether the key should be omitted entirely.
+ explicit_nulls: bool,
+}
+
+impl WriterBuilder {
+ /// Create a new builder for configuring JSON writing options.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use arrow_json::{Writer, WriterBuilder};
+ /// # use arrow_json::writer::LineDelimited;
+ /// # use std::fs::File;
+ ///
+ /// fn example() -> Writer<File, LineDelimited> {
+ /// let file = File::create("target/out.json").unwrap();
+ ///
+ /// // create a builder that keeps keys with null values
+ /// let builder = WriterBuilder::new().with_explicit_nulls(true);
+ /// let writer = builder.build::<_, LineDelimited>(file);
+ ///
+ /// writer
+ /// }
+ /// ```
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Returns `true` if this writer is configured to keep keys with null values.
+ pub fn explicit_nulls(&self) -> bool {
+ self.explicit_nulls
+ }
+
+ /// Set whether to keep keys with null values, or to omit writing them.
+ ///
+ /// For example, with [`LineDelimited`] format:
+ ///
+ /// Skip nulls (set to `false`):
+ ///
+ /// ```json
+ /// {"foo":1}
+ /// {"foo":1,"bar":2}
+ /// {}
+ /// ```
+ ///
+ /// Keep nulls (set to `true`):
+ ///
+ /// ```json
+ /// {"foo":1,"bar":null}
+ /// {"foo":1,"bar":2}
+ /// {"foo":null,"bar":null}
+ /// ```
+ ///
+ /// Default is to skip nulls (set to `false`).
+ pub fn with_explicit_nulls(mut self, explicit_nulls: bool) -> Self {
+ self.explicit_nulls = explicit_nulls;
+ self
+ }
+
+ /// Create a new `Writer` with specified `JsonFormat` and builder options.
+ pub fn build<W, F>(self, writer: W) -> Writer<W, F>
+ where
+ W: Write,
+ F: JsonFormat,
+ {
+ Writer {
+ writer,
+ started: false,
+ finished: false,
+ format: F::default(),
+ explicit_nulls: self.explicit_nulls,
+ }
+ }
+}
+
/// A JSON writer which serializes [`RecordBatch`]es to a stream of
-/// `u8` encoded JSON objects. See the module level documentation for
-/// detailed usage and examples. The specific format of the stream is
-/// controlled by the [`JsonFormat`] type parameter.
+/// `u8` encoded JSON objects.
+///
+/// See the module level documentation for detailed usage and examples.
+/// The specific format of the stream is controlled by the [`JsonFormat`]
+/// type parameter.
+///
+/// By default the writer will skip writing keys with null values for
+/// backward compatibility. See [`WriterBuilder`] on how to customize
+/// this behaviour when creating a new writer.
#[derive(Debug)]
pub struct Writer<W, F>
where
@@ -521,6 +669,9 @@ where
/// Determines how the byte stream is formatted
format: F,
+
+ /// Whether keys with null values should be written or skipped
+ explicit_nulls: bool,
}
impl<W, F> Writer<W, F>
@@ -535,6 +686,7 @@ where
started: false,
finished: false,
format: F::default(),
+ explicit_nulls: false,
}
}
@@ -556,7 +708,7 @@ where
/// Convert the `RecordBatch` into JSON rows, and write them to the output
pub fn write(&mut self, batch: &RecordBatch) -> Result<(), ArrowError> {
- for row in record_batches_to_json_rows(&[batch])? {
+ for row in record_batches_to_json_rows_internal(&[batch], self.explicit_nulls)? {
self.write_row(&Value::Object(row))?;
}
Ok(())
@@ -564,7 +716,7 @@ where
/// Convert the [`RecordBatch`] into JSON rows, and write them to the output
pub fn write_batches(&mut self, batches: &[&RecordBatch]) -> Result<(), ArrowError> {
- for row in record_batches_to_json_rows(batches)? {
+ for row in record_batches_to_json_rows_internal(batches, self.explicit_nulls)? {
self.write_row(&Value::Object(row))?;
}
Ok(())
@@ -609,7 +761,7 @@ mod tests {
use serde_json::json;
- use arrow_array::builder::{Int32Builder, MapBuilder, StringBuilder};
+ use arrow_array::builder::{Int32Builder, Int64Builder, MapBuilder, StringBuilder};
use arrow_buffer::{Buffer, ToByteSlice};
use arrow_data::ArrayData;
@@ -1203,7 +1355,7 @@ mod tests {
);
}
- fn test_write_for_file(test_file: &str) {
+ fn test_write_for_file(test_file: &str, remove_nulls: bool) {
let file = File::open(test_file).unwrap();
let mut reader = BufReader::new(file);
let (schema, _) = infer_json_schema(&mut reader, None).unwrap();
@@ -1215,18 +1367,27 @@ mod tests {
let mut buf = Vec::new();
{
- let mut writer = LineDelimitedWriter::new(&mut buf);
- writer.write_batches(&[&batch]).unwrap();
+ if remove_nulls {
+ let mut writer = LineDelimitedWriter::new(&mut buf);
+ writer.write_batches(&[&batch]).unwrap();
+ } else {
+ let mut writer = WriterBuilder::new()
+ .with_explicit_nulls(true)
+ .build::<_, LineDelimited>(&mut buf);
+ writer.write_batches(&[&batch]).unwrap();
+ }
}
let result = String::from_utf8(buf).unwrap();
let expected = read_to_string(test_file).unwrap();
for (r, e) in result.lines().zip(expected.lines()) {
let mut expected_json = serde_json::from_str::<Value>(e).unwrap();
- // remove null value from object to make comparison consistent:
- if let Value::Object(obj) = expected_json {
- expected_json =
- Value::Object(obj.into_iter().filter(|(_, v)| *v != Value::Null).collect());
+ if remove_nulls {
+ // remove null value from object to make comparison consistent:
+ if let Value::Object(obj) = expected_json {
+ expected_json =
+ Value::Object(obj.into_iter().filter(|(_, v)| *v != Value::Null).collect());
+ }
}
assert_eq!(serde_json::from_str::<Value>(r).unwrap(), expected_json,);
}
@@ -1234,17 +1395,22 @@ mod tests {
#[test]
fn write_basic_rows() {
- test_write_for_file("test/data/basic.json");
+ test_write_for_file("test/data/basic.json", true);
}
#[test]
fn write_arrays() {
- test_write_for_file("test/data/arrays.json");
+ test_write_for_file("test/data/arrays.json", true);
}
#[test]
fn write_basic_nulls() {
- test_write_for_file("test/data/basic_nulls.json");
+ test_write_for_file("test/data/basic_nulls.json", true);
+ }
+
+ #[test]
+ fn write_nested_with_nulls() {
+ test_write_for_file("test/data/nested_with_nulls.json", false);
}
#[test]
@@ -1530,4 +1696,233 @@ mod tests {
assert_eq!(array_to_json_array(&map_array).unwrap(), expected_json);
}
+
+ #[test]
+ fn test_writer_explicit_nulls() -> Result<(), ArrowError> {
+ fn nested_list() -> (Arc<ListArray>, Arc<Field>) {
+ let array = Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
+ Some(vec![None, None, None]),
+ Some(vec![Some(1), Some(2), Some(3)]),
+ None,
+ Some(vec![None, None, None]),
+ ]));
+ let field = Arc::new(Field::new("list", array.data_type().clone(), true));
+ // [{"list":[null,null,null]},{"list":[1,2,3]},{"list":null},{"list":[null,null,null]}]
+ (array, field)
+ }
+
+ fn nested_dict() -> (Arc<DictionaryArray<Int32Type>>, Arc<Field>) {
+ let array = Arc::new(DictionaryArray::from_iter(vec![
+ Some("cupcakes"),
+ None,
+ Some("bear"),
+ Some("kuma"),
+ ]));
+ let field = Arc::new(Field::new("dict", array.data_type().clone(), true));
+ // [{"dict":"cupcakes"},{"dict":null},{"dict":"bear"},{"dict":"kuma"}]
+ (array, field)
+ }
+
+ fn nested_map() -> (Arc<MapArray>, Arc<Field>) {
+ let string_builder = StringBuilder::new();
+ let int_builder = Int64Builder::new();
+ let mut builder = MapBuilder::new(None, string_builder, int_builder);
+
+ // [{"foo": 10}, null, {}, {"bar": 20, "baz": 30, "qux": 40}]
+ builder.keys().append_value("foo");
+ builder.values().append_value(10);
+ builder.append(true).unwrap();
+
+ builder.append(false).unwrap();
+
+ builder.append(true).unwrap();
+
+ builder.keys().append_value("bar");
+ builder.values().append_value(20);
+ builder.keys().append_value("baz");
+ builder.values().append_value(30);
+ builder.keys().append_value("qux");
+ builder.values().append_value(40);
+ builder.append(true).unwrap();
+
+ let array = Arc::new(builder.finish());
+ let field = Arc::new(Field::new("map", array.data_type().clone(), true));
+ (array, field)
+ }
+
+ fn root_list() -> (Arc<ListArray>, Field) {
+ let struct_array = StructArray::from(vec![
+ (
+ Arc::new(Field::new("utf8", DataType::Utf8, true)),
+ Arc::new(StringArray::from(vec![Some("a"), Some("b"), None, None])) as ArrayRef,
+ ),
+ (
+ Arc::new(Field::new("int32", DataType::Int32, true)),
+ Arc::new(Int32Array::from(vec![Some(1), None, Some(5), None])) as ArrayRef,
+ ),
+ ]);
+
+ let field = Field::new_list(
+ "list",
+ Field::new("struct", struct_array.data_type().clone(), true),
+ true,
+ );
+
+ // [{"list":[{"int32":1,"utf8":"a"},{"int32":null,"utf8":"b"}]},{"list":null},{"list":[{int32":5,"utf8":null}]},{"list":null}]
+ let entry_offsets = Buffer::from(&[0, 2, 2, 3, 3].to_byte_slice());
+ let data = ArrayData::builder(field.data_type().clone())
+ .len(4)
+ .add_buffer(entry_offsets)
+ .add_child_data(struct_array.into_data())
+ .null_bit_buffer(Some([0b00000101].into()))
+ .build()
+ .unwrap();
+ let array = Arc::new(ListArray::from(data));
+ (array, field)
+ }
+
+ let (nested_list_array, nested_list_field) = nested_list();
+ let (nested_dict_array, nested_dict_field) = nested_dict();
+ let (nested_map_array, nested_map_field) = nested_map();
+ let (root_list_array, root_list_field) = root_list();
+
+ let schema = Schema::new(vec![
+ Field::new("date", DataType::Date32, true),
+ Field::new("null", DataType::Null, true),
+ Field::new_struct(
+ "struct",
+ vec![
+ Arc::new(Field::new("utf8", DataType::Utf8, true)),
+ nested_list_field.clone(),
+ nested_dict_field.clone(),
+ nested_map_field.clone(),
+ ],
+ true,
+ ),
+ root_list_field,
+ ]);
+
+ let arr_date32 = Date32Array::from(vec![Some(0), None, Some(1), None]);
+ let arr_null = NullArray::new(4);
+ let arr_struct = StructArray::from(vec![
+ // [{"utf8":"a"},{"utf8":null},{"utf8":null},{"utf8":"b"}]
+ (
+ Arc::new(Field::new("utf8", DataType::Utf8, true)),
+ Arc::new(StringArray::from(vec![Some("a"), None, None, Some("b")])) as ArrayRef,
+ ),
+ // [{"list":[null,null,null]},{"list":[1,2,3]},{"list":null},{"list":[null,null,null]}]
+ (nested_list_field, nested_list_array as ArrayRef),
+ // [{"dict":"cupcakes"},{"dict":null},{"dict":"bear"},{"dict":"kuma"}]
+ (nested_dict_field, nested_dict_array as ArrayRef),
+ // [{"foo": 10}, null, {}, {"bar": 20, "baz": 30, "qux": 40}]
+ (nested_map_field, nested_map_array as ArrayRef),
+ ]);
+
+ let batch = RecordBatch::try_new(
+ Arc::new(schema),
+ vec![
+ // [{"date":"1970-01-01"},{"date":null},{"date":"1970-01-02"},{"date":null}]
+ Arc::new(arr_date32),
+ // [{"null":null},{"null":null},{"null":null},{"null":null}]
+ Arc::new(arr_null),
+ Arc::new(arr_struct),
+ // [{"list":[{"int32":1,"utf8":"a"},{"int32":null,"utf8":"b"}]},{"list":null},{"list":[{int32":5,"utf8":null}]},{"list":null}]
+ root_list_array,
+ ],
+ )?;
+
+ let mut buf = Vec::new();
+ {
+ let mut writer = WriterBuilder::new()
+ .with_explicit_nulls(true)
+ .build::<_, JsonArray>(&mut buf);
+ writer.write_batches(&[&batch])?;
+ writer.finish()?;
+ }
+
+ let actual = serde_json::from_slice::<Vec<Value>>(&buf).unwrap();
+ let expected = serde_json::from_value::<Vec<Value>>(json!([
+ {
+ "date": "1970-01-01",
+ "list": [
+ {
+ "int32": 1,
+ "utf8": "a"
+ },
+ {
+ "int32": null,
+ "utf8": "b"
+ }
+ ],
+ "null": null,
+ "struct": {
+ "dict": "cupcakes",
+ "list": [
+ null,
+ null,
+ null
+ ],
+ "map": {
+ "foo": 10
+ },
+ "utf8": "a"
+ }
+ },
+ {
+ "date": null,
+ "list": null,
+ "null": null,
+ "struct": {
+ "dict": null,
+ "list": [
+ 1,
+ 2,
+ 3
+ ],
+ "map": null,
+ "utf8": null
+ }
+ },
+ {
+ "date": "1970-01-02",
+ "list": [
+ {
+ "int32": 5,
+ "utf8": null
+ }
+ ],
+ "null": null,
+ "struct": {
+ "dict": "bear",
+ "list": null,
+ "map": {},
+ "utf8": null
+ }
+ },
+ {
+ "date": null,
+ "list": null,
+ "null": null,
+ "struct": {
+ "dict": "kuma",
+ "list": [
+ null,
+ null,
+ null
+ ],
+ "map": {
+ "bar": 20,
+ "baz": 30,
+ "qux": 40
+ },
+ "utf8": "b"
+ }
+ }
+ ]))
+ .unwrap();
+
+ assert_eq!(actual, expected);
+
+ Ok(())
+ }
}
diff --git a/arrow/src/ffi.rs b/arrow/src/ffi.rs
index c13d4c6e5dff..7e4a7bbf2ede 100644
--- a/arrow/src/ffi.rs
+++ b/arrow/src/ffi.rs
@@ -617,8 +617,6 @@ mod tests {
.downcast_ref::<GenericListArray<Offset>>()
.unwrap();
- dbg!(&array);
-
// verify
let expected = GenericListArray::<Offset>::from(list_data);
assert_eq!(&array.value(0), &expected.value(0));
diff --git a/object_store/src/gcp/builder.rs b/object_store/src/gcp/builder.rs
index 5f718d63d94a..7417ea4c8a50 100644
--- a/object_store/src/gcp/builder.rs
+++ b/object_store/src/gcp/builder.rs
@@ -605,7 +605,7 @@ mod tests {
.with_bucket_name("foo")
.with_proxy_url("https://example.com")
.build();
- assert!(dbg!(gcs).is_ok());
+ assert!(gcs.is_ok());
let err = GoogleCloudStorageBuilder::new()
.with_service_account_path(service_account_path.to_str().unwrap())
|
diff --git a/arrow-json/test/data/nested_with_nulls.json b/arrow-json/test/data/nested_with_nulls.json
new file mode 100644
index 000000000000..932565d56063
--- /dev/null
+++ b/arrow-json/test/data/nested_with_nulls.json
@@ -0,0 +1,4 @@
+{"a": null, "b": null, "c": null, "d": {"d1": null, "d2": [null, 1, 2, null]}}
+{"a": null, "b": -3.5, "c": true, "d": {"d1": null, "d2": null}}
+{"a": null, "b": null, "c": false, "d": {"d1": "1970-01-01", "d2": null}}
+{"a": 1, "b": 2.0, "c": false, "d": {"d1": null, "d2": null}}
diff --git a/arrow/tests/array_cast.rs b/arrow/tests/array_cast.rs
index bfe16db5cc4d..c73f4f50ac01 100644
--- a/arrow/tests/array_cast.rs
+++ b/arrow/tests/array_cast.rs
@@ -47,7 +47,6 @@ fn test_cast_timestamp_to_string() {
let a = TimestampMillisecondArray::from(vec![Some(864000000005), Some(1545696000001), None])
.with_timezone("UTC".to_string());
let array = Arc::new(a) as ArrayRef;
- dbg!(&array);
let b = cast(&array, &DataType::Utf8).unwrap();
let c = b.as_any().downcast_ref::<StringArray>().unwrap();
assert_eq!(&DataType::Utf8, c.data_type());
|
arrow_json::LineDelimitedWriter: Write nulls
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
I am trying to convert Parquet data written using Avro Parquet Writer of Java. This parquet includes the Avro Schema inside the key `parquet.avro.schema` of the metadata, I want to convert this parquet data back to Avro using this schema and programmed in Rust.
I have tried to solve this challenge by converting Parquet into a json with string `arrow_json::LineDelimitedWriter` and then read this data with `serde_json` and serialise to Avro. In Avro Serializer I need that nullable fields are provided as `Option<T>`. The problem is that when I write the data into JSON null fields are skipped and I can't recover them as Options with `serde_json`
**Describe the solution you'd like**
I would like that `arrow_json` has a parameter for specifying if you want to output the null field.
|
2023-11-12T00:11:46Z
|
49.0
|
a9470d3eb083303350fc109f94865666fd0f062f
|
|
apache/arrow-rs
| 5,055
|
apache__arrow-rs-5055
|
[
"1474"
] |
1d1693777e13e0bc9e0b5326f1256d629278d4bd
|
diff --git a/parquet/src/arrow/array_reader/byte_array.rs b/parquet/src/arrow/array_reader/byte_array.rs
index 4612f816146a..01666c0af4e6 100644
--- a/parquet/src/arrow/array_reader/byte_array.rs
+++ b/parquet/src/arrow/array_reader/byte_array.rs
@@ -29,12 +29,12 @@ use crate::data_type::Int32Type;
use crate::encodings::decoding::{Decoder, DeltaBitPackDecoder};
use crate::errors::{ParquetError, Result};
use crate::schema::types::ColumnDescPtr;
-use crate::util::memory::ByteBufferPtr;
use arrow_array::{
Array, ArrayRef, BinaryArray, Decimal128Array, Decimal256Array, OffsetSizeTrait,
};
use arrow_buffer::{i256, Buffer};
use arrow_schema::DataType as ArrowType;
+use bytes::Bytes;
use std::any::Any;
use std::ops::Range;
use std::sync::Arc;
@@ -189,7 +189,7 @@ impl<I: OffsetSizeTrait + ScalarValue> ColumnValueDecoder
fn set_dict(
&mut self,
- buf: ByteBufferPtr,
+ buf: Bytes,
num_values: u32,
encoding: Encoding,
_is_sorted: bool,
@@ -219,7 +219,7 @@ impl<I: OffsetSizeTrait + ScalarValue> ColumnValueDecoder
fn set_data(
&mut self,
encoding: Encoding,
- data: ByteBufferPtr,
+ data: Bytes,
num_levels: usize,
num_values: Option<usize>,
) -> Result<()> {
@@ -263,7 +263,7 @@ pub enum ByteArrayDecoder {
impl ByteArrayDecoder {
pub fn new(
encoding: Encoding,
- data: ByteBufferPtr,
+ data: Bytes,
num_levels: usize,
num_values: Option<usize>,
validate_utf8: bool,
@@ -339,7 +339,7 @@ impl ByteArrayDecoder {
/// Decoder from [`Encoding::PLAIN`] data to [`OffsetBuffer`]
pub struct ByteArrayDecoderPlain {
- buf: ByteBufferPtr,
+ buf: Bytes,
offset: usize,
validate_utf8: bool,
@@ -350,7 +350,7 @@ pub struct ByteArrayDecoderPlain {
impl ByteArrayDecoderPlain {
pub fn new(
- buf: ByteBufferPtr,
+ buf: Bytes,
num_levels: usize,
num_values: Option<usize>,
validate_utf8: bool,
@@ -438,16 +438,16 @@ impl ByteArrayDecoderPlain {
/// Decoder from [`Encoding::DELTA_LENGTH_BYTE_ARRAY`] data to [`OffsetBuffer`]
pub struct ByteArrayDecoderDeltaLength {
lengths: Vec<i32>,
- data: ByteBufferPtr,
+ data: Bytes,
length_offset: usize,
data_offset: usize,
validate_utf8: bool,
}
impl ByteArrayDecoderDeltaLength {
- fn new(data: ByteBufferPtr, validate_utf8: bool) -> Result<Self> {
+ fn new(data: Bytes, validate_utf8: bool) -> Result<Self> {
let mut len_decoder = DeltaBitPackDecoder::<Int32Type>::new();
- len_decoder.set_data(data.all(), 0)?;
+ len_decoder.set_data(data.clone(), 0)?;
let values = len_decoder.values_left();
let mut lengths = vec![0; values];
@@ -522,7 +522,7 @@ pub struct ByteArrayDecoderDelta {
}
impl ByteArrayDecoderDelta {
- fn new(data: ByteBufferPtr, validate_utf8: bool) -> Result<Self> {
+ fn new(data: Bytes, validate_utf8: bool) -> Result<Self> {
Ok(Self {
decoder: DeltaByteArrayDecoder::new(data)?,
validate_utf8,
@@ -558,7 +558,7 @@ pub struct ByteArrayDecoderDictionary {
}
impl ByteArrayDecoderDictionary {
- fn new(data: ByteBufferPtr, num_levels: usize, num_values: Option<usize>) -> Self {
+ fn new(data: Bytes, num_levels: usize, num_values: Option<usize>) -> Self {
Self {
decoder: DictIndexDecoder::new(data, num_levels, num_values),
}
diff --git a/parquet/src/arrow/array_reader/byte_array_dictionary.rs b/parquet/src/arrow/array_reader/byte_array_dictionary.rs
index 841f5a95fd4e..0d216fa08327 100644
--- a/parquet/src/arrow/array_reader/byte_array_dictionary.rs
+++ b/parquet/src/arrow/array_reader/byte_array_dictionary.rs
@@ -23,6 +23,7 @@ use std::sync::Arc;
use arrow_array::{Array, ArrayRef, OffsetSizeTrait};
use arrow_buffer::{ArrowNativeType, Buffer};
use arrow_schema::DataType as ArrowType;
+use bytes::Bytes;
use crate::arrow::array_reader::byte_array::{ByteArrayDecoder, ByteArrayDecoderPlain};
use crate::arrow::array_reader::{read_records, skip_records, ArrayReader};
@@ -39,7 +40,6 @@ use crate::encodings::rle::RleDecoder;
use crate::errors::{ParquetError, Result};
use crate::schema::types::ColumnDescPtr;
use crate::util::bit_util::FromBytes;
-use crate::util::memory::ByteBufferPtr;
/// A macro to reduce verbosity of [`make_byte_array_dictionary_reader`]
macro_rules! make_reader {
@@ -253,7 +253,7 @@ where
fn set_dict(
&mut self,
- buf: ByteBufferPtr,
+ buf: Bytes,
num_values: u32,
encoding: Encoding,
_is_sorted: bool,
@@ -286,7 +286,7 @@ where
fn set_data(
&mut self,
encoding: Encoding,
- data: ByteBufferPtr,
+ data: Bytes,
num_levels: usize,
num_values: Option<usize>,
) -> Result<()> {
@@ -294,7 +294,7 @@ where
Encoding::RLE_DICTIONARY | Encoding::PLAIN_DICTIONARY => {
let bit_width = data[0];
let mut decoder = RleDecoder::new(bit_width);
- decoder.set_data(data.start_from(1));
+ decoder.set_data(data.slice(1..));
MaybeDictionaryDecoder::Dict {
decoder,
max_remaining_values: num_values.unwrap_or(num_levels),
diff --git a/parquet/src/arrow/array_reader/fixed_len_byte_array.rs b/parquet/src/arrow/array_reader/fixed_len_byte_array.rs
index b06091b6b57a..3b1a50ebcce8 100644
--- a/parquet/src/arrow/array_reader/fixed_len_byte_array.rs
+++ b/parquet/src/arrow/array_reader/fixed_len_byte_array.rs
@@ -26,7 +26,6 @@ use crate::column::page::PageIterator;
use crate::column::reader::decoder::{ColumnValueDecoder, ValuesBufferSlice};
use crate::errors::{ParquetError, Result};
use crate::schema::types::ColumnDescPtr;
-use crate::util::memory::ByteBufferPtr;
use arrow_array::{
ArrayRef, Decimal128Array, Decimal256Array, FixedSizeBinaryArray,
IntervalDayTimeArray, IntervalYearMonthArray,
@@ -34,6 +33,7 @@ use arrow_array::{
use arrow_buffer::{i256, Buffer};
use arrow_data::ArrayDataBuilder;
use arrow_schema::{DataType as ArrowType, IntervalUnit};
+use bytes::Bytes;
use std::any::Any;
use std::ops::Range;
use std::sync::Arc;
@@ -298,7 +298,7 @@ impl ValuesBuffer for FixedLenByteArrayBuffer {
struct ValueDecoder {
byte_length: usize,
- dict_page: Option<ByteBufferPtr>,
+ dict_page: Option<Bytes>,
decoder: Option<Decoder>,
}
@@ -315,7 +315,7 @@ impl ColumnValueDecoder for ValueDecoder {
fn set_dict(
&mut self,
- buf: ByteBufferPtr,
+ buf: Bytes,
num_values: u32,
encoding: Encoding,
_is_sorted: bool,
@@ -345,7 +345,7 @@ impl ColumnValueDecoder for ValueDecoder {
fn set_data(
&mut self,
encoding: Encoding,
- data: ByteBufferPtr,
+ data: Bytes,
num_levels: usize,
num_values: Option<usize>,
) -> Result<()> {
@@ -434,7 +434,7 @@ impl ColumnValueDecoder for ValueDecoder {
}
enum Decoder {
- Plain { buf: ByteBufferPtr, offset: usize },
+ Plain { buf: Bytes, offset: usize },
Dict { decoder: DictIndexDecoder },
Delta { decoder: DeltaByteArrayDecoder },
}
diff --git a/parquet/src/arrow/arrow_writer/byte_array.rs b/parquet/src/arrow/arrow_writer/byte_array.rs
index 3db2e4a6a063..28c7c3b00540 100644
--- a/parquet/src/arrow/arrow_writer/byte_array.rs
+++ b/parquet/src/arrow/arrow_writer/byte_array.rs
@@ -236,7 +236,7 @@ impl FallbackEncoder {
let lengths = lengths.flush_buffer()?;
let mut out = Vec::with_capacity(lengths.len() + buffer.len());
- out.extend_from_slice(lengths.data());
+ out.extend_from_slice(&lengths);
out.extend_from_slice(buffer);
buffer.clear();
(out, Encoding::DELTA_LENGTH_BYTE_ARRAY)
@@ -252,8 +252,8 @@ impl FallbackEncoder {
let mut out =
Vec::with_capacity(prefix_lengths.len() + suffix_lengths.len() + buffer.len());
- out.extend_from_slice(prefix_lengths.data());
- out.extend_from_slice(suffix_lengths.data());
+ out.extend_from_slice(&prefix_lengths);
+ out.extend_from_slice(&suffix_lengths);
out.extend_from_slice(buffer);
buffer.clear();
last_value.clear();
diff --git a/parquet/src/arrow/arrow_writer/mod.rs b/parquet/src/arrow/arrow_writer/mod.rs
index a9cd1afb2479..eca1dea791be 100644
--- a/parquet/src/arrow/arrow_writer/mod.rs
+++ b/parquet/src/arrow/arrow_writer/mod.rs
@@ -331,7 +331,7 @@ impl PageWriter for ArrowPageWriter {
buf.length += compressed_size;
buf.data.push(header);
- buf.data.push(data.into());
+ buf.data.push(data);
Ok(spec)
}
diff --git a/parquet/src/arrow/decoder/delta_byte_array.rs b/parquet/src/arrow/decoder/delta_byte_array.rs
index c731cfea97e9..7686a4292c43 100644
--- a/parquet/src/arrow/decoder/delta_byte_array.rs
+++ b/parquet/src/arrow/decoder/delta_byte_array.rs
@@ -15,16 +15,17 @@
// specific language governing permissions and limitations
// under the License.
+use bytes::Bytes;
+
use crate::data_type::Int32Type;
use crate::encodings::decoding::{Decoder, DeltaBitPackDecoder};
use crate::errors::{ParquetError, Result};
-use crate::util::memory::ByteBufferPtr;
/// Decoder for `Encoding::DELTA_BYTE_ARRAY`
pub struct DeltaByteArrayDecoder {
prefix_lengths: Vec<i32>,
suffix_lengths: Vec<i32>,
- data: ByteBufferPtr,
+ data: Bytes,
length_offset: usize,
data_offset: usize,
last_value: Vec<u8>,
@@ -32,16 +33,16 @@ pub struct DeltaByteArrayDecoder {
impl DeltaByteArrayDecoder {
/// Create a new [`DeltaByteArrayDecoder`] with the provided data page
- pub fn new(data: ByteBufferPtr) -> Result<Self> {
+ pub fn new(data: Bytes) -> Result<Self> {
let mut prefix = DeltaBitPackDecoder::<Int32Type>::new();
- prefix.set_data(data.all(), 0)?;
+ prefix.set_data(data.clone(), 0)?;
let num_prefix = prefix.values_left();
let mut prefix_lengths = vec![0; num_prefix];
assert_eq!(prefix.get(&mut prefix_lengths)?, num_prefix);
let mut suffix = DeltaBitPackDecoder::<Int32Type>::new();
- suffix.set_data(data.start_from(prefix.get_offset()), 0)?;
+ suffix.set_data(data.slice(prefix.get_offset()..), 0)?;
let num_suffix = suffix.values_left();
let mut suffix_lengths = vec![0; num_suffix];
diff --git a/parquet/src/arrow/decoder/dictionary_index.rs b/parquet/src/arrow/decoder/dictionary_index.rs
index 32efd564dffb..38f2b058360c 100644
--- a/parquet/src/arrow/decoder/dictionary_index.rs
+++ b/parquet/src/arrow/decoder/dictionary_index.rs
@@ -15,9 +15,10 @@
// specific language governing permissions and limitations
// under the License.
+use bytes::Bytes;
+
use crate::encodings::rle::RleDecoder;
use crate::errors::Result;
-use crate::util::memory::ByteBufferPtr;
/// Decoder for `Encoding::RLE_DICTIONARY` indices
pub struct DictIndexDecoder {
@@ -41,10 +42,10 @@ pub struct DictIndexDecoder {
impl DictIndexDecoder {
/// Create a new [`DictIndexDecoder`] with the provided data page, the number of levels
/// associated with this data page, and the number of non-null values (if known)
- pub fn new(data: ByteBufferPtr, num_levels: usize, num_values: Option<usize>) -> Self {
+ pub fn new(data: Bytes, num_levels: usize, num_values: Option<usize>) -> Self {
let bit_width = data[0];
let mut decoder = RleDecoder::new(bit_width);
- decoder.set_data(data.start_from(1));
+ decoder.set_data(data.slice(1..));
Self {
decoder,
diff --git a/parquet/src/arrow/record_reader/definition_levels.rs b/parquet/src/arrow/record_reader/definition_levels.rs
index 20cda536ae1c..9009c596c4bf 100644
--- a/parquet/src/arrow/record_reader/definition_levels.rs
+++ b/parquet/src/arrow/record_reader/definition_levels.rs
@@ -20,6 +20,7 @@ use std::ops::Range;
use arrow_array::builder::BooleanBufferBuilder;
use arrow_buffer::bit_chunk_iterator::UnalignedBitChunk;
use arrow_buffer::Buffer;
+use bytes::Bytes;
use crate::arrow::buffer::bit_util::count_set_bits;
use crate::basic::Encoding;
@@ -28,7 +29,6 @@ use crate::column::reader::decoder::{
};
use crate::errors::{ParquetError, Result};
use crate::schema::types::ColumnDescPtr;
-use crate::util::memory::ByteBufferPtr;
use super::buffer::ScalarBuffer;
@@ -152,7 +152,7 @@ impl DefinitionLevelBufferDecoder {
impl ColumnLevelDecoder for DefinitionLevelBufferDecoder {
type Slice = DefinitionLevelBuffer;
- fn set_data(&mut self, encoding: Encoding, data: ByteBufferPtr) {
+ fn set_data(&mut self, encoding: Encoding, data: Bytes) {
match &mut self.decoder {
MaybePacked::Packed(d) => d.set_data(encoding, data),
MaybePacked::Fallback(d) => d.set_data(encoding, data),
@@ -219,7 +219,7 @@ impl DefinitionLevelDecoder for DefinitionLevelBufferDecoder {
/// [RLE]: https://github.com/apache/parquet-format/blob/master/Encodings.md#run-length-encoding--bit-packing-hybrid-rle--3
/// [BIT_PACKED]: https://github.com/apache/parquet-format/blob/master/Encodings.md#bit-packed-deprecated-bit_packed--4
struct PackedDecoder {
- data: ByteBufferPtr,
+ data: Bytes,
data_offset: usize,
rle_left: usize,
rle_value: bool,
@@ -278,7 +278,7 @@ impl PackedDecoder {
impl PackedDecoder {
fn new() -> Self {
Self {
- data: ByteBufferPtr::new(vec![]),
+ data: Bytes::from(vec![]),
data_offset: 0,
rle_left: 0,
rle_value: false,
@@ -287,7 +287,7 @@ impl PackedDecoder {
}
}
- fn set_data(&mut self, encoding: Encoding, data: ByteBufferPtr) {
+ fn set_data(&mut self, encoding: Encoding, data: Bytes) {
self.rle_left = 0;
self.rle_value = false;
self.packed_offset = 0;
@@ -385,7 +385,7 @@ mod tests {
let encoded = encoder.consume();
let mut decoder = PackedDecoder::new();
- decoder.set_data(Encoding::RLE, ByteBufferPtr::new(encoded));
+ decoder.set_data(Encoding::RLE, encoded.into());
// Decode data in random length intervals
let mut decoded = BooleanBufferBuilder::new(len);
@@ -424,7 +424,7 @@ mod tests {
let encoded = encoder.consume();
let mut decoder = PackedDecoder::new();
- decoder.set_data(Encoding::RLE, ByteBufferPtr::new(encoded));
+ decoder.set_data(Encoding::RLE, encoded.into());
let mut skip_value = 0;
let mut read_value = 0;
diff --git a/parquet/src/column/page.rs b/parquet/src/column/page.rs
index 933e42386272..947a633f48a2 100644
--- a/parquet/src/column/page.rs
+++ b/parquet/src/column/page.rs
@@ -17,11 +17,12 @@
//! Contains Parquet Page definitions and page reader interface.
+use bytes::Bytes;
+
use crate::basic::{Encoding, PageType};
use crate::errors::{ParquetError, Result};
use crate::file::{metadata::ColumnChunkMetaData, statistics::Statistics};
use crate::format::PageHeader;
-use crate::util::memory::ByteBufferPtr;
/// Parquet Page definition.
///
@@ -31,7 +32,7 @@ use crate::util::memory::ByteBufferPtr;
#[derive(Clone)]
pub enum Page {
DataPage {
- buf: ByteBufferPtr,
+ buf: Bytes,
num_values: u32,
encoding: Encoding,
def_level_encoding: Encoding,
@@ -39,7 +40,7 @@ pub enum Page {
statistics: Option<Statistics>,
},
DataPageV2 {
- buf: ByteBufferPtr,
+ buf: Bytes,
num_values: u32,
encoding: Encoding,
num_nulls: u32,
@@ -50,7 +51,7 @@ pub enum Page {
statistics: Option<Statistics>,
},
DictionaryPage {
- buf: ByteBufferPtr,
+ buf: Bytes,
num_values: u32,
encoding: Encoding,
is_sorted: bool,
@@ -68,7 +69,7 @@ impl Page {
}
/// Returns internal byte buffer reference for this page.
- pub fn buffer(&self) -> &ByteBufferPtr {
+ pub fn buffer(&self) -> &Bytes {
match self {
Page::DataPage { ref buf, .. } => buf,
Page::DataPageV2 { ref buf, .. } => buf,
@@ -159,7 +160,7 @@ impl CompressedPage {
/// Returns slice of compressed buffer in the page.
pub fn data(&self) -> &[u8] {
- self.compressed_page.buffer().data()
+ self.compressed_page.buffer()
}
/// Returns the thrift page header
@@ -370,7 +371,7 @@ mod tests {
#[test]
fn test_page() {
let data_page = Page::DataPage {
- buf: ByteBufferPtr::new(vec![0, 1, 2]),
+ buf: Bytes::from(vec![0, 1, 2]),
num_values: 10,
encoding: Encoding::PLAIN,
def_level_encoding: Encoding::RLE,
@@ -378,7 +379,7 @@ mod tests {
statistics: Some(Statistics::int32(Some(1), Some(2), None, 1, true)),
};
assert_eq!(data_page.page_type(), PageType::DATA_PAGE);
- assert_eq!(data_page.buffer().data(), vec![0, 1, 2].as_slice());
+ assert_eq!(data_page.buffer(), vec![0, 1, 2].as_slice());
assert_eq!(data_page.num_values(), 10);
assert_eq!(data_page.encoding(), Encoding::PLAIN);
assert_eq!(
@@ -387,7 +388,7 @@ mod tests {
);
let data_page_v2 = Page::DataPageV2 {
- buf: ByteBufferPtr::new(vec![0, 1, 2]),
+ buf: Bytes::from(vec![0, 1, 2]),
num_values: 10,
encoding: Encoding::PLAIN,
num_nulls: 5,
@@ -398,7 +399,7 @@ mod tests {
statistics: Some(Statistics::int32(Some(1), Some(2), None, 1, true)),
};
assert_eq!(data_page_v2.page_type(), PageType::DATA_PAGE_V2);
- assert_eq!(data_page_v2.buffer().data(), vec![0, 1, 2].as_slice());
+ assert_eq!(data_page_v2.buffer(), vec![0, 1, 2].as_slice());
assert_eq!(data_page_v2.num_values(), 10);
assert_eq!(data_page_v2.encoding(), Encoding::PLAIN);
assert_eq!(
@@ -407,13 +408,13 @@ mod tests {
);
let dict_page = Page::DictionaryPage {
- buf: ByteBufferPtr::new(vec![0, 1, 2]),
+ buf: Bytes::from(vec![0, 1, 2]),
num_values: 10,
encoding: Encoding::PLAIN,
is_sorted: false,
};
assert_eq!(dict_page.page_type(), PageType::DICTIONARY_PAGE);
- assert_eq!(dict_page.buffer().data(), vec![0, 1, 2].as_slice());
+ assert_eq!(dict_page.buffer(), vec![0, 1, 2].as_slice());
assert_eq!(dict_page.num_values(), 10);
assert_eq!(dict_page.encoding(), Encoding::PLAIN);
assert_eq!(dict_page.statistics(), None);
@@ -422,7 +423,7 @@ mod tests {
#[test]
fn test_compressed_page() {
let data_page = Page::DataPage {
- buf: ByteBufferPtr::new(vec![0, 1, 2]),
+ buf: Bytes::from(vec![0, 1, 2]),
num_values: 10,
encoding: Encoding::PLAIN,
def_level_encoding: Encoding::RLE,
diff --git a/parquet/src/column/reader.rs b/parquet/src/column/reader.rs
index 854e5d994ee8..adfcd6390720 100644
--- a/parquet/src/column/reader.rs
+++ b/parquet/src/column/reader.rs
@@ -17,6 +17,8 @@
//! Contains column reader API.
+use bytes::Bytes;
+
use super::page::{Page, PageReader};
use crate::basic::*;
use crate::column::reader::decoder::{
@@ -27,7 +29,6 @@ use crate::data_type::*;
use crate::errors::{ParquetError, Result};
use crate::schema::types::ColumnDescPtr;
use crate::util::bit_util::{ceil, num_required_bits, read_num_bytes};
-use crate::util::memory::ByteBufferPtr;
pub(crate) mod decoder;
@@ -474,7 +475,7 @@ where
max_rep_level,
num_values,
rep_level_encoding,
- buf.start_from(offset),
+ buf.slice(offset..),
)?;
offset += bytes_read;
@@ -492,7 +493,7 @@ where
max_def_level,
num_values,
def_level_encoding,
- buf.start_from(offset),
+ buf.slice(offset..),
)?;
offset += bytes_read;
@@ -504,7 +505,7 @@ where
self.values_decoder.set_data(
encoding,
- buf.start_from(offset),
+ buf.slice(offset..),
num_values as usize,
None,
)?;
@@ -540,7 +541,7 @@ where
self.rep_level_decoder.as_mut().unwrap().set_data(
Encoding::RLE,
- buf.range(0, rep_levels_byte_len as usize),
+ buf.slice(..rep_levels_byte_len as usize),
);
}
@@ -549,18 +550,16 @@ where
if self.descr.max_def_level() > 0 {
self.def_level_decoder.as_mut().unwrap().set_data(
Encoding::RLE,
- buf.range(
- rep_levels_byte_len as usize,
- def_levels_byte_len as usize,
+ buf.slice(
+ rep_levels_byte_len as usize
+ ..(rep_levels_byte_len + def_levels_byte_len) as usize,
),
);
}
self.values_decoder.set_data(
encoding,
- buf.start_from(
- (rep_levels_byte_len + def_levels_byte_len) as usize,
- ),
+ buf.slice((rep_levels_byte_len + def_levels_byte_len) as usize..),
num_values as usize,
Some((num_values - num_nulls) as usize),
)?;
@@ -595,13 +594,16 @@ fn parse_v1_level(
max_level: i16,
num_buffered_values: u32,
encoding: Encoding,
- buf: ByteBufferPtr,
-) -> Result<(usize, ByteBufferPtr)> {
+ buf: Bytes,
+) -> Result<(usize, Bytes)> {
match encoding {
Encoding::RLE => {
let i32_size = std::mem::size_of::<i32>();
let data_size = read_num_bytes::<i32>(i32_size, buf.as_ref()) as usize;
- Ok((i32_size + data_size, buf.range(i32_size, data_size)))
+ Ok((
+ i32_size + data_size,
+ buf.slice(i32_size..i32_size + data_size),
+ ))
}
Encoding::BIT_PACKED => {
let bit_width = num_required_bits(max_level as u64);
@@ -609,7 +611,7 @@ fn parse_v1_level(
(num_buffered_values as usize * bit_width as usize) as i64,
8,
) as usize;
- Ok((num_bytes, buf.range(0, num_bytes)))
+ Ok((num_bytes, buf.slice(..num_bytes)))
}
_ => Err(general_err!("invalid level encoding: {}", encoding)),
}
diff --git a/parquet/src/column/reader/decoder.rs b/parquet/src/column/reader/decoder.rs
index ec57c4032574..ef62724689a8 100644
--- a/parquet/src/column/reader/decoder.rs
+++ b/parquet/src/column/reader/decoder.rs
@@ -18,6 +18,8 @@
use std::collections::HashMap;
use std::ops::Range;
+use bytes::Bytes;
+
use crate::basic::Encoding;
use crate::data_type::DataType;
use crate::encodings::{
@@ -26,10 +28,7 @@ use crate::encodings::{
};
use crate::errors::{ParquetError, Result};
use crate::schema::types::ColumnDescPtr;
-use crate::util::{
- bit_util::{num_required_bits, BitReader},
- memory::ByteBufferPtr,
-};
+use crate::util::bit_util::{num_required_bits, BitReader};
/// A slice of levels buffer data that is written to by a [`ColumnLevelDecoder`]
pub trait LevelsBufferSlice {
@@ -67,7 +66,7 @@ pub trait ColumnLevelDecoder {
type Slice: LevelsBufferSlice + ?Sized;
/// Set data for this [`ColumnLevelDecoder`]
- fn set_data(&mut self, encoding: Encoding, data: ByteBufferPtr);
+ fn set_data(&mut self, encoding: Encoding, data: Bytes);
}
pub trait RepetitionLevelDecoder: ColumnLevelDecoder {
@@ -132,7 +131,7 @@ pub trait ColumnValueDecoder {
/// Set the current dictionary page
fn set_dict(
&mut self,
- buf: ByteBufferPtr,
+ buf: Bytes,
num_values: u32,
encoding: Encoding,
is_sorted: bool,
@@ -152,7 +151,7 @@ pub trait ColumnValueDecoder {
fn set_data(
&mut self,
encoding: Encoding,
- data: ByteBufferPtr,
+ data: Bytes,
num_levels: usize,
num_values: Option<usize>,
) -> Result<()>;
@@ -197,7 +196,7 @@ impl<T: DataType> ColumnValueDecoder for ColumnValueDecoderImpl<T> {
fn set_dict(
&mut self,
- buf: ByteBufferPtr,
+ buf: Bytes,
num_values: u32,
mut encoding: Encoding,
_is_sorted: bool,
@@ -229,7 +228,7 @@ impl<T: DataType> ColumnValueDecoder for ColumnValueDecoderImpl<T> {
fn set_data(
&mut self,
mut encoding: Encoding,
- data: ByteBufferPtr,
+ data: Bytes,
num_levels: usize,
num_values: Option<usize>,
) -> Result<()> {
@@ -294,7 +293,7 @@ enum LevelDecoder {
}
impl LevelDecoder {
- fn new(encoding: Encoding, data: ByteBufferPtr, bit_width: u8) -> Self {
+ fn new(encoding: Encoding, data: Bytes, bit_width: u8) -> Self {
match encoding {
Encoding::RLE => {
let mut decoder = RleDecoder::new(bit_width);
@@ -335,7 +334,7 @@ impl DefinitionLevelDecoderImpl {
impl ColumnLevelDecoder for DefinitionLevelDecoderImpl {
type Slice = [i16];
- fn set_data(&mut self, encoding: Encoding, data: ByteBufferPtr) {
+ fn set_data(&mut self, encoding: Encoding, data: Bytes) {
self.decoder = Some(LevelDecoder::new(encoding, data, self.bit_width))
}
}
@@ -426,7 +425,7 @@ impl RepetitionLevelDecoderImpl {
impl ColumnLevelDecoder for RepetitionLevelDecoderImpl {
type Slice = [i16];
- fn set_data(&mut self, encoding: Encoding, data: ByteBufferPtr) {
+ fn set_data(&mut self, encoding: Encoding, data: Bytes) {
self.decoder = Some(LevelDecoder::new(encoding, data, self.bit_width));
self.buffer_len = 0;
self.buffer_offset = 0;
@@ -511,7 +510,7 @@ mod tests {
let mut encoder = RleEncoder::new(1, 1024);
encoder.put(0);
(0..3).for_each(|_| encoder.put(1));
- let data = ByteBufferPtr::new(encoder.consume());
+ let data = Bytes::from(encoder.consume());
let mut decoder = RepetitionLevelDecoderImpl::new(1);
decoder.set_data(Encoding::RLE, data.clone());
@@ -537,7 +536,7 @@ mod tests {
for v in &encoded {
encoder.put(*v as _)
}
- let data = ByteBufferPtr::new(encoder.consume());
+ let data = Bytes::from(encoder.consume());
let mut decoder = RepetitionLevelDecoderImpl::new(5);
decoder.set_data(Encoding::RLE, data);
diff --git a/parquet/src/column/writer/encoder.rs b/parquet/src/column/writer/encoder.rs
index 5fd0f9e194d2..2273ae777444 100644
--- a/parquet/src/column/writer/encoder.rs
+++ b/parquet/src/column/writer/encoder.rs
@@ -15,6 +15,8 @@
// specific language governing permissions and limitations
// under the License.
+use bytes::Bytes;
+
use crate::basic::{Encoding, Type};
use crate::bloom_filter::Sbbf;
use crate::column::writer::{
@@ -26,7 +28,6 @@ use crate::encodings::encoding::{get_encoder, DictEncoder, Encoder};
use crate::errors::{ParquetError, Result};
use crate::file::properties::{EnabledStatistics, WriterProperties};
use crate::schema::types::{ColumnDescPtr, ColumnDescriptor};
-use crate::util::memory::ByteBufferPtr;
/// A collection of [`ParquetValueType`] encoded by a [`ColumnValueEncoder`]
pub trait ColumnValues {
@@ -49,14 +50,14 @@ impl<T: ParquetValueType> ColumnValues for [T] {
/// The encoded data for a dictionary page
pub struct DictionaryPage {
- pub buf: ByteBufferPtr,
+ pub buf: Bytes,
pub num_values: usize,
pub is_sorted: bool,
}
/// The encoded values for a data page, with optional statistics
pub struct DataPageValues<T> {
- pub buf: ByteBufferPtr,
+ pub buf: Bytes,
pub num_values: usize,
pub encoding: Encoding,
pub min_value: Option<T>,
diff --git a/parquet/src/column/writer/mod.rs b/parquet/src/column/writer/mod.rs
index 307804e7dc5c..60db90c5d46d 100644
--- a/parquet/src/column/writer/mod.rs
+++ b/parquet/src/column/writer/mod.rs
@@ -17,6 +17,8 @@
//! Contains column writer API.
+use bytes::Bytes;
+
use crate::bloom_filter::Sbbf;
use crate::format::{ColumnIndex, OffsetIndex};
use std::collections::{BTreeSet, VecDeque};
@@ -38,7 +40,6 @@ use crate::file::{
properties::{WriterProperties, WriterPropertiesPtr, WriterVersion},
};
use crate::schema::types::{ColumnDescPtr, ColumnDescriptor};
-use crate::util::memory::ByteBufferPtr;
pub(crate) mod encoder;
@@ -731,7 +732,7 @@ impl<'a, E: ColumnValueEncoder> GenericColumnWriter<'a, E> {
);
}
- buffer.extend_from_slice(values_data.buf.data());
+ buffer.extend_from_slice(&values_data.buf);
let uncompressed_size = buffer.len();
if let Some(ref mut cmpr) = self.compressor {
@@ -741,7 +742,7 @@ impl<'a, E: ColumnValueEncoder> GenericColumnWriter<'a, E> {
}
let data_page = Page::DataPage {
- buf: ByteBufferPtr::new(buffer),
+ buf: buffer.into(),
num_values: self.page_metrics.num_buffered_values,
encoding: values_data.encoding,
def_level_encoding: Encoding::RLE,
@@ -774,13 +775,13 @@ impl<'a, E: ColumnValueEncoder> GenericColumnWriter<'a, E> {
// Data Page v2 compresses values only.
match self.compressor {
Some(ref mut cmpr) => {
- cmpr.compress(values_data.buf.data(), &mut buffer)?;
+ cmpr.compress(&values_data.buf, &mut buffer)?;
}
- None => buffer.extend_from_slice(values_data.buf.data()),
+ None => buffer.extend_from_slice(&values_data.buf),
}
let data_page = Page::DataPageV2 {
- buf: ByteBufferPtr::new(buffer),
+ buf: buffer.into(),
num_values: self.page_metrics.num_buffered_values,
encoding: values_data.encoding,
num_nulls: self.page_metrics.num_page_nulls as u32,
@@ -920,8 +921,8 @@ impl<'a, E: ColumnValueEncoder> GenericColumnWriter<'a, E> {
if let Some(ref mut cmpr) = self.compressor {
let mut output_buf = Vec::with_capacity(uncompressed_size);
- cmpr.compress(page.buf.data(), &mut output_buf)?;
- page.buf = ByteBufferPtr::new(output_buf);
+ cmpr.compress(&page.buf, &mut output_buf)?;
+ page.buf = Bytes::from(output_buf);
}
let dict_page = Page::DictionaryPage {
@@ -2350,10 +2351,10 @@ mod tests {
let mut data = vec![FixedLenByteArray::default(); 3];
// This is the expected min value - "aaa..."
- data[0].set_data(ByteBufferPtr::new(vec![97_u8; 200]));
+ data[0].set_data(Bytes::from(vec![97_u8; 200]));
// This is the expected max value - "ZZZ..."
- data[1].set_data(ByteBufferPtr::new(vec![112_u8; 200]));
- data[2].set_data(ByteBufferPtr::new(vec![98_u8; 200]));
+ data[1].set_data(Bytes::from(vec![112_u8; 200]));
+ data[2].set_data(Bytes::from(vec![98_u8; 200]));
writer.write_batch(&data, None, None).unwrap();
@@ -2420,9 +2421,7 @@ mod tests {
let mut data = vec![FixedLenByteArray::default(); 1];
// This is the expected min value
- data[0].set_data(ByteBufferPtr::new(
- String::from("Blart Versenwald III").into_bytes(),
- ));
+ data[0].set_data(Bytes::from(String::from("Blart Versenwald III")));
writer.write_batch(&data, None, None).unwrap();
@@ -2493,9 +2492,9 @@ mod tests {
// Also show that BinaryArray level comparison works here
let mut greater = ByteArray::new();
- greater.set_data(ByteBufferPtr::new(v));
+ greater.set_data(Bytes::from(v));
let mut original = ByteArray::new();
- original.set_data(ByteBufferPtr::new("hello".as_bytes().to_vec()));
+ original.set_data(Bytes::from("hello".as_bytes().to_vec()));
assert!(greater > original);
// UTF8 string
diff --git a/parquet/src/data_type.rs b/parquet/src/data_type.rs
index eaf4389d4350..b895c2507018 100644
--- a/parquet/src/data_type.rs
+++ b/parquet/src/data_type.rs
@@ -28,7 +28,7 @@ use crate::basic::Type;
use crate::column::reader::{ColumnReader, ColumnReaderImpl};
use crate::column::writer::{ColumnWriter, ColumnWriterImpl};
use crate::errors::{ParquetError, Result};
-use crate::util::{bit_util::FromBytes, memory::ByteBufferPtr};
+use crate::util::bit_util::FromBytes;
/// Rust representation for logical type INT96, value is backed by an array of `u32`.
/// The type only takes 12 bytes, without extra padding.
@@ -103,7 +103,7 @@ impl fmt::Display for Int96 {
/// Value is backed by a byte buffer.
#[derive(Clone, Default)]
pub struct ByteArray {
- data: Option<ByteBufferPtr>,
+ data: Option<Bytes>,
}
// Special case Debug that prints out byte arrays that are valid utf8 as &str's
@@ -130,7 +130,7 @@ impl PartialOrd for ByteArray {
(Some(_), None) => Some(Ordering::Greater),
(Some(self_data), Some(other_data)) => {
// compare slices directly
- self_data.data().partial_cmp(other_data.data())
+ self_data.partial_cmp(&other_data)
}
}
}
@@ -167,7 +167,7 @@ impl ByteArray {
/// Set data from another byte buffer.
#[inline]
- pub fn set_data(&mut self, data: ByteBufferPtr) {
+ pub fn set_data(&mut self, data: Bytes) {
self.data = Some(data);
}
@@ -178,7 +178,7 @@ impl ByteArray {
self.data
.as_ref()
.expect("set_data should have been called")
- .range(start, len),
+ .slice(start..start + len),
)
}
@@ -194,7 +194,7 @@ impl ByteArray {
impl From<Vec<u8>> for ByteArray {
fn from(buf: Vec<u8>) -> ByteArray {
Self {
- data: Some(ByteBufferPtr::new(buf)),
+ data: Some(buf.into()),
}
}
}
@@ -204,7 +204,7 @@ impl<'a> From<&'a [u8]> for ByteArray {
let mut v = Vec::new();
v.extend_from_slice(b);
Self {
- data: Some(ByteBufferPtr::new(v)),
+ data: Some(v.into()),
}
}
}
@@ -214,20 +214,14 @@ impl<'a> From<&'a str> for ByteArray {
let mut v = Vec::new();
v.extend_from_slice(s.as_bytes());
Self {
- data: Some(ByteBufferPtr::new(v)),
+ data: Some(v.into()),
}
}
}
-impl From<ByteBufferPtr> for ByteArray {
- fn from(ptr: ByteBufferPtr) -> ByteArray {
- Self { data: Some(ptr) }
- }
-}
-
impl From<Bytes> for ByteArray {
fn from(value: Bytes) -> Self {
- ByteBufferPtr::from(value).into()
+ Self { data: Some(value) }
}
}
@@ -580,9 +574,10 @@ impl AsBytes for str {
}
pub(crate) mod private {
+ use bytes::Bytes;
+
use crate::encodings::decoding::PlainDecoderDetails;
use crate::util::bit_util::{read_num_bytes, BitReader, BitWriter};
- use crate::util::memory::ByteBufferPtr;
use crate::basic::Type;
use std::convert::TryInto;
@@ -618,7 +613,7 @@ pub(crate) mod private {
) -> Result<()>;
/// Establish the data that will be decoded in a buffer
- fn set_data(decoder: &mut PlainDecoderDetails, data: ByteBufferPtr, num_values: usize);
+ fn set_data(decoder: &mut PlainDecoderDetails, data: Bytes, num_values: usize);
/// Decode the value from a given buffer for a higher level decoder
fn decode(buffer: &mut [Self], decoder: &mut PlainDecoderDetails) -> Result<usize>;
@@ -671,7 +666,7 @@ pub(crate) mod private {
}
#[inline]
- fn set_data(decoder: &mut PlainDecoderDetails, data: ByteBufferPtr, num_values: usize) {
+ fn set_data(decoder: &mut PlainDecoderDetails, data: Bytes, num_values: usize) {
decoder.bit_reader.replace(BitReader::new(data));
decoder.num_values = num_values;
}
@@ -728,7 +723,7 @@ pub(crate) mod private {
}
#[inline]
- fn set_data(decoder: &mut PlainDecoderDetails, data: ByteBufferPtr, num_values: usize) {
+ fn set_data(decoder: &mut PlainDecoderDetails, data: Bytes, num_values: usize) {
decoder.data.replace(data);
decoder.start = 0;
decoder.num_values = num_values;
@@ -748,7 +743,9 @@ pub(crate) mod private {
// SAFETY: Raw types should be as per the standard rust bit-vectors
unsafe {
let raw_buffer = &mut Self::slice_as_bytes_mut(buffer)[..bytes_to_decode];
- raw_buffer.copy_from_slice(data.range(decoder.start, bytes_to_decode).as_ref());
+ raw_buffer.copy_from_slice(data.slice(
+ decoder.start..decoder.start + bytes_to_decode
+ ).as_ref());
};
decoder.start += bytes_to_decode;
decoder.num_values -= num_values;
@@ -815,7 +812,7 @@ pub(crate) mod private {
}
#[inline]
- fn set_data(decoder: &mut PlainDecoderDetails, data: ByteBufferPtr, num_values: usize) {
+ fn set_data(decoder: &mut PlainDecoderDetails, data: Bytes, num_values: usize) {
decoder.data.replace(data);
decoder.start = 0;
decoder.num_values = num_values;
@@ -836,8 +833,8 @@ pub(crate) mod private {
return Err(eof_err!("Not enough bytes to decode"));
}
- let data_range = data.range(decoder.start, bytes_to_decode);
- let bytes: &[u8] = data_range.data();
+ let data_range = data.slice(decoder.start..decoder.start + bytes_to_decode);
+ let bytes: &[u8] = &data_range;
decoder.start += bytes_to_decode;
let mut pos = 0; // position in byte array
@@ -902,7 +899,7 @@ pub(crate) mod private {
}
#[inline]
- fn set_data(decoder: &mut PlainDecoderDetails, data: ByteBufferPtr, num_values: usize) {
+ fn set_data(decoder: &mut PlainDecoderDetails, data: Bytes, num_values: usize) {
decoder.data.replace(data);
decoder.start = 0;
decoder.num_values = num_values;
@@ -917,7 +914,7 @@ pub(crate) mod private {
let num_values = std::cmp::min(buffer.len(), decoder.num_values);
for val_array in buffer.iter_mut().take(num_values) {
let len: usize =
- read_num_bytes::<u32>(4, data.start_from(decoder.start).as_ref()) as usize;
+ read_num_bytes::<u32>(4, data.slice(decoder.start..).as_ref()) as usize;
decoder.start += std::mem::size_of::<u32>();
if data.len() < decoder.start + len {
@@ -926,7 +923,7 @@ pub(crate) mod private {
let val: &mut Self = val_array.as_mut_any().downcast_mut().unwrap();
- val.set_data(data.range(decoder.start, len));
+ val.set_data(data.slice(decoder.start..decoder.start + len));
decoder.start += len;
}
decoder.num_values -= num_values;
@@ -943,7 +940,7 @@ pub(crate) mod private {
for _ in 0..num_values {
let len: usize =
- read_num_bytes::<u32>(4, data.start_from(decoder.start).as_ref()) as usize;
+ read_num_bytes::<u32>(4, data.slice(decoder.start..).as_ref()) as usize;
decoder.start += std::mem::size_of::<u32>() + len;
}
decoder.num_values -= num_values;
@@ -984,7 +981,7 @@ pub(crate) mod private {
}
#[inline]
- fn set_data(decoder: &mut PlainDecoderDetails, data: ByteBufferPtr, num_values: usize) {
+ fn set_data(decoder: &mut PlainDecoderDetails, data: Bytes, num_values: usize) {
decoder.data.replace(data);
decoder.start = 0;
decoder.num_values = num_values;
@@ -1007,7 +1004,7 @@ pub(crate) mod private {
return Err(eof_err!("Not enough bytes to decode"));
}
- item.set_data(data.range(decoder.start, len));
+ item.set_data(data.slice(decoder.start..decoder.start + len));
decoder.start += len;
}
decoder.num_values -= num_values;
@@ -1241,7 +1238,7 @@ mod tests {
);
assert_eq!(ByteArray::from("ABC").data(), &[b'A', b'B', b'C']);
assert_eq!(
- ByteArray::from(ByteBufferPtr::new(vec![1u8, 2u8, 3u8, 4u8, 5u8])).data(),
+ ByteArray::from(Bytes::from(vec![1u8, 2u8, 3u8, 4u8, 5u8])).data(),
&[1u8, 2u8, 3u8, 4u8, 5u8]
);
let buf = vec![6u8, 7u8, 8u8, 9u8, 10u8];
diff --git a/parquet/src/encodings/decoding.rs b/parquet/src/encodings/decoding.rs
index 7aed6df419ee..5843acdb6d0f 100644
--- a/parquet/src/encodings/decoding.rs
+++ b/parquet/src/encodings/decoding.rs
@@ -17,6 +17,7 @@
//! Contains all supported decoders for Parquet.
+use bytes::Bytes;
use num::traits::WrappingAdd;
use num::FromPrimitive;
use std::{cmp, marker::PhantomData, mem};
@@ -28,10 +29,7 @@ use crate::data_type::private::ParquetValueType;
use crate::data_type::*;
use crate::errors::{ParquetError, Result};
use crate::schema::types::ColumnDescPtr;
-use crate::util::{
- bit_util::{self, BitReader},
- memory::ByteBufferPtr,
-};
+use crate::util::bit_util::{self, BitReader};
pub(crate) mod private {
use super::*;
@@ -145,7 +143,7 @@ pub(crate) mod private {
pub trait Decoder<T: DataType>: Send {
/// Sets the data to decode to be `data`, which should contain `num_values` of values
/// to decode.
- fn set_data(&mut self, data: ByteBufferPtr, num_values: usize) -> Result<()>;
+ fn set_data(&mut self, data: Bytes, num_values: usize) -> Result<()>;
/// Consumes values from this decoder and write the results to `buffer`. This will try
/// to fill up `buffer`.
@@ -238,7 +236,7 @@ pub struct PlainDecoderDetails {
pub(crate) type_length: i32,
// The byte array to decode from. Not set if `T` is bool.
- pub(crate) data: Option<ByteBufferPtr>,
+ pub(crate) data: Option<Bytes>,
// Read `data` bit by bit. Only set if `T` is bool.
pub(crate) bit_reader: Option<BitReader>,
@@ -275,7 +273,7 @@ impl<T: DataType> PlainDecoder<T> {
impl<T: DataType> Decoder<T> for PlainDecoder<T> {
#[inline]
- fn set_data(&mut self, data: ByteBufferPtr, num_values: usize) -> Result<()> {
+ fn set_data(&mut self, data: Bytes, num_values: usize) -> Result<()> {
T::T::set_data(&mut self.inner, data, num_values);
Ok(())
}
@@ -350,11 +348,11 @@ impl<T: DataType> DictDecoder<T> {
}
impl<T: DataType> Decoder<T> for DictDecoder<T> {
- fn set_data(&mut self, data: ByteBufferPtr, num_values: usize) -> Result<()> {
+ fn set_data(&mut self, data: Bytes, num_values: usize) -> Result<()> {
// First byte in `data` is bit width
let bit_width = data.as_ref()[0];
let mut rle_decoder = RleDecoder::new(bit_width);
- rle_decoder.set_data(data.start_from(1));
+ rle_decoder.set_data(data.slice(1..));
self.num_values = num_values;
self.rle_decoder = Some(rle_decoder);
Ok(())
@@ -418,7 +416,7 @@ impl<T: DataType> RleValueDecoder<T> {
impl<T: DataType> Decoder<T> for RleValueDecoder<T> {
#[inline]
- fn set_data(&mut self, data: ByteBufferPtr, num_values: usize) -> Result<()> {
+ fn set_data(&mut self, data: Bytes, num_values: usize) -> Result<()> {
// Only support RLE value reader for boolean values with bit width of 1.
ensure_phys_ty!(Type::BOOLEAN, "RleValueDecoder only supports BoolType");
@@ -426,7 +424,8 @@ impl<T: DataType> Decoder<T> for RleValueDecoder<T> {
const I32_SIZE: usize = mem::size_of::<i32>();
let data_size = bit_util::read_num_bytes::<i32>(I32_SIZE, data.as_ref()) as usize;
self.decoder = RleDecoder::new(1);
- self.decoder.set_data(data.range(I32_SIZE, data_size));
+ self.decoder
+ .set_data(data.slice(I32_SIZE..I32_SIZE + data_size));
self.values_left = num_values;
Ok(())
}
@@ -604,7 +603,7 @@ where
{
// # of total values is derived from encoding
#[inline]
- fn set_data(&mut self, data: ByteBufferPtr, _index: usize) -> Result<()> {
+ fn set_data(&mut self, data: Bytes, _index: usize) -> Result<()> {
self.bit_reader = BitReader::new(data);
self.initialized = true;
@@ -811,7 +810,7 @@ pub struct DeltaLengthByteArrayDecoder<T: DataType> {
current_idx: usize,
// Concatenated byte array data
- data: Option<ByteBufferPtr>,
+ data: Option<Bytes>,
// Offset into `data`, always point to the beginning of next byte array.
offset: usize,
@@ -844,16 +843,16 @@ impl<T: DataType> DeltaLengthByteArrayDecoder<T> {
}
impl<T: DataType> Decoder<T> for DeltaLengthByteArrayDecoder<T> {
- fn set_data(&mut self, data: ByteBufferPtr, num_values: usize) -> Result<()> {
+ fn set_data(&mut self, data: Bytes, num_values: usize) -> Result<()> {
match T::get_physical_type() {
Type::BYTE_ARRAY => {
let mut len_decoder = DeltaBitPackDecoder::<Int32Type>::new();
- len_decoder.set_data(data.all(), num_values)?;
+ len_decoder.set_data(data.clone(), num_values)?;
let num_lengths = len_decoder.values_left();
self.lengths.resize(num_lengths, 0);
len_decoder.get(&mut self.lengths[..])?;
- self.data = Some(data.start_from(len_decoder.get_offset()));
+ self.data = Some(data.slice(len_decoder.get_offset()..));
self.offset = 0;
self.current_idx = 0;
self.num_values = num_lengths;
@@ -879,7 +878,7 @@ impl<T: DataType> Decoder<T> for DeltaLengthByteArrayDecoder<T> {
item.as_mut_any()
.downcast_mut::<ByteArray>()
.unwrap()
- .set_data(data.range(self.offset, len));
+ .set_data(data.slice(self.offset..self.offset + len));
self.offset += len;
self.current_idx += 1;
@@ -977,18 +976,18 @@ impl<T: DataType> DeltaByteArrayDecoder<T> {
}
impl<T: DataType> Decoder<T> for DeltaByteArrayDecoder<T> {
- fn set_data(&mut self, data: ByteBufferPtr, num_values: usize) -> Result<()> {
+ fn set_data(&mut self, data: Bytes, num_values: usize) -> Result<()> {
match T::get_physical_type() {
Type::BYTE_ARRAY | Type::FIXED_LEN_BYTE_ARRAY => {
let mut prefix_len_decoder = DeltaBitPackDecoder::<Int32Type>::new();
- prefix_len_decoder.set_data(data.all(), num_values)?;
+ prefix_len_decoder.set_data(data.clone(), num_values)?;
let num_prefixes = prefix_len_decoder.values_left();
self.prefix_lengths.resize(num_prefixes, 0);
prefix_len_decoder.get(&mut self.prefix_lengths[..])?;
let mut suffix_decoder = DeltaLengthByteArrayDecoder::new();
suffix_decoder
- .set_data(data.start_from(prefix_len_decoder.get_offset()), num_values)?;
+ .set_data(data.slice(prefix_len_decoder.get_offset()..), num_values)?;
self.suffix_decoder = Some(suffix_decoder);
self.num_values = num_prefixes;
self.current_idx = 0;
@@ -1023,7 +1022,7 @@ impl<T: DataType> Decoder<T> for DeltaByteArrayDecoder<T> {
result.extend_from_slice(&self.previous_value[0..prefix_len]);
result.extend_from_slice(suffix);
- let data = ByteBufferPtr::new(result.clone());
+ let data = Bytes::from(result.clone());
match ty {
Type::BYTE_ARRAY => item
@@ -1131,33 +1130,21 @@ mod tests {
let data = [42, 18, 52];
let data_bytes = Int32Type::to_byte_array(&data[..]);
let mut buffer = [0; 3];
- test_plain_decode::<Int32Type>(
- ByteBufferPtr::new(data_bytes),
- 3,
- -1,
- &mut buffer[..],
- &data[..],
- );
+ test_plain_decode::<Int32Type>(Bytes::from(data_bytes), 3, -1, &mut buffer[..], &data[..]);
}
#[test]
fn test_plain_skip_int32() {
let data = [42, 18, 52];
let data_bytes = Int32Type::to_byte_array(&data[..]);
- test_plain_skip::<Int32Type>(
- ByteBufferPtr::new(data_bytes),
- 3,
- 1,
- -1,
- &data[1..],
- );
+ test_plain_skip::<Int32Type>(Bytes::from(data_bytes), 3, 1, -1, &data[1..]);
}
#[test]
fn test_plain_skip_all_int32() {
let data = [42, 18, 52];
let data_bytes = Int32Type::to_byte_array(&data[..]);
- test_plain_skip::<Int32Type>(ByteBufferPtr::new(data_bytes), 3, 5, -1, &[]);
+ test_plain_skip::<Int32Type>(Bytes::from(data_bytes), 3, 5, -1, &[]);
}
#[test]
@@ -1169,7 +1156,7 @@ mod tests {
let num_nulls = 5;
let valid_bits = [0b01001010];
test_plain_decode_spaced::<Int32Type>(
- ByteBufferPtr::new(data_bytes),
+ Bytes::from(data_bytes),
3,
-1,
&mut buffer[..],
@@ -1184,33 +1171,21 @@ mod tests {
let data = [42, 18, 52];
let data_bytes = Int64Type::to_byte_array(&data[..]);
let mut buffer = [0; 3];
- test_plain_decode::<Int64Type>(
- ByteBufferPtr::new(data_bytes),
- 3,
- -1,
- &mut buffer[..],
- &data[..],
- );
+ test_plain_decode::<Int64Type>(Bytes::from(data_bytes), 3, -1, &mut buffer[..], &data[..]);
}
#[test]
fn test_plain_skip_int64() {
let data = [42, 18, 52];
let data_bytes = Int64Type::to_byte_array(&data[..]);
- test_plain_skip::<Int64Type>(
- ByteBufferPtr::new(data_bytes),
- 3,
- 2,
- -1,
- &data[2..],
- );
+ test_plain_skip::<Int64Type>(Bytes::from(data_bytes), 3, 2, -1, &data[2..]);
}
#[test]
fn test_plain_skip_all_int64() {
let data = [42, 18, 52];
let data_bytes = Int64Type::to_byte_array(&data[..]);
- test_plain_skip::<Int64Type>(ByteBufferPtr::new(data_bytes), 3, 3, -1, &[]);
+ test_plain_skip::<Int64Type>(Bytes::from(data_bytes), 3, 3, -1, &[]);
}
#[test]
@@ -1218,53 +1193,35 @@ mod tests {
let data = [PI_f32, 2.414, 12.51];
let data_bytes = FloatType::to_byte_array(&data[..]);
let mut buffer = [0.0; 3];
- test_plain_decode::<FloatType>(
- ByteBufferPtr::new(data_bytes),
- 3,
- -1,
- &mut buffer[..],
- &data[..],
- );
+ test_plain_decode::<FloatType>(Bytes::from(data_bytes), 3, -1, &mut buffer[..], &data[..]);
}
#[test]
fn test_plain_skip_float() {
let data = [PI_f32, 2.414, 12.51];
let data_bytes = FloatType::to_byte_array(&data[..]);
- test_plain_skip::<FloatType>(
- ByteBufferPtr::new(data_bytes),
- 3,
- 1,
- -1,
- &data[1..],
- );
+ test_plain_skip::<FloatType>(Bytes::from(data_bytes), 3, 1, -1, &data[1..]);
}
#[test]
fn test_plain_skip_all_float() {
let data = [PI_f32, 2.414, 12.51];
let data_bytes = FloatType::to_byte_array(&data[..]);
- test_plain_skip::<FloatType>(ByteBufferPtr::new(data_bytes), 3, 4, -1, &[]);
+ test_plain_skip::<FloatType>(Bytes::from(data_bytes), 3, 4, -1, &[]);
}
#[test]
fn test_plain_skip_double() {
let data = [PI_f64, 2.414f64, 12.51f64];
let data_bytes = DoubleType::to_byte_array(&data[..]);
- test_plain_skip::<DoubleType>(
- ByteBufferPtr::new(data_bytes),
- 3,
- 1,
- -1,
- &data[1..],
- );
+ test_plain_skip::<DoubleType>(Bytes::from(data_bytes), 3, 1, -1, &data[1..]);
}
#[test]
fn test_plain_skip_all_double() {
let data = [PI_f64, 2.414f64, 12.51f64];
let data_bytes = DoubleType::to_byte_array(&data[..]);
- test_plain_skip::<DoubleType>(ByteBufferPtr::new(data_bytes), 3, 5, -1, &[]);
+ test_plain_skip::<DoubleType>(Bytes::from(data_bytes), 3, 5, -1, &[]);
}
#[test]
@@ -1272,13 +1229,7 @@ mod tests {
let data = [PI_f64, 2.414f64, 12.51f64];
let data_bytes = DoubleType::to_byte_array(&data[..]);
let mut buffer = [0.0f64; 3];
- test_plain_decode::<DoubleType>(
- ByteBufferPtr::new(data_bytes),
- 3,
- -1,
- &mut buffer[..],
- &data[..],
- );
+ test_plain_decode::<DoubleType>(Bytes::from(data_bytes), 3, -1, &mut buffer[..], &data[..]);
}
#[test]
@@ -1290,13 +1241,7 @@ mod tests {
data[3].set_data(40, 50, 60);
let data_bytes = Int96Type::to_byte_array(&data[..]);
let mut buffer = [Int96::new(); 4];
- test_plain_decode::<Int96Type>(
- ByteBufferPtr::new(data_bytes),
- 4,
- -1,
- &mut buffer[..],
- &data[..],
- );
+ test_plain_decode::<Int96Type>(Bytes::from(data_bytes), 4, -1, &mut buffer[..], &data[..]);
}
#[test]
@@ -1307,13 +1252,7 @@ mod tests {
data[2].set_data(10, 20, 30);
data[3].set_data(40, 50, 60);
let data_bytes = Int96Type::to_byte_array(&data[..]);
- test_plain_skip::<Int96Type>(
- ByteBufferPtr::new(data_bytes),
- 4,
- 2,
- -1,
- &data[2..],
- );
+ test_plain_skip::<Int96Type>(Bytes::from(data_bytes), 4, 2, -1, &data[2..]);
}
#[test]
@@ -1324,7 +1263,7 @@ mod tests {
data[2].set_data(10, 20, 30);
data[3].set_data(40, 50, 60);
let data_bytes = Int96Type::to_byte_array(&data[..]);
- test_plain_skip::<Int96Type>(ByteBufferPtr::new(data_bytes), 4, 8, -1, &[]);
+ test_plain_skip::<Int96Type>(Bytes::from(data_bytes), 4, 8, -1, &[]);
}
#[test]
@@ -1334,13 +1273,7 @@ mod tests {
];
let data_bytes = BoolType::to_byte_array(&data[..]);
let mut buffer = [false; 10];
- test_plain_decode::<BoolType>(
- ByteBufferPtr::new(data_bytes),
- 10,
- -1,
- &mut buffer[..],
- &data[..],
- );
+ test_plain_decode::<BoolType>(Bytes::from(data_bytes), 10, -1, &mut buffer[..], &data[..]);
}
#[test]
@@ -1349,13 +1282,7 @@ mod tests {
false, true, false, false, true, false, true, true, false, true,
];
let data_bytes = BoolType::to_byte_array(&data[..]);
- test_plain_skip::<BoolType>(
- ByteBufferPtr::new(data_bytes),
- 10,
- 5,
- -1,
- &data[5..],
- );
+ test_plain_skip::<BoolType>(Bytes::from(data_bytes), 10, 5, -1, &data[5..]);
}
#[test]
@@ -1364,18 +1291,18 @@ mod tests {
false, true, false, false, true, false, true, true, false, true,
];
let data_bytes = BoolType::to_byte_array(&data[..]);
- test_plain_skip::<BoolType>(ByteBufferPtr::new(data_bytes), 10, 20, -1, &[]);
+ test_plain_skip::<BoolType>(Bytes::from(data_bytes), 10, 20, -1, &[]);
}
#[test]
fn test_plain_decode_byte_array() {
let mut data = vec![ByteArray::new(); 2];
- data[0].set_data(ByteBufferPtr::new(String::from("hello").into_bytes()));
- data[1].set_data(ByteBufferPtr::new(String::from("parquet").into_bytes()));
+ data[0].set_data(Bytes::from(String::from("hello")));
+ data[1].set_data(Bytes::from(String::from("parquet")));
let data_bytes = ByteArrayType::to_byte_array(&data[..]);
let mut buffer = vec![ByteArray::new(); 2];
test_plain_decode::<ByteArrayType>(
- ByteBufferPtr::new(data_bytes),
+ Bytes::from(data_bytes),
2,
-1,
&mut buffer[..],
@@ -1386,37 +1313,31 @@ mod tests {
#[test]
fn test_plain_skip_byte_array() {
let mut data = vec![ByteArray::new(); 2];
- data[0].set_data(ByteBufferPtr::new(String::from("hello").into_bytes()));
- data[1].set_data(ByteBufferPtr::new(String::from("parquet").into_bytes()));
+ data[0].set_data(Bytes::from(String::from("hello")));
+ data[1].set_data(Bytes::from(String::from("parquet")));
let data_bytes = ByteArrayType::to_byte_array(&data[..]);
- test_plain_skip::<ByteArrayType>(
- ByteBufferPtr::new(data_bytes),
- 2,
- 1,
- -1,
- &data[1..],
- );
+ test_plain_skip::<ByteArrayType>(Bytes::from(data_bytes), 2, 1, -1, &data[1..]);
}
#[test]
fn test_plain_skip_all_byte_array() {
let mut data = vec![ByteArray::new(); 2];
- data[0].set_data(ByteBufferPtr::new(String::from("hello").into_bytes()));
- data[1].set_data(ByteBufferPtr::new(String::from("parquet").into_bytes()));
+ data[0].set_data(Bytes::from(String::from("hello")));
+ data[1].set_data(Bytes::from(String::from("parquet")));
let data_bytes = ByteArrayType::to_byte_array(&data[..]);
- test_plain_skip::<ByteArrayType>(ByteBufferPtr::new(data_bytes), 2, 2, -1, &[]);
+ test_plain_skip::<ByteArrayType>(Bytes::from(data_bytes), 2, 2, -1, &[]);
}
#[test]
fn test_plain_decode_fixed_len_byte_array() {
let mut data = vec![FixedLenByteArray::default(); 3];
- data[0].set_data(ByteBufferPtr::new(String::from("bird").into_bytes()));
- data[1].set_data(ByteBufferPtr::new(String::from("come").into_bytes()));
- data[2].set_data(ByteBufferPtr::new(String::from("flow").into_bytes()));
+ data[0].set_data(Bytes::from(String::from("bird")));
+ data[1].set_data(Bytes::from(String::from("come")));
+ data[2].set_data(Bytes::from(String::from("flow")));
let data_bytes = FixedLenByteArrayType::to_byte_array(&data[..]);
let mut buffer = vec![FixedLenByteArray::default(); 3];
test_plain_decode::<FixedLenByteArrayType>(
- ByteBufferPtr::new(data_bytes),
+ Bytes::from(data_bytes),
3,
4,
&mut buffer[..],
@@ -1427,37 +1348,25 @@ mod tests {
#[test]
fn test_plain_skip_fixed_len_byte_array() {
let mut data = vec![FixedLenByteArray::default(); 3];
- data[0].set_data(ByteBufferPtr::new(String::from("bird").into_bytes()));
- data[1].set_data(ByteBufferPtr::new(String::from("come").into_bytes()));
- data[2].set_data(ByteBufferPtr::new(String::from("flow").into_bytes()));
+ data[0].set_data(Bytes::from(String::from("bird")));
+ data[1].set_data(Bytes::from(String::from("come")));
+ data[2].set_data(Bytes::from(String::from("flow")));
let data_bytes = FixedLenByteArrayType::to_byte_array(&data[..]);
- test_plain_skip::<FixedLenByteArrayType>(
- ByteBufferPtr::new(data_bytes),
- 3,
- 1,
- 4,
- &data[1..],
- );
+ test_plain_skip::<FixedLenByteArrayType>(Bytes::from(data_bytes), 3, 1, 4, &data[1..]);
}
#[test]
fn test_plain_skip_all_fixed_len_byte_array() {
let mut data = vec![FixedLenByteArray::default(); 3];
- data[0].set_data(ByteBufferPtr::new(String::from("bird").into_bytes()));
- data[1].set_data(ByteBufferPtr::new(String::from("come").into_bytes()));
- data[2].set_data(ByteBufferPtr::new(String::from("flow").into_bytes()));
+ data[0].set_data(Bytes::from(String::from("bird")));
+ data[1].set_data(Bytes::from(String::from("come")));
+ data[2].set_data(Bytes::from(String::from("flow")));
let data_bytes = FixedLenByteArrayType::to_byte_array(&data[..]);
- test_plain_skip::<FixedLenByteArrayType>(
- ByteBufferPtr::new(data_bytes),
- 3,
- 6,
- 4,
- &[],
- );
+ test_plain_skip::<FixedLenByteArrayType>(Bytes::from(data_bytes), 3, 6, 4, &[]);
}
fn test_plain_decode<T: DataType>(
- data: ByteBufferPtr,
+ data: Bytes,
num_values: usize,
type_length: i32,
buffer: &mut [T::T],
@@ -1473,7 +1382,7 @@ mod tests {
}
fn test_plain_skip<T: DataType>(
- data: ByteBufferPtr,
+ data: Bytes,
num_values: usize,
skip: usize,
type_length: i32,
@@ -1501,7 +1410,7 @@ mod tests {
}
fn test_plain_decode_spaced<T: DataType>(
- data: ByteBufferPtr,
+ data: Bytes,
num_values: usize,
type_length: i32,
buffer: &mut [T::T],
@@ -1530,9 +1439,7 @@ mod tests {
#[should_panic(expected = "RleValueDecoder only supports BoolType")]
fn test_rle_value_decode_int32_not_supported() {
let mut decoder = RleValueDecoder::<Int32Type>::new();
- decoder
- .set_data(ByteBufferPtr::new(vec![5, 0, 0, 0]), 1)
- .unwrap();
+ decoder.set_data(Bytes::from(vec![5, 0, 0, 0]), 1).unwrap();
}
#[test]
@@ -1730,9 +1637,8 @@ mod tests {
128, 1, 4, 3, 58, 28, 6, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
- let buffer = ByteBufferPtr::new(data_bytes);
let mut decoder: DeltaBitPackDecoder<Int32Type> = DeltaBitPackDecoder::new();
- decoder.set_data(buffer, 3).unwrap();
+ decoder.set_data(data_bytes.into(), 3).unwrap();
// check exact offsets, because when reading partial values we end up with
// some data not being read from bit reader
assert_eq!(decoder.get_offset(), 5);
@@ -1794,7 +1700,7 @@ mod tests {
let length = data.len();
- let ptr = ByteBufferPtr::new(data);
+ let ptr = Bytes::from(data);
let mut reader = BitReader::new(ptr.clone());
assert_eq!(reader.get_vlq_int().unwrap(), 256);
assert_eq!(reader.get_vlq_int().unwrap(), 4);
@@ -1810,7 +1716,7 @@ mod tests {
assert_eq!(decoder.get_offset(), length);
// Test with truncated buffer
- decoder.set_data(ptr.range(0, 12), 0).unwrap();
+ decoder.set_data(ptr.slice(..12), 0).unwrap();
let err = decoder.get(&mut output).unwrap_err().to_string();
assert!(
err.contains("Expected to read 64 values from miniblock got 8"),
diff --git a/parquet/src/encodings/encoding/dict_encoder.rs b/parquet/src/encodings/encoding/dict_encoder.rs
index 4f4a6ab4f55a..dafae064afbf 100644
--- a/parquet/src/encodings/encoding/dict_encoder.rs
+++ b/parquet/src/encodings/encoding/dict_encoder.rs
@@ -18,6 +18,8 @@
// ----------------------------------------------------------------------
// Dictionary encoding
+use bytes::Bytes;
+
use crate::basic::{Encoding, Type};
use crate::data_type::private::ParquetValueType;
use crate::data_type::DataType;
@@ -27,7 +29,6 @@ use crate::errors::Result;
use crate::schema::types::ColumnDescPtr;
use crate::util::bit_util::num_required_bits;
use crate::util::interner::{Interner, Storage};
-use crate::util::memory::ByteBufferPtr;
#[derive(Debug)]
struct KeyStorage<T: DataType> {
@@ -112,7 +113,7 @@ impl<T: DataType> DictEncoder<T> {
/// Writes out the dictionary values with PLAIN encoding in a byte buffer, and return
/// the result.
- pub fn write_dict(&self) -> Result<ByteBufferPtr> {
+ pub fn write_dict(&self) -> Result<Bytes> {
let mut plain_encoder = PlainEncoder::<T>::new();
plain_encoder.put(&self.interner.storage().uniques)?;
plain_encoder.flush_buffer()
@@ -120,7 +121,7 @@ impl<T: DataType> DictEncoder<T> {
/// Writes out the dictionary values with RLE encoding in a byte buffer, and return
/// the result.
- pub fn write_indices(&mut self) -> Result<ByteBufferPtr> {
+ pub fn write_indices(&mut self) -> Result<Bytes> {
let buffer_len = self.estimated_data_encoded_size();
let mut buffer = Vec::with_capacity(buffer_len);
buffer.push(self.bit_width());
@@ -131,7 +132,7 @@ impl<T: DataType> DictEncoder<T> {
encoder.put(*index)
}
self.indices.clear();
- Ok(ByteBufferPtr::new(encoder.consume()))
+ Ok(encoder.consume().into())
}
fn put_one(&mut self, value: &T::T) {
@@ -165,7 +166,7 @@ impl<T: DataType> Encoder<T> for DictEncoder<T> {
RleEncoder::max_buffer_size(bit_width, self.indices.len())
}
- fn flush_buffer(&mut self) -> Result<ByteBufferPtr> {
+ fn flush_buffer(&mut self) -> Result<Bytes> {
self.write_indices()
}
}
diff --git a/parquet/src/encodings/encoding/mod.rs b/parquet/src/encodings/encoding/mod.rs
index 3088f332183b..89e61ee226ad 100644
--- a/parquet/src/encodings/encoding/mod.rs
+++ b/parquet/src/encodings/encoding/mod.rs
@@ -24,11 +24,9 @@ use crate::data_type::private::ParquetValueType;
use crate::data_type::*;
use crate::encodings::rle::RleEncoder;
use crate::errors::{ParquetError, Result};
-use crate::util::{
- bit_util::{self, num_required_bits, BitWriter},
- memory::ByteBufferPtr,
-};
+use crate::util::bit_util::{self, num_required_bits, BitWriter};
+use bytes::Bytes;
pub use dict_encoder::DictEncoder;
mod dict_encoder;
@@ -70,7 +68,7 @@ pub trait Encoder<T: DataType>: Send {
/// Flushes the underlying byte buffer that's being processed by this encoder, and
/// return the immutable copy of it. This will also reset the internal state.
- fn flush_buffer(&mut self) -> Result<ByteBufferPtr>;
+ fn flush_buffer(&mut self) -> Result<Bytes>;
}
/// Gets a encoder for the particular data type `T` and encoding `encoding`. Memory usage
@@ -143,7 +141,7 @@ impl<T: DataType> Encoder<T> for PlainEncoder<T> {
}
#[inline]
- fn flush_buffer(&mut self) -> Result<ByteBufferPtr> {
+ fn flush_buffer(&mut self) -> Result<Bytes> {
self.buffer
.extend_from_slice(self.bit_writer.flush_buffer());
self.bit_writer.clear();
@@ -223,7 +221,7 @@ impl<T: DataType> Encoder<T> for RleValueEncoder<T> {
}
#[inline]
- fn flush_buffer(&mut self) -> Result<ByteBufferPtr> {
+ fn flush_buffer(&mut self) -> Result<Bytes> {
ensure_phys_ty!(Type::BOOLEAN, "RleValueEncoder only supports BoolType");
let rle_encoder = self
.encoder
@@ -238,7 +236,7 @@ impl<T: DataType> Encoder<T> for RleValueEncoder<T> {
let len = (buf.len() - 4) as i32;
buf[..4].copy_from_slice(&len.to_le_bytes());
- Ok(ByteBufferPtr::new(buf))
+ Ok(buf.into())
}
}
@@ -456,7 +454,7 @@ impl<T: DataType> Encoder<T> for DeltaBitPackEncoder<T> {
self.bit_writer.bytes_written()
}
- fn flush_buffer(&mut self) -> Result<ByteBufferPtr> {
+ fn flush_buffer(&mut self) -> Result<Bytes> {
// Write remaining values
self.flush_block_values()?;
// Write page header with total values
@@ -597,7 +595,7 @@ impl<T: DataType> Encoder<T> for DeltaLengthByteArrayEncoder<T> {
self.len_encoder.estimated_data_encoded_size() + self.encoded_size
}
- fn flush_buffer(&mut self) -> Result<ByteBufferPtr> {
+ fn flush_buffer(&mut self) -> Result<Bytes> {
ensure_phys_ty!(
Type::BYTE_ARRAY | Type::FIXED_LEN_BYTE_ARRAY,
"DeltaLengthByteArrayEncoder only supports ByteArrayType"
@@ -605,14 +603,14 @@ impl<T: DataType> Encoder<T> for DeltaLengthByteArrayEncoder<T> {
let mut total_bytes = vec![];
let lengths = self.len_encoder.flush_buffer()?;
- total_bytes.extend_from_slice(lengths.data());
+ total_bytes.extend_from_slice(&lengths);
self.data.iter().for_each(|byte_array| {
total_bytes.extend_from_slice(byte_array.data());
});
self.data.clear();
self.encoded_size = 0;
- Ok(ByteBufferPtr::new(total_bytes))
+ Ok(total_bytes.into())
}
}
@@ -696,7 +694,7 @@ impl<T: DataType> Encoder<T> for DeltaByteArrayEncoder<T> {
+ self.suffix_writer.estimated_data_encoded_size()
}
- fn flush_buffer(&mut self) -> Result<ByteBufferPtr> {
+ fn flush_buffer(&mut self) -> Result<Bytes> {
match T::get_physical_type() {
Type::BYTE_ARRAY | Type::FIXED_LEN_BYTE_ARRAY => {
// TODO: investigate if we can merge lengths and suffixes
@@ -704,17 +702,17 @@ impl<T: DataType> Encoder<T> for DeltaByteArrayEncoder<T> {
let mut total_bytes = vec![];
// Insert lengths ...
let lengths = self.prefix_len_encoder.flush_buffer()?;
- total_bytes.extend_from_slice(lengths.data());
+ total_bytes.extend_from_slice(&lengths);
// ... followed by suffixes
let suffixes = self.suffix_writer.flush_buffer()?;
- total_bytes.extend_from_slice(suffixes.data());
+ total_bytes.extend_from_slice(&suffixes);
self.previous.clear();
- Ok(ByteBufferPtr::new(total_bytes))
+ Ok(total_bytes.into())
}
_ => panic!(
"DeltaByteArrayEncoder only supports ByteArrayType and FixedLenByteArrayType"
- )
+ ),
}
}
}
diff --git a/parquet/src/encodings/rle.rs b/parquet/src/encodings/rle.rs
index 63ab15c73ead..5807f6b9c527 100644
--- a/parquet/src/encodings/rle.rs
+++ b/parquet/src/encodings/rle.rs
@@ -17,12 +17,11 @@
use std::{cmp, mem::size_of};
+use bytes::Bytes;
+
use crate::errors::{ParquetError, Result};
use crate::util::bit_util::from_le_slice;
-use crate::util::{
- bit_util::{self, BitReader, BitWriter, FromBytes},
- memory::ByteBufferPtr,
-};
+use crate::util::bit_util::{self, BitReader, BitWriter, FromBytes};
/// Rle/Bit-Packing Hybrid Encoding
/// The grammar for this encoding looks like the following (copied verbatim
@@ -326,7 +325,7 @@ impl RleDecoder {
}
#[inline]
- pub fn set_data(&mut self, data: ByteBufferPtr) {
+ pub fn set_data(&mut self, data: Bytes) {
if let Some(ref mut bit_reader) = self.bit_reader {
bit_reader.reset(data);
} else {
@@ -543,17 +542,15 @@ mod tests {
use crate::util::bit_util::ceil;
use rand::{self, distributions::Standard, thread_rng, Rng, SeedableRng};
- use crate::util::memory::ByteBufferPtr;
-
const MAX_WIDTH: usize = 32;
#[test]
fn test_rle_decode_int32() {
// Test data: 0-7 with bit width 3
// 00000011 10001000 11000110 11111010
- let data = ByteBufferPtr::new(vec![0x03, 0x88, 0xC6, 0xFA]);
+ let data = vec![0x03, 0x88, 0xC6, 0xFA];
let mut decoder: RleDecoder = RleDecoder::new(3);
- decoder.set_data(data);
+ decoder.set_data(data.into());
let mut buffer = vec![0; 8];
let expected = vec![0, 1, 2, 3, 4, 5, 6, 7];
let result = decoder.get_batch::<i32>(&mut buffer);
@@ -565,9 +562,9 @@ mod tests {
fn test_rle_skip_int32() {
// Test data: 0-7 with bit width 3
// 00000011 10001000 11000110 11111010
- let data = ByteBufferPtr::new(vec![0x03, 0x88, 0xC6, 0xFA]);
+ let data = vec![0x03, 0x88, 0xC6, 0xFA];
let mut decoder: RleDecoder = RleDecoder::new(3);
- decoder.set_data(data);
+ decoder.set_data(data.into());
let expected = vec![2, 3, 4, 5, 6, 7];
let skipped = decoder.skip(2).expect("skipping values");
assert_eq!(skipped, 2);
@@ -598,18 +595,17 @@ mod tests {
fn test_rle_decode_bool() {
// RLE test data: 50 1s followed by 50 0s
// 01100100 00000001 01100100 00000000
- let data1 = ByteBufferPtr::new(vec![0x64, 0x01, 0x64, 0x00]);
+ let data1 = vec![0x64, 0x01, 0x64, 0x00];
// Bit-packing test data: alternating 1s and 0s, 100 total
// 100 / 8 = 13 groups
// 00011011 10101010 ... 00001010
- let data2 = ByteBufferPtr::new(vec![
- 0x1B, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA,
- 0x0A,
- ]);
+ let data2 = vec![
+ 0x1B, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x0A,
+ ];
let mut decoder: RleDecoder = RleDecoder::new(1);
- decoder.set_data(data1);
+ decoder.set_data(data1.into());
let mut buffer = vec![false; 100];
let mut expected = vec![];
for i in 0..100 {
@@ -623,7 +619,7 @@ mod tests {
assert!(result.is_ok());
assert_eq!(buffer, expected);
- decoder.set_data(data2);
+ decoder.set_data(data2.into());
let mut buffer = vec![false; 100];
let mut expected = vec![];
for i in 0..100 {
@@ -642,18 +638,17 @@ mod tests {
fn test_rle_skip_bool() {
// RLE test data: 50 1s followed by 50 0s
// 01100100 00000001 01100100 00000000
- let data1 = ByteBufferPtr::new(vec![0x64, 0x01, 0x64, 0x00]);
+ let data1 = vec![0x64, 0x01, 0x64, 0x00];
// Bit-packing test data: alternating 1s and 0s, 100 total
// 100 / 8 = 13 groups
// 00011011 10101010 ... 00001010
- let data2 = ByteBufferPtr::new(vec![
- 0x1B, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA,
- 0x0A,
- ]);
+ let data2 = vec![
+ 0x1B, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x0A,
+ ];
let mut decoder: RleDecoder = RleDecoder::new(1);
- decoder.set_data(data1);
+ decoder.set_data(data1.into());
let mut buffer = vec![true; 50];
let expected = vec![false; 50];
@@ -665,7 +660,7 @@ mod tests {
assert_eq!(remainder, 50);
assert_eq!(buffer, expected);
- decoder.set_data(data2);
+ decoder.set_data(data2.into());
let mut buffer = vec![false; 50];
let mut expected = vec![];
for i in 0..50 {
@@ -689,9 +684,9 @@ mod tests {
// Test RLE encoding: 3 0s followed by 4 1s followed by 5 2s
// 00000110 00000000 00001000 00000001 00001010 00000010
let dict = vec![10, 20, 30];
- let data = ByteBufferPtr::new(vec![0x06, 0x00, 0x08, 0x01, 0x0A, 0x02]);
+ let data = vec![0x06, 0x00, 0x08, 0x01, 0x0A, 0x02];
let mut decoder: RleDecoder = RleDecoder::new(3);
- decoder.set_data(data);
+ decoder.set_data(data.into());
let mut buffer = vec![0; 12];
let expected = vec![10, 10, 10, 20, 20, 20, 20, 30, 30, 30, 30, 30];
let result = decoder.get_batch_with_dict::<i32>(&dict, &mut buffer, 12);
@@ -702,9 +697,9 @@ mod tests {
// 011 100 101 011 100 101 011 100 101 100 101 101
// 00000011 01100011 11000111 10001110 00000011 01100101 00001011
let dict = vec!["aaa", "bbb", "ccc", "ddd", "eee", "fff"];
- let data = ByteBufferPtr::new(vec![0x03, 0x63, 0xC7, 0x8E, 0x03, 0x65, 0x0B]);
+ let data = vec![0x03, 0x63, 0xC7, 0x8E, 0x03, 0x65, 0x0B];
let mut decoder: RleDecoder = RleDecoder::new(3);
- decoder.set_data(data);
+ decoder.set_data(data.into());
let mut buffer = vec![""; 12];
let expected = vec![
"ddd", "eee", "fff", "ddd", "eee", "fff", "ddd", "eee", "fff", "eee", "fff",
@@ -724,9 +719,9 @@ mod tests {
// Test RLE encoding: 3 0s followed by 4 1s followed by 5 2s
// 00000110 00000000 00001000 00000001 00001010 00000010
let dict = vec![10, 20, 30];
- let data = ByteBufferPtr::new(vec![0x06, 0x00, 0x08, 0x01, 0x0A, 0x02]);
+ let data = vec![0x06, 0x00, 0x08, 0x01, 0x0A, 0x02];
let mut decoder: RleDecoder = RleDecoder::new(3);
- decoder.set_data(data);
+ decoder.set_data(data.into());
let mut buffer = vec![0; 10];
let expected = vec![10, 20, 20, 20, 20, 30, 30, 30, 30, 30];
let skipped = decoder.skip(2).expect("skipping two values");
@@ -741,9 +736,9 @@ mod tests {
// 011 100 101 011 100 101 011 100 101 100 101 101
// 00000011 01100011 11000111 10001110 00000011 01100101 00001011
let dict = vec!["aaa", "bbb", "ccc", "ddd", "eee", "fff"];
- let data = ByteBufferPtr::new(vec![0x03, 0x63, 0xC7, 0x8E, 0x03, 0x65, 0x0B]);
+ let data = vec![0x03, 0x63, 0xC7, 0x8E, 0x03, 0x65, 0x0B];
let mut decoder: RleDecoder = RleDecoder::new(3);
- decoder.set_data(data);
+ decoder.set_data(data.into());
let mut buffer = vec![""; 8];
let expected = vec!["eee", "fff", "ddd", "eee", "fff", "eee", "fff", "fff"];
let skipped = decoder.skip(4).expect("skipping four values");
@@ -766,7 +761,7 @@ mod tests {
for v in values {
encoder.put(*v as u64)
}
- let buffer = ByteBufferPtr::new(encoder.consume());
+ let buffer: Bytes = encoder.consume().into();
if expected_len != -1 {
assert_eq!(buffer.len(), expected_len as usize);
}
@@ -776,7 +771,7 @@ mod tests {
// Verify read
let mut decoder = RleDecoder::new(bit_width);
- decoder.set_data(buffer.all());
+ decoder.set_data(buffer.clone());
for v in values {
let val: i64 = decoder
.get()
@@ -888,7 +883,7 @@ mod tests {
(3 << 1) | 1, // bit-packed run of 3 * 8
];
data.extend(std::iter::repeat(0xFF).take(20));
- let data = ByteBufferPtr::new(data);
+ let data: Bytes = data.into();
let mut decoder = RleDecoder::new(8);
decoder.set_data(data.clone());
@@ -926,7 +921,7 @@ mod tests {
buffer.push(0);
let mut decoder = RleDecoder::new(bit_width);
- decoder.set_data(ByteBufferPtr::new(buffer));
+ decoder.set_data(buffer.into());
// We don't always reliably know how many non-null values are contained in a page
// and so the decoder must work correctly without a precise value count
@@ -963,7 +958,7 @@ mod tests {
for _ in 0..run_bytes {
writer.put_aligned(0xFF_u8, 1);
}
- let buffer = ByteBufferPtr::new(writer.consume());
+ let buffer: Bytes = writer.consume().into();
let mut decoder = RleDecoder::new(1);
decoder.set_data(buffer.clone());
@@ -992,7 +987,7 @@ mod tests {
}
let buffer = encoder.consume();
let mut decoder = RleDecoder::new(bit_width);
- decoder.set_data(ByteBufferPtr::new(buffer));
+ decoder.set_data(Bytes::from(buffer));
let mut actual_values: Vec<i16> = vec![0; values.len()];
decoder
.get_batch(&mut actual_values)
@@ -1007,11 +1002,11 @@ mod tests {
encoder.put(*v as u64)
}
- let buffer = ByteBufferPtr::new(encoder.consume());
+ let buffer = Bytes::from(encoder.consume());
// Verify read
let mut decoder = RleDecoder::new(bit_width);
- decoder.set_data(buffer.all());
+ decoder.set_data(buffer.clone());
for v in values {
let val = decoder
.get::<i32>()
diff --git a/parquet/src/file/serialized_reader.rs b/parquet/src/file/serialized_reader.rs
index 0d032c27aa06..43e169cd085b 100644
--- a/parquet/src/file/serialized_reader.rs
+++ b/parquet/src/file/serialized_reader.rs
@@ -40,7 +40,7 @@ use crate::record::reader::RowIter;
use crate::record::Row;
use crate::schema::types::Type as SchemaType;
use crate::thrift::{TCompactSliceInputProtocol, TSerializable};
-use crate::util::memory::ByteBufferPtr;
+use bytes::Bytes;
use thrift::protocol::TCompactInputProtocol;
impl TryFrom<File> for SerializedFileReader<File> {
@@ -386,7 +386,7 @@ fn read_page_header_len<T: Read>(input: &mut T) -> Result<(usize, PageHeader)> {
/// Decodes a [`Page`] from the provided `buffer`
pub(crate) fn decode_page(
page_header: PageHeader,
- buffer: ByteBufferPtr,
+ buffer: Bytes,
physical_type: Type,
decompressor: Option<&mut Box<dyn Codec>>,
) -> Result<Page> {
@@ -428,7 +428,7 @@ pub(crate) fn decode_page(
));
}
- ByteBufferPtr::new(decompressed)
+ Bytes::from(decompressed)
}
_ => buffer,
};
@@ -627,7 +627,7 @@ impl<R: ChunkReader> PageReader for SerializedPageReader<R> {
decode_page(
header,
- ByteBufferPtr::new(buffer),
+ Bytes::from(buffer),
self.physical_type,
self.decompressor.as_mut(),
)?
@@ -656,7 +656,7 @@ impl<R: ChunkReader> PageReader for SerializedPageReader<R> {
let bytes = buffer.slice(offset..);
decode_page(
header,
- bytes.into(),
+ bytes,
self.physical_type,
self.decompressor.as_mut(),
)?
diff --git a/parquet/src/file/writer.rs b/parquet/src/file/writer.rs
index dbbd8b4b99a2..2b9f261d9f42 100644
--- a/parquet/src/file/writer.rs
+++ b/parquet/src/file/writer.rs
@@ -756,7 +756,6 @@ mod tests {
use crate::record::{Row, RowAccessor};
use crate::schema::parser::parse_message_type;
use crate::schema::types::{ColumnDescriptor, ColumnPath};
- use crate::util::memory::ByteBufferPtr;
#[test]
fn test_row_group_writer_error_not_all_columns_written() {
@@ -1040,7 +1039,7 @@ mod tests {
fn test_page_writer_data_pages() {
let pages = vec![
Page::DataPage {
- buf: ByteBufferPtr::new(vec![1, 2, 3, 4, 5, 6, 7, 8]),
+ buf: Bytes::from(vec![1, 2, 3, 4, 5, 6, 7, 8]),
num_values: 10,
encoding: Encoding::DELTA_BINARY_PACKED,
def_level_encoding: Encoding::RLE,
@@ -1048,7 +1047,7 @@ mod tests {
statistics: Some(Statistics::int32(Some(1), Some(3), None, 7, true)),
},
Page::DataPageV2 {
- buf: ByteBufferPtr::new(vec![4; 128]),
+ buf: Bytes::from(vec![4; 128]),
num_values: 10,
encoding: Encoding::DELTA_BINARY_PACKED,
num_nulls: 2,
@@ -1068,13 +1067,13 @@ mod tests {
fn test_page_writer_dict_pages() {
let pages = vec![
Page::DictionaryPage {
- buf: ByteBufferPtr::new(vec![1, 2, 3, 4, 5]),
+ buf: Bytes::from(vec![1, 2, 3, 4, 5]),
num_values: 5,
encoding: Encoding::RLE_DICTIONARY,
is_sorted: false,
},
Page::DataPage {
- buf: ByteBufferPtr::new(vec![1, 2, 3, 4, 5, 6, 7, 8]),
+ buf: Bytes::from(vec![1, 2, 3, 4, 5, 6, 7, 8]),
num_values: 10,
encoding: Encoding::DELTA_BINARY_PACKED,
def_level_encoding: Encoding::RLE,
@@ -1082,7 +1081,7 @@ mod tests {
statistics: Some(Statistics::int32(Some(1), Some(3), None, 7, true)),
},
Page::DataPageV2 {
- buf: ByteBufferPtr::new(vec![4; 128]),
+ buf: Bytes::from(vec![4; 128]),
num_values: 10,
encoding: Encoding::DELTA_BINARY_PACKED,
num_nulls: 2,
@@ -1122,10 +1121,10 @@ mod tests {
ref statistics,
} => {
total_num_values += num_values as i64;
- let output_buf = compress_helper(compressor.as_mut(), buf.data());
+ let output_buf = compress_helper(compressor.as_mut(), buf);
Page::DataPage {
- buf: ByteBufferPtr::new(output_buf),
+ buf: Bytes::from(output_buf),
num_values,
encoding,
def_level_encoding,
@@ -1147,12 +1146,12 @@ mod tests {
} => {
total_num_values += num_values as i64;
let offset = (def_levels_byte_len + rep_levels_byte_len) as usize;
- let cmp_buf = compress_helper(compressor.as_mut(), &buf.data()[offset..]);
- let mut output_buf = Vec::from(&buf.data()[..offset]);
+ let cmp_buf = compress_helper(compressor.as_mut(), &buf[offset..]);
+ let mut output_buf = Vec::from(&buf[..offset]);
output_buf.extend_from_slice(&cmp_buf[..]);
Page::DataPageV2 {
- buf: ByteBufferPtr::new(output_buf),
+ buf: Bytes::from(output_buf),
num_values,
encoding,
num_nulls,
@@ -1170,10 +1169,10 @@ mod tests {
encoding,
is_sorted,
} => {
- let output_buf = compress_helper(compressor.as_mut(), buf.data());
+ let output_buf = compress_helper(compressor.as_mut(), buf);
Page::DictionaryPage {
- buf: ByteBufferPtr::new(output_buf),
+ buf: Bytes::from(output_buf),
num_values,
encoding,
is_sorted,
@@ -1248,7 +1247,7 @@ mod tests {
/// Check if pages match.
fn assert_page(left: &Page, right: &Page) {
assert_eq!(left.page_type(), right.page_type());
- assert_eq!(left.buffer().data(), right.buffer().data());
+ assert_eq!(&left.buffer(), &right.buffer());
assert_eq!(left.num_values(), right.num_values());
assert_eq!(left.encoding(), right.encoding());
assert_eq!(to_thrift(left.statistics()), to_thrift(right.statistics()));
diff --git a/parquet/src/lib.rs b/parquet/src/lib.rs
index f1612c90cc2a..0279bbc382ea 100644
--- a/parquet/src/lib.rs
+++ b/parquet/src/lib.rs
@@ -74,10 +74,6 @@ pub mod data_type;
#[doc(hidden)]
pub use self::encodings::{decoding, encoding};
-#[cfg(feature = "experimental")]
-#[doc(hidden)]
-pub use self::util::memory;
-
experimental!(#[macro_use] mod util);
#[cfg(feature = "arrow")]
pub mod arrow;
diff --git a/parquet/src/util/bit_util.rs b/parquet/src/util/bit_util.rs
index 597190a46eff..b1dd23574a19 100644
--- a/parquet/src/util/bit_util.rs
+++ b/parquet/src/util/bit_util.rs
@@ -17,10 +17,11 @@
use std::{cmp, mem::size_of};
+use bytes::Bytes;
+
use crate::data_type::{AsBytes, ByteArray, FixedLenByteArray, Int96};
use crate::errors::{ParquetError, Result};
use crate::util::bit_pack::{unpack16, unpack32, unpack64, unpack8};
-use crate::util::memory::ByteBufferPtr;
#[inline]
pub fn from_le_slice<T: FromBytes>(bs: &[u8]) -> T {
@@ -341,7 +342,7 @@ pub const MAX_VLQ_BYTE_LEN: usize = 10;
pub struct BitReader {
/// The byte buffer to read from, passed in by client
- buffer: ByteBufferPtr,
+ buffer: Bytes,
/// Bytes are memcpy'd from `buffer` and values are read from this variable.
/// This is faster than reading values byte by byte directly from `buffer`
@@ -365,7 +366,7 @@ pub struct BitReader {
/// Utility class to read bit/byte stream. This class can read bits or bytes that are
/// either byte aligned or not.
impl BitReader {
- pub fn new(buffer: ByteBufferPtr) -> Self {
+ pub fn new(buffer: Bytes) -> Self {
BitReader {
buffer,
buffered_values: 0,
@@ -374,7 +375,7 @@ impl BitReader {
}
}
- pub fn reset(&mut self, buffer: ByteBufferPtr) {
+ pub fn reset(&mut self, buffer: Bytes) {
self.buffer = buffer;
self.buffered_values = 0;
self.byte_offset = 0;
@@ -456,8 +457,6 @@ impl BitReader {
}
}
- let in_buf = self.buffer.data();
-
// Read directly into output buffer
match size_of::<T>() {
1 => {
@@ -465,7 +464,7 @@ impl BitReader {
let out = unsafe { std::slice::from_raw_parts_mut(ptr, batch.len()) };
while values_to_read - i >= 8 {
let out_slice = (&mut out[i..i + 8]).try_into().unwrap();
- unpack8(&in_buf[self.byte_offset..], out_slice, num_bits);
+ unpack8(&self.buffer[self.byte_offset..], out_slice, num_bits);
self.byte_offset += num_bits;
i += 8;
}
@@ -475,7 +474,7 @@ impl BitReader {
let out = unsafe { std::slice::from_raw_parts_mut(ptr, batch.len()) };
while values_to_read - i >= 16 {
let out_slice = (&mut out[i..i + 16]).try_into().unwrap();
- unpack16(&in_buf[self.byte_offset..], out_slice, num_bits);
+ unpack16(&self.buffer[self.byte_offset..], out_slice, num_bits);
self.byte_offset += 2 * num_bits;
i += 16;
}
@@ -485,7 +484,7 @@ impl BitReader {
let out = unsafe { std::slice::from_raw_parts_mut(ptr, batch.len()) };
while values_to_read - i >= 32 {
let out_slice = (&mut out[i..i + 32]).try_into().unwrap();
- unpack32(&in_buf[self.byte_offset..], out_slice, num_bits);
+ unpack32(&self.buffer[self.byte_offset..], out_slice, num_bits);
self.byte_offset += 4 * num_bits;
i += 32;
}
@@ -495,7 +494,7 @@ impl BitReader {
let out = unsafe { std::slice::from_raw_parts_mut(ptr, batch.len()) };
while values_to_read - i >= 64 {
let out_slice = (&mut out[i..i + 64]).try_into().unwrap();
- unpack64(&in_buf[self.byte_offset..], out_slice, num_bits);
+ unpack64(&self.buffer[self.byte_offset..], out_slice, num_bits);
self.byte_offset += 8 * num_bits;
i += 64;
}
@@ -506,7 +505,7 @@ impl BitReader {
// Try to read smaller batches if possible
if size_of::<T>() > 4 && values_to_read - i >= 32 && num_bits <= 32 {
let mut out_buf = [0_u32; 32];
- unpack32(&in_buf[self.byte_offset..], &mut out_buf, num_bits);
+ unpack32(&self.buffer[self.byte_offset..], &mut out_buf, num_bits);
self.byte_offset += 4 * num_bits;
for out in out_buf {
@@ -520,7 +519,7 @@ impl BitReader {
if size_of::<T>() > 2 && values_to_read - i >= 16 && num_bits <= 16 {
let mut out_buf = [0_u16; 16];
- unpack16(&in_buf[self.byte_offset..], &mut out_buf, num_bits);
+ unpack16(&self.buffer[self.byte_offset..], &mut out_buf, num_bits);
self.byte_offset += 2 * num_bits;
for out in out_buf {
@@ -534,7 +533,7 @@ impl BitReader {
if size_of::<T>() > 1 && values_to_read - i >= 8 && num_bits <= 8 {
let mut out_buf = [0_u8; 8];
- unpack8(&in_buf[self.byte_offset..], &mut out_buf, num_bits);
+ unpack8(&self.buffer[self.byte_offset..], &mut out_buf, num_bits);
self.byte_offset += num_bits;
for out in out_buf {
@@ -595,7 +594,7 @@ impl BitReader {
self.byte_offset = self.get_byte_offset();
self.bit_offset = 0;
- let src = &self.buffer.data()[self.byte_offset..];
+ let src = &self.buffer[self.byte_offset..];
let to_read = num_bytes.min(src.len());
buf.extend_from_slice(&src[..to_read]);
@@ -620,7 +619,7 @@ impl BitReader {
}
// Advance byte_offset to next unread byte and read num_bytes
- let v = read_num_bytes::<T>(num_bytes, &self.buffer.data()[self.byte_offset..]);
+ let v = read_num_bytes::<T>(num_bytes, &self.buffer[self.byte_offset..]);
self.byte_offset += num_bytes;
Some(v)
@@ -672,14 +671,14 @@ impl BitReader {
fn load_buffered_values(&mut self) {
let bytes_to_read = cmp::min(self.buffer.len() - self.byte_offset, 8);
self.buffered_values =
- read_num_bytes::<u64>(bytes_to_read, &self.buffer.data()[self.byte_offset..]);
+ read_num_bytes::<u64>(bytes_to_read, &self.buffer[self.byte_offset..]);
}
}
impl From<Vec<u8>> for BitReader {
#[inline]
fn from(buffer: Vec<u8>) -> Self {
- BitReader::new(ByteBufferPtr::new(buffer))
+ BitReader::new(buffer.into())
}
}
@@ -771,12 +770,12 @@ mod tests {
#[test]
fn test_bit_reader_get_aligned() {
// 01110101 11001011
- let buffer = ByteBufferPtr::new(vec![0x75, 0xCB]);
- let mut bit_reader = BitReader::new(buffer.all());
+ let buffer = Bytes::from(vec![0x75, 0xCB]);
+ let mut bit_reader = BitReader::new(buffer.clone());
assert_eq!(bit_reader.get_value::<i32>(3), Some(5));
assert_eq!(bit_reader.get_aligned::<i32>(1), Some(203));
assert_eq!(bit_reader.get_value::<i32>(1), None);
- bit_reader.reset(buffer.all());
+ bit_reader.reset(buffer.clone());
assert_eq!(bit_reader.get_aligned::<i32>(3), None);
}
@@ -1128,7 +1127,7 @@ mod tests {
#[test]
fn test_get_batch_zero_extend() {
let to_read = vec![0xFF; 4];
- let mut reader = BitReader::new(ByteBufferPtr::new(to_read));
+ let mut reader = BitReader::from(to_read);
// Create a non-zeroed output buffer
let mut output = [u64::MAX; 32];
diff --git a/parquet/src/util/memory.rs b/parquet/src/util/memory.rs
deleted file mode 100644
index 25d15dd4ff73..000000000000
--- a/parquet/src/util/memory.rs
+++ /dev/null
@@ -1,149 +0,0 @@
-// 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.
-
-//! Utility methods and structs for working with memory.
-
-use bytes::Bytes;
-use std::{
- fmt::{Debug, Display, Formatter, Result as FmtResult},
- ops::Index,
-};
-
-// ----------------------------------------------------------------------
-// Immutable Buffer (BufferPtr) classes
-
-/// An representation of a slice on a reference-counting and read-only byte array.
-/// Sub-slices can be further created from this. The byte array will be released
-/// when all slices are dropped.
-///
-/// TODO: Remove and replace with [`bytes::Bytes`]
-#[derive(Clone, Debug)]
-pub struct ByteBufferPtr {
- data: Bytes,
-}
-
-impl ByteBufferPtr {
- /// Creates new buffer from a vector.
- pub fn new(v: Vec<u8>) -> Self {
- Self { data: v.into() }
- }
-
- /// Returns slice of data in this buffer.
- #[inline]
- pub fn data(&self) -> &[u8] {
- &self.data
- }
-
- /// Returns length of this buffer
- #[inline]
- pub fn len(&self) -> usize {
- self.data.len()
- }
-
- /// Returns whether this buffer is empty
- #[inline]
- pub fn is_empty(&self) -> bool {
- self.data.is_empty()
- }
-
- /// Returns a shallow copy of the buffer.
- /// Reference counted pointer to the data is copied.
- pub fn all(&self) -> Self {
- self.clone()
- }
-
- /// Returns a shallow copy of the buffer that starts with `start` position.
- pub fn start_from(&self, start: usize) -> Self {
- Self {
- data: self.data.slice(start..),
- }
- }
-
- /// Returns a shallow copy that is a range slice within this buffer.
- pub fn range(&self, start: usize, len: usize) -> Self {
- Self {
- data: self.data.slice(start..start + len),
- }
- }
-}
-
-impl Index<usize> for ByteBufferPtr {
- type Output = u8;
-
- fn index(&self, index: usize) -> &u8 {
- &self.data[index]
- }
-}
-
-impl Display for ByteBufferPtr {
- fn fmt(&self, f: &mut Formatter) -> FmtResult {
- write!(f, "{:?}", self.data)
- }
-}
-
-impl AsRef<[u8]> for ByteBufferPtr {
- #[inline]
- fn as_ref(&self) -> &[u8] {
- &self.data
- }
-}
-
-impl From<Vec<u8>> for ByteBufferPtr {
- fn from(data: Vec<u8>) -> Self {
- Self { data: data.into() }
- }
-}
-
-impl From<Bytes> for ByteBufferPtr {
- fn from(data: Bytes) -> Self {
- Self { data }
- }
-}
-
-impl From<ByteBufferPtr> for Bytes {
- fn from(value: ByteBufferPtr) -> Self {
- value.data
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn test_byte_ptr() {
- let values = (0..50).collect();
- let ptr = ByteBufferPtr::new(values);
- assert_eq!(ptr.len(), 50);
- assert_eq!(ptr[40], 40);
-
- let ptr2 = ptr.all();
- assert_eq!(ptr2.len(), 50);
- assert_eq!(ptr2[40], 40);
-
- let ptr3 = ptr.start_from(20);
- assert_eq!(ptr3.len(), 30);
- assert_eq!(ptr3[0], 20);
-
- let ptr4 = ptr3.range(10, 10);
- assert_eq!(ptr4.len(), 10);
- assert_eq!(ptr4[0], 30);
-
- let expected: Vec<u8> = (30..40).collect();
- assert_eq!(ptr4.as_ref(), expected.as_slice());
- }
-}
diff --git a/parquet/src/util/mod.rs b/parquet/src/util/mod.rs
index d96a62a9f363..dfa1285afcf2 100644
--- a/parquet/src/util/mod.rs
+++ b/parquet/src/util/mod.rs
@@ -15,7 +15,6 @@
// specific language governing permissions and limitations
// under the License.
-pub mod memory;
#[macro_use]
pub mod bit_util;
mod bit_pack;
|
diff --git a/parquet/src/arrow/array_reader/test_util.rs b/parquet/src/arrow/array_reader/test_util.rs
index 7e66efead2e5..05032920139b 100644
--- a/parquet/src/arrow/array_reader/test_util.rs
+++ b/parquet/src/arrow/array_reader/test_util.rs
@@ -17,6 +17,7 @@
use arrow_array::{Array, ArrayRef};
use arrow_schema::DataType as ArrowType;
+use bytes::Bytes;
use std::any::Any;
use std::sync::Arc;
@@ -27,7 +28,6 @@ use crate::data_type::{ByteArray, ByteArrayType};
use crate::encodings::encoding::{get_encoder, DictEncoder, Encoder};
use crate::errors::Result;
use crate::schema::types::{ColumnDescPtr, ColumnDescriptor, ColumnPath, Type};
-use crate::util::memory::ByteBufferPtr;
/// Returns a descriptor for a UTF-8 column
pub fn utf8_column() -> ColumnDescPtr {
@@ -45,7 +45,7 @@ pub fn utf8_column() -> ColumnDescPtr {
}
/// Encode `data` with the provided `encoding`
-pub fn encode_byte_array(encoding: Encoding, data: &[ByteArray]) -> ByteBufferPtr {
+pub fn encode_byte_array(encoding: Encoding, data: &[ByteArray]) -> Bytes {
let mut encoder = get_encoder::<ByteArrayType>(encoding).unwrap();
encoder.put(data).unwrap();
@@ -53,7 +53,7 @@ pub fn encode_byte_array(encoding: Encoding, data: &[ByteArray]) -> ByteBufferPt
}
/// Returns the encoded dictionary and value data
-pub fn encode_dictionary(data: &[ByteArray]) -> (ByteBufferPtr, ByteBufferPtr) {
+pub fn encode_dictionary(data: &[ByteArray]) -> (Bytes, Bytes) {
let mut dict_encoder = DictEncoder::<ByteArrayType>::new(utf8_column());
dict_encoder.put(data).unwrap();
@@ -68,7 +68,7 @@ pub fn encode_dictionary(data: &[ByteArray]) -> (ByteBufferPtr, ByteBufferPtr) {
/// Returns an array of data with its associated encoding, along with an encoded dictionary
pub fn byte_array_all_encodings(
data: Vec<impl Into<ByteArray>>,
-) -> (Vec<(Encoding, ByteBufferPtr)>, ByteBufferPtr) {
+) -> (Vec<(Encoding, Bytes)>, Bytes) {
let data: Vec<_> = data.into_iter().map(Into::into).collect();
let (encoded_dictionary, encoded_rle) = encode_dictionary(&data);
diff --git a/parquet/src/util/test_common/page_util.rs b/parquet/src/util/test_common/page_util.rs
index c51c5158cd42..b4fed752fdc5 100644
--- a/parquet/src/util/test_common/page_util.rs
+++ b/parquet/src/util/test_common/page_util.rs
@@ -15,6 +15,8 @@
// specific language governing permissions and limitations
// under the License.
+use bytes::Bytes;
+
use crate::basic::Encoding;
use crate::column::page::{Page, PageIterator};
use crate::column::page::{PageMetadata, PageReader};
@@ -23,7 +25,6 @@ use crate::encodings::encoding::{get_encoder, Encoder};
use crate::encodings::levels::LevelEncoder;
use crate::errors::Result;
use crate::schema::types::ColumnDescPtr;
-use crate::util::memory::ByteBufferPtr;
use std::iter::Peekable;
use std::mem;
@@ -31,7 +32,7 @@ pub trait DataPageBuilder {
fn add_rep_levels(&mut self, max_level: i16, rep_levels: &[i16]);
fn add_def_levels(&mut self, max_level: i16, def_levels: &[i16]);
fn add_values<T: DataType>(&mut self, encoding: Encoding, values: &[T::T]);
- fn add_indices(&mut self, indices: ByteBufferPtr);
+ fn add_indices(&mut self, indices: Bytes);
fn consume(self) -> Page;
}
@@ -112,18 +113,18 @@ impl DataPageBuilder for DataPageBuilderImpl {
let encoded_values = encoder
.flush_buffer()
.expect("consume_buffer() should be OK");
- self.buffer.extend_from_slice(encoded_values.data());
+ self.buffer.extend_from_slice(&encoded_values);
}
- fn add_indices(&mut self, indices: ByteBufferPtr) {
+ fn add_indices(&mut self, indices: Bytes) {
self.encoding = Some(Encoding::RLE_DICTIONARY);
- self.buffer.extend_from_slice(indices.data());
+ self.buffer.extend_from_slice(&indices);
}
fn consume(self) -> Page {
if self.datapage_v2 {
Page::DataPageV2 {
- buf: ByteBufferPtr::new(self.buffer),
+ buf: Bytes::from(self.buffer),
num_values: self.num_values,
encoding: self.encoding.unwrap(),
num_nulls: 0, /* set to dummy value - don't need this when reading
@@ -137,7 +138,7 @@ impl DataPageBuilder for DataPageBuilderImpl {
}
} else {
Page::DataPage {
- buf: ByteBufferPtr::new(self.buffer),
+ buf: Bytes::from(self.buffer),
num_values: self.num_values,
encoding: self.encoding.unwrap(),
def_level_encoding: Encoding::RLE,
diff --git a/parquet/src/util/test_common/rand_gen.rs b/parquet/src/util/test_common/rand_gen.rs
index c36b9060ca58..a267c34840c1 100644
--- a/parquet/src/util/test_common/rand_gen.rs
+++ b/parquet/src/util/test_common/rand_gen.rs
@@ -17,6 +17,7 @@
use crate::basic::Encoding;
use crate::column::page::Page;
+use bytes::Bytes;
use rand::{
distributions::{uniform::SampleUniform, Distribution, Standard},
thread_rng, Rng,
@@ -26,7 +27,6 @@ use std::collections::VecDeque;
use crate::data_type::*;
use crate::encodings::encoding::{DictEncoder, Encoder};
use crate::schema::types::ColumnDescPtr;
-use crate::util::memory::ByteBufferPtr;
use crate::util::{DataPageBuilder, DataPageBuilderImpl};
/// Random generator of data type `T` values and sequences.
@@ -90,7 +90,7 @@ impl RandGen<ByteArrayType> for ByteArrayType {
for _ in 0..len {
value.push(rng.gen_range(0..255));
}
- result.set_data(ByteBufferPtr::new(value));
+ result.set_data(Bytes::from(value));
result
}
}
|
Replace Custom Buffer Implementation with Bytes in Parquet
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
The parquet crate currently rolls its own `ByteBufferPtr`, `BufferPtr`, `Buffer`, etc... and this feels like functionality that could be provided by an upstream crate.
**Describe the solution you'd like**
The [bytes](https://docs.rs/bytes/latest/bytes/) crate has wide ecosystem adoption and supports most of the necessary functionality. It does not support memory tracking, but I'm not sure this is being used given the `util::memory` module was made experimental and therefore not public in https://github.com/apache/arrow-rs/pull/1134 and there hasn't been any wailing nor gnashing of teeth resulting from this.
**Describe alternatives you've considered**
Continue to use custom buffer abstractions.
Tagging @sunchao as I believe he added this code all the way back in 2018 :sweat_smile:
|
Thanks. Yes these are pretty out-dated and I think it will be good to replace them. Have you thought about just use `MutableBuffer` from Arrow side too?
> Have you thought about just use MutableBuffer from Arrow side too?
I hadn't, but I'm not sure it is a good fit
* I would like to use the ecosystem standard abstraction if possible
* `arrow` is currently an optional dependency of `parquet`
* `MutableBuffer` is really designed for arrays of primitives, not raw byte arrays
* I have a long-term hope to eventually phase out `MutableBuffer` and replace it with a typed construction that is easier to use without unsafe. Something with a similar interface to the ScalarBuffer I added to parquet might be a candidate
If possible, we could use Arrow's buffer based on the `arrow` feature, then use some abstraction (I'd be fine with `bytes`) for the other cases. The perf cliff is whenever we create multiple small `ByteBuffer` instances (e.g. representing vec!["hello", "there"]` as 2 instances instead of a single `ByteBuffer` with offsets into the 2 values. I think having a single buffer per page/row group would be helpful.
The upside of using Arrow's buffer is minimising/eliminating data copies. I was able to improve the Arrow side here (https://github.com/apache/arrow-rs/pull/820), and see @alamb's comment (https://github.com/apache/arrow-rs/pull/820#discussion_r724365907).
> I have a long-term hope to eventually phase out MutableBuffer and replace it with a typed construction that is easier to use without unsafe. Something with a similar interface to the ScalarBuffer I added to parquet might be a candidate
This would be great, as it seems that a lot of the safety (and some perf) issues lie there.
I think using `Bytes` would have many advantages (such as potentially avoiding copies from data that are read from remote object stores. etc)
|
2023-11-07T20:52:19Z
|
49.0
|
a9470d3eb083303350fc109f94865666fd0f062f
|
apache/arrow-rs
| 5,003
|
apache__arrow-rs-5003
|
[
"4986"
] |
f53f284b3e6933433c656f4d66e851b566c58c32
|
diff --git a/parquet/Cargo.toml b/parquet/Cargo.toml
index e5f5e1652b82..bdcbcb81cfce 100644
--- a/parquet/Cargo.toml
+++ b/parquet/Cargo.toml
@@ -66,6 +66,7 @@ tokio = { version = "1.0", optional = true, default-features = false, features =
hashbrown = { version = "0.14", default-features = false }
twox-hash = { version = "1.6", default-features = false }
paste = { version = "1.0" }
+half = { version = "2.1", default-features = false, features = ["num-traits"] }
[dev-dependencies]
base64 = { version = "0.21", default-features = false, features = ["std"] }
diff --git a/parquet/regen.sh b/parquet/regen.sh
index b8c3549e2324..91539634339d 100755
--- a/parquet/regen.sh
+++ b/parquet/regen.sh
@@ -17,7 +17,7 @@
# specific language governing permissions and limitations
# under the License.
-REVISION=aeae80660c1d0c97314e9da837de1abdebd49c37
+REVISION=46cc3a0647d301bb9579ca8dd2cc356caf2a72d2
SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)"
diff --git a/parquet/src/arrow/array_reader/fixed_len_byte_array.rs b/parquet/src/arrow/array_reader/fixed_len_byte_array.rs
index 3b1a50ebcce8..b846997d36b8 100644
--- a/parquet/src/arrow/array_reader/fixed_len_byte_array.rs
+++ b/parquet/src/arrow/array_reader/fixed_len_byte_array.rs
@@ -27,13 +27,14 @@ use crate::column::reader::decoder::{ColumnValueDecoder, ValuesBufferSlice};
use crate::errors::{ParquetError, Result};
use crate::schema::types::ColumnDescPtr;
use arrow_array::{
- ArrayRef, Decimal128Array, Decimal256Array, FixedSizeBinaryArray,
+ ArrayRef, Decimal128Array, Decimal256Array, FixedSizeBinaryArray, Float16Array,
IntervalDayTimeArray, IntervalYearMonthArray,
};
use arrow_buffer::{i256, Buffer};
use arrow_data::ArrayDataBuilder;
use arrow_schema::{DataType as ArrowType, IntervalUnit};
use bytes::Bytes;
+use half::f16;
use std::any::Any;
use std::ops::Range;
use std::sync::Arc;
@@ -88,6 +89,14 @@ pub fn make_fixed_len_byte_array_reader(
));
}
}
+ ArrowType::Float16 => {
+ if byte_length != 2 {
+ return Err(general_err!(
+ "float 16 type must be 2 bytes, got {}",
+ byte_length
+ ));
+ }
+ }
_ => {
return Err(general_err!(
"invalid data type for fixed length byte array reader - {}",
@@ -208,6 +217,12 @@ impl ArrayReader for FixedLenByteArrayReader {
}
}
}
+ ArrowType::Float16 => Arc::new(
+ binary
+ .iter()
+ .map(|o| o.map(|b| f16::from_le_bytes(b[..2].try_into().unwrap())))
+ .collect::<Float16Array>(),
+ ) as ArrayRef,
_ => Arc::new(binary) as ArrayRef,
};
diff --git a/parquet/src/arrow/arrow_reader/mod.rs b/parquet/src/arrow/arrow_reader/mod.rs
index 16cdf2934e6f..b9e9d2898459 100644
--- a/parquet/src/arrow/arrow_reader/mod.rs
+++ b/parquet/src/arrow/arrow_reader/mod.rs
@@ -712,13 +712,14 @@ mod tests {
use std::sync::Arc;
use bytes::Bytes;
+ use half::f16;
use num::PrimInt;
use rand::{thread_rng, Rng, RngCore};
use tempfile::tempfile;
use arrow_array::builder::*;
use arrow_array::cast::AsArray;
- use arrow_array::types::{Decimal128Type, Decimal256Type, DecimalType};
+ use arrow_array::types::{Decimal128Type, Decimal256Type, DecimalType, Float16Type};
use arrow_array::*;
use arrow_array::{RecordBatch, RecordBatchReader};
use arrow_buffer::{i256, ArrowNativeType, Buffer};
@@ -924,6 +925,66 @@ mod tests {
.unwrap();
}
+ #[test]
+ fn test_float16_roundtrip() -> Result<()> {
+ let schema = Arc::new(Schema::new(vec![
+ Field::new("float16", ArrowDataType::Float16, false),
+ Field::new("float16-nullable", ArrowDataType::Float16, true),
+ ]));
+
+ let mut buf = Vec::with_capacity(1024);
+ let mut writer = ArrowWriter::try_new(&mut buf, schema.clone(), None)?;
+
+ let original = RecordBatch::try_new(
+ schema,
+ vec![
+ Arc::new(Float16Array::from_iter_values([
+ f16::EPSILON,
+ f16::MIN,
+ f16::MAX,
+ f16::NAN,
+ f16::INFINITY,
+ f16::NEG_INFINITY,
+ f16::ONE,
+ f16::NEG_ONE,
+ f16::ZERO,
+ f16::NEG_ZERO,
+ f16::E,
+ f16::PI,
+ f16::FRAC_1_PI,
+ ])),
+ Arc::new(Float16Array::from(vec![
+ None,
+ None,
+ None,
+ Some(f16::NAN),
+ Some(f16::INFINITY),
+ Some(f16::NEG_INFINITY),
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ Some(f16::FRAC_1_PI),
+ ])),
+ ],
+ )?;
+
+ writer.write(&original)?;
+ writer.close()?;
+
+ let mut reader = ParquetRecordBatchReader::try_new(Bytes::from(buf), 1024)?;
+ let ret = reader.next().unwrap()?;
+ assert_eq!(ret, original);
+
+ // Ensure can be downcast to the correct type
+ ret.column(0).as_primitive::<Float16Type>();
+ ret.column(1).as_primitive::<Float16Type>();
+
+ Ok(())
+ }
+
struct RandFixedLenGen {}
impl RandGen<FixedLenByteArrayType> for RandFixedLenGen {
@@ -1255,6 +1316,62 @@ mod tests {
}
}
+ #[test]
+ fn test_read_float16_nonzeros_file() {
+ use arrow_array::Float16Array;
+ let testdata = arrow::util::test_util::parquet_test_data();
+ // see https://github.com/apache/parquet-testing/pull/40
+ let path = format!("{testdata}/float16_nonzeros_and_nans.parquet");
+ let file = File::open(path).unwrap();
+ let mut record_reader = ParquetRecordBatchReader::try_new(file, 32).unwrap();
+
+ let batch = record_reader.next().unwrap().unwrap();
+ assert_eq!(batch.num_rows(), 8);
+ let col = batch
+ .column(0)
+ .as_any()
+ .downcast_ref::<Float16Array>()
+ .unwrap();
+
+ let f16_two = f16::ONE + f16::ONE;
+
+ assert_eq!(col.null_count(), 1);
+ assert!(col.is_null(0));
+ assert_eq!(col.value(1), f16::ONE);
+ assert_eq!(col.value(2), -f16_two);
+ assert!(col.value(3).is_nan());
+ assert_eq!(col.value(4), f16::ZERO);
+ assert!(col.value(4).is_sign_positive());
+ assert_eq!(col.value(5), f16::NEG_ONE);
+ assert_eq!(col.value(6), f16::NEG_ZERO);
+ assert!(col.value(6).is_sign_negative());
+ assert_eq!(col.value(7), f16_two);
+ }
+
+ #[test]
+ fn test_read_float16_zeros_file() {
+ use arrow_array::Float16Array;
+ let testdata = arrow::util::test_util::parquet_test_data();
+ // see https://github.com/apache/parquet-testing/pull/40
+ let path = format!("{testdata}/float16_zeros_and_nans.parquet");
+ let file = File::open(path).unwrap();
+ let mut record_reader = ParquetRecordBatchReader::try_new(file, 32).unwrap();
+
+ let batch = record_reader.next().unwrap().unwrap();
+ assert_eq!(batch.num_rows(), 3);
+ let col = batch
+ .column(0)
+ .as_any()
+ .downcast_ref::<Float16Array>()
+ .unwrap();
+
+ assert_eq!(col.null_count(), 1);
+ assert!(col.is_null(0));
+ assert_eq!(col.value(1), f16::ZERO);
+ assert!(col.value(1).is_sign_positive());
+ assert!(col.value(2).is_nan());
+ }
+
/// Parameters for single_column_reader_test
#[derive(Clone)]
struct TestOptions {
diff --git a/parquet/src/arrow/arrow_writer/mod.rs b/parquet/src/arrow/arrow_writer/mod.rs
index eca1dea791be..ea7b1eee99b8 100644
--- a/parquet/src/arrow/arrow_writer/mod.rs
+++ b/parquet/src/arrow/arrow_writer/mod.rs
@@ -771,6 +771,10 @@ fn write_leaf(writer: &mut ColumnWriter<'_>, levels: &ArrayLevels) -> Result<usi
.unwrap();
get_decimal_256_array_slice(array, indices)
}
+ ArrowDataType::Float16 => {
+ let array = column.as_primitive::<Float16Type>();
+ get_float_16_array_slice(array, indices)
+ }
_ => {
return Err(ParquetError::NYI(
"Attempting to write an Arrow type that is not yet implemented".to_string(),
@@ -867,6 +871,18 @@ fn get_decimal_256_array_slice(
values
}
+fn get_float_16_array_slice(
+ array: &arrow_array::Float16Array,
+ indices: &[usize],
+) -> Vec<FixedLenByteArray> {
+ let mut values = Vec::with_capacity(indices.len());
+ for i in indices {
+ let value = array.value(*i).to_le_bytes().to_vec();
+ values.push(FixedLenByteArray::from(ByteArray::from(value)));
+ }
+ values
+}
+
fn get_fsb_array_slice(
array: &arrow_array::FixedSizeBinaryArray,
indices: &[usize],
diff --git a/parquet/src/arrow/schema/mod.rs b/parquet/src/arrow/schema/mod.rs
index d56cc42d4313..4c350c4b1d8c 100644
--- a/parquet/src/arrow/schema/mod.rs
+++ b/parquet/src/arrow/schema/mod.rs
@@ -373,7 +373,12 @@ fn arrow_to_parquet_type(field: &Field) -> Result<Type> {
.with_repetition(repetition)
.with_id(id)
.build(),
- DataType::Float16 => Err(arrow_err!("Float16 arrays not supported")),
+ DataType::Float16 => Type::primitive_type_builder(name, PhysicalType::FIXED_LEN_BYTE_ARRAY)
+ .with_repetition(repetition)
+ .with_id(id)
+ .with_logical_type(Some(LogicalType::Float16))
+ .with_length(2)
+ .build(),
DataType::Float32 => Type::primitive_type_builder(name, PhysicalType::FLOAT)
.with_repetition(repetition)
.with_id(id)
@@ -604,9 +609,10 @@ mod tests {
REQUIRED INT32 uint8 (INTEGER(8,false));
REQUIRED INT32 uint16 (INTEGER(16,false));
REQUIRED INT32 int32;
- REQUIRED INT64 int64 ;
+ REQUIRED INT64 int64;
OPTIONAL DOUBLE double;
OPTIONAL FLOAT float;
+ OPTIONAL FIXED_LEN_BYTE_ARRAY (2) float16 (FLOAT16);
OPTIONAL BINARY string (UTF8);
OPTIONAL BINARY string_2 (STRING);
OPTIONAL BINARY json (JSON);
@@ -628,6 +634,7 @@ mod tests {
Field::new("int64", DataType::Int64, false),
Field::new("double", DataType::Float64, true),
Field::new("float", DataType::Float32, true),
+ Field::new("float16", DataType::Float16, true),
Field::new("string", DataType::Utf8, true),
Field::new("string_2", DataType::Utf8, true),
Field::new("json", DataType::Utf8, true),
@@ -1303,6 +1310,7 @@ mod tests {
REQUIRED INT64 int64;
OPTIONAL DOUBLE double;
OPTIONAL FLOAT float;
+ OPTIONAL FIXED_LEN_BYTE_ARRAY (2) float16 (FLOAT16);
OPTIONAL BINARY string (UTF8);
REPEATED BOOLEAN bools;
OPTIONAL INT32 date (DATE);
@@ -1339,6 +1347,7 @@ mod tests {
Field::new("int64", DataType::Int64, false),
Field::new("double", DataType::Float64, true),
Field::new("float", DataType::Float32, true),
+ Field::new("float16", DataType::Float16, true),
Field::new("string", DataType::Utf8, true),
Field::new_list(
"bools",
@@ -1398,6 +1407,7 @@ mod tests {
REQUIRED INT64 int64;
OPTIONAL DOUBLE double;
OPTIONAL FLOAT float;
+ OPTIONAL FIXED_LEN_BYTE_ARRAY (2) float16 (FLOAT16);
OPTIONAL BINARY string (STRING);
OPTIONAL GROUP bools (LIST) {
REPEATED GROUP list {
@@ -1448,6 +1458,7 @@ mod tests {
Field::new("int64", DataType::Int64, false),
Field::new("double", DataType::Float64, true),
Field::new("float", DataType::Float32, true),
+ Field::new("float16", DataType::Float16, true),
Field::new("string", DataType::Utf8, true),
Field::new_list(
"bools",
@@ -1661,6 +1672,8 @@ mod tests {
vec![
Field::new("a", DataType::Int16, true),
Field::new("b", DataType::Float64, false),
+ Field::new("c", DataType::Float32, false),
+ Field::new("d", DataType::Float16, false),
]
.into(),
),
diff --git a/parquet/src/arrow/schema/primitive.rs b/parquet/src/arrow/schema/primitive.rs
index 7d8b6a04ee81..fdc744831a25 100644
--- a/parquet/src/arrow/schema/primitive.rs
+++ b/parquet/src/arrow/schema/primitive.rs
@@ -304,6 +304,16 @@ fn from_fixed_len_byte_array(
// would be incorrect if all 12 bytes of the interval are populated
Ok(DataType::Interval(IntervalUnit::DayTime))
}
+ (Some(LogicalType::Float16), _) => {
+ if type_length == 2 {
+ Ok(DataType::Float16)
+ } else {
+ Err(ParquetError::General(
+ "FLOAT16 logical type must be Fixed Length Byte Array with length 2"
+ .to_string(),
+ ))
+ }
+ }
_ => Ok(DataType::FixedSizeBinary(type_length)),
}
}
diff --git a/parquet/src/basic.rs b/parquet/src/basic.rs
index 3c8602b8022b..2327e1d84b41 100644
--- a/parquet/src/basic.rs
+++ b/parquet/src/basic.rs
@@ -194,6 +194,7 @@ pub enum LogicalType {
Json,
Bson,
Uuid,
+ Float16,
}
// ----------------------------------------------------------------------
@@ -505,6 +506,7 @@ impl ColumnOrder {
LogicalType::Timestamp { .. } => SortOrder::SIGNED,
LogicalType::Unknown => SortOrder::UNDEFINED,
LogicalType::Uuid => SortOrder::UNSIGNED,
+ LogicalType::Float16 => SortOrder::SIGNED,
},
// Fall back to converted type
None => Self::get_converted_sort_order(converted_type, physical_type),
@@ -766,6 +768,7 @@ impl From<parquet::LogicalType> for LogicalType {
parquet::LogicalType::JSON(_) => LogicalType::Json,
parquet::LogicalType::BSON(_) => LogicalType::Bson,
parquet::LogicalType::UUID(_) => LogicalType::Uuid,
+ parquet::LogicalType::FLOAT16(_) => LogicalType::Float16,
}
}
}
@@ -806,6 +809,7 @@ impl From<LogicalType> for parquet::LogicalType {
LogicalType::Json => parquet::LogicalType::JSON(Default::default()),
LogicalType::Bson => parquet::LogicalType::BSON(Default::default()),
LogicalType::Uuid => parquet::LogicalType::UUID(Default::default()),
+ LogicalType::Float16 => parquet::LogicalType::FLOAT16(Default::default()),
}
}
}
@@ -853,10 +857,11 @@ impl From<Option<LogicalType>> for ConvertedType {
(64, false) => ConvertedType::UINT_64,
t => panic!("Integer type {t:?} is not supported"),
},
- LogicalType::Unknown => ConvertedType::NONE,
LogicalType::Json => ConvertedType::JSON,
LogicalType::Bson => ConvertedType::BSON,
- LogicalType::Uuid => ConvertedType::NONE,
+ LogicalType::Uuid | LogicalType::Float16 | LogicalType::Unknown => {
+ ConvertedType::NONE
+ }
},
None => ConvertedType::NONE,
}
@@ -1102,6 +1107,7 @@ impl str::FromStr for LogicalType {
"INTERVAL" => Err(general_err!(
"Interval parquet logical type not yet supported"
)),
+ "FLOAT16" => Ok(LogicalType::Float16),
other => Err(general_err!("Invalid parquet logical type {}", other)),
}
}
@@ -1746,6 +1752,10 @@ mod tests {
ConvertedType::from(Some(LogicalType::Enum)),
ConvertedType::ENUM
);
+ assert_eq!(
+ ConvertedType::from(Some(LogicalType::Float16)),
+ ConvertedType::NONE
+ );
assert_eq!(
ConvertedType::from(Some(LogicalType::Unknown)),
ConvertedType::NONE
@@ -2119,6 +2129,7 @@ mod tests {
is_adjusted_to_u_t_c: true,
unit: TimeUnit::NANOS(Default::default()),
},
+ LogicalType::Float16,
];
check_sort_order(signed, SortOrder::SIGNED);
diff --git a/parquet/src/column/writer/encoder.rs b/parquet/src/column/writer/encoder.rs
index 2273ae777444..d0720dd24306 100644
--- a/parquet/src/column/writer/encoder.rs
+++ b/parquet/src/column/writer/encoder.rs
@@ -16,8 +16,9 @@
// under the License.
use bytes::Bytes;
+use half::f16;
-use crate::basic::{Encoding, Type};
+use crate::basic::{Encoding, LogicalType, Type};
use crate::bloom_filter::Sbbf;
use crate::column::writer::{
compare_greater, fallback_encoding, has_dictionary_support, is_nan, update_max, update_min,
@@ -291,7 +292,7 @@ where
{
let first = loop {
let next = iter.next()?;
- if !is_nan(next) {
+ if !is_nan(descr, next) {
break next;
}
};
@@ -299,7 +300,7 @@ where
let mut min = first;
let mut max = first;
for val in iter {
- if is_nan(val) {
+ if is_nan(descr, val) {
continue;
}
if compare_greater(descr, min, val) {
@@ -318,14 +319,14 @@ where
//
// For max, it has similar logic but will be written as 0.0
// (positive zero)
- let min = replace_zero(min, -0.0);
- let max = replace_zero(max, 0.0);
+ let min = replace_zero(min, descr, -0.0);
+ let max = replace_zero(max, descr, 0.0);
Some((min, max))
}
#[inline]
-fn replace_zero<T: ParquetValueType>(val: &T, replace: f32) -> T {
+fn replace_zero<T: ParquetValueType>(val: &T, descr: &ColumnDescriptor, replace: f32) -> T {
match T::PHYSICAL_TYPE {
Type::FLOAT if f32::from_le_bytes(val.as_bytes().try_into().unwrap()) == 0.0 => {
T::try_from_le_slice(&f32::to_le_bytes(replace)).unwrap()
@@ -333,6 +334,12 @@ fn replace_zero<T: ParquetValueType>(val: &T, replace: f32) -> T {
Type::DOUBLE if f64::from_le_bytes(val.as_bytes().try_into().unwrap()) == 0.0 => {
T::try_from_le_slice(&f64::to_le_bytes(replace as f64)).unwrap()
}
+ Type::FIXED_LEN_BYTE_ARRAY
+ if descr.logical_type() == Some(LogicalType::Float16)
+ && f16::from_le_bytes(val.as_bytes().try_into().unwrap()) == f16::NEG_ZERO =>
+ {
+ T::try_from_le_slice(&f16::to_le_bytes(f16::from_f32(replace))).unwrap()
+ }
_ => val.clone(),
}
}
diff --git a/parquet/src/column/writer/mod.rs b/parquet/src/column/writer/mod.rs
index 60db90c5d46d..a917c4864988 100644
--- a/parquet/src/column/writer/mod.rs
+++ b/parquet/src/column/writer/mod.rs
@@ -18,6 +18,7 @@
//! Contains column writer API.
use bytes::Bytes;
+use half::f16;
use crate::bloom_filter::Sbbf;
use crate::format::{ColumnIndex, OffsetIndex};
@@ -968,18 +969,23 @@ impl<'a, E: ColumnValueEncoder> GenericColumnWriter<'a, E> {
}
fn update_min<T: ParquetValueType>(descr: &ColumnDescriptor, val: &T, min: &mut Option<T>) {
- update_stat::<T, _>(val, min, |cur| compare_greater(descr, cur, val))
+ update_stat::<T, _>(descr, val, min, |cur| compare_greater(descr, cur, val))
}
fn update_max<T: ParquetValueType>(descr: &ColumnDescriptor, val: &T, max: &mut Option<T>) {
- update_stat::<T, _>(val, max, |cur| compare_greater(descr, val, cur))
+ update_stat::<T, _>(descr, val, max, |cur| compare_greater(descr, val, cur))
}
#[inline]
#[allow(clippy::eq_op)]
-fn is_nan<T: ParquetValueType>(val: &T) -> bool {
+fn is_nan<T: ParquetValueType>(descr: &ColumnDescriptor, val: &T) -> bool {
match T::PHYSICAL_TYPE {
Type::FLOAT | Type::DOUBLE => val != val,
+ Type::FIXED_LEN_BYTE_ARRAY if descr.logical_type() == Some(LogicalType::Float16) => {
+ let val = val.as_bytes();
+ let val = f16::from_le_bytes([val[0], val[1]]);
+ val.is_nan()
+ }
_ => false,
}
}
@@ -989,11 +995,15 @@ fn is_nan<T: ParquetValueType>(val: &T) -> bool {
/// If `cur` is `None`, sets `cur` to `Some(val)`, otherwise calls `should_update` with
/// the value of `cur`, and updates `cur` to `Some(val)` if it returns `true`
-fn update_stat<T: ParquetValueType, F>(val: &T, cur: &mut Option<T>, should_update: F)
-where
+fn update_stat<T: ParquetValueType, F>(
+ descr: &ColumnDescriptor,
+ val: &T,
+ cur: &mut Option<T>,
+ should_update: F,
+) where
F: Fn(&T) -> bool,
{
- if is_nan(val) {
+ if is_nan(descr, val) {
return;
}
@@ -1039,6 +1049,14 @@ fn compare_greater<T: ParquetValueType>(descr: &ColumnDescriptor, a: &T, b: &T)
};
};
+ if let Some(LogicalType::Float16) = descr.logical_type() {
+ let a = a.as_bytes();
+ let a = f16::from_le_bytes([a[0], a[1]]);
+ let b = b.as_bytes();
+ let b = f16::from_le_bytes([b[0], b[1]]);
+ return a > b;
+ }
+
a > b
}
@@ -1170,6 +1188,7 @@ fn increment_utf8(mut data: Vec<u8>) -> Option<Vec<u8>> {
mod tests {
use crate::{file::properties::DEFAULT_COLUMN_INDEX_TRUNCATE_LENGTH, format::BoundaryOrder};
use bytes::Bytes;
+ use half::f16;
use rand::distributions::uniform::SampleUniform;
use std::sync::Arc;
@@ -2078,6 +2097,135 @@ mod tests {
}
}
+ #[test]
+ fn test_column_writer_check_float16_min_max() {
+ let input = [
+ -f16::ONE,
+ f16::from_f32(3.0),
+ -f16::from_f32(2.0),
+ f16::from_f32(2.0),
+ ]
+ .into_iter()
+ .map(|s| ByteArray::from(s).into())
+ .collect::<Vec<_>>();
+
+ let stats = float16_statistics_roundtrip(&input);
+ assert!(stats.has_min_max_set());
+ assert!(stats.is_min_max_backwards_compatible());
+ assert_eq!(stats.min(), &ByteArray::from(-f16::from_f32(2.0)));
+ assert_eq!(stats.max(), &ByteArray::from(f16::from_f32(3.0)));
+ }
+
+ #[test]
+ fn test_column_writer_check_float16_nan_middle() {
+ let input = [f16::ONE, f16::NAN, f16::ONE + f16::ONE]
+ .into_iter()
+ .map(|s| ByteArray::from(s).into())
+ .collect::<Vec<_>>();
+
+ let stats = float16_statistics_roundtrip(&input);
+ assert!(stats.has_min_max_set());
+ assert!(stats.is_min_max_backwards_compatible());
+ assert_eq!(stats.min(), &ByteArray::from(f16::ONE));
+ assert_eq!(stats.max(), &ByteArray::from(f16::ONE + f16::ONE));
+ }
+
+ #[test]
+ fn test_float16_statistics_nan_middle() {
+ let input = [f16::ONE, f16::NAN, f16::ONE + f16::ONE]
+ .into_iter()
+ .map(|s| ByteArray::from(s).into())
+ .collect::<Vec<_>>();
+
+ let stats = float16_statistics_roundtrip(&input);
+ assert!(stats.has_min_max_set());
+ assert!(stats.is_min_max_backwards_compatible());
+ assert_eq!(stats.min(), &ByteArray::from(f16::ONE));
+ assert_eq!(stats.max(), &ByteArray::from(f16::ONE + f16::ONE));
+ }
+
+ #[test]
+ fn test_float16_statistics_nan_start() {
+ let input = [f16::NAN, f16::ONE, f16::ONE + f16::ONE]
+ .into_iter()
+ .map(|s| ByteArray::from(s).into())
+ .collect::<Vec<_>>();
+
+ let stats = float16_statistics_roundtrip(&input);
+ assert!(stats.has_min_max_set());
+ assert!(stats.is_min_max_backwards_compatible());
+ assert_eq!(stats.min(), &ByteArray::from(f16::ONE));
+ assert_eq!(stats.max(), &ByteArray::from(f16::ONE + f16::ONE));
+ }
+
+ #[test]
+ fn test_float16_statistics_nan_only() {
+ let input = [f16::NAN, f16::NAN]
+ .into_iter()
+ .map(|s| ByteArray::from(s).into())
+ .collect::<Vec<_>>();
+
+ let stats = float16_statistics_roundtrip(&input);
+ assert!(!stats.has_min_max_set());
+ assert!(stats.is_min_max_backwards_compatible());
+ }
+
+ #[test]
+ fn test_float16_statistics_zero_only() {
+ let input = [f16::ZERO]
+ .into_iter()
+ .map(|s| ByteArray::from(s).into())
+ .collect::<Vec<_>>();
+
+ let stats = float16_statistics_roundtrip(&input);
+ assert!(stats.has_min_max_set());
+ assert!(stats.is_min_max_backwards_compatible());
+ assert_eq!(stats.min(), &ByteArray::from(f16::NEG_ZERO));
+ assert_eq!(stats.max(), &ByteArray::from(f16::ZERO));
+ }
+
+ #[test]
+ fn test_float16_statistics_neg_zero_only() {
+ let input = [f16::NEG_ZERO]
+ .into_iter()
+ .map(|s| ByteArray::from(s).into())
+ .collect::<Vec<_>>();
+
+ let stats = float16_statistics_roundtrip(&input);
+ assert!(stats.has_min_max_set());
+ assert!(stats.is_min_max_backwards_compatible());
+ assert_eq!(stats.min(), &ByteArray::from(f16::NEG_ZERO));
+ assert_eq!(stats.max(), &ByteArray::from(f16::ZERO));
+ }
+
+ #[test]
+ fn test_float16_statistics_zero_min() {
+ let input = [f16::ZERO, f16::ONE, f16::NAN, f16::PI]
+ .into_iter()
+ .map(|s| ByteArray::from(s).into())
+ .collect::<Vec<_>>();
+
+ let stats = float16_statistics_roundtrip(&input);
+ assert!(stats.has_min_max_set());
+ assert!(stats.is_min_max_backwards_compatible());
+ assert_eq!(stats.min(), &ByteArray::from(f16::NEG_ZERO));
+ assert_eq!(stats.max(), &ByteArray::from(f16::PI));
+ }
+
+ #[test]
+ fn test_float16_statistics_neg_zero_max() {
+ let input = [f16::NEG_ZERO, f16::NEG_ONE, f16::NAN, -f16::PI]
+ .into_iter()
+ .map(|s| ByteArray::from(s).into())
+ .collect::<Vec<_>>();
+
+ let stats = float16_statistics_roundtrip(&input);
+ assert!(stats.has_min_max_set());
+ assert!(stats.is_min_max_backwards_compatible());
+ assert_eq!(stats.min(), &ByteArray::from(-f16::PI));
+ assert_eq!(stats.max(), &ByteArray::from(f16::ZERO));
+ }
+
#[test]
fn test_float_statistics_nan_middle() {
let stats = statistics_roundtrip::<FloatType>(&[1.0, f32::NAN, 2.0]);
@@ -2850,6 +2998,50 @@ mod tests {
ColumnDescriptor::new(Arc::new(tpe), max_def_level, max_rep_level, path)
}
+ fn float16_statistics_roundtrip(
+ values: &[FixedLenByteArray],
+ ) -> ValueStatistics<FixedLenByteArray> {
+ let page_writer = get_test_page_writer();
+ let props = Default::default();
+ let mut writer =
+ get_test_float16_column_writer::<FixedLenByteArrayType>(page_writer, 0, 0, props);
+ writer.write_batch(values, None, None).unwrap();
+
+ let metadata = writer.close().unwrap().metadata;
+ if let Some(Statistics::FixedLenByteArray(stats)) = metadata.statistics() {
+ stats.clone()
+ } else {
+ panic!("metadata missing statistics");
+ }
+ }
+
+ fn get_test_float16_column_writer<T: DataType>(
+ page_writer: Box<dyn PageWriter>,
+ max_def_level: i16,
+ max_rep_level: i16,
+ props: WriterPropertiesPtr,
+ ) -> ColumnWriterImpl<'static, T> {
+ let descr = Arc::new(get_test_float16_column_descr::<T>(
+ max_def_level,
+ max_rep_level,
+ ));
+ let column_writer = get_column_writer(descr, props, page_writer);
+ get_typed_column_writer::<T>(column_writer)
+ }
+
+ fn get_test_float16_column_descr<T: DataType>(
+ max_def_level: i16,
+ max_rep_level: i16,
+ ) -> ColumnDescriptor {
+ let path = ColumnPath::from("col");
+ let tpe = SchemaType::primitive_type_builder("col", T::get_physical_type())
+ .with_length(2)
+ .with_logical_type(Some(LogicalType::Float16))
+ .build()
+ .unwrap();
+ ColumnDescriptor::new(Arc::new(tpe), max_def_level, max_rep_level, path)
+ }
+
/// Returns column writer for UINT32 Column provided as ConvertedType only
fn get_test_unsigned_int_given_as_converted_column_writer<'a, T: DataType>(
page_writer: Box<dyn PageWriter + 'a>,
diff --git a/parquet/src/data_type.rs b/parquet/src/data_type.rs
index b895c2507018..86da7a3acee4 100644
--- a/parquet/src/data_type.rs
+++ b/parquet/src/data_type.rs
@@ -18,6 +18,7 @@
//! Data types that connect Parquet physical types with their Rust-specific
//! representations.
use bytes::Bytes;
+use half::f16;
use std::cmp::Ordering;
use std::fmt;
use std::mem;
@@ -225,6 +226,12 @@ impl From<Bytes> for ByteArray {
}
}
+impl From<f16> for ByteArray {
+ fn from(value: f16) -> Self {
+ Self::from(value.to_le_bytes().as_slice())
+ }
+}
+
impl PartialEq for ByteArray {
fn eq(&self, other: &ByteArray) -> bool {
match (&self.data, &other.data) {
diff --git a/parquet/src/file/statistics.rs b/parquet/src/file/statistics.rs
index b36e37a80c97..345fe7dd2615 100644
--- a/parquet/src/file/statistics.rs
+++ b/parquet/src/file/statistics.rs
@@ -243,6 +243,8 @@ pub fn to_thrift(stats: Option<&Statistics>) -> Option<TStatistics> {
distinct_count: stats.distinct_count().map(|value| value as i64),
max_value: None,
min_value: None,
+ is_max_value_exact: None,
+ is_min_value_exact: None,
};
// Get min/max if set.
@@ -607,6 +609,8 @@ mod tests {
distinct_count: None,
max_value: None,
min_value: None,
+ is_max_value_exact: None,
+ is_min_value_exact: None,
};
from_thrift(Type::INT32, Some(thrift_stats)).unwrap();
diff --git a/parquet/src/format.rs b/parquet/src/format.rs
index 46adc39e6406..4700b05dc282 100644
--- a/parquet/src/format.rs
+++ b/parquet/src/format.rs
@@ -657,16 +657,26 @@ pub struct Statistics {
pub null_count: Option<i64>,
/// count of distinct values occurring
pub distinct_count: Option<i64>,
- /// Min and max values for the column, determined by its ColumnOrder.
+ /// Lower and upper bound values for the column, determined by its ColumnOrder.
+ ///
+ /// These may be the actual minimum and maximum values found on a page or column
+ /// chunk, but can also be (more compact) values that do not exist on a page or
+ /// column chunk. For example, instead of storing "Blart Versenwald III", a writer
+ /// may set min_value="B", max_value="C". Such more compact values must still be
+ /// valid values within the column's logical type.
///
/// Values are encoded using PLAIN encoding, except that variable-length byte
/// arrays do not include a length prefix.
pub max_value: Option<Vec<u8>>,
pub min_value: Option<Vec<u8>>,
+ /// If true, max_value is the actual maximum value for a column
+ pub is_max_value_exact: Option<bool>,
+ /// If true, min_value is the actual minimum value for a column
+ pub is_min_value_exact: Option<bool>,
}
impl Statistics {
- pub fn new<F1, F2, F3, F4, F5, F6>(max: F1, min: F2, null_count: F3, distinct_count: F4, max_value: F5, min_value: F6) -> Statistics where F1: Into<Option<Vec<u8>>>, F2: Into<Option<Vec<u8>>>, F3: Into<Option<i64>>, F4: Into<Option<i64>>, F5: Into<Option<Vec<u8>>>, F6: Into<Option<Vec<u8>>> {
+ pub fn new<F1, F2, F3, F4, F5, F6, F7, F8>(max: F1, min: F2, null_count: F3, distinct_count: F4, max_value: F5, min_value: F6, is_max_value_exact: F7, is_min_value_exact: F8) -> Statistics where F1: Into<Option<Vec<u8>>>, F2: Into<Option<Vec<u8>>>, F3: Into<Option<i64>>, F4: Into<Option<i64>>, F5: Into<Option<Vec<u8>>>, F6: Into<Option<Vec<u8>>>, F7: Into<Option<bool>>, F8: Into<Option<bool>> {
Statistics {
max: max.into(),
min: min.into(),
@@ -674,6 +684,8 @@ impl Statistics {
distinct_count: distinct_count.into(),
max_value: max_value.into(),
min_value: min_value.into(),
+ is_max_value_exact: is_max_value_exact.into(),
+ is_min_value_exact: is_min_value_exact.into(),
}
}
}
@@ -687,6 +699,8 @@ impl crate::thrift::TSerializable for Statistics {
let mut f_4: Option<i64> = None;
let mut f_5: Option<Vec<u8>> = None;
let mut f_6: Option<Vec<u8>> = None;
+ let mut f_7: Option<bool> = None;
+ let mut f_8: Option<bool> = None;
loop {
let field_ident = i_prot.read_field_begin()?;
if field_ident.field_type == TType::Stop {
@@ -718,6 +732,14 @@ impl crate::thrift::TSerializable for Statistics {
let val = i_prot.read_bytes()?;
f_6 = Some(val);
},
+ 7 => {
+ let val = i_prot.read_bool()?;
+ f_7 = Some(val);
+ },
+ 8 => {
+ let val = i_prot.read_bool()?;
+ f_8 = Some(val);
+ },
_ => {
i_prot.skip(field_ident.field_type)?;
},
@@ -732,6 +754,8 @@ impl crate::thrift::TSerializable for Statistics {
distinct_count: f_4,
max_value: f_5,
min_value: f_6,
+ is_max_value_exact: f_7,
+ is_min_value_exact: f_8,
};
Ok(ret)
}
@@ -768,6 +792,16 @@ impl crate::thrift::TSerializable for Statistics {
o_prot.write_bytes(fld_var)?;
o_prot.write_field_end()?
}
+ if let Some(fld_var) = self.is_max_value_exact {
+ o_prot.write_field_begin(&TFieldIdentifier::new("is_max_value_exact", TType::Bool, 7))?;
+ o_prot.write_bool(fld_var)?;
+ o_prot.write_field_end()?
+ }
+ if let Some(fld_var) = self.is_min_value_exact {
+ o_prot.write_field_begin(&TFieldIdentifier::new("is_min_value_exact", TType::Bool, 8))?;
+ o_prot.write_bool(fld_var)?;
+ o_prot.write_field_end()?
+ }
o_prot.write_field_stop()?;
o_prot.write_struct_end()
}
@@ -996,6 +1030,43 @@ impl crate::thrift::TSerializable for DateType {
}
}
+//
+// Float16Type
+//
+
+#[derive(Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
+pub struct Float16Type {
+}
+
+impl Float16Type {
+ pub fn new() -> Float16Type {
+ Float16Type {}
+ }
+}
+
+impl crate::thrift::TSerializable for Float16Type {
+ fn read_from_in_protocol<T: TInputProtocol>(i_prot: &mut T) -> thrift::Result<Float16Type> {
+ i_prot.read_struct_begin()?;
+ loop {
+ let field_ident = i_prot.read_field_begin()?;
+ if field_ident.field_type == TType::Stop {
+ break;
+ }
+ i_prot.skip(field_ident.field_type)?;
+ i_prot.read_field_end()?;
+ }
+ i_prot.read_struct_end()?;
+ let ret = Float16Type {};
+ Ok(ret)
+ }
+ fn write_to_out_protocol<T: TOutputProtocol>(&self, o_prot: &mut T) -> thrift::Result<()> {
+ let struct_ident = TStructIdentifier::new("Float16Type");
+ o_prot.write_struct_begin(&struct_ident)?;
+ o_prot.write_field_stop()?;
+ o_prot.write_struct_end()
+ }
+}
+
//
// NullType
//
@@ -1640,6 +1711,7 @@ pub enum LogicalType {
JSON(JsonType),
BSON(BsonType),
UUID(UUIDType),
+ FLOAT16(Float16Type),
}
impl crate::thrift::TSerializable for LogicalType {
@@ -1745,6 +1817,13 @@ impl crate::thrift::TSerializable for LogicalType {
}
received_field_count += 1;
},
+ 15 => {
+ let val = Float16Type::read_from_in_protocol(i_prot)?;
+ if ret.is_none() {
+ ret = Some(LogicalType::FLOAT16(val));
+ }
+ received_field_count += 1;
+ },
_ => {
i_prot.skip(field_ident.field_type)?;
received_field_count += 1;
@@ -1844,6 +1923,11 @@ impl crate::thrift::TSerializable for LogicalType {
f.write_to_out_protocol(o_prot)?;
o_prot.write_field_end()?;
},
+ LogicalType::FLOAT16(ref f) => {
+ o_prot.write_field_begin(&TFieldIdentifier::new("FLOAT16", TType::Struct, 15))?;
+ f.write_to_out_protocol(o_prot)?;
+ o_prot.write_field_end()?;
+ },
}
o_prot.write_field_stop()?;
o_prot.write_struct_end()
diff --git a/parquet/src/record/api.rs b/parquet/src/record/api.rs
index c7a0b09c37ed..e4f473562e01 100644
--- a/parquet/src/record/api.rs
+++ b/parquet/src/record/api.rs
@@ -20,9 +20,11 @@
use std::fmt;
use chrono::{TimeZone, Utc};
+use half::f16;
+use num::traits::Float;
use num_bigint::{BigInt, Sign};
-use crate::basic::{ConvertedType, Type as PhysicalType};
+use crate::basic::{ConvertedType, LogicalType, Type as PhysicalType};
use crate::data_type::{ByteArray, Decimal, Int96};
use crate::errors::{ParquetError, Result};
use crate::schema::types::ColumnDescPtr;
@@ -121,6 +123,7 @@ pub trait RowAccessor {
fn get_ushort(&self, i: usize) -> Result<u16>;
fn get_uint(&self, i: usize) -> Result<u32>;
fn get_ulong(&self, i: usize) -> Result<u64>;
+ fn get_float16(&self, i: usize) -> Result<f16>;
fn get_float(&self, i: usize) -> Result<f32>;
fn get_double(&self, i: usize) -> Result<f64>;
fn get_timestamp_millis(&self, i: usize) -> Result<i64>;
@@ -215,6 +218,8 @@ impl RowAccessor for Row {
row_primitive_accessor!(get_ulong, ULong, u64);
+ row_primitive_accessor!(get_float16, Float16, f16);
+
row_primitive_accessor!(get_float, Float, f32);
row_primitive_accessor!(get_double, Double, f64);
@@ -293,6 +298,7 @@ pub trait ListAccessor {
fn get_ushort(&self, i: usize) -> Result<u16>;
fn get_uint(&self, i: usize) -> Result<u32>;
fn get_ulong(&self, i: usize) -> Result<u64>;
+ fn get_float16(&self, i: usize) -> Result<f16>;
fn get_float(&self, i: usize) -> Result<f32>;
fn get_double(&self, i: usize) -> Result<f64>;
fn get_timestamp_millis(&self, i: usize) -> Result<i64>;
@@ -358,6 +364,8 @@ impl ListAccessor for List {
list_primitive_accessor!(get_ulong, ULong, u64);
+ list_primitive_accessor!(get_float16, Float16, f16);
+
list_primitive_accessor!(get_float, Float, f32);
list_primitive_accessor!(get_double, Double, f64);
@@ -449,6 +457,8 @@ impl<'a> ListAccessor for MapList<'a> {
map_list_primitive_accessor!(get_ulong, ULong, u64);
+ map_list_primitive_accessor!(get_float16, Float16, f16);
+
map_list_primitive_accessor!(get_float, Float, f32);
map_list_primitive_accessor!(get_double, Double, f64);
@@ -510,6 +520,8 @@ pub enum Field {
UInt(u32),
// Unsigned integer UINT_64.
ULong(u64),
+ /// IEEE 16-bit floating point value.
+ Float16(f16),
/// IEEE 32-bit floating point value.
Float(f32),
/// IEEE 64-bit floating point value.
@@ -552,6 +564,7 @@ impl Field {
Field::UShort(_) => "UShort",
Field::UInt(_) => "UInt",
Field::ULong(_) => "ULong",
+ Field::Float16(_) => "Float16",
Field::Float(_) => "Float",
Field::Double(_) => "Double",
Field::Decimal(_) => "Decimal",
@@ -636,8 +649,8 @@ impl Field {
Field::Double(value)
}
- /// Converts Parquet BYTE_ARRAY type with converted type into either UTF8 string or
- /// array of bytes.
+ /// Converts Parquet BYTE_ARRAY type with converted type into a UTF8
+ /// string, decimal, float16, or an array of bytes.
#[inline]
pub fn convert_byte_array(descr: &ColumnDescPtr, value: ByteArray) -> Result<Self> {
let field = match descr.physical_type() {
@@ -666,6 +679,16 @@ impl Field {
descr.type_precision(),
descr.type_scale(),
)),
+ ConvertedType::NONE if descr.logical_type() == Some(LogicalType::Float16) => {
+ if value.len() != 2 {
+ return Err(general_err!(
+ "Error reading FIXED_LEN_BYTE_ARRAY as FLOAT16. Length must be 2, got {}",
+ value.len()
+ ));
+ }
+ let bytes = [value.data()[0], value.data()[1]];
+ Field::Float16(f16::from_le_bytes(bytes))
+ }
ConvertedType::NONE => Field::Bytes(value),
_ => nyi!(descr, value),
},
@@ -690,6 +713,9 @@ impl Field {
Field::UShort(n) => Value::Number(serde_json::Number::from(*n)),
Field::UInt(n) => Value::Number(serde_json::Number::from(*n)),
Field::ULong(n) => Value::Number(serde_json::Number::from(*n)),
+ Field::Float16(n) => serde_json::Number::from_f64(f64::from(*n))
+ .map(Value::Number)
+ .unwrap_or(Value::Null),
Field::Float(n) => serde_json::Number::from_f64(f64::from(*n))
.map(Value::Number)
.unwrap_or(Value::Null),
@@ -736,6 +762,15 @@ impl fmt::Display for Field {
Field::UShort(value) => write!(f, "{value}"),
Field::UInt(value) => write!(f, "{value}"),
Field::ULong(value) => write!(f, "{value}"),
+ Field::Float16(value) => {
+ if !value.is_finite() {
+ write!(f, "{value}")
+ } else if value.trunc() == value {
+ write!(f, "{value}.0")
+ } else {
+ write!(f, "{value}")
+ }
+ }
Field::Float(value) => {
if !(1e-15..=1e19).contains(&value) {
write!(f, "{value:E}")
@@ -1069,6 +1104,24 @@ mod tests {
Field::Decimal(Decimal::from_bytes(value, 17, 5))
);
+ // FLOAT16
+ let descr = {
+ let tpe = PrimitiveTypeBuilder::new("col", PhysicalType::FIXED_LEN_BYTE_ARRAY)
+ .with_logical_type(Some(LogicalType::Float16))
+ .with_length(2)
+ .build()
+ .unwrap();
+ Arc::new(ColumnDescriptor::new(
+ Arc::new(tpe),
+ 0,
+ 0,
+ ColumnPath::from("col"),
+ ))
+ };
+ let value = ByteArray::from(f16::PI);
+ let row = Field::convert_byte_array(&descr, value.clone());
+ assert_eq!(row.unwrap(), Field::Float16(f16::PI));
+
// NONE (FIXED_LEN_BYTE_ARRAY)
let descr = make_column_descr![
PhysicalType::FIXED_LEN_BYTE_ARRAY,
@@ -1145,6 +1198,18 @@ mod tests {
check_datetime_conversion(2014, 11, 28, 21, 15, 12);
}
+ #[test]
+ fn test_convert_float16_to_string() {
+ assert_eq!(format!("{}", Field::Float16(f16::ONE)), "1.0");
+ assert_eq!(format!("{}", Field::Float16(f16::PI)), "3.140625");
+ assert_eq!(format!("{}", Field::Float16(f16::MAX)), "65504.0");
+ assert_eq!(format!("{}", Field::Float16(f16::NAN)), "NaN");
+ assert_eq!(format!("{}", Field::Float16(f16::INFINITY)), "inf");
+ assert_eq!(format!("{}", Field::Float16(f16::NEG_INFINITY)), "-inf");
+ assert_eq!(format!("{}", Field::Float16(f16::ZERO)), "0.0");
+ assert_eq!(format!("{}", Field::Float16(f16::NEG_ZERO)), "-0.0");
+ }
+
#[test]
fn test_convert_float_to_string() {
assert_eq!(format!("{}", Field::Float(1.0)), "1.0");
@@ -1218,6 +1283,7 @@ mod tests {
assert_eq!(format!("{}", Field::UShort(2)), "2");
assert_eq!(format!("{}", Field::UInt(3)), "3");
assert_eq!(format!("{}", Field::ULong(4)), "4");
+ assert_eq!(format!("{}", Field::Float16(f16::E)), "2.71875");
assert_eq!(format!("{}", Field::Float(5.0)), "5.0");
assert_eq!(format!("{}", Field::Float(5.1234)), "5.1234");
assert_eq!(format!("{}", Field::Double(6.0)), "6.0");
@@ -1284,6 +1350,7 @@ mod tests {
assert!(Field::UShort(2).is_primitive());
assert!(Field::UInt(3).is_primitive());
assert!(Field::ULong(4).is_primitive());
+ assert!(Field::Float16(f16::E).is_primitive());
assert!(Field::Float(5.0).is_primitive());
assert!(Field::Float(5.1234).is_primitive());
assert!(Field::Double(6.0).is_primitive());
@@ -1344,6 +1411,7 @@ mod tests {
("15".to_string(), Field::TimestampMillis(1262391174000)),
("16".to_string(), Field::TimestampMicros(1262391174000000)),
("17".to_string(), Field::Decimal(Decimal::from_i32(4, 7, 2))),
+ ("18".to_string(), Field::Float16(f16::PI)),
]);
assert_eq!("null", format!("{}", row.fmt(0)));
@@ -1370,6 +1438,7 @@ mod tests {
format!("{}", row.fmt(16))
);
assert_eq!("0.04", format!("{}", row.fmt(17)));
+ assert_eq!("3.140625", format!("{}", row.fmt(18)));
}
#[test]
@@ -1429,6 +1498,7 @@ mod tests {
Field::Bytes(ByteArray::from(vec![1, 2, 3, 4, 5])),
),
("o".to_string(), Field::Decimal(Decimal::from_i32(4, 7, 2))),
+ ("p".to_string(), Field::Float16(f16::from_f32(9.1))),
]);
assert!(!row.get_bool(1).unwrap());
@@ -1445,6 +1515,7 @@ mod tests {
assert_eq!("abc", row.get_string(12).unwrap());
assert_eq!(5, row.get_bytes(13).unwrap().len());
assert_eq!(7, row.get_decimal(14).unwrap().precision());
+ assert!((f16::from_f32(9.1) - row.get_float16(15).unwrap()).abs() < f16::EPSILON);
}
#[test]
@@ -1469,6 +1540,7 @@ mod tests {
Field::Bytes(ByteArray::from(vec![1, 2, 3, 4, 5])),
),
("o".to_string(), Field::Decimal(Decimal::from_i32(4, 7, 2))),
+ ("p".to_string(), Field::Float16(f16::from_f32(9.1))),
]);
for i in 0..row.len() {
@@ -1583,6 +1655,9 @@ mod tests {
let list = make_list(vec![Field::ULong(6), Field::ULong(7)]);
assert_eq!(7, list.get_ulong(1).unwrap());
+ let list = make_list(vec![Field::Float16(f16::PI)]);
+ assert!((f16::PI - list.get_float16(0).unwrap()).abs() < f16::EPSILON);
+
let list = make_list(vec![
Field::Float(8.1),
Field::Float(9.2),
@@ -1633,6 +1708,9 @@ mod tests {
let list = make_list(vec![Field::ULong(6), Field::ULong(7)]);
assert!(list.get_float(1).is_err());
+ let list = make_list(vec![Field::Float16(f16::PI)]);
+ assert!(list.get_string(0).is_err());
+
let list = make_list(vec![
Field::Float(8.1),
Field::Float(9.2),
@@ -1768,6 +1846,10 @@ mod tests {
Field::ULong(4).to_json_value(),
Value::Number(serde_json::Number::from(4))
);
+ assert_eq!(
+ Field::Float16(f16::from_f32(5.0)).to_json_value(),
+ Value::Number(serde_json::Number::from_f64(5.0).unwrap())
+ );
assert_eq!(
Field::Float(5.0).to_json_value(),
Value::Number(serde_json::Number::from_f64(5.0).unwrap())
diff --git a/parquet/src/schema/parser.rs b/parquet/src/schema/parser.rs
index 5e213e3bb9e5..dcef11aa66d4 100644
--- a/parquet/src/schema/parser.rs
+++ b/parquet/src/schema/parser.rs
@@ -823,6 +823,7 @@ mod tests {
message root {
optional fixed_len_byte_array(5) f1 (DECIMAL(9, 3));
optional fixed_len_byte_array (16) f2 (DECIMAL (38, 18));
+ optional fixed_len_byte_array (2) f3 (FLOAT16);
}
";
let message = parse(schema).unwrap();
@@ -855,6 +856,13 @@ mod tests {
.build()
.unwrap(),
),
+ Arc::new(
+ Type::primitive_type_builder("f3", PhysicalType::FIXED_LEN_BYTE_ARRAY)
+ .with_logical_type(Some(LogicalType::Float16))
+ .with_length(2)
+ .build()
+ .unwrap(),
+ ),
])
.build()
.unwrap();
diff --git a/parquet/src/schema/printer.rs b/parquet/src/schema/printer.rs
index fe4757d41aed..2dec8a5be9f7 100644
--- a/parquet/src/schema/printer.rs
+++ b/parquet/src/schema/printer.rs
@@ -270,6 +270,7 @@ fn print_logical_and_converted(
LogicalType::Enum => "ENUM".to_string(),
LogicalType::List => "LIST".to_string(),
LogicalType::Map => "MAP".to_string(),
+ LogicalType::Float16 => "FLOAT16".to_string(),
LogicalType::Unknown => "UNKNOWN".to_string(),
},
None => {
@@ -667,6 +668,15 @@ mod tests {
.unwrap(),
"OPTIONAL FIXED_LEN_BYTE_ARRAY (9) decimal (DECIMAL(19,4));",
),
+ (
+ Type::primitive_type_builder("float16", PhysicalType::FIXED_LEN_BYTE_ARRAY)
+ .with_logical_type(Some(LogicalType::Float16))
+ .with_length(2)
+ .with_repetition(Repetition::REQUIRED)
+ .build()
+ .unwrap(),
+ "REQUIRED FIXED_LEN_BYTE_ARRAY (2) float16 (FLOAT16);",
+ ),
];
types_and_strings.into_iter().for_each(|(field, expected)| {
diff --git a/parquet/src/schema/types.rs b/parquet/src/schema/types.rs
index 11c735420957..2f36deffbab5 100644
--- a/parquet/src/schema/types.rs
+++ b/parquet/src/schema/types.rs
@@ -356,6 +356,14 @@ impl<'a> PrimitiveTypeBuilder<'a> {
(LogicalType::Json, PhysicalType::BYTE_ARRAY) => {}
(LogicalType::Bson, PhysicalType::BYTE_ARRAY) => {}
(LogicalType::Uuid, PhysicalType::FIXED_LEN_BYTE_ARRAY) => {}
+ (LogicalType::Float16, PhysicalType::FIXED_LEN_BYTE_ARRAY)
+ if self.length == 2 => {}
+ (LogicalType::Float16, PhysicalType::FIXED_LEN_BYTE_ARRAY) => {
+ return Err(general_err!(
+ "FLOAT16 cannot annotate field '{}' because it is not a FIXED_LEN_BYTE_ARRAY(2) field",
+ self.name
+ ))
+ }
(a, b) => {
return Err(general_err!(
"Cannot annotate {:?} from {} for field '{}'",
@@ -1504,6 +1512,41 @@ mod tests {
"Parquet error: Invalid FIXED_LEN_BYTE_ARRAY length: -1 for field 'foo'"
);
}
+
+ result = Type::primitive_type_builder("foo", PhysicalType::FIXED_LEN_BYTE_ARRAY)
+ .with_repetition(Repetition::REQUIRED)
+ .with_logical_type(Some(LogicalType::Float16))
+ .with_length(2)
+ .build();
+ assert!(result.is_ok());
+
+ // Can't be other than FIXED_LEN_BYTE_ARRAY for physical type
+ result = Type::primitive_type_builder("foo", PhysicalType::FLOAT)
+ .with_repetition(Repetition::REQUIRED)
+ .with_logical_type(Some(LogicalType::Float16))
+ .with_length(2)
+ .build();
+ assert!(result.is_err());
+ if let Err(e) = result {
+ assert_eq!(
+ format!("{e}"),
+ "Parquet error: Cannot annotate Float16 from FLOAT for field 'foo'"
+ );
+ }
+
+ // Must have length 2
+ result = Type::primitive_type_builder("foo", PhysicalType::FIXED_LEN_BYTE_ARRAY)
+ .with_repetition(Repetition::REQUIRED)
+ .with_logical_type(Some(LogicalType::Float16))
+ .with_length(4)
+ .build();
+ assert!(result.is_err());
+ if let Err(e) = result {
+ assert_eq!(
+ format!("{e}"),
+ "Parquet error: FLOAT16 cannot annotate field 'foo' because it is not a FIXED_LEN_BYTE_ARRAY(2) field"
+ );
+ }
}
#[test]
@@ -1981,6 +2024,7 @@ mod tests {
let message_type = "
message conversions {
REQUIRED INT64 id;
+ OPTIONAL FIXED_LEN_BYTE_ARRAY (2) f16 (FLOAT16);
OPTIONAL group int_array_Array (LIST) {
REPEATED group list {
OPTIONAL group element (LIST) {
|
diff --git a/parquet-testing b/parquet-testing
index aafd3fc9df43..506afff9b695 160000
--- a/parquet-testing
+++ b/parquet-testing
@@ -1,1 +1,1 @@
-Subproject commit aafd3fc9df431c2625a514fb46626e5614f1d199
+Subproject commit 506afff9b6957ffe10d08470d467867d43e1bb91
|
Add Float16/Half-float logical type to Parquet
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
There is a proposal for an addition of Logical Float-16 (with Fixed Length Byte Array physical typed) to the Parquet Format: https://github.com/apache/parquet-format/pull/184.
The [vote has passed](https://lists.apache.org/thread/odm5pmxssyd9kw1wvgdkg8hd044czqnk). Close to completion are a [Java implementation](https://github.com/apache/parquet-mr/pull/1142), [C++ implementation](https://github.com/apache/arrow/pull/36073), and a [Go](https://github.com/apache/arrow/pull/37599).
**Describe the solution you'd like**
Float-16 is supported in [arrow-rs](https://github.com/apache/arrow-rs/pull/888), and it would be great to expand that support to Rust Parquet.
|
I'd like to take a stab at this if no one has yet
|
2023-10-29T10:53:10Z
|
49.0
|
a9470d3eb083303350fc109f94865666fd0f062f
|
apache/arrow-rs
| 4,984
|
apache__arrow-rs-4984
|
[
"4879"
] |
e78d1409c265ae5c216fc62e51a0f20aa55f6415
|
diff --git a/object_store/src/aws/builder.rs b/object_store/src/aws/builder.rs
index 75a5299a0859..79ea75b5aba2 100644
--- a/object_store/src/aws/builder.rs
+++ b/object_store/src/aws/builder.rs
@@ -20,7 +20,8 @@ use crate::aws::credential::{
InstanceCredentialProvider, TaskCredentialProvider, WebIdentityProvider,
};
use crate::aws::{
- AmazonS3, AwsCredential, AwsCredentialProvider, Checksum, S3CopyIfNotExists, STORE,
+ AmazonS3, AwsCredential, AwsCredentialProvider, Checksum, S3ConditionalPut, S3CopyIfNotExists,
+ STORE,
};
use crate::client::TokenCredentialProvider;
use crate::config::ConfigValue;
@@ -152,6 +153,8 @@ pub struct AmazonS3Builder {
skip_signature: ConfigValue<bool>,
/// Copy if not exists
copy_if_not_exists: Option<ConfigValue<S3CopyIfNotExists>>,
+ /// Put precondition
+ conditional_put: Option<ConfigValue<S3ConditionalPut>>,
}
/// Configuration keys for [`AmazonS3Builder`]
@@ -288,6 +291,11 @@ pub enum AmazonS3ConfigKey {
/// See [`S3CopyIfNotExists`]
CopyIfNotExists,
+ /// Configure how to provide conditional put operations
+ ///
+ /// See [`S3ConditionalPut`]
+ ConditionalPut,
+
/// Skip signing request
SkipSignature,
@@ -312,7 +320,8 @@ impl AsRef<str> for AmazonS3ConfigKey {
Self::Checksum => "aws_checksum_algorithm",
Self::ContainerCredentialsRelativeUri => "aws_container_credentials_relative_uri",
Self::SkipSignature => "aws_skip_signature",
- Self::CopyIfNotExists => "copy_if_not_exists",
+ Self::CopyIfNotExists => "aws_copy_if_not_exists",
+ Self::ConditionalPut => "aws_conditional_put",
Self::Client(opt) => opt.as_ref(),
}
}
@@ -339,7 +348,8 @@ impl FromStr for AmazonS3ConfigKey {
"aws_checksum_algorithm" | "checksum_algorithm" => Ok(Self::Checksum),
"aws_container_credentials_relative_uri" => Ok(Self::ContainerCredentialsRelativeUri),
"aws_skip_signature" | "skip_signature" => Ok(Self::SkipSignature),
- "copy_if_not_exists" => Ok(Self::CopyIfNotExists),
+ "aws_copy_if_not_exists" | "copy_if_not_exists" => Ok(Self::CopyIfNotExists),
+ "aws_conditional_put" | "conditional_put" => Ok(Self::ConditionalPut),
// Backwards compatibility
"aws_allow_http" => Ok(Self::Client(ClientConfigKey::AllowHttp)),
_ => match s.parse() {
@@ -446,6 +456,9 @@ impl AmazonS3Builder {
AmazonS3ConfigKey::CopyIfNotExists => {
self.copy_if_not_exists = Some(ConfigValue::Deferred(value.into()))
}
+ AmazonS3ConfigKey::ConditionalPut => {
+ self.conditional_put = Some(ConfigValue::Deferred(value.into()))
+ }
};
self
}
@@ -509,6 +522,9 @@ impl AmazonS3Builder {
AmazonS3ConfigKey::CopyIfNotExists => {
self.copy_if_not_exists.as_ref().map(ToString::to_string)
}
+ AmazonS3ConfigKey::ConditionalPut => {
+ self.conditional_put.as_ref().map(ToString::to_string)
+ }
}
}
@@ -713,6 +729,12 @@ impl AmazonS3Builder {
self
}
+ /// Configure how to provide conditional put operations
+ pub fn with_conditional_put(mut self, config: S3ConditionalPut) -> Self {
+ self.conditional_put = Some(config.into());
+ self
+ }
+
/// Create a [`AmazonS3`] instance from the provided values,
/// consuming `self`.
pub fn build(mut self) -> Result<AmazonS3> {
@@ -724,6 +746,7 @@ impl AmazonS3Builder {
let region = self.region.context(MissingRegionSnafu)?;
let checksum = self.checksum_algorithm.map(|x| x.get()).transpose()?;
let copy_if_not_exists = self.copy_if_not_exists.map(|x| x.get()).transpose()?;
+ let put_precondition = self.conditional_put.map(|x| x.get()).transpose()?;
let credentials = if let Some(credentials) = self.credentials {
credentials
@@ -830,6 +853,7 @@ impl AmazonS3Builder {
skip_signature: self.skip_signature.get()?,
checksum,
copy_if_not_exists,
+ conditional_put: put_precondition,
};
let client = Arc::new(S3Client::new(config)?);
diff --git a/object_store/src/aws/client.rs b/object_store/src/aws/client.rs
index 4e98f259f8dd..20c2a96b57cd 100644
--- a/object_store/src/aws/client.rs
+++ b/object_store/src/aws/client.rs
@@ -17,13 +17,18 @@
use crate::aws::checksum::Checksum;
use crate::aws::credential::{AwsCredential, CredentialExt};
-use crate::aws::{AwsCredentialProvider, S3CopyIfNotExists, STORE, STRICT_PATH_ENCODE_SET};
+use crate::aws::{
+ AwsCredentialProvider, S3ConditionalPut, S3CopyIfNotExists, STORE, STRICT_PATH_ENCODE_SET,
+};
use crate::client::get::GetClient;
-use crate::client::header::get_etag;
use crate::client::header::HeaderConfig;
+use crate::client::header::{get_put_result, get_version};
use crate::client::list::ListClient;
-use crate::client::list_response::ListResponse;
use crate::client::retry::RetryExt;
+use crate::client::s3::{
+ CompleteMultipartUpload, CompleteMultipartUploadResult, InitiateMultipartUploadResult,
+ ListResponse,
+};
use crate::client::GetOptionsExt;
use crate::multipart::PartId;
use crate::path::DELIMITER;
@@ -34,17 +39,20 @@ use async_trait::async_trait;
use base64::prelude::BASE64_STANDARD;
use base64::Engine;
use bytes::{Buf, Bytes};
+use hyper::http::HeaderName;
use itertools::Itertools;
use percent_encoding::{utf8_percent_encode, PercentEncode};
use quick_xml::events::{self as xml_events};
use reqwest::{
header::{CONTENT_LENGTH, CONTENT_TYPE},
- Client as ReqwestClient, Method, Response, StatusCode,
+ Client as ReqwestClient, Method, RequestBuilder, Response, StatusCode,
};
use serde::{Deserialize, Serialize};
use snafu::{ResultExt, Snafu};
use std::sync::Arc;
+const VERSION_HEADER: &str = "x-amz-version-id";
+
/// A specialized `Error` for object store-related errors
#[derive(Debug, Snafu)]
#[allow(missing_docs)]
@@ -147,33 +155,6 @@ impl From<Error> for crate::Error {
}
}
-#[derive(Debug, Deserialize)]
-#[serde(rename_all = "PascalCase")]
-struct InitiateMultipart {
- upload_id: String,
-}
-
-#[derive(Debug, Serialize)]
-#[serde(rename_all = "PascalCase", rename = "CompleteMultipartUpload")]
-struct CompleteMultipart {
- part: Vec<MultipartPart>,
-}
-
-#[derive(Debug, Serialize)]
-struct MultipartPart {
- #[serde(rename = "ETag")]
- e_tag: String,
- #[serde(rename = "PartNumber")]
- part_number: usize,
-}
-
-#[derive(Debug, Deserialize)]
-#[serde(rename_all = "PascalCase", rename = "CompleteMultipartUploadResult")]
-struct CompleteMultipartResult {
- #[serde(rename = "ETag")]
- e_tag: String,
-}
-
#[derive(Deserialize)]
#[serde(rename_all = "PascalCase", rename = "DeleteResult")]
struct BatchDeleteResponse {
@@ -225,12 +206,61 @@ pub struct S3Config {
pub skip_signature: bool,
pub checksum: Option<Checksum>,
pub copy_if_not_exists: Option<S3CopyIfNotExists>,
+ pub conditional_put: Option<S3ConditionalPut>,
}
impl S3Config {
pub(crate) fn path_url(&self, path: &Path) -> String {
format!("{}/{}", self.bucket_endpoint, encode_path(path))
}
+
+ async fn get_credential(&self) -> Result<Option<Arc<AwsCredential>>> {
+ Ok(match self.skip_signature {
+ false => Some(self.credentials.get_credential().await?),
+ true => None,
+ })
+ }
+}
+
+/// A builder for a put request allowing customisation of the headers and query string
+pub(crate) struct PutRequest<'a> {
+ path: &'a Path,
+ config: &'a S3Config,
+ builder: RequestBuilder,
+ payload_sha256: Option<Vec<u8>>,
+}
+
+impl<'a> PutRequest<'a> {
+ pub fn query<T: Serialize + ?Sized + Sync>(self, query: &T) -> Self {
+ let builder = self.builder.query(query);
+ Self { builder, ..self }
+ }
+
+ pub fn header(self, k: &HeaderName, v: &str) -> Self {
+ let builder = self.builder.header(k, v);
+ Self { builder, ..self }
+ }
+
+ pub async fn send(self) -> Result<PutResult> {
+ let credential = self.config.get_credential().await?;
+
+ let response = self
+ .builder
+ .with_aws_sigv4(
+ credential.as_deref(),
+ &self.config.region,
+ "s3",
+ self.config.sign_payload,
+ self.payload_sha256.as_deref(),
+ )
+ .send_retry(&self.config.retry_config)
+ .await
+ .context(PutRequestSnafu {
+ path: self.path.as_ref(),
+ })?;
+
+ Ok(get_put_result(response.headers(), VERSION_HEADER).context(MetadataSnafu)?)
+ }
}
#[derive(Debug)]
@@ -250,23 +280,10 @@ impl S3Client {
&self.config
}
- async fn get_credential(&self) -> Result<Option<Arc<AwsCredential>>> {
- Ok(match self.config.skip_signature {
- false => Some(self.config.credentials.get_credential().await?),
- true => None,
- })
- }
-
/// Make an S3 PUT request <https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObject.html>
///
/// Returns the ETag
- pub async fn put_request<T: Serialize + ?Sized + Sync>(
- &self,
- path: &Path,
- bytes: Bytes,
- query: &T,
- ) -> Result<String> {
- let credential = self.get_credential().await?;
+ pub fn put_request<'a>(&'a self, path: &'a Path, bytes: Bytes) -> PutRequest<'a> {
let url = self.config.path_url(path);
let mut builder = self.client.request(Method::PUT, url);
let mut payload_sha256 = None;
@@ -288,22 +305,12 @@ impl S3Client {
builder = builder.header(CONTENT_TYPE, value);
}
- let response = builder
- .query(query)
- .with_aws_sigv4(
- credential.as_deref(),
- &self.config.region,
- "s3",
- self.config.sign_payload,
- payload_sha256.as_deref(),
- )
- .send_retry(&self.config.retry_config)
- .await
- .context(PutRequestSnafu {
- path: path.as_ref(),
- })?;
-
- Ok(get_etag(response.headers()).context(MetadataSnafu)?)
+ PutRequest {
+ path,
+ builder,
+ payload_sha256,
+ config: &self.config,
+ }
}
/// Make an S3 Delete request <https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteObject.html>
@@ -312,7 +319,7 @@ impl S3Client {
path: &Path,
query: &T,
) -> Result<()> {
- let credential = self.get_credential().await?;
+ let credential = self.config.get_credential().await?;
let url = self.config.path_url(path);
self.client
@@ -346,7 +353,7 @@ impl S3Client {
return Ok(Vec::new());
}
- let credential = self.get_credential().await?;
+ let credential = self.config.get_credential().await?;
let url = format!("{}?delete", self.config.bucket_endpoint);
let mut buffer = Vec::new();
@@ -444,7 +451,7 @@ impl S3Client {
/// Make an S3 Copy request <https://docs.aws.amazon.com/AmazonS3/latest/API/API_CopyObject.html>
pub async fn copy_request(&self, from: &Path, to: &Path, overwrite: bool) -> Result<()> {
- let credential = self.get_credential().await?;
+ let credential = self.config.get_credential().await?;
let url = self.config.path_url(to);
let source = format!("{}/{}", self.config.bucket, encode_path(from));
@@ -492,7 +499,7 @@ impl S3Client {
}
pub async fn create_multipart(&self, location: &Path) -> Result<MultipartId> {
- let credential = self.get_credential().await?;
+ let credential = self.config.get_credential().await?;
let url = format!("{}?uploads=", self.config.path_url(location),);
let response = self
@@ -512,7 +519,7 @@ impl S3Client {
.await
.context(CreateMultipartResponseBodySnafu)?;
- let response: InitiateMultipart =
+ let response: InitiateMultipartUploadResult =
quick_xml::de::from_reader(response.reader()).context(InvalidMultipartResponseSnafu)?;
Ok(response.upload_id)
@@ -527,15 +534,15 @@ impl S3Client {
) -> Result<PartId> {
let part = (part_idx + 1).to_string();
- let content_id = self
- .put_request(
- path,
- data,
- &[("partNumber", &part), ("uploadId", upload_id)],
- )
+ let result = self
+ .put_request(path, data)
+ .query(&[("partNumber", &part), ("uploadId", upload_id)])
+ .send()
.await?;
- Ok(PartId { content_id })
+ Ok(PartId {
+ content_id: result.e_tag.unwrap(),
+ })
}
pub async fn complete_multipart(
@@ -544,19 +551,10 @@ impl S3Client {
upload_id: &str,
parts: Vec<PartId>,
) -> Result<PutResult> {
- let parts = parts
- .into_iter()
- .enumerate()
- .map(|(part_idx, part)| MultipartPart {
- e_tag: part.content_id,
- part_number: part_idx + 1,
- })
- .collect();
-
- let request = CompleteMultipart { part: parts };
+ let request = CompleteMultipartUpload::from(parts);
let body = quick_xml::se::to_string(&request).unwrap();
- let credential = self.get_credential().await?;
+ let credential = self.config.get_credential().await?;
let url = self.config.path_url(location);
let response = self
@@ -575,16 +573,19 @@ impl S3Client {
.await
.context(CompleteMultipartRequestSnafu)?;
+ let version = get_version(response.headers(), VERSION_HEADER).context(MetadataSnafu)?;
+
let data = response
.bytes()
.await
.context(CompleteMultipartResponseBodySnafu)?;
- let response: CompleteMultipartResult =
+ let response: CompleteMultipartUploadResult =
quick_xml::de::from_reader(data.reader()).context(InvalidMultipartResponseSnafu)?;
Ok(PutResult {
e_tag: Some(response.e_tag),
+ version,
})
}
}
@@ -596,12 +597,12 @@ impl GetClient for S3Client {
const HEADER_CONFIG: HeaderConfig = HeaderConfig {
etag_required: false,
last_modified_required: false,
- version_header: Some("x-amz-version-id"),
+ version_header: Some(VERSION_HEADER),
};
/// Make an S3 GET request <https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html>
async fn get_request(&self, path: &Path, options: GetOptions) -> Result<Response> {
- let credential = self.get_credential().await?;
+ let credential = self.config.get_credential().await?;
let url = self.config.path_url(path);
let method = match options.head {
true => Method::HEAD,
@@ -643,7 +644,7 @@ impl ListClient for S3Client {
token: Option<&str>,
offset: Option<&str>,
) -> Result<(ListResult, Option<String>)> {
- let credential = self.get_credential().await?;
+ let credential = self.config.get_credential().await?;
let url = self.config.bucket_endpoint.clone();
let mut query = Vec::with_capacity(4);
diff --git a/object_store/src/aws/mod.rs b/object_store/src/aws/mod.rs
index 57254c7cf4e8..99e637695059 100644
--- a/object_store/src/aws/mod.rs
+++ b/object_store/src/aws/mod.rs
@@ -35,6 +35,7 @@ use async_trait::async_trait;
use bytes::Bytes;
use futures::stream::BoxStream;
use futures::{StreamExt, TryStreamExt};
+use reqwest::header::{IF_MATCH, IF_NONE_MATCH};
use reqwest::Method;
use std::{sync::Arc, time::Duration};
use tokio::io::AsyncWrite;
@@ -47,20 +48,20 @@ use crate::client::CredentialProvider;
use crate::multipart::{MultiPartStore, PartId, PutPart, WriteMultiPart};
use crate::signer::Signer;
use crate::{
- GetOptions, GetResult, ListResult, MultipartId, ObjectMeta, ObjectStore, Path, PutResult,
- Result,
+ Error, GetOptions, GetResult, ListResult, MultipartId, ObjectMeta, ObjectStore, Path, PutMode,
+ PutOptions, PutResult, Result,
};
mod builder;
mod checksum;
mod client;
-mod copy;
mod credential;
+mod precondition;
mod resolve;
pub use builder::{AmazonS3Builder, AmazonS3ConfigKey};
pub use checksum::Checksum;
-pub use copy::S3CopyIfNotExists;
+pub use precondition::{S3ConditionalPut, S3CopyIfNotExists};
pub use resolve::resolve_bucket_region;
// http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
@@ -158,9 +159,33 @@ impl Signer for AmazonS3 {
#[async_trait]
impl ObjectStore for AmazonS3 {
- async fn put(&self, location: &Path, bytes: Bytes) -> Result<PutResult> {
- let e_tag = self.client.put_request(location, bytes, &()).await?;
- Ok(PutResult { e_tag: Some(e_tag) })
+ async fn put_opts(&self, location: &Path, bytes: Bytes, opts: PutOptions) -> Result<PutResult> {
+ let request = self.client.put_request(location, bytes);
+ match (opts.mode, &self.client.config().conditional_put) {
+ (PutMode::Overwrite, _) => request.send().await,
+ (PutMode::Create | PutMode::Update(_), None) => Err(Error::NotImplemented),
+ (PutMode::Create, Some(S3ConditionalPut::ETagMatch)) => {
+ match request.header(&IF_NONE_MATCH, "*").send().await {
+ // Technically If-None-Match should return NotModified but some stores,
+ // such as R2, instead return PreconditionFailed
+ // https://developers.cloudflare.com/r2/api/s3/extensions/#conditional-operations-in-putobject
+ Err(e @ Error::NotModified { .. } | e @ Error::Precondition { .. }) => {
+ Err(Error::AlreadyExists {
+ path: location.to_string(),
+ source: Box::new(e),
+ })
+ }
+ r => r,
+ }
+ }
+ (PutMode::Update(v), Some(S3ConditionalPut::ETagMatch)) => {
+ let etag = v.e_tag.ok_or_else(|| Error::Generic {
+ store: STORE,
+ source: "ETag required for conditional put".to_string().into(),
+ })?;
+ request.header(&IF_MATCH, etag.as_str()).send().await
+ }
+ }
}
async fn put_multipart(
@@ -306,6 +331,7 @@ mod tests {
let config = integration.client.config();
let is_local = config.endpoint.starts_with("http://");
let test_not_exists = config.copy_if_not_exists.is_some();
+ let test_conditional_put = config.conditional_put.is_some();
// Localstack doesn't support listing with spaces https://github.com/localstack/localstack/issues/6328
put_get_delete_list_opts(&integration, is_local).await;
@@ -319,6 +345,9 @@ mod tests {
if test_not_exists {
copy_if_not_exists(&integration).await;
}
+ if test_conditional_put {
+ put_opts(&integration, true).await;
+ }
// run integration test with unsigned payload enabled
let builder = AmazonS3Builder::from_env().with_unsigned_payload(true);
diff --git a/object_store/src/aws/copy.rs b/object_store/src/aws/precondition.rs
similarity index 68%
rename from object_store/src/aws/copy.rs
rename to object_store/src/aws/precondition.rs
index da4e2809be1a..a50b57fe23f7 100644
--- a/object_store/src/aws/copy.rs
+++ b/object_store/src/aws/precondition.rs
@@ -17,8 +17,7 @@
use crate::config::Parse;
-/// Configure how to provide [`ObjectStore::copy_if_not_exists`] for
-/// [`AmazonS3`].
+/// Configure how to provide [`ObjectStore::copy_if_not_exists`] for [`AmazonS3`].
///
/// [`ObjectStore::copy_if_not_exists`]: crate::ObjectStore::copy_if_not_exists
/// [`AmazonS3`]: super::AmazonS3
@@ -70,3 +69,45 @@ impl Parse for S3CopyIfNotExists {
})
}
}
+
+/// Configure how to provide conditional put support for [`AmazonS3`].
+///
+/// [`AmazonS3`]: super::AmazonS3
+#[derive(Debug, Clone)]
+#[allow(missing_copy_implementations)]
+#[non_exhaustive]
+pub enum S3ConditionalPut {
+ /// Some S3-compatible stores, such as Cloudflare R2 and minio support conditional
+ /// put using the standard [HTTP precondition] headers If-Match and If-None-Match
+ ///
+ /// Encoded as `etag` ignoring whitespace
+ ///
+ /// [HTTP precondition]: https://datatracker.ietf.org/doc/html/rfc9110#name-preconditions
+ ETagMatch,
+}
+
+impl std::fmt::Display for S3ConditionalPut {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::ETagMatch => write!(f, "etag"),
+ }
+ }
+}
+
+impl S3ConditionalPut {
+ fn from_str(s: &str) -> Option<Self> {
+ match s.trim() {
+ "etag" => Some(Self::ETagMatch),
+ _ => None,
+ }
+ }
+}
+
+impl Parse for S3ConditionalPut {
+ fn parse(v: &str) -> crate::Result<Self> {
+ Self::from_str(v).ok_or_else(|| crate::Error::Generic {
+ store: "Config",
+ source: format!("Failed to parse \"{v}\" as S3PutConditional").into(),
+ })
+ }
+}
diff --git a/object_store/src/azure/client.rs b/object_store/src/azure/client.rs
index 9f47b9a8152b..c7bd79149872 100644
--- a/object_store/src/azure/client.rs
+++ b/object_store/src/azure/client.rs
@@ -19,7 +19,7 @@ use super::credential::AzureCredential;
use crate::azure::credential::*;
use crate::azure::{AzureCredentialProvider, STORE};
use crate::client::get::GetClient;
-use crate::client::header::{get_etag, HeaderConfig};
+use crate::client::header::{get_put_result, HeaderConfig};
use crate::client::list::ListClient;
use crate::client::retry::RetryExt;
use crate::client::GetOptionsExt;
@@ -27,25 +27,29 @@ use crate::multipart::PartId;
use crate::path::DELIMITER;
use crate::util::deserialize_rfc1123;
use crate::{
- ClientOptions, GetOptions, ListResult, ObjectMeta, Path, PutResult, Result, RetryConfig,
+ ClientOptions, GetOptions, ListResult, ObjectMeta, Path, PutMode, PutOptions, PutResult,
+ Result, RetryConfig,
};
use async_trait::async_trait;
use base64::prelude::BASE64_STANDARD;
use base64::Engine;
use bytes::{Buf, Bytes};
use chrono::{DateTime, Utc};
+use hyper::http::HeaderName;
use itertools::Itertools;
use reqwest::header::CONTENT_TYPE;
use reqwest::{
- header::{HeaderValue, CONTENT_LENGTH, IF_NONE_MATCH},
- Client as ReqwestClient, Method, Response, StatusCode,
+ header::{HeaderValue, CONTENT_LENGTH, IF_MATCH, IF_NONE_MATCH},
+ Client as ReqwestClient, Method, RequestBuilder, Response,
};
use serde::{Deserialize, Serialize};
-use snafu::{ResultExt, Snafu};
+use snafu::{OptionExt, ResultExt, Snafu};
use std::collections::HashMap;
use std::sync::Arc;
use url::Url;
+const VERSION_HEADER: &str = "x-ms-version-id";
+
/// A specialized `Error` for object store-related errors
#[derive(Debug, Snafu)]
#[allow(missing_docs)]
@@ -92,6 +96,9 @@ pub(crate) enum Error {
Metadata {
source: crate::client::header::Error,
},
+
+ #[snafu(display("ETag required for conditional update"))]
+ MissingETag,
}
impl From<Error> for crate::Error {
@@ -134,6 +141,39 @@ impl AzureConfig {
}
}
+/// A builder for a put request allowing customisation of the headers and query string
+struct PutRequest<'a> {
+ path: &'a Path,
+ config: &'a AzureConfig,
+ builder: RequestBuilder,
+}
+
+impl<'a> PutRequest<'a> {
+ fn header(self, k: &HeaderName, v: &str) -> Self {
+ let builder = self.builder.header(k, v);
+ Self { builder, ..self }
+ }
+
+ fn query<T: Serialize + ?Sized + Sync>(self, query: &T) -> Self {
+ let builder = self.builder.query(query);
+ Self { builder, ..self }
+ }
+
+ async fn send(self) -> Result<Response> {
+ let credential = self.config.credentials.get_credential().await?;
+ let response = self
+ .builder
+ .with_azure_authorization(&credential, &self.config.account)
+ .send_retry(&self.config.retry_config)
+ .await
+ .context(PutRequestSnafu {
+ path: self.path.as_ref(),
+ })?;
+
+ Ok(response)
+ }
+}
+
#[derive(Debug)]
pub(crate) struct AzureClient {
config: AzureConfig,
@@ -156,63 +196,52 @@ impl AzureClient {
self.config.credentials.get_credential().await
}
- /// Make an Azure PUT request <https://docs.microsoft.com/en-us/rest/api/storageservices/put-blob>
- pub async fn put_request<T: Serialize + crate::Debug + ?Sized + Sync>(
- &self,
- path: &Path,
- bytes: Option<Bytes>,
- is_block_op: bool,
- query: &T,
- ) -> Result<Response> {
- let credential = self.get_credential().await?;
+ fn put_request<'a>(&'a self, path: &'a Path, bytes: Bytes) -> PutRequest<'a> {
let url = self.config.path_url(path);
let mut builder = self.client.request(Method::PUT, url);
- if !is_block_op {
- builder = builder.header(&BLOB_TYPE, "BlockBlob").query(query);
- } else {
- builder = builder.query(query);
- }
-
if let Some(value) = self.config().client_options.get_content_type(path) {
builder = builder.header(CONTENT_TYPE, value);
}
- if let Some(bytes) = bytes {
- builder = builder
- .header(CONTENT_LENGTH, HeaderValue::from(bytes.len()))
- .body(bytes)
- } else {
- builder = builder.header(CONTENT_LENGTH, HeaderValue::from_static("0"));
+ builder = builder
+ .header(CONTENT_LENGTH, HeaderValue::from(bytes.len()))
+ .body(bytes);
+
+ PutRequest {
+ path,
+ builder,
+ config: &self.config,
}
+ }
- let response = builder
- .with_azure_authorization(&credential, &self.config.account)
- .send_retry(&self.config.retry_config)
- .await
- .context(PutRequestSnafu {
- path: path.as_ref(),
- })?;
+ /// Make an Azure PUT request <https://docs.microsoft.com/en-us/rest/api/storageservices/put-blob>
+ pub async fn put_blob(&self, path: &Path, bytes: Bytes, opts: PutOptions) -> Result<PutResult> {
+ let builder = self.put_request(path, bytes);
+
+ let builder = match &opts.mode {
+ PutMode::Overwrite => builder,
+ PutMode::Create => builder.header(&IF_NONE_MATCH, "*"),
+ PutMode::Update(v) => {
+ let etag = v.e_tag.as_ref().context(MissingETagSnafu)?;
+ builder.header(&IF_MATCH, etag)
+ }
+ };
- Ok(response)
+ let response = builder.header(&BLOB_TYPE, "BlockBlob").send().await?;
+ Ok(get_put_result(response.headers(), VERSION_HEADER).context(MetadataSnafu)?)
}
/// PUT a block <https://learn.microsoft.com/en-us/rest/api/storageservices/put-block>
pub async fn put_block(&self, path: &Path, part_idx: usize, data: Bytes) -> Result<PartId> {
let content_id = format!("{part_idx:20}");
- let block_id: BlockId = content_id.clone().into();
+ let block_id = BASE64_STANDARD.encode(&content_id);
- self.put_request(
- path,
- Some(data),
- true,
- &[
- ("comp", "block"),
- ("blockid", &BASE64_STANDARD.encode(block_id)),
- ],
- )
- .await?;
+ self.put_request(path, data)
+ .query(&[("comp", "block"), ("blockid", &block_id)])
+ .send()
+ .await?;
Ok(PartId { content_id })
}
@@ -224,15 +253,13 @@ impl AzureClient {
.map(|part| BlockId::from(part.content_id))
.collect();
- let block_list = BlockList { blocks };
- let block_xml = block_list.to_xml();
-
let response = self
- .put_request(path, Some(block_xml.into()), true, &[("comp", "blocklist")])
+ .put_request(path, BlockList { blocks }.to_xml().into())
+ .query(&[("comp", "blocklist")])
+ .send()
.await?;
- let e_tag = get_etag(response.headers()).context(MetadataSnafu)?;
- Ok(PutResult { e_tag: Some(e_tag) })
+ Ok(get_put_result(response.headers(), VERSION_HEADER).context(MetadataSnafu)?)
}
/// Make an Azure Delete request <https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob>
@@ -284,13 +311,7 @@ impl AzureClient {
.with_azure_authorization(&credential, &self.config.account)
.send_retry(&self.config.retry_config)
.await
- .map_err(|err| match err.status() {
- Some(StatusCode::CONFLICT) => crate::Error::AlreadyExists {
- source: Box::new(err),
- path: to.to_string(),
- },
- _ => err.error(STORE, from.to_string()),
- })?;
+ .map_err(|err| err.error(STORE, from.to_string()))?;
Ok(())
}
@@ -303,7 +324,7 @@ impl GetClient for AzureClient {
const HEADER_CONFIG: HeaderConfig = HeaderConfig {
etag_required: true,
last_modified_required: true,
- version_header: Some("x-ms-version-id"),
+ version_header: Some(VERSION_HEADER),
};
/// Make an Azure GET request
diff --git a/object_store/src/azure/mod.rs b/object_store/src/azure/mod.rs
index 779ac2f71ff8..762a51dd9d60 100644
--- a/object_store/src/azure/mod.rs
+++ b/object_store/src/azure/mod.rs
@@ -29,7 +29,8 @@
use crate::{
multipart::{PartId, PutPart, WriteMultiPart},
path::Path,
- GetOptions, GetResult, ListResult, MultipartId, ObjectMeta, ObjectStore, PutResult, Result,
+ GetOptions, GetResult, ListResult, MultipartId, ObjectMeta, ObjectStore, PutOptions, PutResult,
+ Result,
};
use async_trait::async_trait;
use bytes::Bytes;
@@ -49,7 +50,6 @@ mod credential;
/// [`CredentialProvider`] for [`MicrosoftAzure`]
pub type AzureCredentialProvider = Arc<dyn CredentialProvider<Credential = AzureCredential>>;
-use crate::client::header::get_etag;
use crate::multipart::MultiPartStore;
pub use builder::{AzureConfigKey, MicrosoftAzureBuilder};
pub use credential::AzureCredential;
@@ -82,16 +82,8 @@ impl std::fmt::Display for MicrosoftAzure {
#[async_trait]
impl ObjectStore for MicrosoftAzure {
- async fn put(&self, location: &Path, bytes: Bytes) -> Result<PutResult> {
- let response = self
- .client
- .put_request(location, Some(bytes), false, &())
- .await?;
- let e_tag = get_etag(response.headers()).map_err(|e| crate::Error::Generic {
- store: STORE,
- source: Box::new(e),
- })?;
- Ok(PutResult { e_tag: Some(e_tag) })
+ async fn put_opts(&self, location: &Path, bytes: Bytes, opts: PutOptions) -> Result<PutResult> {
+ self.client.put_blob(location, bytes, opts).await
}
async fn put_multipart(
@@ -208,6 +200,7 @@ mod tests {
rename_and_copy(&integration).await;
copy_if_not_exists(&integration).await;
stream_get(&integration).await;
+ put_opts(&integration, true).await;
multipart(&integration, &integration).await;
}
diff --git a/object_store/src/chunked.rs b/object_store/src/chunked.rs
index 021f9f50156b..d33556f4b12e 100644
--- a/object_store/src/chunked.rs
+++ b/object_store/src/chunked.rs
@@ -29,7 +29,8 @@ use tokio::io::AsyncWrite;
use crate::path::Path;
use crate::{
- GetOptions, GetResult, GetResultPayload, ListResult, ObjectMeta, ObjectStore, PutResult,
+ GetOptions, GetResult, GetResultPayload, ListResult, ObjectMeta, ObjectStore, PutOptions,
+ PutResult,
};
use crate::{MultipartId, Result};
@@ -62,8 +63,8 @@ impl Display for ChunkedStore {
#[async_trait]
impl ObjectStore for ChunkedStore {
- async fn put(&self, location: &Path, bytes: Bytes) -> Result<PutResult> {
- self.inner.put(location, bytes).await
+ async fn put_opts(&self, location: &Path, bytes: Bytes, opts: PutOptions) -> Result<PutResult> {
+ self.inner.put_opts(location, bytes, opts).await
}
async fn put_multipart(
diff --git a/object_store/src/client/header.rs b/object_store/src/client/header.rs
index e67496833b99..e85bf6ba52d0 100644
--- a/object_store/src/client/header.rs
+++ b/object_store/src/client/header.rs
@@ -67,6 +67,23 @@ pub enum Error {
},
}
+/// Extracts a PutResult from the provided [`HeaderMap`]
+#[cfg(any(feature = "aws", feature = "gcp", feature = "azure"))]
+pub fn get_put_result(headers: &HeaderMap, version: &str) -> Result<crate::PutResult, Error> {
+ let e_tag = Some(get_etag(headers)?);
+ let version = get_version(headers, version)?;
+ Ok(crate::PutResult { e_tag, version })
+}
+
+/// Extracts a optional version from the provided [`HeaderMap`]
+#[cfg(any(feature = "aws", feature = "gcp", feature = "azure"))]
+pub fn get_version(headers: &HeaderMap, version: &str) -> Result<Option<String>, Error> {
+ Ok(match headers.get(version) {
+ Some(x) => Some(x.to_str().context(BadHeaderSnafu)?.to_string()),
+ None => None,
+ })
+}
+
/// Extracts an etag from the provided [`HeaderMap`]
pub fn get_etag(headers: &HeaderMap) -> Result<String, Error> {
let e_tag = headers.get(ETAG).ok_or(Error::MissingEtag)?;
diff --git a/object_store/src/client/mod.rs b/object_store/src/client/mod.rs
index 77eee7fc92f3..ae092edac095 100644
--- a/object_store/src/client/mod.rs
+++ b/object_store/src/client/mod.rs
@@ -38,7 +38,7 @@ pub mod token;
pub mod header;
#[cfg(any(feature = "aws", feature = "gcp"))]
-pub mod list_response;
+pub mod s3;
use async_trait::async_trait;
use std::collections::HashMap;
diff --git a/object_store/src/client/retry.rs b/object_store/src/client/retry.rs
index d70d6d88de32..789103c0f74f 100644
--- a/object_store/src/client/retry.rs
+++ b/object_store/src/client/retry.rs
@@ -79,6 +79,10 @@ impl Error {
path,
source: Box::new(self),
},
+ Some(StatusCode::CONFLICT) => crate::Error::AlreadyExists {
+ path,
+ source: Box::new(self),
+ },
_ => crate::Error::Generic {
store,
source: Box::new(self),
diff --git a/object_store/src/client/list_response.rs b/object_store/src/client/s3.rs
similarity index 68%
rename from object_store/src/client/list_response.rs
rename to object_store/src/client/s3.rs
index 7a170c584156..61237dc4beab 100644
--- a/object_store/src/client/list_response.rs
+++ b/object_store/src/client/s3.rs
@@ -14,12 +14,13 @@
// specific language governing permissions and limitations
// under the License.
-//! The list response format used by GCP and AWS
+//! The list and multipart API used by both GCS and S3
+use crate::multipart::PartId;
use crate::path::Path;
use crate::{ListResult, ObjectMeta, Result};
use chrono::{DateTime, Utc};
-use serde::Deserialize;
+use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
@@ -84,3 +85,44 @@ impl TryFrom<ListContents> for ObjectMeta {
})
}
}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct InitiateMultipartUploadResult {
+ pub upload_id: String,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct CompleteMultipartUpload {
+ pub part: Vec<MultipartPart>,
+}
+
+impl From<Vec<PartId>> for CompleteMultipartUpload {
+ fn from(value: Vec<PartId>) -> Self {
+ let part = value
+ .into_iter()
+ .enumerate()
+ .map(|(part_number, part)| MultipartPart {
+ e_tag: part.content_id,
+ part_number: part_number + 1,
+ })
+ .collect();
+ Self { part }
+ }
+}
+
+#[derive(Debug, Serialize)]
+pub struct MultipartPart {
+ #[serde(rename = "ETag")]
+ pub e_tag: String,
+ #[serde(rename = "PartNumber")]
+ pub part_number: usize,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct CompleteMultipartUploadResult {
+ #[serde(rename = "ETag")]
+ pub e_tag: String,
+}
diff --git a/object_store/src/gcp/client.rs b/object_store/src/gcp/client.rs
index 8c44f9016480..78964077e2fe 100644
--- a/object_store/src/gcp/client.rs
+++ b/object_store/src/gcp/client.rs
@@ -16,23 +16,34 @@
// under the License.
use crate::client::get::GetClient;
-use crate::client::header::{get_etag, HeaderConfig};
+use crate::client::header::{get_put_result, get_version, HeaderConfig};
use crate::client::list::ListClient;
-use crate::client::list_response::ListResponse;
use crate::client::retry::RetryExt;
+use crate::client::s3::{
+ CompleteMultipartUpload, CompleteMultipartUploadResult, InitiateMultipartUploadResult,
+ ListResponse,
+};
use crate::client::GetOptionsExt;
use crate::gcp::{GcpCredential, GcpCredentialProvider, STORE};
use crate::multipart::PartId;
use crate::path::{Path, DELIMITER};
-use crate::{ClientOptions, GetOptions, ListResult, MultipartId, PutResult, Result, RetryConfig};
+use crate::{
+ ClientOptions, GetOptions, ListResult, MultipartId, PutMode, PutOptions, PutResult, Result,
+ RetryConfig,
+};
use async_trait::async_trait;
use bytes::{Buf, Bytes};
use percent_encoding::{percent_encode, utf8_percent_encode, NON_ALPHANUMERIC};
-use reqwest::{header, Client, Method, Response, StatusCode};
+use reqwest::header::HeaderName;
+use reqwest::{header, Client, Method, RequestBuilder, Response, StatusCode};
use serde::Serialize;
-use snafu::{ResultExt, Snafu};
+use snafu::{OptionExt, ResultExt, Snafu};
use std::sync::Arc;
+const VERSION_HEADER: &str = "x-goog-generation";
+
+static VERSION_MATCH: HeaderName = HeaderName::from_static("x-goog-if-generation-match");
+
#[derive(Debug, Snafu)]
enum Error {
#[snafu(display("Error performing list request: {}", source))]
@@ -78,6 +89,18 @@ enum Error {
Metadata {
source: crate::client::header::Error,
},
+
+ #[snafu(display("Version required for conditional update"))]
+ MissingVersion,
+
+ #[snafu(display("Error performing complete multipart request: {}", source))]
+ CompleteMultipartRequest { source: crate::client::retry::Error },
+
+ #[snafu(display("Error getting complete multipart response body: {}", source))]
+ CompleteMultipartResponseBody { source: reqwest::Error },
+
+ #[snafu(display("Got invalid multipart response: {}", source))]
+ InvalidMultipartResponse { source: quick_xml::de::DeError },
}
impl From<Error> for crate::Error {
@@ -107,6 +130,39 @@ pub struct GoogleCloudStorageConfig {
pub client_options: ClientOptions,
}
+/// A builder for a put request allowing customisation of the headers and query string
+pub struct PutRequest<'a> {
+ path: &'a Path,
+ config: &'a GoogleCloudStorageConfig,
+ builder: RequestBuilder,
+}
+
+impl<'a> PutRequest<'a> {
+ fn header(self, k: &HeaderName, v: &str) -> Self {
+ let builder = self.builder.header(k, v);
+ Self { builder, ..self }
+ }
+
+ fn query<T: Serialize + ?Sized + Sync>(self, query: &T) -> Self {
+ let builder = self.builder.query(query);
+ Self { builder, ..self }
+ }
+
+ async fn send(self) -> Result<PutResult> {
+ let credential = self.config.credentials.get_credential().await?;
+ let response = self
+ .builder
+ .bearer_auth(&credential.bearer)
+ .send_retry(&self.config.retry_config)
+ .await
+ .context(PutRequestSnafu {
+ path: self.path.as_ref(),
+ })?;
+
+ Ok(get_put_result(response.headers(), VERSION_HEADER).context(MetadataSnafu)?)
+ }
+}
+
#[derive(Debug)]
pub struct GoogleCloudStorageClient {
config: GoogleCloudStorageConfig,
@@ -152,13 +208,7 @@ impl GoogleCloudStorageClient {
/// Perform a put request <https://cloud.google.com/storage/docs/xml-api/put-object-upload>
///
/// Returns the new ETag
- pub async fn put_request<T: Serialize + ?Sized + Sync>(
- &self,
- path: &Path,
- payload: Bytes,
- query: &T,
- ) -> Result<String> {
- let credential = self.get_credential().await?;
+ pub fn put_request<'a>(&'a self, path: &'a Path, payload: Bytes) -> PutRequest<'a> {
let url = self.object_url(path);
let content_type = self
@@ -167,21 +217,38 @@ impl GoogleCloudStorageClient {
.get_content_type(path)
.unwrap_or("application/octet-stream");
- let response = self
+ let builder = self
.client
.request(Method::PUT, url)
- .query(query)
- .bearer_auth(&credential.bearer)
.header(header::CONTENT_TYPE, content_type)
.header(header::CONTENT_LENGTH, payload.len())
- .body(payload)
- .send_retry(&self.config.retry_config)
- .await
- .context(PutRequestSnafu {
- path: path.as_ref(),
- })?;
+ .body(payload);
- Ok(get_etag(response.headers()).context(MetadataSnafu)?)
+ PutRequest {
+ path,
+ builder,
+ config: &self.config,
+ }
+ }
+
+ pub async fn put(&self, path: &Path, data: Bytes, opts: PutOptions) -> Result<PutResult> {
+ let builder = self.put_request(path, data);
+
+ let builder = match &opts.mode {
+ PutMode::Overwrite => builder,
+ PutMode::Create => builder.header(&VERSION_MATCH, "0"),
+ PutMode::Update(v) => {
+ let etag = v.version.as_ref().context(MissingVersionSnafu)?;
+ builder.header(&VERSION_MATCH, etag)
+ }
+ };
+
+ match (opts.mode, builder.send().await) {
+ (PutMode::Create, Err(crate::Error::Precondition { path, source })) => {
+ Err(crate::Error::AlreadyExists { path, source })
+ }
+ (_, r) => r,
+ }
}
/// Perform a put part request <https://cloud.google.com/storage/docs/xml-api/put-object-multipart>
@@ -194,18 +261,15 @@ impl GoogleCloudStorageClient {
part_idx: usize,
data: Bytes,
) -> Result<PartId> {
- let content_id = self
- .put_request(
- path,
- data,
- &[
- ("partNumber", &format!("{}", part_idx + 1)),
- ("uploadId", upload_id),
- ],
- )
- .await?;
-
- Ok(PartId { content_id })
+ let query = &[
+ ("partNumber", &format!("{}", part_idx + 1)),
+ ("uploadId", upload_id),
+ ];
+ let result = self.put_request(path, data).query(query).send().await?;
+
+ Ok(PartId {
+ content_id: result.e_tag.unwrap(),
+ })
}
/// Initiate a multi-part upload <https://cloud.google.com/storage/docs/xml-api/post-object-multipart>
@@ -268,17 +332,8 @@ impl GoogleCloudStorageClient {
let upload_id = multipart_id.clone();
let url = self.object_url(path);
- let parts = completed_parts
- .into_iter()
- .enumerate()
- .map(|(part_number, part)| MultipartPart {
- e_tag: part.content_id,
- part_number: part_number + 1,
- })
- .collect();
-
+ let upload_info = CompleteMultipartUpload::from(completed_parts);
let credential = self.get_credential().await?;
- let upload_info = CompleteMultipartUpload { parts };
let data = quick_xml::se::to_string(&upload_info)
.context(InvalidPutResponseSnafu)?
@@ -287,7 +342,7 @@ impl GoogleCloudStorageClient {
// https://github.com/tafia/quick-xml/issues/350
.replace(""", "\"");
- let result = self
+ let response = self
.client
.request(Method::POST, &url)
.bearer_auth(&credential.bearer)
@@ -295,12 +350,22 @@ impl GoogleCloudStorageClient {
.body(data)
.send_retry(&self.config.retry_config)
.await
- .context(PostRequestSnafu {
- path: path.as_ref(),
- })?;
+ .context(CompleteMultipartRequestSnafu)?;
- let etag = get_etag(result.headers()).context(MetadataSnafu)?;
- Ok(PutResult { e_tag: Some(etag) })
+ let version = get_version(response.headers(), VERSION_HEADER).context(MetadataSnafu)?;
+
+ let data = response
+ .bytes()
+ .await
+ .context(CompleteMultipartResponseBodySnafu)?;
+
+ let response: CompleteMultipartUploadResult =
+ quick_xml::de::from_reader(data.reader()).context(InvalidMultipartResponseSnafu)?;
+
+ Ok(PutResult {
+ e_tag: Some(response.e_tag),
+ version,
+ })
}
/// Perform a delete request <https://cloud.google.com/storage/docs/xml-api/delete-object>
@@ -334,7 +399,7 @@ impl GoogleCloudStorageClient {
.header("x-goog-copy-source", source);
if if_not_exists {
- builder = builder.header("x-goog-if-generation-match", 0);
+ builder = builder.header(&VERSION_MATCH, 0);
}
builder
@@ -362,7 +427,7 @@ impl GetClient for GoogleCloudStorageClient {
const HEADER_CONFIG: HeaderConfig = HeaderConfig {
etag_required: true,
last_modified_required: true,
- version_header: Some("x-goog-generation"),
+ version_header: Some(VERSION_HEADER),
};
/// Perform a get request <https://cloud.google.com/storage/docs/xml-api/get-object-download>
@@ -375,13 +440,18 @@ impl GetClient for GoogleCloudStorageClient {
false => Method::GET,
};
- let mut request = self.client.request(method, url).with_get_options(options);
+ let mut request = self.client.request(method, url);
+
+ if let Some(version) = &options.version {
+ request = request.query(&[("generation", version)]);
+ }
if !credential.bearer.is_empty() {
request = request.bearer_auth(&credential.bearer);
}
let response = request
+ .with_get_options(options)
.send_retry(&self.config.retry_config)
.await
.context(GetRequestSnafu {
@@ -444,24 +514,3 @@ impl ListClient for GoogleCloudStorageClient {
Ok((response.try_into()?, token))
}
}
-
-#[derive(serde::Deserialize, Debug)]
-#[serde(rename_all = "PascalCase")]
-struct InitiateMultipartUploadResult {
- upload_id: String,
-}
-
-#[derive(serde::Serialize, Debug)]
-#[serde(rename_all = "PascalCase", rename(serialize = "Part"))]
-struct MultipartPart {
- #[serde(rename = "PartNumber")]
- part_number: usize,
- e_tag: String,
-}
-
-#[derive(serde::Serialize, Debug)]
-#[serde(rename_all = "PascalCase")]
-struct CompleteMultipartUpload {
- #[serde(rename = "Part", default)]
- parts: Vec<MultipartPart>,
-}
diff --git a/object_store/src/gcp/mod.rs b/object_store/src/gcp/mod.rs
index 0eb3e9c23c43..7721b1278a80 100644
--- a/object_store/src/gcp/mod.rs
+++ b/object_store/src/gcp/mod.rs
@@ -35,7 +35,8 @@ use crate::client::CredentialProvider;
use crate::{
multipart::{PartId, PutPart, WriteMultiPart},
path::Path,
- GetOptions, GetResult, ListResult, MultipartId, ObjectMeta, ObjectStore, PutResult, Result,
+ GetOptions, GetResult, ListResult, MultipartId, ObjectMeta, ObjectStore, PutOptions, PutResult,
+ Result,
};
use async_trait::async_trait;
use bytes::Bytes;
@@ -107,9 +108,8 @@ impl PutPart for GCSMultipartUpload {
#[async_trait]
impl ObjectStore for GoogleCloudStorage {
- async fn put(&self, location: &Path, bytes: Bytes) -> Result<PutResult> {
- let e_tag = self.client.put_request(location, bytes, &()).await?;
- Ok(PutResult { e_tag: Some(e_tag) })
+ async fn put_opts(&self, location: &Path, bytes: Bytes, opts: PutOptions) -> Result<PutResult> {
+ self.client.put(location, bytes, opts).await
}
async fn put_multipart(
@@ -221,6 +221,7 @@ mod test {
multipart(&integration, &integration).await;
// Fake GCS server doesn't currently honor preconditions
get_opts(&integration).await;
+ put_opts(&integration, true).await;
}
}
diff --git a/object_store/src/http/client.rs b/object_store/src/http/client.rs
index a7dbdfcbe844..8700775fb243 100644
--- a/object_store/src/http/client.rs
+++ b/object_store/src/http/client.rs
@@ -243,6 +243,10 @@ impl Client {
.header("Destination", self.path_url(to).as_str());
if !overwrite {
+ // While the Overwrite header appears to duplicate
+ // the functionality of the If-Match: * header of HTTP/1.1, If-Match
+ // applies only to the Request-URI, and not to the Destination of a COPY
+ // or MOVE.
builder = builder.header("Overwrite", "F");
}
diff --git a/object_store/src/http/mod.rs b/object_store/src/http/mod.rs
index 8f61011ccae1..cfcde27fd781 100644
--- a/object_store/src/http/mod.rs
+++ b/object_store/src/http/mod.rs
@@ -46,7 +46,7 @@ use crate::http::client::Client;
use crate::path::Path;
use crate::{
ClientConfigKey, ClientOptions, GetOptions, GetResult, ListResult, MultipartId, ObjectMeta,
- ObjectStore, PutResult, Result, RetryConfig,
+ ObjectStore, PutMode, PutOptions, PutResult, Result, RetryConfig,
};
mod client;
@@ -96,14 +96,23 @@ impl std::fmt::Display for HttpStore {
#[async_trait]
impl ObjectStore for HttpStore {
- async fn put(&self, location: &Path, bytes: Bytes) -> Result<PutResult> {
+ async fn put_opts(&self, location: &Path, bytes: Bytes, opts: PutOptions) -> Result<PutResult> {
+ if opts.mode != PutMode::Overwrite {
+ // TODO: Add support for If header - https://datatracker.ietf.org/doc/html/rfc2518#section-9.4
+ return Err(crate::Error::NotImplemented);
+ }
+
let response = self.client.put(location, bytes).await?;
let e_tag = match get_etag(response.headers()) {
Ok(e_tag) => Some(e_tag),
Err(crate::client::header::Error::MissingEtag) => None,
Err(source) => return Err(Error::Metadata { source }.into()),
};
- Ok(PutResult { e_tag })
+
+ Ok(PutResult {
+ e_tag,
+ version: None,
+ })
}
async fn put_multipart(
diff --git a/object_store/src/lib.rs b/object_store/src/lib.rs
index 9a0667229803..66964304e853 100644
--- a/object_store/src/lib.rs
+++ b/object_store/src/lib.rs
@@ -299,7 +299,12 @@ pub trait ObjectStore: std::fmt::Display + Send + Sync + Debug + 'static {
/// The operation is guaranteed to be atomic, it will either successfully
/// write the entirety of `bytes` to `location`, or fail. No clients
/// should be able to observe a partially written object
- async fn put(&self, location: &Path, bytes: Bytes) -> Result<PutResult>;
+ async fn put(&self, location: &Path, bytes: Bytes) -> Result<PutResult> {
+ self.put_opts(location, bytes, PutOptions::default()).await
+ }
+
+ /// Save the provided bytes to the specified location with the given options
+ async fn put_opts(&self, location: &Path, bytes: Bytes, opts: PutOptions) -> Result<PutResult>;
/// Get a multi-part upload that allows writing data in chunks.
///
@@ -531,6 +536,15 @@ macro_rules! as_ref_impl {
self.as_ref().put(location, bytes).await
}
+ async fn put_opts(
+ &self,
+ location: &Path,
+ bytes: Bytes,
+ opts: PutOptions,
+ ) -> Result<PutResult> {
+ self.as_ref().put_opts(location, bytes, opts).await
+ }
+
async fn put_multipart(
&self,
location: &Path,
@@ -837,13 +851,65 @@ impl GetResult {
}
}
+/// Configure preconditions for the put operation
+#[derive(Debug, Clone, PartialEq, Eq, Default)]
+pub enum PutMode {
+ /// Perform an atomic write operation, overwriting any object present at the provided path
+ #[default]
+ Overwrite,
+ /// Perform an atomic write operation, returning [`Error::AlreadyExists`] if an
+ /// object already exists at the provided path
+ Create,
+ /// Perform an atomic write operation if the current version of the object matches the
+ /// provided [`UpdateVersion`], returning [`Error::Precondition`] otherwise
+ Update(UpdateVersion),
+}
+
+/// Uniquely identifies a version of an object to update
+///
+/// Stores will use differing combinations of `e_tag` and `version` to provide conditional
+/// updates, and it is therefore recommended applications preserve both
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct UpdateVersion {
+ /// The unique identifier for the newly created object
+ ///
+ /// <https://datatracker.ietf.org/doc/html/rfc9110#name-etag>
+ pub e_tag: Option<String>,
+ /// A version indicator for the newly created object
+ pub version: Option<String>,
+}
+
+impl From<PutResult> for UpdateVersion {
+ fn from(value: PutResult) -> Self {
+ Self {
+ e_tag: value.e_tag,
+ version: value.version,
+ }
+ }
+}
+
+/// Options for a put request
+#[derive(Debug, Clone, PartialEq, Eq, Default)]
+pub struct PutOptions {
+ /// Configure the [`PutMode`] for this operation
+ pub mode: PutMode,
+}
+
+impl From<PutMode> for PutOptions {
+ fn from(mode: PutMode) -> Self {
+ Self { mode }
+ }
+}
+
/// Result for a put request
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PutResult {
- /// The unique identifier for the object
+ /// The unique identifier for the newly created object
///
/// <https://datatracker.ietf.org/doc/html/rfc9110#name-etag>
pub e_tag: Option<String>,
+ /// A version indicator for the newly created object
+ pub version: Option<String>,
}
/// A specialized `Result` for object store-related errors
@@ -947,6 +1013,7 @@ mod tests {
use crate::multipart::MultiPartStore;
use crate::test_util::flatten_list_stream;
use chrono::TimeZone;
+ use futures::stream::FuturesUnordered;
use rand::{thread_rng, Rng};
use tokio::io::AsyncWriteExt;
@@ -1406,7 +1473,7 @@ mod tests {
// Can retrieve previous version
let get_opts = storage.get_opts(&path, options).await.unwrap();
let old = get_opts.bytes().await.unwrap();
- assert_eq!(old, b"foo".as_slice());
+ assert_eq!(old, b"test".as_slice());
// Current version contains the updated data
let current = storage.get(&path).await.unwrap().bytes().await.unwrap();
@@ -1414,6 +1481,104 @@ mod tests {
}
}
+ pub(crate) async fn put_opts(storage: &dyn ObjectStore, supports_update: bool) {
+ delete_fixtures(storage).await;
+ let path = Path::from("put_opts");
+ let v1 = storage
+ .put_opts(&path, "a".into(), PutMode::Create.into())
+ .await
+ .unwrap();
+
+ let err = storage
+ .put_opts(&path, "b".into(), PutMode::Create.into())
+ .await
+ .unwrap_err();
+ assert!(matches!(err, Error::AlreadyExists { .. }), "{err}");
+
+ let b = storage.get(&path).await.unwrap().bytes().await.unwrap();
+ assert_eq!(b.as_ref(), b"a");
+
+ if !supports_update {
+ return;
+ }
+
+ let v2 = storage
+ .put_opts(&path, "c".into(), PutMode::Update(v1.clone().into()).into())
+ .await
+ .unwrap();
+
+ let b = storage.get(&path).await.unwrap().bytes().await.unwrap();
+ assert_eq!(b.as_ref(), b"c");
+
+ let err = storage
+ .put_opts(&path, "d".into(), PutMode::Update(v1.into()).into())
+ .await
+ .unwrap_err();
+ assert!(matches!(err, Error::Precondition { .. }), "{err}");
+
+ storage
+ .put_opts(&path, "e".into(), PutMode::Update(v2.clone().into()).into())
+ .await
+ .unwrap();
+
+ let b = storage.get(&path).await.unwrap().bytes().await.unwrap();
+ assert_eq!(b.as_ref(), b"e");
+
+ // Update not exists
+ let path = Path::from("I don't exist");
+ let err = storage
+ .put_opts(&path, "e".into(), PutMode::Update(v2.into()).into())
+ .await
+ .unwrap_err();
+ assert!(matches!(err, Error::Precondition { .. }), "{err}");
+
+ const NUM_WORKERS: usize = 5;
+ const NUM_INCREMENTS: usize = 10;
+
+ let path = Path::from("RACE");
+ let mut futures: FuturesUnordered<_> = (0..NUM_WORKERS)
+ .map(|_| async {
+ for _ in 0..NUM_INCREMENTS {
+ loop {
+ match storage.get(&path).await {
+ Ok(r) => {
+ let mode = PutMode::Update(UpdateVersion {
+ e_tag: r.meta.e_tag.clone(),
+ version: r.meta.version.clone(),
+ });
+
+ let b = r.bytes().await.unwrap();
+ let v: usize = std::str::from_utf8(&b).unwrap().parse().unwrap();
+ let new = (v + 1).to_string();
+
+ match storage.put_opts(&path, new.into(), mode.into()).await {
+ Ok(_) => break,
+ Err(Error::Precondition { .. }) => continue,
+ Err(e) => return Err(e),
+ }
+ }
+ Err(Error::NotFound { .. }) => {
+ let mode = PutMode::Create;
+ match storage.put_opts(&path, "1".into(), mode.into()).await {
+ Ok(_) => break,
+ Err(Error::AlreadyExists { .. }) => continue,
+ Err(e) => return Err(e),
+ }
+ }
+ Err(e) => return Err(e),
+ }
+ }
+ }
+ Ok(())
+ })
+ .collect();
+
+ while futures.next().await.transpose().unwrap().is_some() {}
+ let b = storage.get(&path).await.unwrap().bytes().await.unwrap();
+ let v = std::str::from_utf8(&b).unwrap().parse::<usize>().unwrap();
+ assert_eq!(v, NUM_WORKERS * NUM_INCREMENTS);
+ }
+
/// Returns a chunk of length `chunk_length`
fn get_chunk(chunk_length: usize) -> Bytes {
let mut data = vec![0_u8; chunk_length];
diff --git a/object_store/src/limit.rs b/object_store/src/limit.rs
index cd01a964dc3e..39cc605c4768 100644
--- a/object_store/src/limit.rs
+++ b/object_store/src/limit.rs
@@ -19,7 +19,7 @@
use crate::{
BoxStream, GetOptions, GetResult, GetResultPayload, ListResult, MultipartId, ObjectMeta,
- ObjectStore, Path, PutResult, Result, StreamExt,
+ ObjectStore, Path, PutOptions, PutResult, Result, StreamExt,
};
use async_trait::async_trait;
use bytes::Bytes;
@@ -77,6 +77,10 @@ impl<T: ObjectStore> ObjectStore for LimitStore<T> {
self.inner.put(location, bytes).await
}
+ async fn put_opts(&self, location: &Path, bytes: Bytes, opts: PutOptions) -> Result<PutResult> {
+ let _permit = self.semaphore.acquire().await.unwrap();
+ self.inner.put_opts(location, bytes, opts).await
+ }
async fn put_multipart(
&self,
location: &Path,
diff --git a/object_store/src/local.rs b/object_store/src/local.rs
index ce9aa4683499..919baf71b0a8 100644
--- a/object_store/src/local.rs
+++ b/object_store/src/local.rs
@@ -20,7 +20,7 @@ use crate::{
maybe_spawn_blocking,
path::{absolute_path_to_url, Path},
GetOptions, GetResult, GetResultPayload, ListResult, MultipartId, ObjectMeta, ObjectStore,
- PutResult, Result,
+ PutMode, PutOptions, PutResult, Result,
};
use async_trait::async_trait;
use bytes::Bytes;
@@ -271,20 +271,44 @@ impl Config {
#[async_trait]
impl ObjectStore for LocalFileSystem {
- async fn put(&self, location: &Path, bytes: Bytes) -> Result<PutResult> {
+ async fn put_opts(&self, location: &Path, bytes: Bytes, opts: PutOptions) -> Result<PutResult> {
+ if matches!(opts.mode, PutMode::Update(_)) {
+ return Err(crate::Error::NotImplemented);
+ }
+
let path = self.config.path_to_filesystem(location)?;
maybe_spawn_blocking(move || {
let (mut file, suffix) = new_staged_upload(&path)?;
let staging_path = staged_upload_path(&path, &suffix);
- file.write_all(&bytes)
- .context(UnableToCopyDataToFileSnafu)
- .and_then(|_| {
- std::fs::rename(&staging_path, &path).context(UnableToRenameFileSnafu)
- })
- .map_err(|e| {
- let _ = std::fs::remove_file(&staging_path); // Attempt to cleanup
- e
- })?;
+
+ let err = match file.write_all(&bytes) {
+ Ok(_) => match opts.mode {
+ PutMode::Overwrite => match std::fs::rename(&staging_path, &path) {
+ Ok(_) => None,
+ Err(source) => Some(Error::UnableToRenameFile { source }),
+ },
+ PutMode::Create => match std::fs::hard_link(&staging_path, &path) {
+ Ok(_) => {
+ let _ = std::fs::remove_file(&staging_path); // Attempt to cleanup
+ None
+ }
+ Err(source) => match source.kind() {
+ ErrorKind::AlreadyExists => Some(Error::AlreadyExists {
+ path: path.to_str().unwrap().to_string(),
+ source,
+ }),
+ _ => Some(Error::UnableToRenameFile { source }),
+ },
+ },
+ PutMode::Update(_) => unreachable!(),
+ },
+ Err(source) => Some(Error::UnableToCopyDataToFile { source }),
+ };
+
+ if let Some(err) = err {
+ let _ = std::fs::remove_file(&staging_path); // Attempt to cleanup
+ return Err(err.into());
+ }
let metadata = file.metadata().map_err(|e| Error::Metadata {
source: e.into(),
@@ -293,6 +317,7 @@ impl ObjectStore for LocalFileSystem {
Ok(PutResult {
e_tag: Some(get_etag(&metadata)),
+ version: None,
})
})
.await
@@ -1054,6 +1079,7 @@ mod tests {
rename_and_copy(&integration).await;
copy_if_not_exists(&integration).await;
stream_get(&integration).await;
+ put_opts(&integration, false).await;
}
#[test]
diff --git a/object_store/src/memory.rs b/object_store/src/memory.rs
index 8b9522e48de8..9d79a798ad1f 100644
--- a/object_store/src/memory.rs
+++ b/object_store/src/memory.rs
@@ -17,7 +17,8 @@
//! An in-memory object store implementation
use crate::{
- path::Path, GetResult, GetResultPayload, ListResult, ObjectMeta, ObjectStore, PutResult, Result,
+ path::Path, GetResult, GetResultPayload, ListResult, ObjectMeta, ObjectStore, PutMode,
+ PutOptions, PutResult, Result, UpdateVersion,
};
use crate::{GetOptions, MultipartId};
use async_trait::async_trait;
@@ -52,6 +53,9 @@ enum Error {
#[snafu(display("Object already exists at that location: {path}"))]
AlreadyExists { path: String },
+
+ #[snafu(display("ETag required for conditional update"))]
+ MissingETag,
}
impl From<Error> for super::Error {
@@ -110,9 +114,50 @@ impl Storage {
let etag = self.next_etag;
self.next_etag += 1;
let entry = Entry::new(bytes, Utc::now(), etag);
- self.map.insert(location.clone(), entry);
+ self.overwrite(location, entry);
etag
}
+
+ fn overwrite(&mut self, location: &Path, entry: Entry) {
+ self.map.insert(location.clone(), entry);
+ }
+
+ fn create(&mut self, location: &Path, entry: Entry) -> Result<()> {
+ use std::collections::btree_map;
+ match self.map.entry(location.clone()) {
+ btree_map::Entry::Occupied(_) => Err(Error::AlreadyExists {
+ path: location.to_string(),
+ }
+ .into()),
+ btree_map::Entry::Vacant(v) => {
+ v.insert(entry);
+ Ok(())
+ }
+ }
+ }
+
+ fn update(&mut self, location: &Path, v: UpdateVersion, entry: Entry) -> Result<()> {
+ match self.map.get_mut(location) {
+ // Return Precondition instead of NotFound for consistency with stores
+ None => Err(crate::Error::Precondition {
+ path: location.to_string(),
+ source: format!("Object at location {location} not found").into(),
+ }),
+ Some(e) => {
+ let existing = e.e_tag.to_string();
+ let expected = v.e_tag.context(MissingETagSnafu)?;
+ if existing == expected {
+ *e = entry;
+ Ok(())
+ } else {
+ Err(crate::Error::Precondition {
+ path: location.to_string(),
+ source: format!("{existing} does not match {expected}").into(),
+ })
+ }
+ }
+ }
+ }
}
impl std::fmt::Display for InMemory {
@@ -123,10 +168,21 @@ impl std::fmt::Display for InMemory {
#[async_trait]
impl ObjectStore for InMemory {
- async fn put(&self, location: &Path, bytes: Bytes) -> Result<PutResult> {
- let etag = self.storage.write().insert(location, bytes);
+ async fn put_opts(&self, location: &Path, bytes: Bytes, opts: PutOptions) -> Result<PutResult> {
+ let mut storage = self.storage.write();
+ let etag = storage.next_etag;
+ let entry = Entry::new(bytes, Utc::now(), etag);
+
+ match opts.mode {
+ PutMode::Overwrite => storage.overwrite(location, entry),
+ PutMode::Create => storage.create(location, entry)?,
+ PutMode::Update(v) => storage.update(location, v, entry)?,
+ }
+ storage.next_etag += 1;
+
Ok(PutResult {
e_tag: Some(etag.to_string()),
+ version: None,
})
}
@@ -425,7 +481,7 @@ impl AsyncWrite for InMemoryAppend {
fn poll_shutdown(
self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
- ) -> std::task::Poll<Result<(), io::Error>> {
+ ) -> Poll<Result<(), io::Error>> {
self.poll_flush(cx)
}
}
@@ -449,6 +505,7 @@ mod tests {
rename_and_copy(&integration).await;
copy_if_not_exists(&integration).await;
stream_get(&integration).await;
+ put_opts(&integration, true).await;
}
#[tokio::test]
diff --git a/object_store/src/prefix.rs b/object_store/src/prefix.rs
index b5bff8b12dd7..68101307fbdf 100644
--- a/object_store/src/prefix.rs
+++ b/object_store/src/prefix.rs
@@ -23,7 +23,8 @@ use tokio::io::AsyncWrite;
use crate::path::Path;
use crate::{
- GetOptions, GetResult, ListResult, MultipartId, ObjectMeta, ObjectStore, PutResult, Result,
+ GetOptions, GetResult, ListResult, MultipartId, ObjectMeta, ObjectStore, PutOptions, PutResult,
+ Result,
};
#[doc(hidden)]
@@ -85,6 +86,11 @@ impl<T: ObjectStore> ObjectStore for PrefixStore<T> {
self.inner.put(&full_path, bytes).await
}
+ async fn put_opts(&self, location: &Path, bytes: Bytes, opts: PutOptions) -> Result<PutResult> {
+ let full_path = self.full_path(location);
+ self.inner.put_opts(&full_path, bytes, opts).await
+ }
+
async fn put_multipart(
&self,
location: &Path,
diff --git a/object_store/src/throttle.rs b/object_store/src/throttle.rs
index c5521256b8a6..dcd2c04bcf05 100644
--- a/object_store/src/throttle.rs
+++ b/object_store/src/throttle.rs
@@ -21,7 +21,8 @@ use std::ops::Range;
use std::{convert::TryInto, sync::Arc};
use crate::{
- path::Path, GetResult, GetResultPayload, ListResult, ObjectMeta, ObjectStore, PutResult, Result,
+ path::Path, GetResult, GetResultPayload, ListResult, ObjectMeta, ObjectStore, PutOptions,
+ PutResult, Result,
};
use crate::{GetOptions, MultipartId};
use async_trait::async_trait;
@@ -149,10 +150,14 @@ impl<T: ObjectStore> std::fmt::Display for ThrottledStore<T> {
impl<T: ObjectStore> ObjectStore for ThrottledStore<T> {
async fn put(&self, location: &Path, bytes: Bytes) -> Result<PutResult> {
sleep(self.config().wait_put_per_call).await;
-
self.inner.put(location, bytes).await
}
+ async fn put_opts(&self, location: &Path, bytes: Bytes, opts: PutOptions) -> Result<PutResult> {
+ sleep(self.config().wait_put_per_call).await;
+ self.inner.put_opts(location, bytes, opts).await
+ }
+
async fn put_multipart(
&self,
_location: &Path,
|
diff --git a/object_store/tests/get_range_file.rs b/object_store/tests/get_range_file.rs
index 3fa1cc7104b3..85231a5a5b9b 100644
--- a/object_store/tests/get_range_file.rs
+++ b/object_store/tests/get_range_file.rs
@@ -22,9 +22,7 @@ use bytes::Bytes;
use futures::stream::BoxStream;
use object_store::local::LocalFileSystem;
use object_store::path::Path;
-use object_store::{
- GetOptions, GetResult, ListResult, MultipartId, ObjectMeta, ObjectStore, PutResult,
-};
+use object_store::*;
use std::fmt::Formatter;
use tempfile::tempdir;
use tokio::io::AsyncWrite;
@@ -40,50 +38,42 @@ impl std::fmt::Display for MyStore {
#[async_trait]
impl ObjectStore for MyStore {
- async fn put(&self, path: &Path, data: Bytes) -> object_store::Result<PutResult> {
- self.0.put(path, data).await
+ async fn put_opts(&self, path: &Path, data: Bytes, opts: PutOptions) -> Result<PutResult> {
+ self.0.put_opts(path, data, opts).await
}
async fn put_multipart(
&self,
_: &Path,
- ) -> object_store::Result<(MultipartId, Box<dyn AsyncWrite + Unpin + Send>)> {
+ ) -> Result<(MultipartId, Box<dyn AsyncWrite + Unpin + Send>)> {
todo!()
}
- async fn abort_multipart(&self, _: &Path, _: &MultipartId) -> object_store::Result<()> {
+ async fn abort_multipart(&self, _: &Path, _: &MultipartId) -> Result<()> {
todo!()
}
- async fn get_opts(
- &self,
- location: &Path,
- options: GetOptions,
- ) -> object_store::Result<GetResult> {
+ async fn get_opts(&self, location: &Path, options: GetOptions) -> Result<GetResult> {
self.0.get_opts(location, options).await
}
- async fn head(&self, _: &Path) -> object_store::Result<ObjectMeta> {
- todo!()
- }
-
- async fn delete(&self, _: &Path) -> object_store::Result<()> {
+ async fn delete(&self, _: &Path) -> Result<()> {
todo!()
}
- fn list(&self, _: Option<&Path>) -> BoxStream<'_, object_store::Result<ObjectMeta>> {
+ fn list(&self, _: Option<&Path>) -> BoxStream<'_, Result<ObjectMeta>> {
todo!()
}
- async fn list_with_delimiter(&self, _: Option<&Path>) -> object_store::Result<ListResult> {
+ async fn list_with_delimiter(&self, _: Option<&Path>) -> Result<ListResult> {
todo!()
}
- async fn copy(&self, _: &Path, _: &Path) -> object_store::Result<()> {
+ async fn copy(&self, _: &Path, _: &Path) -> Result<()> {
todo!()
}
- async fn copy_if_not_exists(&self, _: &Path, _: &Path) -> object_store::Result<()> {
+ async fn copy_if_not_exists(&self, _: &Path, _: &Path) -> Result<()> {
todo!()
}
}
|
Conditional Put Support
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
<!--
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
(This section helps Arrow developers understand the context and *why* for this feature, in addition to the *what*)
-->
All ObjectStores apart from S3 support conditional predicates on PUT. This is incredibly useful for building transactions on top of object storage.
**Describe the solution you'd like**
<!--
A clear and concise description of what you want to happen.
-->
I would like to propose a new put_opts call, in a similar vein to the existing get_opts. This would take a `PutOptions` similar to `GetOptions` and containing these predicates.
**Describe alternatives you've considered**
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
#4754 would likely also benefit from a put_opts call
|
So it turns out that despite [docs](https://cloud.google.com/storage/docs/request-preconditions) that would suggest it is supported, GCS doesn't support preconditions on write other than based on the version number. This is why we test :sweat_smile:
|
2023-10-24T13:41:59Z
|
48.0
|
e78d1409c265ae5c216fc62e51a0f20aa55f6415
|
apache/arrow-rs
| 4,944
|
apache__arrow-rs-4944
|
[
"4934"
] |
fa7a61a4b074ca4ec9bf429cc84b6c325057d96e
|
diff --git a/object_store/src/aws/client.rs b/object_store/src/aws/client.rs
index 8a45a9f3ac47..eb81e92fb932 100644
--- a/object_store/src/aws/client.rs
+++ b/object_store/src/aws/client.rs
@@ -21,6 +21,7 @@ use crate::aws::{
AwsCredentialProvider, S3CopyIfNotExists, STORE, STRICT_PATH_ENCODE_SET,
};
use crate::client::get::GetClient;
+use crate::client::header::get_etag;
use crate::client::list::ListClient;
use crate::client::list_response::ListResponse;
use crate::client::retry::RetryExt;
@@ -122,6 +123,11 @@ pub(crate) enum Error {
#[snafu(display("Got invalid multipart response: {}", source))]
InvalidMultipartResponse { source: quick_xml::de::DeError },
+
+ #[snafu(display("Unable to extract metadata from headers: {}", source))]
+ Metadata {
+ source: crate::client::header::Error,
+ },
}
impl From<Error> for crate::Error {
@@ -243,12 +249,14 @@ impl S3Client {
}
/// Make an S3 PUT request <https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObject.html>
+ ///
+ /// Returns the ETag
pub async fn put_request<T: Serialize + ?Sized + Sync>(
&self,
path: &Path,
bytes: Bytes,
query: &T,
- ) -> Result<Response> {
+ ) -> Result<String> {
let credential = self.get_credential().await?;
let url = self.config.path_url(path);
let mut builder = self.client.request(Method::PUT, url);
@@ -287,7 +295,7 @@ impl S3Client {
path: path.as_ref(),
})?;
- Ok(response)
+ Ok(get_etag(response.headers()).context(MetadataSnafu)?)
}
/// Make an S3 Delete request <https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteObject.html>
diff --git a/object_store/src/aws/mod.rs b/object_store/src/aws/mod.rs
index d3c50861c122..6d5aecea2d17 100644
--- a/object_store/src/aws/mod.rs
+++ b/object_store/src/aws/mod.rs
@@ -59,7 +59,7 @@ use crate::multipart::{PartId, PutPart, WriteMultiPart};
use crate::signer::Signer;
use crate::{
ClientOptions, GetOptions, GetResult, ListResult, MultipartId, ObjectMeta,
- ObjectStore, Path, Result, RetryConfig,
+ ObjectStore, Path, PutResult, Result, RetryConfig,
};
mod checksum;
@@ -109,12 +109,6 @@ enum Error {
#[snafu(display("Missing SecretAccessKey"))]
MissingSecretAccessKey,
- #[snafu(display("ETag Header missing from response"))]
- MissingEtag,
-
- #[snafu(display("Received header containing non-ASCII data"))]
- BadHeader { source: reqwest::header::ToStrError },
-
#[snafu(display("Unable parse source url. Url: {}, Error: {}", url, source))]
UnableToParseUrl {
source: url::ParseError,
@@ -273,9 +267,9 @@ impl Signer for AmazonS3 {
#[async_trait]
impl ObjectStore for AmazonS3 {
- async fn put(&self, location: &Path, bytes: Bytes) -> Result<()> {
- self.client.put_request(location, bytes, &()).await?;
- Ok(())
+ async fn put(&self, location: &Path, bytes: Bytes) -> Result<PutResult> {
+ let e_tag = self.client.put_request(location, bytes, &()).await?;
+ Ok(PutResult { e_tag: Some(e_tag) })
}
async fn put_multipart(
@@ -365,10 +359,9 @@ struct S3MultiPartUpload {
#[async_trait]
impl PutPart for S3MultiPartUpload {
async fn put_part(&self, buf: Vec<u8>, part_idx: usize) -> Result<PartId> {
- use reqwest::header::ETAG;
let part = (part_idx + 1).to_string();
- let response = self
+ let content_id = self
.client
.put_request(
&self.location,
@@ -377,13 +370,7 @@ impl PutPart for S3MultiPartUpload {
)
.await?;
- let etag = response.headers().get(ETAG).context(MissingEtagSnafu)?;
-
- let etag = etag.to_str().context(BadHeaderSnafu)?;
-
- Ok(PartId {
- content_id: etag.to_string(),
- })
+ Ok(PartId { content_id })
}
async fn complete(&self, completed_parts: Vec<PartId>) -> Result<()> {
diff --git a/object_store/src/azure/mod.rs b/object_store/src/azure/mod.rs
index 2a08c6775807..0e638efc399f 100644
--- a/object_store/src/azure/mod.rs
+++ b/object_store/src/azure/mod.rs
@@ -31,7 +31,7 @@ use crate::{
multipart::{PartId, PutPart, WriteMultiPart},
path::Path,
ClientOptions, GetOptions, GetResult, ListResult, MultipartId, ObjectMeta,
- ObjectStore, Result, RetryConfig,
+ ObjectStore, PutResult, Result, RetryConfig,
};
use async_trait::async_trait;
use base64::prelude::BASE64_STANDARD;
@@ -62,6 +62,7 @@ mod credential;
/// [`CredentialProvider`] for [`MicrosoftAzure`]
pub type AzureCredentialProvider =
Arc<dyn CredentialProvider<Credential = AzureCredential>>;
+use crate::client::header::get_etag;
pub use credential::AzureCredential;
const STORE: &str = "MicrosoftAzure";
@@ -81,9 +82,6 @@ const MSI_ENDPOINT_ENV_KEY: &str = "IDENTITY_ENDPOINT";
#[derive(Debug, Snafu)]
#[allow(missing_docs)]
enum Error {
- #[snafu(display("Received header containing non-ASCII data"))]
- BadHeader { source: reqwest::header::ToStrError },
-
#[snafu(display("Unable parse source url. Url: {}, Error: {}", url, source))]
UnableToParseUrl {
source: url::ParseError,
@@ -126,8 +124,10 @@ enum Error {
#[snafu(display("Configuration key: '{}' is not known.", key))]
UnknownConfigurationKey { key: String },
- #[snafu(display("ETag Header missing from response"))]
- MissingEtag,
+ #[snafu(display("Unable to extract metadata from headers: {}", source))]
+ Metadata {
+ source: crate::client::header::Error,
+ },
}
impl From<Error> for super::Error {
@@ -170,11 +170,13 @@ impl std::fmt::Display for MicrosoftAzure {
#[async_trait]
impl ObjectStore for MicrosoftAzure {
- async fn put(&self, location: &Path, bytes: Bytes) -> Result<()> {
- self.client
+ async fn put(&self, location: &Path, bytes: Bytes) -> Result<PutResult> {
+ let response = self
+ .client
.put_request(location, Some(bytes), false, &())
.await?;
- Ok(())
+ let e_tag = Some(get_etag(response.headers()).context(MetadataSnafu)?);
+ Ok(PutResult { e_tag })
}
async fn put_multipart(
diff --git a/object_store/src/chunked.rs b/object_store/src/chunked.rs
index d3e02b412725..5694c55d787f 100644
--- a/object_store/src/chunked.rs
+++ b/object_store/src/chunked.rs
@@ -30,6 +30,7 @@ use tokio::io::AsyncWrite;
use crate::path::Path;
use crate::{
GetOptions, GetResult, GetResultPayload, ListResult, ObjectMeta, ObjectStore,
+ PutResult,
};
use crate::{MultipartId, Result};
@@ -62,7 +63,7 @@ impl Display for ChunkedStore {
#[async_trait]
impl ObjectStore for ChunkedStore {
- async fn put(&self, location: &Path, bytes: Bytes) -> Result<()> {
+ async fn put(&self, location: &Path, bytes: Bytes) -> Result<PutResult> {
self.inner.put(location, bytes).await
}
diff --git a/object_store/src/client/header.rs b/object_store/src/client/header.rs
index 6499eff5aebe..17f83a2ba8c8 100644
--- a/object_store/src/client/header.rs
+++ b/object_store/src/client/header.rs
@@ -64,6 +64,12 @@ pub enum Error {
},
}
+/// Extracts an etag from the provided [`HeaderMap`]
+pub fn get_etag(headers: &HeaderMap) -> Result<String, Error> {
+ let e_tag = headers.get(ETAG).ok_or(Error::MissingEtag)?;
+ Ok(e_tag.to_str().context(BadHeaderSnafu)?.to_string())
+}
+
/// Extracts [`ObjectMeta`] from the provided [`HeaderMap`]
pub fn header_meta(
location: &Path,
@@ -81,13 +87,10 @@ pub fn header_meta(
None => Utc.timestamp_nanos(0),
};
- let e_tag = match headers.get(ETAG) {
- Some(e_tag) => {
- let e_tag = e_tag.to_str().context(BadHeaderSnafu)?;
- Some(e_tag.to_string())
- }
- None if cfg.etag_required => return Err(Error::MissingEtag),
- None => None,
+ let e_tag = match get_etag(headers) {
+ Ok(e_tag) => Some(e_tag),
+ Err(Error::MissingEtag) if !cfg.etag_required => None,
+ Err(e) => return Err(e),
};
let content_length = headers
diff --git a/object_store/src/gcp/mod.rs b/object_store/src/gcp/mod.rs
index 513e396cbae6..97755c07c671 100644
--- a/object_store/src/gcp/mod.rs
+++ b/object_store/src/gcp/mod.rs
@@ -54,7 +54,7 @@ use crate::{
multipart::{PartId, PutPart, WriteMultiPart},
path::{Path, DELIMITER},
ClientOptions, GetOptions, GetResult, ListResult, MultipartId, ObjectMeta,
- ObjectStore, Result, RetryConfig,
+ ObjectStore, PutResult, Result, RetryConfig,
};
use credential::{InstanceCredentialProvider, ServiceAccountCredentials};
@@ -65,6 +65,7 @@ const STORE: &str = "GCS";
/// [`CredentialProvider`] for [`GoogleCloudStorage`]
pub type GcpCredentialProvider = Arc<dyn CredentialProvider<Credential = GcpCredential>>;
+use crate::client::header::get_etag;
use crate::gcp::credential::{ApplicationDefaultCredentials, DEFAULT_GCS_BASE_URL};
pub use credential::GcpCredential;
@@ -155,11 +156,10 @@ enum Error {
#[snafu(display("Configuration key: '{}' is not known.", key))]
UnknownConfigurationKey { key: String },
- #[snafu(display("ETag Header missing from response"))]
- MissingEtag,
-
- #[snafu(display("Received header containing non-ASCII data"))]
- BadHeader { source: header::ToStrError },
+ #[snafu(display("Unable to extract metadata from headers: {}", source))]
+ Metadata {
+ source: crate::client::header::Error,
+ },
}
impl From<Error> for super::Error {
@@ -247,7 +247,14 @@ impl GoogleCloudStorageClient {
}
/// Perform a put request <https://cloud.google.com/storage/docs/xml-api/put-object-upload>
- async fn put_request(&self, path: &Path, payload: Bytes) -> Result<()> {
+ ///
+ /// Returns the new ETag
+ async fn put_request<T: Serialize + ?Sized + Sync>(
+ &self,
+ path: &Path,
+ payload: Bytes,
+ query: &T,
+ ) -> Result<String> {
let credential = self.get_credential().await?;
let url = self.object_url(path);
@@ -256,8 +263,10 @@ impl GoogleCloudStorageClient {
.get_content_type(path)
.unwrap_or("application/octet-stream");
- self.client
+ let response = self
+ .client
.request(Method::PUT, url)
+ .query(query)
.bearer_auth(&credential.bearer)
.header(header::CONTENT_TYPE, content_type)
.header(header::CONTENT_LENGTH, payload.len())
@@ -268,7 +277,7 @@ impl GoogleCloudStorageClient {
path: path.as_ref(),
})?;
- Ok(())
+ Ok(get_etag(response.headers()).context(MetadataSnafu)?)
}
/// Initiate a multi-part upload <https://cloud.google.com/storage/docs/xml-api/post-object-multipart>
@@ -469,7 +478,7 @@ impl ListClient for GoogleCloudStorageClient {
struct GCSMultipartUpload {
client: Arc<GoogleCloudStorageClient>,
- encoded_path: String,
+ path: Path,
multipart_id: MultipartId,
}
@@ -478,38 +487,17 @@ impl PutPart for GCSMultipartUpload {
/// Upload an object part <https://cloud.google.com/storage/docs/xml-api/put-object-multipart>
async fn put_part(&self, buf: Vec<u8>, part_idx: usize) -> Result<PartId> {
let upload_id = self.multipart_id.clone();
- let url = format!(
- "{}/{}/{}",
- self.client.base_url, self.client.bucket_name_encoded, self.encoded_path
- );
-
- let credential = self.client.get_credential().await?;
-
- let response = self
+ let content_id = self
.client
- .client
- .request(Method::PUT, &url)
- .bearer_auth(&credential.bearer)
- .query(&[
- ("partNumber", format!("{}", part_idx + 1)),
- ("uploadId", upload_id),
- ])
- .header(header::CONTENT_TYPE, "application/octet-stream")
- .header(header::CONTENT_LENGTH, format!("{}", buf.len()))
- .body(buf)
- .send_retry(&self.client.retry_config)
- .await
- .context(PutRequestSnafu {
- path: &self.encoded_path,
- })?;
-
- let content_id = response
- .headers()
- .get("ETag")
- .context(MissingEtagSnafu)?
- .to_str()
- .context(BadHeaderSnafu)?
- .to_string();
+ .put_request(
+ &self.path,
+ buf.into(),
+ &[
+ ("partNumber", format!("{}", part_idx + 1)),
+ ("uploadId", upload_id),
+ ],
+ )
+ .await?;
Ok(PartId { content_id })
}
@@ -517,10 +505,7 @@ impl PutPart for GCSMultipartUpload {
/// Complete a multipart upload <https://cloud.google.com/storage/docs/xml-api/post-object-complete>
async fn complete(&self, completed_parts: Vec<PartId>) -> Result<()> {
let upload_id = self.multipart_id.clone();
- let url = format!(
- "{}/{}/{}",
- self.client.base_url, self.client.bucket_name_encoded, self.encoded_path
- );
+ let url = self.client.object_url(&self.path);
let parts = completed_parts
.into_iter()
@@ -550,7 +535,7 @@ impl PutPart for GCSMultipartUpload {
.send_retry(&self.client.retry_config)
.await
.context(PostRequestSnafu {
- path: &self.encoded_path,
+ path: self.path.as_ref(),
})?;
Ok(())
@@ -559,8 +544,9 @@ impl PutPart for GCSMultipartUpload {
#[async_trait]
impl ObjectStore for GoogleCloudStorage {
- async fn put(&self, location: &Path, bytes: Bytes) -> Result<()> {
- self.client.put_request(location, bytes).await
+ async fn put(&self, location: &Path, bytes: Bytes) -> Result<PutResult> {
+ let e_tag = self.client.put_request(location, bytes, &()).await?;
+ Ok(PutResult { e_tag: Some(e_tag) })
}
async fn put_multipart(
@@ -569,12 +555,9 @@ impl ObjectStore for GoogleCloudStorage {
) -> Result<(MultipartId, Box<dyn AsyncWrite + Unpin + Send>)> {
let upload_id = self.client.multipart_initiate(location).await?;
- let encoded_path =
- percent_encode(location.to_string().as_bytes(), NON_ALPHANUMERIC).to_string();
-
let inner = GCSMultipartUpload {
client: Arc::clone(&self.client),
- encoded_path,
+ path: location.clone(),
multipart_id: upload_id.clone(),
};
diff --git a/object_store/src/http/client.rs b/object_store/src/http/client.rs
index b2a6ac0aa34a..4c2a7fcf8db3 100644
--- a/object_store/src/http/client.rs
+++ b/object_store/src/http/client.rs
@@ -160,7 +160,7 @@ impl Client {
Ok(())
}
- pub async fn put(&self, location: &Path, bytes: Bytes) -> Result<()> {
+ pub async fn put(&self, location: &Path, bytes: Bytes) -> Result<Response> {
let mut retry = false;
loop {
let url = self.path_url(location);
@@ -170,7 +170,7 @@ impl Client {
}
match builder.send_retry(&self.retry_config).await {
- Ok(_) => return Ok(()),
+ Ok(response) => return Ok(response),
Err(source) => match source.status() {
// Some implementations return 404 instead of 409
Some(StatusCode::CONFLICT | StatusCode::NOT_FOUND) if !retry => {
diff --git a/object_store/src/http/mod.rs b/object_store/src/http/mod.rs
index 2fd7850b6bbf..e41e4f990110 100644
--- a/object_store/src/http/mod.rs
+++ b/object_store/src/http/mod.rs
@@ -41,11 +41,12 @@ use tokio::io::AsyncWrite;
use url::Url;
use crate::client::get::GetClientExt;
+use crate::client::header::get_etag;
use crate::http::client::Client;
use crate::path::Path;
use crate::{
ClientConfigKey, ClientOptions, GetOptions, GetResult, ListResult, MultipartId,
- ObjectMeta, ObjectStore, Result, RetryConfig,
+ ObjectMeta, ObjectStore, PutResult, Result, RetryConfig,
};
mod client;
@@ -95,8 +96,14 @@ impl std::fmt::Display for HttpStore {
#[async_trait]
impl ObjectStore for HttpStore {
- async fn put(&self, location: &Path, bytes: Bytes) -> Result<()> {
- self.client.put(location, bytes).await
+ async fn put(&self, location: &Path, bytes: Bytes) -> Result<PutResult> {
+ let response = self.client.put(location, bytes).await?;
+ let e_tag = match get_etag(response.headers()) {
+ Ok(e_tag) => Some(e_tag),
+ Err(crate::client::header::Error::MissingEtag) => None,
+ Err(source) => return Err(Error::Metadata { source }.into()),
+ };
+ Ok(PutResult { e_tag })
}
async fn put_multipart(
diff --git a/object_store/src/lib.rs b/object_store/src/lib.rs
index 9b396444fa0d..018f0f5e8dec 100644
--- a/object_store/src/lib.rs
+++ b/object_store/src/lib.rs
@@ -300,7 +300,7 @@ pub trait ObjectStore: std::fmt::Display + Send + Sync + Debug + 'static {
/// The operation is guaranteed to be atomic, it will either successfully
/// write the entirety of `bytes` to `location`, or fail. No clients
/// should be able to observe a partially written object
- async fn put(&self, location: &Path, bytes: Bytes) -> Result<()>;
+ async fn put(&self, location: &Path, bytes: Bytes) -> Result<PutResult>;
/// Get a multi-part upload that allows writing data in chunks
///
@@ -528,7 +528,7 @@ macro_rules! as_ref_impl {
($type:ty) => {
#[async_trait]
impl ObjectStore for $type {
- async fn put(&self, location: &Path, bytes: Bytes) -> Result<()> {
+ async fn put(&self, location: &Path, bytes: Bytes) -> Result<PutResult> {
self.as_ref().put(location, bytes).await
}
@@ -659,6 +659,8 @@ pub struct ObjectMeta {
/// The size in bytes of the object
pub size: usize,
/// The unique identifier for the object
+ ///
+ /// <https://datatracker.ietf.org/doc/html/rfc9110#name-etag>
pub e_tag: Option<String>,
}
@@ -850,6 +852,15 @@ impl GetResult {
}
}
+/// Result for a put request
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct PutResult {
+ /// The unique identifier for the object
+ ///
+ /// <https://datatracker.ietf.org/doc/html/rfc9110#name-etag>
+ pub e_tag: Option<String>,
+}
+
/// A specialized `Result` for object store-related errors
pub type Result<T, E = Error> = std::result::Result<T, E>;
@@ -1383,6 +1394,26 @@ mod tests {
..GetOptions::default()
};
storage.get_opts(&path, options).await.unwrap();
+
+ let result = storage.put(&path, "test".into()).await.unwrap();
+ let new_tag = result.e_tag.unwrap();
+ assert_ne!(tag, new_tag);
+
+ let meta = storage.head(&path).await.unwrap();
+ assert_eq!(meta.e_tag.unwrap(), new_tag);
+
+ let options = GetOptions {
+ if_match: Some(new_tag),
+ ..GetOptions::default()
+ };
+ storage.get_opts(&path, options).await.unwrap();
+
+ let options = GetOptions {
+ if_match: Some(tag),
+ ..GetOptions::default()
+ };
+ let err = storage.get_opts(&path, options).await.unwrap_err();
+ assert!(matches!(err, Error::Precondition { .. }), "{err}");
}
/// Returns a chunk of length `chunk_length`
diff --git a/object_store/src/limit.rs b/object_store/src/limit.rs
index 00cbce023c3d..8a453813c24e 100644
--- a/object_store/src/limit.rs
+++ b/object_store/src/limit.rs
@@ -19,7 +19,7 @@
use crate::{
BoxStream, GetOptions, GetResult, GetResultPayload, ListResult, MultipartId,
- ObjectMeta, ObjectStore, Path, Result, StreamExt,
+ ObjectMeta, ObjectStore, Path, PutResult, Result, StreamExt,
};
use async_trait::async_trait;
use bytes::Bytes;
@@ -72,7 +72,7 @@ impl<T: ObjectStore> std::fmt::Display for LimitStore<T> {
#[async_trait]
impl<T: ObjectStore> ObjectStore for LimitStore<T> {
- async fn put(&self, location: &Path, bytes: Bytes) -> Result<()> {
+ async fn put(&self, location: &Path, bytes: Bytes) -> Result<PutResult> {
let _permit = self.semaphore.acquire().await.unwrap();
self.inner.put(location, bytes).await
}
diff --git a/object_store/src/local.rs b/object_store/src/local.rs
index 38467c3a9e7c..4b7c96346e4d 100644
--- a/object_store/src/local.rs
+++ b/object_store/src/local.rs
@@ -20,7 +20,7 @@ use crate::{
maybe_spawn_blocking,
path::{absolute_path_to_url, Path},
GetOptions, GetResult, GetResultPayload, ListResult, MultipartId, ObjectMeta,
- ObjectStore, Result,
+ ObjectStore, PutResult, Result,
};
use async_trait::async_trait;
use bytes::Bytes;
@@ -36,6 +36,7 @@ use std::ops::Range;
use std::pin::Pin;
use std::sync::Arc;
use std::task::Poll;
+use std::time::SystemTime;
use std::{collections::BTreeSet, convert::TryFrom, io};
use std::{collections::VecDeque, path::PathBuf};
use tokio::io::AsyncWrite;
@@ -270,7 +271,7 @@ impl Config {
#[async_trait]
impl ObjectStore for LocalFileSystem {
- async fn put(&self, location: &Path, bytes: Bytes) -> Result<()> {
+ async fn put(&self, location: &Path, bytes: Bytes) -> Result<PutResult> {
let path = self.config.path_to_filesystem(location)?;
maybe_spawn_blocking(move || {
let (mut file, suffix) = new_staged_upload(&path)?;
@@ -282,8 +283,17 @@ impl ObjectStore for LocalFileSystem {
})
.map_err(|e| {
let _ = std::fs::remove_file(&staging_path); // Attempt to cleanup
- e.into()
- })
+ e
+ })?;
+
+ let metadata = file.metadata().map_err(|e| Error::Metadata {
+ source: e.into(),
+ path: path.to_string_lossy().to_string(),
+ })?;
+
+ Ok(PutResult {
+ e_tag: Some(get_etag(&metadata)),
+ })
})
.await
}
@@ -959,24 +969,33 @@ fn last_modified(metadata: &Metadata) -> DateTime<Utc> {
.into()
}
+fn get_etag(metadata: &Metadata) -> String {
+ let inode = get_inode(metadata);
+ let size = metadata.len();
+ let mtime = metadata
+ .modified()
+ .ok()
+ .and_then(|mtime| mtime.duration_since(SystemTime::UNIX_EPOCH).ok())
+ .unwrap_or_default()
+ .as_micros();
+
+ // Use an ETag scheme based on that used by many popular HTTP servers
+ // <https://httpd.apache.org/docs/2.2/mod/core.html#fileetag>
+ // <https://stackoverflow.com/questions/47512043/how-etags-are-generated-and-configured>
+ format!("{inode:x}-{mtime:x}-{size:x}")
+}
+
fn convert_metadata(metadata: Metadata, location: Path) -> Result<ObjectMeta> {
let last_modified = last_modified(&metadata);
let size = usize::try_from(metadata.len()).context(FileSizeOverflowedUsizeSnafu {
path: location.as_ref(),
})?;
- let inode = get_inode(&metadata);
- let mtime = last_modified.timestamp_micros();
-
- // Use an ETag scheme based on that used by many popular HTTP servers
- // <https://httpd.apache.org/docs/2.2/mod/core.html#fileetag>
- // <https://stackoverflow.com/questions/47512043/how-etags-are-generated-and-configured>
- let etag = format!("{inode:x}-{mtime:x}-{size:x}");
Ok(ObjectMeta {
location,
last_modified,
size,
- e_tag: Some(etag),
+ e_tag: Some(get_etag(&metadata)),
})
}
diff --git a/object_store/src/memory.rs b/object_store/src/memory.rs
index 00b330b5eb94..952b45739759 100644
--- a/object_store/src/memory.rs
+++ b/object_store/src/memory.rs
@@ -17,7 +17,8 @@
//! An in-memory object store implementation
use crate::{
- path::Path, GetResult, GetResultPayload, ListResult, ObjectMeta, ObjectStore, Result,
+ path::Path, GetResult, GetResultPayload, ListResult, ObjectMeta, ObjectStore,
+ PutResult, Result,
};
use crate::{GetOptions, MultipartId};
use async_trait::async_trait;
@@ -106,11 +107,12 @@ struct Storage {
type SharedStorage = Arc<RwLock<Storage>>;
impl Storage {
- fn insert(&mut self, location: &Path, bytes: Bytes) {
+ fn insert(&mut self, location: &Path, bytes: Bytes) -> usize {
let etag = self.next_etag;
self.next_etag += 1;
let entry = Entry::new(bytes, Utc::now(), etag);
self.map.insert(location.clone(), entry);
+ etag
}
}
@@ -122,9 +124,11 @@ impl std::fmt::Display for InMemory {
#[async_trait]
impl ObjectStore for InMemory {
- async fn put(&self, location: &Path, bytes: Bytes) -> Result<()> {
- self.storage.write().insert(location, bytes);
- Ok(())
+ async fn put(&self, location: &Path, bytes: Bytes) -> Result<PutResult> {
+ let etag = self.storage.write().insert(location, bytes);
+ Ok(PutResult {
+ e_tag: Some(etag.to_string()),
+ })
}
async fn put_multipart(
diff --git a/object_store/src/prefix.rs b/object_store/src/prefix.rs
index 3776dec2e872..21f6c1d99dc9 100644
--- a/object_store/src/prefix.rs
+++ b/object_store/src/prefix.rs
@@ -23,7 +23,8 @@ use tokio::io::AsyncWrite;
use crate::path::Path;
use crate::{
- GetOptions, GetResult, ListResult, MultipartId, ObjectMeta, ObjectStore, Result,
+ GetOptions, GetResult, ListResult, MultipartId, ObjectMeta, ObjectStore, PutResult,
+ Result,
};
#[doc(hidden)]
@@ -79,7 +80,7 @@ impl<T: ObjectStore> PrefixStore<T> {
#[async_trait::async_trait]
impl<T: ObjectStore> ObjectStore for PrefixStore<T> {
- async fn put(&self, location: &Path, bytes: Bytes) -> Result<()> {
+ async fn put(&self, location: &Path, bytes: Bytes) -> Result<PutResult> {
let full_path = self.full_path(location);
self.inner.put(&full_path, bytes).await
}
diff --git a/object_store/src/throttle.rs b/object_store/src/throttle.rs
index f716a11f8a05..d6f191baf82e 100644
--- a/object_store/src/throttle.rs
+++ b/object_store/src/throttle.rs
@@ -21,7 +21,8 @@ use std::ops::Range;
use std::{convert::TryInto, sync::Arc};
use crate::{
- path::Path, GetResult, GetResultPayload, ListResult, ObjectMeta, ObjectStore, Result,
+ path::Path, GetResult, GetResultPayload, ListResult, ObjectMeta, ObjectStore,
+ PutResult, Result,
};
use crate::{GetOptions, MultipartId};
use async_trait::async_trait;
@@ -147,7 +148,7 @@ impl<T: ObjectStore> std::fmt::Display for ThrottledStore<T> {
#[async_trait]
impl<T: ObjectStore> ObjectStore for ThrottledStore<T> {
- async fn put(&self, location: &Path, bytes: Bytes) -> Result<()> {
+ async fn put(&self, location: &Path, bytes: Bytes) -> Result<PutResult> {
sleep(self.config().wait_put_per_call).await;
self.inner.put(location, bytes).await
|
diff --git a/object_store/tests/get_range_file.rs b/object_store/tests/get_range_file.rs
index 25c469260675..5703d7f24844 100644
--- a/object_store/tests/get_range_file.rs
+++ b/object_store/tests/get_range_file.rs
@@ -23,7 +23,7 @@ use futures::stream::BoxStream;
use object_store::local::LocalFileSystem;
use object_store::path::Path;
use object_store::{
- GetOptions, GetResult, ListResult, MultipartId, ObjectMeta, ObjectStore,
+ GetOptions, GetResult, ListResult, MultipartId, ObjectMeta, ObjectStore, PutResult,
};
use std::fmt::Formatter;
use tempfile::tempdir;
@@ -40,7 +40,7 @@ impl std::fmt::Display for MyStore {
#[async_trait]
impl ObjectStore for MyStore {
- async fn put(&self, path: &Path, data: Bytes) -> object_store::Result<()> {
+ async fn put(&self, path: &Path, data: Bytes) -> object_store::Result<PutResult> {
self.0.put(path, data).await
}
|
Return ETag and Version on Put
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
<!--
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
(This section helps Arrow developers understand the context and *why* for this feature, in addition to the *what*)
-->
Combined with #4925 and #4879 this will provide a complete interface for implementing transactions and snapshotting on object stores.
**Describe the solution you'd like**
<!--
A clear and concise description of what you want to happen.
-->
We could return ObjectMeta, however, many stores do not return the last modified time on write and so this might not be a good idea. Perhaps we could return a PutResult structure or something similar :thinking:
**Describe alternatives you've considered**
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
|
2023-10-17T12:20:03Z
|
47.0
|
fa7a61a4b074ca4ec9bf429cc84b6c325057d96e
|
|
apache/arrow-rs
| 4,941
|
apache__arrow-rs-4941
|
[
"4924"
] |
31bc84c91e7d6c509443f6e73bda0df32a0a5cba
|
diff --git a/arrow/Cargo.toml b/arrow/Cargo.toml
index 8abb4f73a384..37f03a05b3fa 100644
--- a/arrow/Cargo.toml
+++ b/arrow/Cargo.toml
@@ -60,7 +60,7 @@ arrow-select = { workspace = true }
arrow-string = { workspace = true }
rand = { version = "0.8", default-features = false, features = ["std", "std_rng"], optional = true }
-pyo3 = { version = "0.19", default-features = false, optional = true }
+pyo3 = { version = "0.20", default-features = false, optional = true }
[package.metadata.docs.rs]
features = ["prettyprint", "ipc_compression", "ffi", "pyarrow"]
|
diff --git a/arrow-pyarrow-integration-testing/Cargo.toml b/arrow-pyarrow-integration-testing/Cargo.toml
index 50987b03ca9e..8c60c086c29a 100644
--- a/arrow-pyarrow-integration-testing/Cargo.toml
+++ b/arrow-pyarrow-integration-testing/Cargo.toml
@@ -34,4 +34,4 @@ crate-type = ["cdylib"]
[dependencies]
arrow = { path = "../arrow", features = ["pyarrow"] }
-pyo3 = { version = "0.19", features = ["extension-module"] }
+pyo3 = { version = "0.20", features = ["extension-module"] }
diff --git a/arrow-pyarrow-integration-testing/pyproject.toml b/arrow-pyarrow-integration-testing/pyproject.toml
index d75f8de1ac4c..d85db24c2e18 100644
--- a/arrow-pyarrow-integration-testing/pyproject.toml
+++ b/arrow-pyarrow-integration-testing/pyproject.toml
@@ -16,7 +16,7 @@
# under the License.
[build-system]
-requires = ["maturin"]
+requires = ["maturin>=1.0,<2.0"]
build-backend = "maturin"
dependencies = ["pyarrow>=1"]
|
Update pyo3 requirement from 0.19 to 0.20
Updates the requirements on [pyo3](https://github.com/pyo3/pyo3) to permit the latest version.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a href="https://github.com/pyo3/pyo3/releases">pyo3's releases</a>.</em></p>
<blockquote>
<h2>PyO3 0.20.0</h2>
<p>This release is the first PyO3 release to be dual-licensed under Apache 2.0 OR MIT licensing (expanding from just Apache 2.0 of previous releases).</p>
<p>Python 3.12 stable is now supported. The minimum supported Rust version has been increased to Rust 1.56.</p>
<p>The <code>__eq__</code>, <code>__ne__</code>,<code> __lt__</code>, <code>__le__</code>, <code>__gt__</code> and <code>__ge__</code> magic methods are now usable in <code>#[pymethods]</code> to implement Python operators as an alternative to the <code>__richcmp__</code> method PyO3 already offered.</p>
<p><code>#[pyclass(rename_all = "renaming_rule")]</code> has been added to rename all fields of structs exposed to Python (e.g. <code>rename_all = "snake_case"</code>) .</p>
<p><code>PyDict::get_item</code> now returns <code>Result<Option<&PyAny>></code> instead of just <code>Option<&PyAny></code>. The previous implementation which ignored Python errors used APIs now considered deprecated by the Python language designers; it is now considered best practice to bubble up any exception raised during dictionary <code>__getitem__</code>. For most users migration for this change will simply require addition of a <code>?</code> on each use of <code>PyDict::get_item</code>.</p>
<p>Note that Python 3.7 is end of life but PyO3 will continue to support for now as a number of downstream Python packages still have high proportions of downloads on 3.7. A future release is expected to drop Python 3.7 when these numbers reduce.</p>
<p>There have been numerous other smaller improvements, changes and fixes. For full details see the <a href="https://pyo3.rs/v0.20.0/changelog.html">CHANGELOG</a>.</p>
<p>Please consult the <a href="https://pyo3.rs/v0.20.0/migration.html">migration guide</a> for help upgrading.</p>
<p>Thank you to everyone who contributed code, documentation, design ideas, bug reports, and feedback. The following users' commits are included in this release:</p>
<p><a href="https://github.com/adamreichold"><code>@adamreichold</code></a>
<a href="https://github.com/adriangb"><code>@adriangb</code></a>
<a href="https://github.com/alex"><code>@alex</code></a>
<a href="https://github.com/BooleanCat"><code>@BooleanCat</code></a>
<a href="https://github.com/CallMeMSL"><code>@CallMeMSL</code></a>
<a href="https://github.com/cdce8p"><code>@cdce8p</code></a>
<a href="https://github.com/DataTriny"><code>@DataTriny</code></a>
<a href="https://github.com/davidhewitt"><code>@davidhewitt</code></a>
<a href="https://github.com/ecarrara"><code>@ecarrara</code></a>
<a href="https://github.com/GoldsteinE"><code>@GoldsteinE</code></a>
<a href="https://github.com/grantslatton"><code>@grantslatton</code></a>
<a href="https://github.com/Hofer-Julian"><code>@Hofer-Julian</code></a>
<a href="https://github.com/ijl"><code>@ijl</code></a>
<a href="https://github.com/iliya-malecki"><code>@iliya-malecki</code></a>
<a href="https://github.com/jakelishman"><code>@jakelishman</code></a>
<a href="https://github.com/jeffs"><code>@jeffs</code></a>
<a href="https://github.com/juntyr"><code>@juntyr</code></a>
<a href="https://github.com/krpatter-intc"><code>@krpatter-intc</code></a>
<a href="https://github.com/lucatrv"><code>@lucatrv</code></a>
<a href="https://github.com/mejrs"><code>@mejrs</code></a>
<a href="https://github.com/messense"><code>@messense</code></a>
<a href="https://github.com/mhils"><code>@mhils</code></a>
<a href="https://github.com/panpilkarz"><code>@panpilkarz</code></a>
<a href="https://github.com/puradox"><code>@puradox</code></a>
<a href="https://github.com/ringsaturn"><code>@ringsaturn</code></a>
<a href="https://github.com/rytheo"><code>@rytheo</code></a>
<a href="https://github.com/SigureMo"><code>@SigureMo</code></a>
<a href="https://github.com/smheidrich"><code>@smheidrich</code></a>
<a href="https://github.com/Tpt"><code>@Tpt</code></a>
<a href="https://github.com/youknowone"><code>@youknowone</code></a>
<a href="https://github.com/zakstucke"><code>@zakstucke</code></a></p>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a href="https://github.com/PyO3/pyo3/blob/main/CHANGELOG.md">pyo3's changelog</a>.</em></p>
<blockquote>
<h2>[0.20.0] - 2023-10-11</h2>
<h3>Packaging</h3>
<ul>
<li>Dual-license PyO3 under either the Apache 2.0 OR the MIT license. This makes the project GPLv2 compatible. <a href="https://redirect.github.com/PyO3/pyo3/pull/3108">#3108</a></li>
<li>Update MSRV to Rust 1.56. <a href="https://redirect.github.com/PyO3/pyo3/pull/3208">#3208</a></li>
<li>Bump <code>indoc</code> dependency to 2.0 and <code>unindent</code> dependency to 0.2. <a href="https://redirect.github.com/PyO3/pyo3/pull/3237">#3237</a></li>
<li>Bump <code>syn</code> dependency to 2.0. <a href="https://redirect.github.com/PyO3/pyo3/pull/3239">#3239</a></li>
<li>Drop support for debug builds of Python 3.7. <a href="https://redirect.github.com/PyO3/pyo3/pull/3387">#3387</a></li>
<li>Bump <code>chrono</code> optional dependency to require 0.4.25 or newer. <a href="https://redirect.github.com/PyO3/pyo3/pull/3427">#3427</a></li>
<li>Support Python 3.12. <a href="https://redirect.github.com/PyO3/pyo3/pull/3488">#3488</a></li>
</ul>
<h3>Added</h3>
<ul>
<li>Support <code>__lt__</code>, <code>__le__</code>, <code>__eq__</code>, <code>__ne__</code>, <code>__gt__</code> and <code>__ge__</code> in <code>#[pymethods]</code>. <a href="https://redirect.github.com/PyO3/pyo3/pull/3203">#3203</a></li>
<li>Add FFI definition <code>Py_GETENV</code>. <a href="https://redirect.github.com/PyO3/pyo3/pull/3336">#3336</a></li>
<li>Add <code>as_ptr</code> and <code>into_ptr</code> inherent methods for <code>Py</code>, <code>PyAny</code>, <code>PyRef</code>, and <code>PyRefMut</code>. <a href="https://redirect.github.com/PyO3/pyo3/pull/3359">#3359</a></li>
<li>Implement <code>DoubleEndedIterator</code> for <code>PyTupleIterator</code> and <code>PyListIterator</code>. <a href="https://redirect.github.com/PyO3/pyo3/pull/3366">#3366</a></li>
<li>Add <code>#[pyclass(rename_all = "...")]</code> option: this allows renaming all getters and setters of a struct, or all variants of an enum. Available renaming rules are: <code>"camelCase"</code>, <code>"kebab-case"</code>, <code>"lowercase"</code>, <code>"PascalCase"</code>, <code>"SCREAMING-KEBAB-CASE"</code>, <code>"SCREAMING_SNAKE_CASE"</code>, <code>"snake_case"</code>, <code>"UPPERCASE"</code>. <a href="https://redirect.github.com/PyO3/pyo3/pull/3384">#3384</a></li>
<li>Add FFI definitions <code>PyObject_GC_IsTracked</code> and <code>PyObject_GC_IsFinalized</code> on Python 3.9 and up (PyPy 3.10 and up). <a href="https://redirect.github.com/PyO3/pyo3/pull/3403">#3403</a></li>
<li>Add types for <code>None</code>, <code>Ellipsis</code>, and <code>NotImplemented</code>. <a href="https://redirect.github.com/PyO3/pyo3/pull/3408">#3408</a></li>
<li>Add FFI definitions for the <code>Py_mod_multiple_interpreters</code> constant and its possible values. <a href="https://redirect.github.com/PyO3/pyo3/pull/3494">#3494</a></li>
<li>Add FFI definitions for <code>PyInterpreterConfig</code> struct, its constants and <code>Py_NewInterpreterFromConfig</code>. <a href="https://redirect.github.com/PyO3/pyo3/pull/3502">#3502</a></li>
</ul>
<h3>Changed</h3>
<ul>
<li>Change <code>PySet::discard</code> to return <code>PyResult<bool></code> (previously returned nothing). <a href="https://redirect.github.com/PyO3/pyo3/pull/3281">#3281</a></li>
<li>Optimize implmentation of <code>IntoPy</code> for Rust tuples to Python tuples. <a href="https://redirect.github.com/PyO3/pyo3/pull/3321">#3321</a></li>
<li>Change <code>PyDict::get_item</code> to no longer suppress arbitrary exceptions (the return type is now <code>PyResult<Option<&PyAny>></code> instead of <code>Option<&PyAny></code>), and deprecate <code>PyDict::get_item_with_error</code>. <a href="https://redirect.github.com/PyO3/pyo3/pull/3330">#3330</a></li>
<li>Deprecate FFI definitions which are deprecated in Python 3.12. <a href="https://redirect.github.com/PyO3/pyo3/pull/3336">#3336</a></li>
<li><code>AsPyPointer</code> is now an <code>unsafe trait</code>. <a href="https://redirect.github.com/PyO3/pyo3/pull/3358">#3358</a></li>
<li>Accept all <code>os.PathLike</code> values in implementation of <code>FromPyObject</code> for <code>PathBuf</code>. <a href="https://redirect.github.com/PyO3/pyo3/pull/3374">#3374</a></li>
<li>Add <code>__builtins__</code> to globals in <code>py.run()</code> and <code>py.eval()</code> if they're missing. <a href="https://redirect.github.com/PyO3/pyo3/pull/3378">#3378</a></li>
<li>Optimize implementation of <code>FromPyObject</code> for <code>BigInt</code> and <code>BigUint</code>. <a href="https://redirect.github.com/PyO3/pyo3/pull/3379">#3379</a></li>
<li><code>PyIterator::from_object</code> and <code>PyByteArray::from</code> now take a single argument of type <code>&PyAny</code> (previously took two arguments <code>Python</code> and <code>AsPyPointer</code>). <a href="https://redirect.github.com/PyO3/pyo3/pull/3389">#3389</a></li>
<li>Replace <code>AsPyPointer</code> with <code>AsRef<PyAny></code> as a bound in the blanket implementation of <code>From<&T> for PyObject</code>. <a href="https://redirect.github.com/PyO3/pyo3/pull/3391">#3391</a></li>
<li>Replace blanket <code>impl IntoPy<PyObject> for &T where T: AsPyPointer</code> with implementations of <code>impl IntoPy<PyObject></code> for <code>&PyAny</code>, <code>&T where T: AsRef<PyAny></code>, and <code>&Py<T></code>. <a href="https://redirect.github.com/PyO3/pyo3/pull/3393">#3393</a></li>
<li>Preserve <code>std::io::Error</code> kind in implementation of <code>From<std::io::IntoInnerError></code> for <code>PyErr</code> <a href="https://redirect.github.com/PyO3/pyo3/pull/3396">#3396</a></li>
<li>Try to select a relevant <code>ErrorKind</code> in implementation of <code>From<PyErr></code> for <code>OSError</code> subclass. <a href="https://redirect.github.com/PyO3/pyo3/pull/3397">#3397</a></li>
<li>Retrieve the original <code>PyErr</code> in implementation of <code>From<std::io::Error></code> for <code>PyErr</code> if the <code>std::io::Error</code> has been built using a Python exception (previously would create a new exception wrapping the <code>std::io::Error</code>). <a href="https://redirect.github.com/PyO3/pyo3/pull/3402">#3402</a></li>
<li><code>#[pymodule]</code> will now return the same module object on repeated import by the same Python interpreter, on Python 3.9 and up. <a href="https://redirect.github.com/PyO3/pyo3/pull/3446">#3446</a></li>
<li>Truncate leap-seconds and warn when converting <code>chrono</code> types to Python <code>datetime</code> types (<code>datetime</code> cannot represent leap-seconds). <a href="https://redirect.github.com/PyO3/pyo3/pull/3458">#3458</a></li>
<li><code>Err</code> returned from <code>#[pyfunction]</code> will now have a non-None <code>__context__</code> if called from inside a <code>catch</code> block. <a href="https://redirect.github.com/PyO3/pyo3/pull/3455">#3455</a></li>
<li>Deprecate undocumented <code>#[__new__]</code> form of <code>#[new]</code> attribute. <a href="https://redirect.github.com/PyO3/pyo3/pull/3505">#3505</a></li>
</ul>
<h3>Removed</h3>
<ul>
<li>Remove all functionality deprecated in PyO3 0.18, including <code>#[args]</code> attribute for <code>#[pymethods]</code>. <a href="https://redirect.github.com/PyO3/pyo3/pull/3232">#3232</a></li>
<li>Remove <code>IntoPyPointer</code> trait in favour of <code>into_ptr</code> inherent methods. <a href="https://redirect.github.com/PyO3/pyo3/pull/3385">#3385</a></li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a href="https://github.com/PyO3/pyo3/commit/c77deee18ec545b3b5fa480068e5da62a33e7c42"><code>c77deee</code></a> release: 0.20.0</li>
<li><a href="https://github.com/PyO3/pyo3/commit/b03c4cb33cc30da738270a4db8322d5d9b74fb8c"><code>b03c4cb</code></a> Merge pull request <a href="https://redirect.github.com/pyo3/pyo3/issues/3506">#3506</a> from davidhewitt/default-ne</li>
<li><a href="https://github.com/PyO3/pyo3/commit/e1d4173827f1881411baf20cd379b1ce77b88acb"><code>e1d4173</code></a> Fix bug in default implementation of <code>__ne__</code></li>
<li><a href="https://github.com/PyO3/pyo3/commit/b73c06948cb2924ce39f676319dd2ec6cd83f147"><code>b73c069</code></a> Merge pull request <a href="https://redirect.github.com/pyo3/pyo3/issues/3504">#3504</a> from davidhewitt/classmethod-receiver</li>
<li><a href="https://github.com/PyO3/pyo3/commit/76bf521ed07ab41dced572f6e7ebdd71cee72be6"><code>76bf521</code></a> Merge pull request <a href="https://redirect.github.com/pyo3/pyo3/issues/3505">#3505</a> from davidhewitt/deprecate_dunder_new</li>
<li><a href="https://github.com/PyO3/pyo3/commit/6c90325a1ce4ef9eeda9e50d8c421abde0e3212d"><code>6c90325</code></a> deprecate undocumented <code>#[__new__]</code> form of <code>#[new]</code></li>
<li><a href="https://github.com/PyO3/pyo3/commit/c0b5004cfaec28cda6ec77202180e27e21e0198a"><code>c0b5004</code></a> Merge pull request <a href="https://redirect.github.com/pyo3/pyo3/issues/3455">#3455</a> from davidhewitt/normalized-exceptions</li>
<li><a href="https://github.com/PyO3/pyo3/commit/80bbb30f56077fd66b619c3a08e4e38af433de7b"><code>80bbb30</code></a> Merge pull request <a href="https://redirect.github.com/pyo3/pyo3/issues/3500">#3500</a> from ecarrara/fix-eval-frame-py311</li>
<li><a href="https://github.com/PyO3/pyo3/commit/ddc04ea0939d8997659d512dd801f114a4e87aae"><code>ddc04ea</code></a> emit helpful error hint for classmethod with receiver</li>
<li><a href="https://github.com/PyO3/pyo3/commit/0e0e6623f37b64f09e0abd957e19e3490bffbef8"><code>0e0e662</code></a> fix _PyFrameEvalFunction. Since python 3.11 it receives a <code>_PyInterpreterFrame</code></li>
<li>Additional commits viewable in <a href="https://github.com/pyo3/pyo3/compare/v0.19.0...v0.20.0">compare view</a></li>
</ul>
</details>
<br />
Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.
[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)
---
<details>
<summary>Dependabot commands and options</summary>
<br />
You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
</details>
|
2023-10-16T12:20:01Z
|
47.0
|
fa7a61a4b074ca4ec9bf429cc84b6c325057d96e
|
|
apache/arrow-rs
| 4,930
|
apache__arrow-rs-4930
|
[
"4946"
] |
ab87abdd69ab787fdf247cf36f04abc1fbfa6266
|
diff --git a/object_store/src/aws/mod.rs b/object_store/src/aws/mod.rs
index 0028be99fa2e..3c9431091018 100644
--- a/object_store/src/aws/mod.rs
+++ b/object_store/src/aws/mod.rs
@@ -335,19 +335,16 @@ impl ObjectStore for AmazonS3 {
.boxed()
}
- async fn list(
- &self,
- prefix: Option<&Path>,
- ) -> Result<BoxStream<'_, Result<ObjectMeta>>> {
- self.client.list(prefix).await
+ fn list(&self, prefix: Option<&Path>) -> BoxStream<'_, Result<ObjectMeta>> {
+ self.client.list(prefix)
}
- async fn list_with_offset(
+ fn list_with_offset(
&self,
prefix: Option<&Path>,
offset: &Path,
- ) -> Result<BoxStream<'_, Result<ObjectMeta>>> {
- self.client.list_with_offset(prefix, offset).await
+ ) -> BoxStream<'_, Result<ObjectMeta>> {
+ self.client.list_with_offset(prefix, offset)
}
async fn list_with_delimiter(&self, prefix: Option<&Path>) -> Result<ListResult> {
diff --git a/object_store/src/azure/mod.rs b/object_store/src/azure/mod.rs
index b210d486d9bf..c95bb140d6d3 100644
--- a/object_store/src/azure/mod.rs
+++ b/object_store/src/azure/mod.rs
@@ -210,11 +210,8 @@ impl ObjectStore for MicrosoftAzure {
self.client.delete_request(location, &()).await
}
- async fn list(
- &self,
- prefix: Option<&Path>,
- ) -> Result<BoxStream<'_, Result<ObjectMeta>>> {
- self.client.list(prefix).await
+ fn list(&self, prefix: Option<&Path>) -> BoxStream<'_, Result<ObjectMeta>> {
+ self.client.list(prefix)
}
async fn list_with_delimiter(&self, prefix: Option<&Path>) -> Result<ListResult> {
diff --git a/object_store/src/chunked.rs b/object_store/src/chunked.rs
index 008dec679413..d3e02b412725 100644
--- a/object_store/src/chunked.rs
+++ b/object_store/src/chunked.rs
@@ -147,19 +147,16 @@ impl ObjectStore for ChunkedStore {
self.inner.delete(location).await
}
- async fn list(
- &self,
- prefix: Option<&Path>,
- ) -> Result<BoxStream<'_, Result<ObjectMeta>>> {
- self.inner.list(prefix).await
+ fn list(&self, prefix: Option<&Path>) -> BoxStream<'_, Result<ObjectMeta>> {
+ self.inner.list(prefix)
}
- async fn list_with_offset(
+ fn list_with_offset(
&self,
prefix: Option<&Path>,
offset: &Path,
- ) -> Result<BoxStream<'_, Result<ObjectMeta>>> {
- self.inner.list_with_offset(prefix, offset).await
+ ) -> BoxStream<'_, Result<ObjectMeta>> {
+ self.inner.list_with_offset(prefix, offset)
}
async fn list_with_delimiter(&self, prefix: Option<&Path>) -> Result<ListResult> {
diff --git a/object_store/src/client/list.rs b/object_store/src/client/list.rs
index b2dbee27f14d..371894dfeb71 100644
--- a/object_store/src/client/list.rs
+++ b/object_store/src/client/list.rs
@@ -46,16 +46,13 @@ pub trait ListClientExt {
offset: Option<&Path>,
) -> BoxStream<'_, Result<ListResult>>;
- async fn list(
- &self,
- prefix: Option<&Path>,
- ) -> Result<BoxStream<'_, Result<ObjectMeta>>>;
+ fn list(&self, prefix: Option<&Path>) -> BoxStream<'_, Result<ObjectMeta>>;
- async fn list_with_offset(
+ fn list_with_offset(
&self,
prefix: Option<&Path>,
offset: &Path,
- ) -> Result<BoxStream<'_, Result<ObjectMeta>>>;
+ ) -> BoxStream<'_, Result<ObjectMeta>>;
async fn list_with_delimiter(&self, prefix: Option<&Path>) -> Result<ListResult>;
}
@@ -90,31 +87,22 @@ impl<T: ListClient> ListClientExt for T {
.boxed()
}
- async fn list(
- &self,
- prefix: Option<&Path>,
- ) -> Result<BoxStream<'_, Result<ObjectMeta>>> {
- let stream = self
- .list_paginated(prefix, false, None)
+ fn list(&self, prefix: Option<&Path>) -> BoxStream<'_, Result<ObjectMeta>> {
+ self.list_paginated(prefix, false, None)
.map_ok(|r| futures::stream::iter(r.objects.into_iter().map(Ok)))
.try_flatten()
- .boxed();
-
- Ok(stream)
+ .boxed()
}
- async fn list_with_offset(
+ fn list_with_offset(
&self,
prefix: Option<&Path>,
offset: &Path,
- ) -> Result<BoxStream<'_, Result<ObjectMeta>>> {
- let stream = self
- .list_paginated(prefix, false, Some(offset))
+ ) -> BoxStream<'_, Result<ObjectMeta>> {
+ self.list_paginated(prefix, false, Some(offset))
.map_ok(|r| futures::stream::iter(r.objects.into_iter().map(Ok)))
.try_flatten()
- .boxed();
-
- Ok(stream)
+ .boxed()
}
async fn list_with_delimiter(&self, prefix: Option<&Path>) -> Result<ListResult> {
diff --git a/object_store/src/gcp/mod.rs b/object_store/src/gcp/mod.rs
index a0a60f27a6aa..b4846848a6c8 100644
--- a/object_store/src/gcp/mod.rs
+++ b/object_store/src/gcp/mod.rs
@@ -612,11 +612,8 @@ impl ObjectStore for GoogleCloudStorage {
self.client.delete_request(location).await
}
- async fn list(
- &self,
- prefix: Option<&Path>,
- ) -> Result<BoxStream<'_, Result<ObjectMeta>>> {
- self.client.list(prefix).await
+ fn list(&self, prefix: Option<&Path>) -> BoxStream<'_, Result<ObjectMeta>> {
+ self.client.list(prefix)
}
async fn list_with_delimiter(&self, prefix: Option<&Path>) -> Result<ListResult> {
diff --git a/object_store/src/http/mod.rs b/object_store/src/http/mod.rs
index e9ed5902d8f5..d0e7b0e8fc19 100644
--- a/object_store/src/http/mod.rs
+++ b/object_store/src/http/mod.rs
@@ -34,7 +34,7 @@
use async_trait::async_trait;
use bytes::Bytes;
use futures::stream::BoxStream;
-use futures::StreamExt;
+use futures::{StreamExt, TryStreamExt};
use itertools::Itertools;
use snafu::{OptionExt, ResultExt, Snafu};
use tokio::io::AsyncWrite;
@@ -126,14 +126,13 @@ impl ObjectStore for HttpStore {
self.client.delete(location).await
}
- async fn list(
- &self,
- prefix: Option<&Path>,
- ) -> Result<BoxStream<'_, Result<ObjectMeta>>> {
+ fn list(&self, prefix: Option<&Path>) -> BoxStream<'_, Result<ObjectMeta>> {
let prefix_len = prefix.map(|p| p.as_ref().len()).unwrap_or_default();
- let status = self.client.list(prefix, "infinity").await?;
- Ok(futures::stream::iter(
- status
+ let prefix = prefix.cloned();
+ futures::stream::once(async move {
+ let status = self.client.list(prefix.as_ref(), "infinity").await?;
+
+ let iter = status
.response
.into_iter()
.filter(|r| !r.is_dir())
@@ -142,9 +141,12 @@ impl ObjectStore for HttpStore {
response.object_meta(self.client.base_url())
})
// Filter out exact prefix matches
- .filter_ok(move |r| r.location.as_ref().len() > prefix_len),
- )
- .boxed())
+ .filter_ok(move |r| r.location.as_ref().len() > prefix_len);
+
+ Ok::<_, crate::Error>(futures::stream::iter(iter))
+ })
+ .try_flatten()
+ .boxed()
}
async fn list_with_delimiter(&self, prefix: Option<&Path>) -> Result<ListResult> {
diff --git a/object_store/src/lib.rs b/object_store/src/lib.rs
index 68e785b3a31e..ddaefc94c61a 100644
--- a/object_store/src/lib.rs
+++ b/object_store/src/lib.rs
@@ -95,18 +95,18 @@
//!
//! ```
//! # use object_store::local::LocalFileSystem;
+//! # use std::sync::Arc;
+//! # use object_store::{path::Path, ObjectStore};
+//! # use futures::stream::StreamExt;
//! # // use LocalFileSystem for example
-//! # fn get_object_store() -> LocalFileSystem {
-//! # LocalFileSystem::new_with_prefix("/tmp").unwrap()
+//! # fn get_object_store() -> Arc<dyn ObjectStore> {
+//! # Arc::new(LocalFileSystem::new())
//! # }
-//!
+//! #
//! # async fn example() {
-//! use std::sync::Arc;
-//! use object_store::{path::Path, ObjectStore};
-//! use futures::stream::StreamExt;
-//!
+//! #
//! // create an ObjectStore
-//! let object_store: Arc<dyn ObjectStore> = Arc::new(get_object_store());
+//! let object_store: Arc<dyn ObjectStore> = get_object_store();
//!
//! // Recursively list all files below the 'data' path.
//! // 1. On AWS S3 this would be the 'data/' prefix
@@ -114,21 +114,12 @@
//! let prefix: Path = "data".try_into().unwrap();
//!
//! // Get an `async` stream of Metadata objects:
-//! let list_stream = object_store
-//! .list(Some(&prefix))
-//! .await
-//! .expect("Error listing files");
+//! let mut list_stream = object_store.list(Some(&prefix));
//!
-//! // Print a line about each object based on its metadata
-//! // using for_each from `StreamExt` trait.
-//! list_stream
-//! .for_each(move |meta| {
-//! async {
-//! let meta = meta.expect("Error listing");
-//! println!("Name: {}, size: {}", meta.location, meta.size);
-//! }
-//! })
-//! .await;
+//! // Print a line about each object
+//! while let Some(meta) = list_stream.next().await.transpose().unwrap() {
+//! println!("Name: {}, size: {}", meta.location, meta.size);
+//! }
//! # }
//! ```
//!
@@ -147,19 +138,18 @@
//! from remote storage or files in the local filesystem as a stream.
//!
//! ```
+//! # use futures::TryStreamExt;
//! # use object_store::local::LocalFileSystem;
-//! # // use LocalFileSystem for example
-//! # fn get_object_store() -> LocalFileSystem {
-//! # LocalFileSystem::new_with_prefix("/tmp").unwrap()
+//! # use std::sync::Arc;
+//! # use object_store::{path::Path, ObjectStore};
+//! # fn get_object_store() -> Arc<dyn ObjectStore> {
+//! # Arc::new(LocalFileSystem::new())
//! # }
-//!
+//! #
//! # async fn example() {
-//! use std::sync::Arc;
-//! use object_store::{path::Path, ObjectStore};
-//! use futures::stream::StreamExt;
-//!
+//! #
//! // create an ObjectStore
-//! let object_store: Arc<dyn ObjectStore> = Arc::new(get_object_store());
+//! let object_store: Arc<dyn ObjectStore> = get_object_store();
//!
//! // Retrieve a specific file
//! let path: Path = "data/file01.parquet".try_into().unwrap();
@@ -171,16 +161,11 @@
//! .unwrap()
//! .into_stream();
//!
-//! // Count the '0's using `map` from `StreamExt` trait
+//! // Count the '0's using `try_fold` from `TryStreamExt` trait
//! let num_zeros = stream
-//! .map(|bytes| {
-//! let bytes = bytes.unwrap();
-//! bytes.iter().filter(|b| **b == 0).count()
-//! })
-//! .collect::<Vec<usize>>()
-//! .await
-//! .into_iter()
-//! .sum::<usize>();
+//! .try_fold(0, |acc, bytes| async move {
+//! Ok(acc + bytes.iter().filter(|b| **b == 0).count())
+//! }).await.unwrap();
//!
//! println!("Num zeros in {} is {}", path, num_zeros);
//! # }
@@ -196,22 +181,19 @@
//!
//! ```
//! # use object_store::local::LocalFileSystem;
-//! # fn get_object_store() -> LocalFileSystem {
-//! # LocalFileSystem::new_with_prefix("/tmp").unwrap()
+//! # use object_store::ObjectStore;
+//! # use std::sync::Arc;
+//! # use bytes::Bytes;
+//! # use object_store::path::Path;
+//! # fn get_object_store() -> Arc<dyn ObjectStore> {
+//! # Arc::new(LocalFileSystem::new())
//! # }
//! # async fn put() {
-//! use object_store::ObjectStore;
-//! use std::sync::Arc;
-//! use bytes::Bytes;
-//! use object_store::path::Path;
-//!
-//! let object_store: Arc<dyn ObjectStore> = Arc::new(get_object_store());
+//! #
+//! let object_store: Arc<dyn ObjectStore> = get_object_store();
//! let path: Path = "data/file1".try_into().unwrap();
//! let bytes = Bytes::from_static(b"hello");
-//! object_store
-//! .put(&path, bytes)
-//! .await
-//! .unwrap();
+//! object_store.put(&path, bytes).await.unwrap();
//! # }
//! ```
//!
@@ -220,22 +202,20 @@
//!
//! ```
//! # use object_store::local::LocalFileSystem;
-//! # fn get_object_store() -> LocalFileSystem {
-//! # LocalFileSystem::new_with_prefix("/tmp").unwrap()
+//! # use object_store::ObjectStore;
+//! # use std::sync::Arc;
+//! # use bytes::Bytes;
+//! # use tokio::io::AsyncWriteExt;
+//! # use object_store::path::Path;
+//! # fn get_object_store() -> Arc<dyn ObjectStore> {
+//! # Arc::new(LocalFileSystem::new())
//! # }
//! # async fn multi_upload() {
-//! use object_store::ObjectStore;
-//! use std::sync::Arc;
-//! use bytes::Bytes;
-//! use tokio::io::AsyncWriteExt;
-//! use object_store::path::Path;
-//!
-//! let object_store: Arc<dyn ObjectStore> = Arc::new(get_object_store());
+//! #
+//! let object_store: Arc<dyn ObjectStore> = get_object_store();
//! let path: Path = "data/large_file".try_into().unwrap();
-//! let (_id, mut writer) = object_store
-//! .put_multipart(&path)
-//! .await
-//! .unwrap();
+//! let (_id, mut writer) = object_store.put_multipart(&path).await.unwrap();
+//!
//! let bytes = Bytes::from_static(b"hello");
//! writer.write_all(&bytes).await.unwrap();
//! writer.flush().await.unwrap();
@@ -433,23 +413,22 @@ pub trait ObjectStore: std::fmt::Display + Send + Sync + Debug + 'static {
/// return Ok. If it is an error, it will be [`Error::NotFound`].
///
/// ```
+ /// # use futures::{StreamExt, TryStreamExt};
/// # use object_store::local::LocalFileSystem;
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// # let root = tempfile::TempDir::new().unwrap();
/// # let store = LocalFileSystem::new_with_prefix(root.path()).unwrap();
- /// use object_store::{ObjectStore, ObjectMeta};
- /// use object_store::path::Path;
- /// use futures::{StreamExt, TryStreamExt};
- /// use bytes::Bytes;
- ///
+ /// # use object_store::{ObjectStore, ObjectMeta};
+ /// # use object_store::path::Path;
+ /// # use futures::{StreamExt, TryStreamExt};
+ /// # use bytes::Bytes;
+ /// #
/// // Create two objects
/// store.put(&Path::from("foo"), Bytes::from("foo")).await?;
/// store.put(&Path::from("bar"), Bytes::from("bar")).await?;
///
/// // List object
- /// let locations = store.list(None).await?
- /// .map(|meta: Result<ObjectMeta, _>| meta.map(|m| m.location))
- /// .boxed();
+ /// let locations = store.list(None).map_ok(|m| m.location).boxed();
///
/// // Delete them
/// store.delete_stream(locations).try_collect::<Vec<Path>>().await?;
@@ -478,10 +457,7 @@ pub trait ObjectStore: std::fmt::Display + Send + Sync + Debug + 'static {
/// `foo/bar_baz/x`.
///
/// Note: the order of returned [`ObjectMeta`] is not guaranteed
- async fn list(
- &self,
- prefix: Option<&Path>,
- ) -> Result<BoxStream<'_, Result<ObjectMeta>>>;
+ fn list(&self, prefix: Option<&Path>) -> BoxStream<'_, Result<ObjectMeta>>;
/// List all the objects with the given prefix and a location greater than `offset`
///
@@ -489,18 +465,15 @@ pub trait ObjectStore: std::fmt::Display + Send + Sync + Debug + 'static {
/// the number of network requests required
///
/// Note: the order of returned [`ObjectMeta`] is not guaranteed
- async fn list_with_offset(
+ fn list_with_offset(
&self,
prefix: Option<&Path>,
offset: &Path,
- ) -> Result<BoxStream<'_, Result<ObjectMeta>>> {
+ ) -> BoxStream<'_, Result<ObjectMeta>> {
let offset = offset.clone();
- let stream = self
- .list(prefix)
- .await?
+ self.list(prefix)
.try_filter(move |f| futures::future::ready(f.location > offset))
- .boxed();
- Ok(stream)
+ .boxed()
}
/// List objects with the given prefix and an implementation specific
@@ -618,19 +591,16 @@ macro_rules! as_ref_impl {
self.as_ref().delete_stream(locations)
}
- async fn list(
- &self,
- prefix: Option<&Path>,
- ) -> Result<BoxStream<'_, Result<ObjectMeta>>> {
- self.as_ref().list(prefix).await
+ fn list(&self, prefix: Option<&Path>) -> BoxStream<'_, Result<ObjectMeta>> {
+ self.as_ref().list(prefix)
}
- async fn list_with_offset(
+ fn list_with_offset(
&self,
prefix: Option<&Path>,
offset: &Path,
- ) -> Result<BoxStream<'_, Result<ObjectMeta>>> {
- self.as_ref().list_with_offset(prefix, offset).await
+ ) -> BoxStream<'_, Result<ObjectMeta>> {
+ self.as_ref().list_with_offset(prefix, offset)
}
async fn list_with_delimiter(
@@ -931,7 +901,6 @@ mod test_util {
) -> Result<Vec<Path>> {
storage
.list(prefix)
- .await?
.map_ok(|meta| meta.location)
.try_collect::<Vec<Path>>()
.await
@@ -1221,11 +1190,7 @@ mod tests {
];
for (prefix, offset) in cases {
- let s = storage
- .list_with_offset(prefix.as_ref(), &offset)
- .await
- .unwrap();
-
+ let s = storage.list_with_offset(prefix.as_ref(), &offset);
let mut actual: Vec<_> =
s.map_ok(|x| x.location).try_collect().await.unwrap();
@@ -1658,12 +1623,7 @@ mod tests {
}
async fn delete_fixtures(storage: &DynObjectStore) {
- let paths = storage
- .list(None)
- .await
- .unwrap()
- .map_ok(|meta| meta.location)
- .boxed();
+ let paths = storage.list(None).map_ok(|meta| meta.location).boxed();
storage
.delete_stream(paths)
.try_collect::<Vec<_>>()
@@ -1672,18 +1632,18 @@ mod tests {
}
/// Test that the returned stream does not borrow the lifetime of Path
- async fn list_store<'a, 'b>(
+ fn list_store<'a>(
store: &'a dyn ObjectStore,
- path_str: &'b str,
- ) -> super::Result<BoxStream<'a, super::Result<ObjectMeta>>> {
+ path_str: &str,
+ ) -> BoxStream<'a, Result<ObjectMeta>> {
let path = Path::from(path_str);
- store.list(Some(&path)).await
+ store.list(Some(&path))
}
#[tokio::test]
async fn test_list_lifetimes() {
let store = memory::InMemory::new();
- let mut stream = list_store(&store, "path").await.unwrap();
+ let mut stream = list_store(&store, "path");
assert!(stream.next().await.is_none());
}
diff --git a/object_store/src/limit.rs b/object_store/src/limit.rs
index a9b8c4b05020..00cbce023c3d 100644
--- a/object_store/src/limit.rs
+++ b/object_store/src/limit.rs
@@ -23,7 +23,7 @@ use crate::{
};
use async_trait::async_trait;
use bytes::Bytes;
-use futures::Stream;
+use futures::{FutureExt, Stream};
use std::io::{Error, IoSlice};
use std::ops::Range;
use std::pin::Pin;
@@ -147,23 +147,31 @@ impl<T: ObjectStore> ObjectStore for LimitStore<T> {
self.inner.delete_stream(locations)
}
- async fn list(
- &self,
- prefix: Option<&Path>,
- ) -> Result<BoxStream<'_, Result<ObjectMeta>>> {
- let permit = Arc::clone(&self.semaphore).acquire_owned().await.unwrap();
- let s = self.inner.list(prefix).await?;
- Ok(PermitWrapper::new(s, permit).boxed())
+ fn list(&self, prefix: Option<&Path>) -> BoxStream<'_, Result<ObjectMeta>> {
+ let prefix = prefix.cloned();
+ let fut = Arc::clone(&self.semaphore)
+ .acquire_owned()
+ .map(move |permit| {
+ let s = self.inner.list(prefix.as_ref());
+ PermitWrapper::new(s, permit.unwrap())
+ });
+ fut.into_stream().flatten().boxed()
}
- async fn list_with_offset(
+ fn list_with_offset(
&self,
prefix: Option<&Path>,
offset: &Path,
- ) -> Result<BoxStream<'_, Result<ObjectMeta>>> {
- let permit = Arc::clone(&self.semaphore).acquire_owned().await.unwrap();
- let s = self.inner.list_with_offset(prefix, offset).await?;
- Ok(PermitWrapper::new(s, permit).boxed())
+ ) -> BoxStream<'_, Result<ObjectMeta>> {
+ let prefix = prefix.cloned();
+ let offset = offset.clone();
+ let fut = Arc::clone(&self.semaphore)
+ .acquire_owned()
+ .map(move |permit| {
+ let s = self.inner.list_with_offset(prefix.as_ref(), &offset);
+ PermitWrapper::new(s, permit.unwrap())
+ });
+ fut.into_stream().flatten().boxed()
}
async fn list_with_delimiter(&self, prefix: Option<&Path>) -> Result<ListResult> {
@@ -272,6 +280,8 @@ mod tests {
use crate::memory::InMemory;
use crate::tests::*;
use crate::ObjectStore;
+ use futures::stream::StreamExt;
+ use std::pin::Pin;
use std::time::Duration;
use tokio::time::timeout;
@@ -290,19 +300,21 @@ mod tests {
let mut streams = Vec::with_capacity(max_requests);
for _ in 0..max_requests {
- let stream = integration.list(None).await.unwrap();
+ let mut stream = integration.list(None).peekable();
+ Pin::new(&mut stream).peek().await; // Ensure semaphore is acquired
streams.push(stream);
}
let t = Duration::from_millis(20);
// Expect to not be able to make another request
- assert!(timeout(t, integration.list(None)).await.is_err());
+ let fut = integration.list(None).collect::<Vec<_>>();
+ assert!(timeout(t, fut).await.is_err());
// Drop one of the streams
streams.pop();
// Can now make another request
- integration.list(None).await.unwrap();
+ integration.list(None).collect::<Vec<_>>().await;
}
}
diff --git a/object_store/src/local.rs b/object_store/src/local.rs
index 69da170b0872..e6961ee1dd4e 100644
--- a/object_store/src/local.rs
+++ b/object_store/src/local.rs
@@ -460,14 +460,14 @@ impl ObjectStore for LocalFileSystem {
.await
}
- async fn list(
- &self,
- prefix: Option<&Path>,
- ) -> Result<BoxStream<'_, Result<ObjectMeta>>> {
+ fn list(&self, prefix: Option<&Path>) -> BoxStream<'_, Result<ObjectMeta>> {
let config = Arc::clone(&self.config);
let root_path = match prefix {
- Some(prefix) => config.path_to_filesystem(prefix)?,
+ Some(prefix) => match config.path_to_filesystem(prefix) {
+ Ok(path) => path,
+ Err(e) => return futures::future::ready(Err(e)).into_stream().boxed(),
+ },
None => self.config.root.to_file_path().unwrap(),
};
@@ -497,36 +497,34 @@ impl ObjectStore for LocalFileSystem {
// If no tokio context, return iterator directly as no
// need to perform chunked spawn_blocking reads
if tokio::runtime::Handle::try_current().is_err() {
- return Ok(futures::stream::iter(s).boxed());
+ return futures::stream::iter(s).boxed();
}
// Otherwise list in batches of CHUNK_SIZE
const CHUNK_SIZE: usize = 1024;
let buffer = VecDeque::with_capacity(CHUNK_SIZE);
- let stream =
- futures::stream::try_unfold((s, buffer), |(mut s, mut buffer)| async move {
- if buffer.is_empty() {
- (s, buffer) = tokio::task::spawn_blocking(move || {
- for _ in 0..CHUNK_SIZE {
- match s.next() {
- Some(r) => buffer.push_back(r),
- None => break,
- }
+ futures::stream::try_unfold((s, buffer), |(mut s, mut buffer)| async move {
+ if buffer.is_empty() {
+ (s, buffer) = tokio::task::spawn_blocking(move || {
+ for _ in 0..CHUNK_SIZE {
+ match s.next() {
+ Some(r) => buffer.push_back(r),
+ None => break,
}
- (s, buffer)
- })
- .await?;
- }
-
- match buffer.pop_front() {
- Some(Err(e)) => Err(e),
- Some(Ok(meta)) => Ok(Some((meta, (s, buffer)))),
- None => Ok(None),
- }
- });
+ }
+ (s, buffer)
+ })
+ .await?;
+ }
- Ok(stream.boxed())
+ match buffer.pop_front() {
+ Some(Err(e)) => Err(e),
+ Some(Ok(meta)) => Ok(Some((meta, (s, buffer)))),
+ None => Ok(None),
+ }
+ })
+ .boxed()
}
async fn list_with_delimiter(&self, prefix: Option<&Path>) -> Result<ListResult> {
@@ -1158,21 +1156,14 @@ mod tests {
let store = LocalFileSystem::new_with_prefix(root.path()).unwrap();
- // `list` must fail
- match store.list(None).await {
- Err(_) => {
- // ok, error found
- }
- Ok(mut stream) => {
- let mut any_err = false;
- while let Some(res) = stream.next().await {
- if res.is_err() {
- any_err = true;
- }
- }
- assert!(any_err);
+ let mut stream = store.list(None);
+ let mut any_err = false;
+ while let Some(res) = stream.next().await {
+ if res.is_err() {
+ any_err = true;
}
}
+ assert!(any_err);
// `list_with_delimiter
assert!(store.list_with_delimiter(None).await.is_err());
@@ -1246,13 +1237,7 @@ mod tests {
prefix: Option<&Path>,
expected: &[&str],
) {
- let result: Vec<_> = integration
- .list(prefix)
- .await
- .unwrap()
- .try_collect()
- .await
- .unwrap();
+ let result: Vec<_> = integration.list(prefix).try_collect().await.unwrap();
let mut strings: Vec<_> = result.iter().map(|x| x.location.as_ref()).collect();
strings.sort_unstable();
@@ -1448,8 +1433,7 @@ mod tests {
std::fs::write(temp_dir.path().join(filename), "foo").unwrap();
- let list_stream = integration.list(None).await.unwrap();
- let res: Vec<_> = list_stream.try_collect().await.unwrap();
+ let res: Vec<_> = integration.list(None).try_collect().await.unwrap();
assert_eq!(res.len(), 1);
assert_eq!(res[0].location.as_ref(), filename);
diff --git a/object_store/src/memory.rs b/object_store/src/memory.rs
index 0e229885b006..38420410677f 100644
--- a/object_store/src/memory.rs
+++ b/object_store/src/memory.rs
@@ -199,10 +199,7 @@ impl ObjectStore for InMemory {
Ok(())
}
- async fn list(
- &self,
- prefix: Option<&Path>,
- ) -> Result<BoxStream<'_, Result<ObjectMeta>>> {
+ fn list(&self, prefix: Option<&Path>) -> BoxStream<'_, Result<ObjectMeta>> {
let root = Path::default();
let prefix = prefix.unwrap_or(&root);
@@ -226,7 +223,7 @@ impl ObjectStore for InMemory {
})
.collect();
- Ok(futures::stream::iter(values).boxed())
+ futures::stream::iter(values).boxed()
}
/// The memory implementation returns all results, as opposed to the cloud
diff --git a/object_store/src/prefix.rs b/object_store/src/prefix.rs
index 39585f73b692..3776dec2e872 100644
--- a/object_store/src/prefix.rs
+++ b/object_store/src/prefix.rs
@@ -144,24 +144,21 @@ impl<T: ObjectStore> ObjectStore for PrefixStore<T> {
self.inner.delete(&full_path).await
}
- async fn list(
- &self,
- prefix: Option<&Path>,
- ) -> Result<BoxStream<'_, Result<ObjectMeta>>> {
+ fn list(&self, prefix: Option<&Path>) -> BoxStream<'_, Result<ObjectMeta>> {
let prefix = self.full_path(prefix.unwrap_or(&Path::default()));
- let s = self.inner.list(Some(&prefix)).await?;
- Ok(s.map_ok(|meta| self.strip_meta(meta)).boxed())
+ let s = self.inner.list(Some(&prefix));
+ s.map_ok(|meta| self.strip_meta(meta)).boxed()
}
- async fn list_with_offset(
+ fn list_with_offset(
&self,
prefix: Option<&Path>,
offset: &Path,
- ) -> Result<BoxStream<'_, Result<ObjectMeta>>> {
+ ) -> BoxStream<'_, Result<ObjectMeta>> {
let offset = self.full_path(offset);
let prefix = self.full_path(prefix.unwrap_or(&Path::default()));
- let s = self.inner.list_with_offset(Some(&prefix), &offset).await?;
- Ok(s.map_ok(|meta| self.strip_meta(meta)).boxed())
+ let s = self.inner.list_with_offset(Some(&prefix), &offset);
+ s.map_ok(|meta| self.strip_meta(meta)).boxed()
}
async fn list_with_delimiter(&self, prefix: Option<&Path>) -> Result<ListResult> {
diff --git a/object_store/src/throttle.rs b/object_store/src/throttle.rs
index 58c476ab4530..f716a11f8a05 100644
--- a/object_store/src/throttle.rs
+++ b/object_store/src/throttle.rs
@@ -233,29 +233,30 @@ impl<T: ObjectStore> ObjectStore for ThrottledStore<T> {
self.inner.delete(location).await
}
- async fn list(
- &self,
- prefix: Option<&Path>,
- ) -> Result<BoxStream<'_, Result<ObjectMeta>>> {
- sleep(self.config().wait_list_per_call).await;
-
- // need to copy to avoid moving / referencing `self`
- let wait_list_per_entry = self.config().wait_list_per_entry;
- let stream = self.inner.list(prefix).await?;
- Ok(throttle_stream(stream, move |_| wait_list_per_entry))
+ fn list(&self, prefix: Option<&Path>) -> BoxStream<'_, Result<ObjectMeta>> {
+ let stream = self.inner.list(prefix);
+ futures::stream::once(async move {
+ let wait_list_per_entry = self.config().wait_list_per_entry;
+ sleep(self.config().wait_list_per_call).await;
+ throttle_stream(stream, move |_| wait_list_per_entry)
+ })
+ .flatten()
+ .boxed()
}
- async fn list_with_offset(
+ fn list_with_offset(
&self,
prefix: Option<&Path>,
offset: &Path,
- ) -> Result<BoxStream<'_, Result<ObjectMeta>>> {
- sleep(self.config().wait_list_per_call).await;
-
- // need to copy to avoid moving / referencing `self`
- let wait_list_per_entry = self.config().wait_list_per_entry;
- let stream = self.inner.list_with_offset(prefix, offset).await?;
- Ok(throttle_stream(stream, move |_| wait_list_per_entry))
+ ) -> BoxStream<'_, Result<ObjectMeta>> {
+ let stream = self.inner.list_with_offset(prefix, offset);
+ futures::stream::once(async move {
+ let wait_list_per_entry = self.config().wait_list_per_entry;
+ sleep(self.config().wait_list_per_call).await;
+ throttle_stream(stream, move |_| wait_list_per_entry)
+ })
+ .flatten()
+ .boxed()
}
async fn list_with_delimiter(&self, prefix: Option<&Path>) -> Result<ListResult> {
@@ -511,13 +512,7 @@ mod tests {
let prefix = Path::from("foo");
// clean up store
- let entries: Vec<_> = store
- .list(Some(&prefix))
- .await
- .unwrap()
- .try_collect()
- .await
- .unwrap();
+ let entries: Vec<_> = store.list(Some(&prefix)).try_collect().await.unwrap();
for entry in entries {
store.delete(&entry.location).await.unwrap();
@@ -583,8 +578,6 @@ mod tests {
let t0 = Instant::now();
store
.list(Some(&prefix))
- .await
- .unwrap()
.try_collect::<Vec<_>>()
.await
.unwrap();
|
diff --git a/object_store/tests/get_range_file.rs b/object_store/tests/get_range_file.rs
index f926e3b07f2a..25c469260675 100644
--- a/object_store/tests/get_range_file.rs
+++ b/object_store/tests/get_range_file.rs
@@ -75,10 +75,7 @@ impl ObjectStore for MyStore {
todo!()
}
- async fn list(
- &self,
- _: Option<&Path>,
- ) -> object_store::Result<BoxStream<'_, object_store::Result<ObjectMeta>>> {
+ fn list(&self, _: Option<&Path>) -> BoxStream<'_, object_store::Result<ObjectMeta>> {
todo!()
}
|
Simplify ObjectStore::List
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
<!--
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
(This section helps Arrow developers understand the context and *why* for this feature, in addition to the *what*)
-->
Having two layers of asynchrony and fallibility makes for a rather obnoxious interface. Removing this makes for better client ergonomics, at the expense of slightly more arcane logic to implement the ObjectStore
**Describe the solution you'd like**
<!--
A clear and concise description of what you want to happen.
-->
I would like `ObjectStore::list` to synchronously return an async stream
**Describe alternatives you've considered**
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
|
2023-10-13T13:42:45Z
|
47.0
|
fa7a61a4b074ca4ec9bf429cc84b6c325057d96e
|
|
apache/arrow-rs
| 4,910
|
apache__arrow-rs-4910
|
[
"4903"
] |
2af51631e492e0ea0ac71da67b3dba6a846dafd5
|
diff --git a/arrow-csv/src/reader/mod.rs b/arrow-csv/src/reader/mod.rs
index 17db7a34e06f..2ba49cadc73f 100644
--- a/arrow-csv/src/reader/mod.rs
+++ b/arrow-csv/src/reader/mod.rs
@@ -193,6 +193,7 @@ impl InferredDataType {
/// Returns the inferred data type
fn get(&self) -> DataType {
match self.packed {
+ 0 => DataType::Null,
1 => DataType::Boolean,
2 => DataType::Int64,
4 | 6 => DataType::Float64, // Promote Int64 to Float64
@@ -785,6 +786,9 @@ fn parse(
null_regex,
)
}
+ DataType::Null => {
+ Ok(Arc::new(NullArray::builder(rows.len()).finish()) as ArrayRef)
+ }
DataType::Utf8 => Ok(Arc::new(
rows.iter()
.map(|row| Some(row.get(i)))
@@ -1511,6 +1515,62 @@ mod tests {
assert!(!batch.column(1).is_null(4));
}
+ #[test]
+ fn test_init_nulls() {
+ let schema = Arc::new(Schema::new(vec![
+ Field::new("c_int", DataType::UInt64, true),
+ Field::new("c_float", DataType::Float32, true),
+ Field::new("c_string", DataType::Utf8, true),
+ Field::new("c_bool", DataType::Boolean, true),
+ Field::new("c_null", DataType::Null, true),
+ ]));
+ let file = File::open("test/data/init_null_test.csv").unwrap();
+
+ let mut csv = ReaderBuilder::new(schema)
+ .has_header(true)
+ .build(file)
+ .unwrap();
+
+ let batch = csv.next().unwrap().unwrap();
+
+ assert!(batch.column(1).is_null(0));
+ assert!(!batch.column(1).is_null(1));
+ assert!(batch.column(1).is_null(2));
+ assert!(!batch.column(1).is_null(3));
+ assert!(!batch.column(1).is_null(4));
+ }
+
+ #[test]
+ fn test_init_nulls_with_inference() {
+ let format = Format::default().with_header(true).with_delimiter(b',');
+
+ let mut file = File::open("test/data/init_null_test.csv").unwrap();
+ let (schema, _) = format.infer_schema(&mut file, None).unwrap();
+ file.rewind().unwrap();
+
+ let expected_schema = Schema::new(vec![
+ Field::new("c_int", DataType::Int64, true),
+ Field::new("c_float", DataType::Float64, true),
+ Field::new("c_string", DataType::Utf8, true),
+ Field::new("c_bool", DataType::Boolean, true),
+ Field::new("c_null", DataType::Null, true),
+ ]);
+ assert_eq!(schema, expected_schema);
+
+ let mut csv = ReaderBuilder::new(Arc::new(schema))
+ .with_format(format)
+ .build(file)
+ .unwrap();
+
+ let batch = csv.next().unwrap().unwrap();
+
+ assert!(batch.column(1).is_null(0));
+ assert!(!batch.column(1).is_null(1));
+ assert!(batch.column(1).is_null(2));
+ assert!(!batch.column(1).is_null(3));
+ assert!(!batch.column(1).is_null(4));
+ }
+
#[test]
fn test_custom_nulls() {
let schema = Arc::new(Schema::new(vec![
@@ -2283,7 +2343,7 @@ mod tests {
#[test]
fn test_inference() {
let cases: &[(&[&str], DataType)] = &[
- (&[], DataType::Utf8),
+ (&[], DataType::Null),
(&["false", "12"], DataType::Utf8),
(&["12", "cupcakes"], DataType::Utf8),
(&["12", "12.4"], DataType::Float64),
|
diff --git a/arrow-csv/test/data/init_null_test.csv b/arrow-csv/test/data/init_null_test.csv
new file mode 100644
index 000000000000..f7d8a299645d
--- /dev/null
+++ b/arrow-csv/test/data/init_null_test.csv
@@ -0,0 +1,6 @@
+c_int,c_float,c_string,c_bool,c_null
+,,,,
+2,2.2,"a",TRUE,
+3,,"b",true,
+4,4.4,,False,
+5,6.6,"",FALSE,
\ No newline at end of file
|
CSV schema inference assumes `Utf8` for empty columns
**Describe the bug**
When rows processed by schema inference do not contain any data (are empty) for given column, that column is inferred as nullable `DataType::Utf8`. This data type is in fact a "catch-all" that permits any values later on, but it is in fact a limiting and to a degree incorrect behavior, since user is led to assume this column did contain some data and it was string or something that forced string type.
**To Reproduce**
```csv
int_column,null_column,string_column
1,,"a"
2,,"b"
```
**Expected behavior**
Inference should return `int*`, `null`, `utf8`
**Additional context**
My algorithm uses inference with limited number of rows as a kind of best-effort / incremental performance improvement, when I read some data and see inferred schema has nulls, I may repeat inference with more rows or without row limit. If inference wrongly returns some data-type that isn't there, then I will end up with unnecessarily widened `Utf8` datatime, while in fact later on this column actually contains just ints or booleans.
Another use-case is that I have several files of the same shape (or they could be several random offsets into the same file) and I want to infer schemas for each of them, then merge them to see if any still contain nulls.
With https://github.com/apache/arrow-rs/issues/4901 and fixing behavior described in this issue I can implement above strategy correctly.
|
2023-10-09T17:24:04Z
|
47.0
|
fa7a61a4b074ca4ec9bf429cc84b6c325057d96e
|
|
apache/arrow-rs
| 4,909
|
apache__arrow-rs-4909
|
[
"4735"
] |
ed58e767d7607e954085842a57a680b6807794e0
|
diff --git a/arrow-csv/src/writer.rs b/arrow-csv/src/writer.rs
index 840e8e8a93cc..1ca956e2c73f 100644
--- a/arrow-csv/src/writer.rs
+++ b/arrow-csv/src/writer.rs
@@ -70,11 +70,6 @@ use csv::ByteRecord;
use std::io::Write;
use crate::map_csv_error;
-
-const DEFAULT_DATE_FORMAT: &str = "%F";
-const DEFAULT_TIME_FORMAT: &str = "%T";
-const DEFAULT_TIMESTAMP_FORMAT: &str = "%FT%H:%M:%S.%9f";
-const DEFAULT_TIMESTAMP_TZ_FORMAT: &str = "%FT%H:%M:%S.%9f%:z";
const DEFAULT_NULL_VALUE: &str = "";
/// A CSV writer
@@ -82,41 +77,29 @@ const DEFAULT_NULL_VALUE: &str = "";
pub struct Writer<W: Write> {
/// The object to write to
writer: csv::Writer<W>,
- /// Whether file should be written with headers. Defaults to `true`
+ /// Whether file should be written with headers, defaults to `true`
has_headers: bool,
- /// The date format for date arrays
+ /// The date format for date arrays, defaults to RFC3339
date_format: Option<String>,
- /// The datetime format for datetime arrays
+ /// The datetime format for datetime arrays, defaults to RFC3339
datetime_format: Option<String>,
- /// The timestamp format for timestamp arrays
+ /// The timestamp format for timestamp arrays, defaults to RFC3339
timestamp_format: Option<String>,
- /// The timestamp format for timestamp (with timezone) arrays
+ /// The timestamp format for timestamp (with timezone) arrays, defaults to RFC3339
timestamp_tz_format: Option<String>,
- /// The time format for time arrays
+ /// The time format for time arrays, defaults to RFC3339
time_format: Option<String>,
/// Is the beginning-of-writer
beginning: bool,
- /// The value to represent null entries
- null_value: String,
+ /// The value to represent null entries, defaults to [`DEFAULT_NULL_VALUE`]
+ null_value: Option<String>,
}
impl<W: Write> Writer<W> {
/// Create a new CsvWriter from a writable object, with default options
pub fn new(writer: W) -> Self {
let delimiter = b',';
- let mut builder = csv::WriterBuilder::new();
- let writer = builder.delimiter(delimiter).from_writer(writer);
- Writer {
- writer,
- has_headers: true,
- date_format: Some(DEFAULT_DATE_FORMAT.to_string()),
- datetime_format: Some(DEFAULT_TIMESTAMP_FORMAT.to_string()),
- time_format: Some(DEFAULT_TIME_FORMAT.to_string()),
- timestamp_format: Some(DEFAULT_TIMESTAMP_FORMAT.to_string()),
- timestamp_tz_format: Some(DEFAULT_TIMESTAMP_TZ_FORMAT.to_string()),
- beginning: true,
- null_value: DEFAULT_NULL_VALUE.to_string(),
- }
+ WriterBuilder::new().with_delimiter(delimiter).build(writer)
}
/// Write a vector of record batches to a writable object
@@ -138,7 +121,7 @@ impl<W: Write> Writer<W> {
}
let options = FormatOptions::default()
- .with_null(&self.null_value)
+ .with_null(self.null_value.as_deref().unwrap_or(DEFAULT_NULL_VALUE))
.with_date_format(self.date_format.as_deref())
.with_datetime_format(self.datetime_format.as_deref())
.with_timestamp_format(self.timestamp_format.as_deref())
@@ -207,9 +190,9 @@ impl<W: Write> RecordBatchWriter for Writer<W> {
#[derive(Clone, Debug)]
pub struct WriterBuilder {
/// Optional column delimiter. Defaults to `b','`
- delimiter: Option<u8>,
+ delimiter: u8,
/// Whether to write column names as file headers. Defaults to `true`
- has_headers: bool,
+ has_header: bool,
/// Optional date format for date arrays
date_format: Option<String>,
/// Optional datetime format for datetime arrays
@@ -227,14 +210,14 @@ pub struct WriterBuilder {
impl Default for WriterBuilder {
fn default() -> Self {
Self {
- has_headers: true,
- delimiter: None,
- date_format: Some(DEFAULT_DATE_FORMAT.to_string()),
- datetime_format: Some(DEFAULT_TIMESTAMP_FORMAT.to_string()),
- time_format: Some(DEFAULT_TIME_FORMAT.to_string()),
- timestamp_format: Some(DEFAULT_TIMESTAMP_FORMAT.to_string()),
- timestamp_tz_format: Some(DEFAULT_TIMESTAMP_TZ_FORMAT.to_string()),
- null_value: Some(DEFAULT_NULL_VALUE.to_string()),
+ has_header: true,
+ delimiter: b',',
+ date_format: None,
+ datetime_format: None,
+ time_format: None,
+ timestamp_format: None,
+ timestamp_tz_format: None,
+ null_value: None,
}
}
}
@@ -254,7 +237,7 @@ impl WriterBuilder {
/// let file = File::create("target/out.csv").unwrap();
///
/// // create a builder that doesn't write headers
- /// let builder = WriterBuilder::new().has_headers(false);
+ /// let builder = WriterBuilder::new().with_header(false);
/// let writer = builder.build(file);
///
/// writer
@@ -265,48 +248,92 @@ impl WriterBuilder {
}
/// Set whether to write headers
+ #[deprecated(note = "Use Self::with_header")]
+ #[doc(hidden)]
pub fn has_headers(mut self, has_headers: bool) -> Self {
- self.has_headers = has_headers;
+ self.has_header = has_headers;
+ self
+ }
+
+ /// Set whether to write the CSV file with a header
+ pub fn with_header(mut self, header: bool) -> Self {
+ self.has_header = header;
self
}
+ /// Returns `true` if this writer is configured to write a header
+ pub fn header(&self) -> bool {
+ self.has_header
+ }
+
/// Set the CSV file's column delimiter as a byte character
pub fn with_delimiter(mut self, delimiter: u8) -> Self {
- self.delimiter = Some(delimiter);
+ self.delimiter = delimiter;
self
}
+ /// Get the CSV file's column delimiter as a byte character
+ pub fn delimiter(&self) -> u8 {
+ self.delimiter
+ }
+
/// Set the CSV file's date format
pub fn with_date_format(mut self, format: String) -> Self {
self.date_format = Some(format);
self
}
+ /// Get the CSV file's date format if set, defaults to RFC3339
+ pub fn date_format(&self) -> Option<&str> {
+ self.date_format.as_deref()
+ }
+
/// Set the CSV file's datetime format
pub fn with_datetime_format(mut self, format: String) -> Self {
self.datetime_format = Some(format);
self
}
+ /// Get the CSV file's datetime format if set, defaults to RFC3339
+ pub fn datetime_format(&self) -> Option<&str> {
+ self.datetime_format.as_deref()
+ }
+
/// Set the CSV file's time format
pub fn with_time_format(mut self, format: String) -> Self {
self.time_format = Some(format);
self
}
+ /// Get the CSV file's datetime time if set, defaults to RFC3339
+ pub fn time_format(&self) -> Option<&str> {
+ self.time_format.as_deref()
+ }
+
/// Set the CSV file's timestamp format
pub fn with_timestamp_format(mut self, format: String) -> Self {
self.timestamp_format = Some(format);
self
}
+ /// Get the CSV file's timestamp format if set, defaults to RFC3339
+ pub fn timestamp_format(&self) -> Option<&str> {
+ self.timestamp_format.as_deref()
+ }
+
/// Set the value to represent null in output
pub fn with_null(mut self, null_value: String) -> Self {
self.null_value = Some(null_value);
self
}
- /// Use RFC3339 format for date/time/timestamps
+ /// Get the value to represent null in output
+ pub fn null(&self) -> &str {
+ self.null_value.as_deref().unwrap_or(DEFAULT_NULL_VALUE)
+ }
+
+ /// Use RFC3339 format for date/time/timestamps (default)
+ #[deprecated(note = "Use WriterBuilder::default()")]
pub fn with_rfc3339(mut self) -> Self {
self.date_format = None;
self.datetime_format = None;
@@ -318,21 +345,18 @@ impl WriterBuilder {
/// Create a new `Writer`
pub fn build<W: Write>(self, writer: W) -> Writer<W> {
- let delimiter = self.delimiter.unwrap_or(b',');
let mut builder = csv::WriterBuilder::new();
- let writer = builder.delimiter(delimiter).from_writer(writer);
+ let writer = builder.delimiter(self.delimiter).from_writer(writer);
Writer {
writer,
- has_headers: self.has_headers,
+ beginning: true,
+ has_headers: self.has_header,
date_format: self.date_format,
datetime_format: self.datetime_format,
time_format: self.time_format,
timestamp_format: self.timestamp_format,
timestamp_tz_format: self.timestamp_tz_format,
- beginning: true,
- null_value: self
- .null_value
- .unwrap_or_else(|| DEFAULT_NULL_VALUE.to_string()),
+ null_value: self.null_value,
}
}
}
@@ -411,11 +435,11 @@ mod tests {
let expected = r#"c1,c2,c3,c4,c5,c6,c7
Lorem ipsum dolor sit amet,123.564532,3,true,,00:20:34,cupcakes
-consectetur adipiscing elit,,2,false,2019-04-18T10:54:47.378000000,06:51:20,cupcakes
-sed do eiusmod tempor,-556132.25,1,,2019-04-18T02:45:55.555000000,23:46:03,foo
+consectetur adipiscing elit,,2,false,2019-04-18T10:54:47.378,06:51:20,cupcakes
+sed do eiusmod tempor,-556132.25,1,,2019-04-18T02:45:55.555,23:46:03,foo
Lorem ipsum dolor sit amet,123.564532,3,true,,00:20:34,cupcakes
-consectetur adipiscing elit,,2,false,2019-04-18T10:54:47.378000000,06:51:20,cupcakes
-sed do eiusmod tempor,-556132.25,1,,2019-04-18T02:45:55.555000000,23:46:03,foo
+consectetur adipiscing elit,,2,false,2019-04-18T10:54:47.378,06:51:20,cupcakes
+sed do eiusmod tempor,-556132.25,1,,2019-04-18T02:45:55.555,23:46:03,foo
"#;
assert_eq!(expected.to_string(), String::from_utf8(buffer).unwrap());
}
@@ -512,7 +536,7 @@ sed do eiusmod tempor,-556132.25,1,,2019-04-18T02:45:55.555000000,23:46:03,foo
let mut file = tempfile::tempfile().unwrap();
let builder = WriterBuilder::new()
- .has_headers(false)
+ .with_header(false)
.with_delimiter(b'|')
.with_null("NULL".to_string())
.with_time_format("%r".to_string());
@@ -560,7 +584,7 @@ sed do eiusmod tempor,-556132.25,1,,2019-04-18T02:45:55.555000000,23:46:03,foo
)
.unwrap();
- let builder = WriterBuilder::new().has_headers(false);
+ let builder = WriterBuilder::new().with_header(false);
let mut buf: Cursor<Vec<u8>> = Default::default();
// drop the writer early to release the borrow.
@@ -652,7 +676,7 @@ sed do eiusmod tempor,-556132.25,1,,2019-04-18T02:45:55.555000000,23:46:03,foo
let mut file = tempfile::tempfile().unwrap();
- let builder = WriterBuilder::new().with_rfc3339();
+ let builder = WriterBuilder::new();
let mut writer = builder.build(&mut file);
let batches = vec![&batch];
for batch in batches {
|
diff --git a/arrow/tests/csv.rs b/arrow/tests/csv.rs
index 3ee319101757..a79b6b44c2d3 100644
--- a/arrow/tests/csv.rs
+++ b/arrow/tests/csv.rs
@@ -53,48 +53,6 @@ fn test_export_csv_timestamps() {
}
drop(writer);
- let left = "c1,c2
-2019-04-18T20:54:47.378000000+10:00,2019-04-18T10:54:47.378000000
-2021-10-30T17:59:07.000000000+11:00,2021-10-30T06:59:07.000000000\n";
- let right = String::from_utf8(sw).unwrap();
- assert_eq!(left, right);
-}
-
-#[test]
-fn test_export_csv_timestamps_using_rfc3339() {
- let schema = Schema::new(vec![
- Field::new(
- "c1",
- DataType::Timestamp(TimeUnit::Millisecond, Some("Australia/Sydney".into())),
- true,
- ),
- Field::new("c2", DataType::Timestamp(TimeUnit::Millisecond, None), true),
- ]);
-
- let c1 = TimestampMillisecondArray::from(
- // 1555584887 converts to 2019-04-18, 20:54:47 in time zone Australia/Sydney (AEST).
- // The offset (difference to UTC) is +10:00.
- // 1635577147 converts to 2021-10-30 17:59:07 in time zone Australia/Sydney (AEDT)
- // The offset (difference to UTC) is +11:00. Note that daylight savings is in effect on 2021-10-30.
- //
- vec![Some(1555584887378), Some(1635577147000)],
- )
- .with_timezone("Australia/Sydney");
- let c2 =
- TimestampMillisecondArray::from(vec![Some(1555584887378), Some(1635577147000)]);
- let batch =
- RecordBatch::try_new(Arc::new(schema), vec![Arc::new(c1), Arc::new(c2)]).unwrap();
-
- let mut sw = Vec::new();
- let mut writer = arrow_csv::WriterBuilder::new()
- .with_rfc3339()
- .build(&mut sw);
- let batches = vec![&batch];
- for batch in batches {
- writer.write(batch).unwrap();
- }
- drop(writer);
-
let left = "c1,c2
2019-04-18T20:54:47.378+10:00,2019-04-18T10:54:47.378
2021-10-30T17:59:07+11:00,2021-10-30T06:59:07\n";
|
Add read access to settings in `csv::WriterBuilder`
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
While implementing CSV writing in DataFusion (see https://github.com/apache/arrow-datafusion/pull/7390/files), we would like to be able to check the value of `has_headers` before actually constructing a csv writer. However, the current API has no way to do read the current values (only modify them): https://docs.rs/arrow-csv/45.0.0/arrow_csv/writer/struct.WriterBuilder.html
**Describe the solution you'd like**
It would be nice to have read only access to the fields. Maybe something like
```rust
let builder = WriterBuilder::new().has_headers(false);
let has_headers = builder.get_has_headers()
```
It is somewhat unfortunate that the builder already uses `has_headers` to set the field names rather than `with_has_headers`
**Describe alternatives you've considered**
We can keep a copy of has_headers around as @devinjdangelo has done in https://github.com/apache/arrow-datafusion/pull/7390/files
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
|
Looks it is easy.
|
2023-10-09T16:11:31Z
|
47.0
|
fa7a61a4b074ca4ec9bf429cc84b6c325057d96e
|
apache/arrow-rs
| 4,808
|
apache__arrow-rs-4808
|
[
"4807"
] |
878217b9e330b4f1ed13e798a214ea11fbeb2bbb
|
diff --git a/arrow-array/src/array/map_array.rs b/arrow-array/src/array/map_array.rs
index fca49cd7836f..77a7b9d4d547 100644
--- a/arrow-array/src/array/map_array.rs
+++ b/arrow-array/src/array/map_array.rs
@@ -330,7 +330,7 @@ impl MapArray {
Arc::new(Field::new(
"entries",
entry_struct.data_type().clone(),
- true,
+ false,
)),
false,
);
@@ -477,7 +477,7 @@ mod tests {
Arc::new(Field::new(
"entries",
entry_struct.data_type().clone(),
- true,
+ false,
)),
false,
);
@@ -523,7 +523,7 @@ mod tests {
Arc::new(Field::new(
"entries",
entry_struct.data_type().clone(),
- true,
+ false,
)),
false,
);
@@ -645,7 +645,7 @@ mod tests {
Arc::new(Field::new(
"entries",
entry_struct.data_type().clone(),
- true,
+ false,
)),
false,
);
diff --git a/arrow-ipc/src/reader.rs b/arrow-ipc/src/reader.rs
index 96cb4393ba58..75c91be21dde 100644
--- a/arrow-ipc/src/reader.rs
+++ b/arrow-ipc/src/reader.rs
@@ -1487,7 +1487,7 @@ mod tests {
let keys_field = Arc::new(Field::new_dict(
"keys",
DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Utf8)),
- true,
+ true, // It is technically not legal for this field to be null.
1,
false,
));
@@ -1506,7 +1506,7 @@ mod tests {
Arc::new(Field::new(
"entries",
entry_struct.data_type().clone(),
- true,
+ false,
)),
false,
);
diff --git a/arrow-json/src/writer.rs b/arrow-json/src/writer.rs
index a918f44b54ff..a5b5a78190b3 100644
--- a/arrow-json/src/writer.rs
+++ b/arrow-json/src/writer.rs
@@ -1385,7 +1385,7 @@ mod tests {
Arc::new(Field::new(
"entries",
entry_struct.data_type().clone(),
- true,
+ false,
)),
false,
);
diff --git a/arrow-schema/src/ffi.rs b/arrow-schema/src/ffi.rs
index cd3c207a56c5..a17dbe769f2e 100644
--- a/arrow-schema/src/ffi.rs
+++ b/arrow-schema/src/ffi.rs
@@ -833,7 +833,7 @@ mod tests {
// Construct a map array from the above two
let map_data_type =
- DataType::Map(Arc::new(Field::new("entries", entry_struct, true)), true);
+ DataType::Map(Arc::new(Field::new("entries", entry_struct, false)), true);
let arrow_schema = FFI_ArrowSchema::try_from(map_data_type).unwrap();
assert!(arrow_schema.map_keys_sorted());
|
diff --git a/arrow-integration-testing/src/bin/arrow-json-integration-test.rs b/arrow-integration-testing/src/bin/arrow-json-integration-test.rs
index 2c36e8d9b8ae..db5df8b58a6f 100644
--- a/arrow-integration-testing/src/bin/arrow-json-integration-test.rs
+++ b/arrow-integration-testing/src/bin/arrow-json-integration-test.rs
@@ -124,7 +124,7 @@ fn canonicalize_schema(schema: &Schema) -> Schema {
let key_field = Arc::new(Field::new(
"key",
first_field.data_type().clone(),
- first_field.is_nullable(),
+ false,
));
let second_field = fields.get(1).unwrap();
let value_field = Arc::new(Field::new(
@@ -135,8 +135,7 @@ fn canonicalize_schema(schema: &Schema) -> Schema {
let fields = Fields::from([key_field, value_field]);
let struct_type = DataType::Struct(fields);
- let child_field =
- Field::new("entries", struct_type, child_field.is_nullable());
+ let child_field = Field::new("entries", struct_type, false);
Arc::new(Field::new(
field.name().as_str(),
|
MapArray::new_from_strings creates nullable entries field
**Describe the bug**
This line creates a nullable entries field:
https://github.com/apache/arrow-rs/blob/878217b9e330b4f1ed13e798a214ea11fbeb2bbb/arrow-array/src/array/map_array.rs#L330-L334
The Arrow spec dictates this should not be nullable:
https://github.com/apache/arrow/blob/c4b01c60fba85bbfc3a1b1510e179153c0f79515/format/Schema.fbs#L124
**To Reproduce**
<!--
Steps to reproduce the behavior:
-->
**Expected behavior**
Creates a compliant map array.
**Additional context**
<!--
Add any other context about the problem here.
-->
|
2023-09-10T00:06:58Z
|
46.0
|
878217b9e330b4f1ed13e798a214ea11fbeb2bbb
|
|
apache/arrow-rs
| 4,806
|
apache__arrow-rs-4806
|
[
"4805"
] |
878217b9e330b4f1ed13e798a214ea11fbeb2bbb
|
diff --git a/arrow/src/pyarrow.rs b/arrow/src/pyarrow.rs
index 6063ae763228..ab0ea8ef8d74 100644
--- a/arrow/src/pyarrow.rs
+++ b/arrow/src/pyarrow.rs
@@ -59,14 +59,14 @@ use std::convert::{From, TryFrom};
use std::ptr::{addr_of, addr_of_mut};
use std::sync::Arc;
-use arrow_array::RecordBatchReader;
+use arrow_array::{RecordBatchIterator, RecordBatchReader};
use pyo3::exceptions::{PyTypeError, PyValueError};
use pyo3::ffi::Py_uintptr_t;
use pyo3::import_exception;
use pyo3::prelude::*;
-use pyo3::types::{PyDict, PyList, PyTuple};
+use pyo3::types::{PyList, PyTuple};
-use crate::array::{make_array, Array, ArrayData};
+use crate::array::{make_array, ArrayData};
use crate::datatypes::{DataType, Field, Schema};
use crate::error::ArrowError;
use crate::ffi;
@@ -270,25 +270,12 @@ impl FromPyArrow for RecordBatch {
impl ToPyArrow for RecordBatch {
fn to_pyarrow(&self, py: Python) -> PyResult<PyObject> {
- let mut py_arrays = vec![];
-
- let schema = self.schema();
- let columns = self.columns().iter();
-
- for array in columns {
- py_arrays.push(array.to_data().to_pyarrow(py)?);
- }
-
- let py_schema = schema.to_pyarrow(py)?;
-
- let module = py.import("pyarrow")?;
- let class = module.getattr("RecordBatch")?;
- let args = (py_arrays,);
- let kwargs = PyDict::new(py);
- kwargs.set_item("schema", py_schema)?;
- let record = class.call_method("from_arrays", args, Some(kwargs))?;
-
- Ok(PyObject::from(record))
+ // Workaround apache/arrow#37669 by returning RecordBatchIterator
+ let reader =
+ RecordBatchIterator::new(vec![Ok(self.clone())], self.schema().clone());
+ let reader: Box<dyn RecordBatchReader + Send> = Box::new(reader);
+ let py_reader = reader.into_pyarrow(py)?;
+ py_reader.call_method0(py, "read_next_batch")
}
}
|
diff --git a/arrow-pyarrow-integration-testing/tests/test_sql.py b/arrow-pyarrow-integration-testing/tests/test_sql.py
index 3be5b9ec52fe..1748fd3ffb6b 100644
--- a/arrow-pyarrow-integration-testing/tests/test_sql.py
+++ b/arrow-pyarrow-integration-testing/tests/test_sql.py
@@ -393,6 +393,23 @@ def test_sparse_union_python():
del a
del b
+def test_tensor_array():
+ tensor_type = pa.fixed_shape_tensor(pa.float32(), [2, 3])
+ inner = pa.array([float(x) for x in range(1, 7)] + [None] * 12, pa.float32())
+ storage = pa.FixedSizeListArray.from_arrays(inner, 6)
+ f32_array = pa.ExtensionArray.from_storage(tensor_type, storage)
+
+ # Round-tripping as an array gives back storage type, because arrow-rs has
+ # no notion of extension types.
+ b = rust.round_trip_array(f32_array)
+ assert b == f32_array.storage
+
+ batch = pa.record_batch([f32_array], ["tensor"])
+ b = rust.round_trip_record_batch(batch)
+ assert b == batch
+
+ del b
+
def test_record_batch_reader():
"""
Python -> Rust -> Python
|
pyarrow module can't roundtrip tensor arrays
**Describe the bug**
When exporting a tensor array (a kind of extension array) as a record batch, PyArrow segfaults. This does not happen if the batch is exported as a stream.
**To Reproduce**
The following test will fail in `arrow-pyarrow-integration-testing/tests/test_sql.py`:
```python
def test_tensor_array():
tensor_type = pa.fixed_shape_tensor(pa.float32(), [2, 3])
inner = pa.array([float(x) for x in range(1, 7)] + [None] * 12, pa.float32())
storage = pa.FixedSizeListArray.from_arrays(inner, 6)
f32_array = pa.ExtensionArray.from_storage(tensor_type, storage)
# Round-tripping as an array gives back storage type, because arrow-rs has
# no notion of extension types.
b = rust.round_trip_array(f32_array)
assert b == f32_array.storage
batch = pa.record_batch([f32_array], ["tensor"])
b = rust.round_trip_record_batch(batch)
assert b == batch
del b
```
**Expected behavior**
We should round trip the array type successfully.
**Additional context**
The record batch exporting is done by exporting each individual array, but this separates the extension arrays from their metadata. I suspect PyArrow segfaults because it is receiving a plain array and then later told it is an extension in the final schema.
|
2023-09-09T19:32:20Z
|
46.0
|
878217b9e330b4f1ed13e798a214ea11fbeb2bbb
|
|
apache/arrow-rs
| 4,797
|
apache__arrow-rs-4797
|
[
"4658",
"3598"
] |
15dde87d4ecefadedb22a1df1aeebc0a09cfab0e
|
diff --git a/arrow-flight/examples/flight_sql_server.rs b/arrow-flight/examples/flight_sql_server.rs
index 1e99957390d8..d1aeae6f0a6c 100644
--- a/arrow-flight/examples/flight_sql_server.rs
+++ b/arrow-flight/examples/flight_sql_server.rs
@@ -15,6 +15,7 @@
// specific language governing permissions and limitations
// under the License.
+use arrow_flight::sql::server::PeekableFlightDataStream;
use base64::prelude::BASE64_STANDARD;
use base64::Engine;
use futures::{stream, Stream, TryStreamExt};
@@ -602,7 +603,7 @@ impl FlightSqlService for FlightSqlServiceImpl {
async fn do_put_statement_update(
&self,
_ticket: CommandStatementUpdate,
- _request: Request<Streaming<FlightData>>,
+ _request: Request<PeekableFlightDataStream>,
) -> Result<i64, Status> {
Ok(FAKE_UPDATE_RESULT)
}
@@ -610,7 +611,7 @@ impl FlightSqlService for FlightSqlServiceImpl {
async fn do_put_substrait_plan(
&self,
_ticket: CommandStatementSubstraitPlan,
- _request: Request<Streaming<FlightData>>,
+ _request: Request<PeekableFlightDataStream>,
) -> Result<i64, Status> {
Err(Status::unimplemented(
"do_put_substrait_plan not implemented",
@@ -620,7 +621,7 @@ impl FlightSqlService for FlightSqlServiceImpl {
async fn do_put_prepared_statement_query(
&self,
_query: CommandPreparedStatementQuery,
- _request: Request<Streaming<FlightData>>,
+ _request: Request<PeekableFlightDataStream>,
) -> Result<Response<<Self as FlightService>::DoPutStream>, Status> {
Err(Status::unimplemented(
"do_put_prepared_statement_query not implemented",
@@ -630,7 +631,7 @@ impl FlightSqlService for FlightSqlServiceImpl {
async fn do_put_prepared_statement_update(
&self,
_query: CommandPreparedStatementUpdate,
- _request: Request<Streaming<FlightData>>,
+ _request: Request<PeekableFlightDataStream>,
) -> Result<i64, Status> {
Err(Status::unimplemented(
"do_put_prepared_statement_update not implemented",
diff --git a/arrow-flight/src/bin/flight_sql_client.rs b/arrow-flight/src/bin/flight_sql_client.rs
index 20c8062f899e..d7b02414c5cc 100644
--- a/arrow-flight/src/bin/flight_sql_client.rs
+++ b/arrow-flight/src/bin/flight_sql_client.rs
@@ -15,15 +15,16 @@
// specific language governing permissions and limitations
// under the License.
-use std::{sync::Arc, time::Duration};
+use std::{error::Error, sync::Arc, time::Duration};
-use arrow_array::RecordBatch;
-use arrow_cast::pretty::pretty_format_batches;
+use arrow_array::{ArrayRef, Datum, RecordBatch, StringArray};
+use arrow_cast::{cast_with_options, pretty::pretty_format_batches, CastOptions};
use arrow_flight::{
sql::client::FlightSqlServiceClient, utils::flight_data_to_batches, FlightData,
+ FlightInfo,
};
use arrow_schema::{ArrowError, Schema};
-use clap::Parser;
+use clap::{Parser, Subcommand};
use futures::TryStreamExt;
use tonic::transport::{Channel, ClientTlsConfig, Endpoint};
use tracing_log::log::info;
@@ -98,8 +99,20 @@ struct Args {
#[clap(flatten)]
client_args: ClientArgs,
- /// SQL query.
- query: String,
+ #[clap(subcommand)]
+ cmd: Command,
+}
+
+#[derive(Debug, Subcommand)]
+enum Command {
+ StatementQuery {
+ query: String,
+ },
+ PreparedStatementQuery {
+ query: String,
+ #[clap(short, value_parser = parse_key_val)]
+ params: Vec<(String, String)>,
+ },
}
#[tokio::main]
@@ -108,12 +121,50 @@ async fn main() {
setup_logging();
let mut client = setup_client(args.client_args).await.expect("setup client");
- let info = client
- .execute(args.query, None)
+ let flight_info = match args.cmd {
+ Command::StatementQuery { query } => client
+ .execute(query, None)
+ .await
+ .expect("execute statement"),
+ Command::PreparedStatementQuery { query, params } => {
+ let mut prepared_stmt = client
+ .prepare(query, None)
+ .await
+ .expect("prepare statement");
+
+ if !params.is_empty() {
+ prepared_stmt
+ .set_parameters(
+ construct_record_batch_from_params(
+ ¶ms,
+ prepared_stmt
+ .parameter_schema()
+ .expect("get parameter schema"),
+ )
+ .expect("construct parameters"),
+ )
+ .expect("bind parameters")
+ }
+
+ prepared_stmt
+ .execute()
+ .await
+ .expect("execute prepared statement")
+ }
+ };
+
+ let batches = execute_flight(&mut client, flight_info)
.await
- .expect("prepare statement");
- info!("got flight info");
+ .expect("read flight data");
+ let res = pretty_format_batches(batches.as_slice()).expect("format results");
+ println!("{res}");
+}
+
+async fn execute_flight(
+ client: &mut FlightSqlServiceClient<Channel>,
+ info: FlightInfo,
+) -> Result<Vec<RecordBatch>, ArrowError> {
let schema = Arc::new(Schema::try_from(info.clone()).expect("valid schema"));
let mut batches = Vec::with_capacity(info.endpoint.len() + 1);
batches.push(RecordBatch::new_empty(schema));
@@ -134,8 +185,27 @@ async fn main() {
}
info!("received data");
- let res = pretty_format_batches(batches.as_slice()).expect("format results");
- println!("{res}");
+ Ok(batches)
+}
+
+fn construct_record_batch_from_params(
+ params: &[(String, String)],
+ parameter_schema: &Schema,
+) -> Result<RecordBatch, ArrowError> {
+ let mut items = Vec::<(&String, ArrayRef)>::new();
+
+ for (name, value) in params {
+ let field = parameter_schema.field_with_name(name)?;
+ let value_as_array = StringArray::new_scalar(value);
+ let casted = cast_with_options(
+ value_as_array.get().0,
+ field.data_type(),
+ &CastOptions::default(),
+ )?;
+ items.push((name, casted))
+ }
+
+ RecordBatch::try_from_iter(items)
}
fn setup_logging() {
@@ -203,3 +273,13 @@ async fn setup_client(
Ok(client)
}
+
+/// Parse a single key-value pair
+fn parse_key_val(
+ s: &str,
+) -> Result<(String, String), Box<dyn Error + Send + Sync + 'static>> {
+ let pos = s
+ .find('=')
+ .ok_or_else(|| format!("invalid KEY=value: no `=` found in `{s}`"))?;
+ Ok((s[..pos].parse()?, s[pos + 1..].parse()?))
+}
diff --git a/arrow-flight/src/sql/client.rs b/arrow-flight/src/sql/client.rs
index 4b1f38ebcbb7..2d382cf2ca20 100644
--- a/arrow-flight/src/sql/client.rs
+++ b/arrow-flight/src/sql/client.rs
@@ -24,6 +24,8 @@ use std::collections::HashMap;
use std::str::FromStr;
use tonic::metadata::AsciiMetadataKey;
+use crate::encode::FlightDataEncoderBuilder;
+use crate::error::FlightError;
use crate::flight_service_client::FlightServiceClient;
use crate::sql::server::{CLOSE_PREPARED_STATEMENT, CREATE_PREPARED_STATEMENT};
use crate::sql::{
@@ -32,8 +34,8 @@ use crate::sql::{
CommandGetCrossReference, CommandGetDbSchemas, CommandGetExportedKeys,
CommandGetImportedKeys, CommandGetPrimaryKeys, CommandGetSqlInfo,
CommandGetTableTypes, CommandGetTables, CommandGetXdbcTypeInfo,
- CommandPreparedStatementQuery, CommandStatementQuery, CommandStatementUpdate,
- DoPutUpdateResult, ProstMessageExt, SqlInfo,
+ CommandPreparedStatementQuery, CommandPreparedStatementUpdate, CommandStatementQuery,
+ CommandStatementUpdate, DoPutUpdateResult, ProstMessageExt, SqlInfo,
};
use crate::{
Action, FlightData, FlightDescriptor, FlightInfo, HandshakeRequest,
@@ -439,9 +441,12 @@ impl PreparedStatement<Channel> {
/// Executes the prepared statement query on the server.
pub async fn execute(&mut self) -> Result<FlightInfo, ArrowError> {
+ self.write_bind_params().await?;
+
let cmd = CommandPreparedStatementQuery {
prepared_statement_handle: self.handle.clone(),
};
+
let result = self
.flight_sql_client
.get_flight_info_for_command(cmd)
@@ -451,7 +456,9 @@ impl PreparedStatement<Channel> {
/// Executes the prepared statement update query on the server.
pub async fn execute_update(&mut self) -> Result<i64, ArrowError> {
- let cmd = CommandPreparedStatementQuery {
+ self.write_bind_params().await?;
+
+ let cmd = CommandPreparedStatementUpdate {
prepared_statement_handle: self.handle.clone(),
};
let descriptor = FlightDescriptor::new_cmd(cmd.as_any().encode_to_vec());
@@ -492,6 +499,36 @@ impl PreparedStatement<Channel> {
Ok(())
}
+ /// Submit parameters to the server, if any have been set on this prepared statement instance
+ async fn write_bind_params(&mut self) -> Result<(), ArrowError> {
+ if let Some(ref params_batch) = self.parameter_binding {
+ let cmd = CommandPreparedStatementQuery {
+ prepared_statement_handle: self.handle.clone(),
+ };
+
+ let descriptor = FlightDescriptor::new_cmd(cmd.as_any().encode_to_vec());
+ let flight_stream_builder = FlightDataEncoderBuilder::new()
+ .with_flight_descriptor(Some(descriptor))
+ .with_schema(params_batch.schema());
+ let flight_data = flight_stream_builder
+ .build(futures::stream::iter(
+ self.parameter_binding.clone().map(Ok),
+ ))
+ .try_collect::<Vec<_>>()
+ .await
+ .map_err(flight_error_to_arrow_error)?;
+
+ self.flight_sql_client
+ .do_put(stream::iter(flight_data))
+ .await?
+ .try_collect::<Vec<_>>()
+ .await
+ .map_err(status_to_arrow_error)?;
+ }
+
+ Ok(())
+ }
+
/// Close the prepared statement, so that this PreparedStatement can not used
/// anymore and server can free up any resources.
pub async fn close(mut self) -> Result<(), ArrowError> {
@@ -515,6 +552,13 @@ fn status_to_arrow_error(status: tonic::Status) -> ArrowError {
ArrowError::IpcError(format!("{status:?}"))
}
+fn flight_error_to_arrow_error(err: FlightError) -> ArrowError {
+ match err {
+ FlightError::Arrow(e) => e,
+ e => ArrowError::ExternalError(Box::new(e)),
+ }
+}
+
// A polymorphic structure to natively represent different types of data contained in `FlightData`
pub enum ArrowFlightData {
RecordBatch(RecordBatch),
diff --git a/arrow-flight/src/sql/server.rs b/arrow-flight/src/sql/server.rs
index 102d97105a2e..a158ed77f54d 100644
--- a/arrow-flight/src/sql/server.rs
+++ b/arrow-flight/src/sql/server.rs
@@ -19,7 +19,7 @@
use std::pin::Pin;
-use futures::Stream;
+use futures::{stream::Peekable, Stream, StreamExt};
use prost::Message;
use tonic::{Request, Response, Status, Streaming};
@@ -366,7 +366,7 @@ pub trait FlightSqlService: Sync + Send + Sized + 'static {
/// Implementors may override to handle additional calls to do_put()
async fn do_put_fallback(
&self,
- _request: Request<Streaming<FlightData>>,
+ _request: Request<PeekableFlightDataStream>,
message: Any,
) -> Result<Response<<Self as FlightService>::DoPutStream>, Status> {
Err(Status::unimplemented(format!(
@@ -379,7 +379,7 @@ pub trait FlightSqlService: Sync + Send + Sized + 'static {
async fn do_put_statement_update(
&self,
_ticket: CommandStatementUpdate,
- _request: Request<Streaming<FlightData>>,
+ _request: Request<PeekableFlightDataStream>,
) -> Result<i64, Status> {
Err(Status::unimplemented(
"do_put_statement_update has no default implementation",
@@ -390,7 +390,7 @@ pub trait FlightSqlService: Sync + Send + Sized + 'static {
async fn do_put_prepared_statement_query(
&self,
_query: CommandPreparedStatementQuery,
- _request: Request<Streaming<FlightData>>,
+ _request: Request<PeekableFlightDataStream>,
) -> Result<Response<<Self as FlightService>::DoPutStream>, Status> {
Err(Status::unimplemented(
"do_put_prepared_statement_query has no default implementation",
@@ -401,7 +401,7 @@ pub trait FlightSqlService: Sync + Send + Sized + 'static {
async fn do_put_prepared_statement_update(
&self,
_query: CommandPreparedStatementUpdate,
- _request: Request<Streaming<FlightData>>,
+ _request: Request<PeekableFlightDataStream>,
) -> Result<i64, Status> {
Err(Status::unimplemented(
"do_put_prepared_statement_update has no default implementation",
@@ -412,7 +412,7 @@ pub trait FlightSqlService: Sync + Send + Sized + 'static {
async fn do_put_substrait_plan(
&self,
_query: CommandStatementSubstraitPlan,
- _request: Request<Streaming<FlightData>>,
+ _request: Request<PeekableFlightDataStream>,
) -> Result<i64, Status> {
Err(Status::unimplemented(
"do_put_substrait_plan has no default implementation",
@@ -688,9 +688,17 @@ where
async fn do_put(
&self,
- mut request: Request<Streaming<FlightData>>,
+ request: Request<Streaming<FlightData>>,
) -> Result<Response<Self::DoPutStream>, Status> {
- let cmd = request.get_mut().message().await?.unwrap();
+ // See issue #4658: https://github.com/apache/arrow-rs/issues/4658
+ // To dispatch to the correct `do_put` method, we cannot discard the first message,
+ // as it may contain the Arrow schema, which the `do_put` handler may need.
+ // To allow the first message to be reused by the `do_put` handler,
+ // we wrap this stream in a `Peekable` one, which allows us to peek at
+ // the first message without discarding it.
+ let mut request = request.map(PeekableFlightDataStream::new);
+ let cmd = Pin::new(request.get_mut()).peek().await.unwrap().clone()?;
+
let message = Any::decode(&*cmd.flight_descriptor.unwrap().cmd)
.map_err(decode_error_to_status)?;
match Command::try_from(message).map_err(arrow_error_to_status)? {
@@ -957,3 +965,89 @@ fn decode_error_to_status(err: prost::DecodeError) -> Status {
fn arrow_error_to_status(err: arrow_schema::ArrowError) -> Status {
Status::internal(format!("{err:?}"))
}
+
+/// A wrapper around [`Streaming<FlightData>`] that allows "peeking" at the
+/// message at the front of the stream without consuming it.
+/// This is needed because sometimes the first message in the stream will contain
+/// a [`FlightDescriptor`] in addition to potentially any data, and the dispatch logic
+/// must inspect this information.
+///
+/// # Example
+///
+/// [`PeekableFlightDataStream::peek`] can be used to peek at the first message without
+/// discarding it; otherwise, `PeekableFlightDataStream` can be used as a regular stream.
+/// See the following example:
+///
+/// ```no_run
+/// use arrow_array::RecordBatch;
+/// use arrow_flight::decode::FlightRecordBatchStream;
+/// use arrow_flight::FlightDescriptor;
+/// use arrow_flight::error::FlightError;
+/// use arrow_flight::sql::server::PeekableFlightDataStream;
+/// use tonic::{Request, Status};
+/// use futures::TryStreamExt;
+///
+/// #[tokio::main]
+/// async fn main() -> Result<(), Status> {
+/// let request: Request<PeekableFlightDataStream> = todo!();
+/// let stream: PeekableFlightDataStream = request.into_inner();
+///
+/// // The first message contains the flight descriptor and the schema.
+/// // Read the flight descriptor without discarding the schema:
+/// let flight_descriptor: FlightDescriptor = stream
+/// .peek()
+/// .await
+/// .cloned()
+/// .transpose()?
+/// .and_then(|data| data.flight_descriptor)
+/// .expect("first message should contain flight descriptor");
+///
+/// // Pass the stream through a decoder
+/// let batches: Vec<RecordBatch> = FlightRecordBatchStream::new_from_flight_data(
+/// request.into_inner().map_err(|e| e.into()),
+/// )
+/// .try_collect()
+/// .await?;
+/// }
+/// ```
+pub struct PeekableFlightDataStream {
+ inner: Peekable<Streaming<FlightData>>,
+}
+
+impl PeekableFlightDataStream {
+ fn new(stream: Streaming<FlightData>) -> Self {
+ Self {
+ inner: stream.peekable(),
+ }
+ }
+
+ /// Convert this stream into a `Streaming<FlightData>`.
+ /// Any messages observed through [`Self::peek`] will be lost
+ /// after the conversion.
+ pub fn into_inner(self) -> Streaming<FlightData> {
+ self.inner.into_inner()
+ }
+
+ /// Convert this stream into a `Peekable<Streaming<FlightData>>`.
+ /// Preserves the state of the stream, so that calls to [`Self::peek`]
+ /// and [`Self::poll_next`] are the same.
+ pub fn into_peekable(self) -> Peekable<Streaming<FlightData>> {
+ self.inner
+ }
+
+ /// Peek at the head of this stream without advancing it.
+ pub async fn peek(&mut self) -> Option<&Result<FlightData, Status>> {
+ Pin::new(&mut self.inner).peek().await
+ }
+}
+
+impl Stream for PeekableFlightDataStream {
+ type Item = Result<FlightData, Status>;
+
+ fn poll_next(
+ mut self: Pin<&mut Self>,
+ cx: &mut std::task::Context<'_>,
+ ) -> std::task::Poll<Option<Self::Item>> {
+ self.inner.poll_next_unpin(cx)
+ }
+}
|
diff --git a/arrow-flight/tests/flight_sql_client_cli.rs b/arrow-flight/tests/flight_sql_client_cli.rs
index 912bcc75a9df..221e776218c3 100644
--- a/arrow-flight/tests/flight_sql_client_cli.rs
+++ b/arrow-flight/tests/flight_sql_client_cli.rs
@@ -19,11 +19,13 @@ use std::{net::SocketAddr, pin::Pin, sync::Arc, time::Duration};
use arrow_array::{ArrayRef, Int64Array, RecordBatch, StringArray};
use arrow_flight::{
+ decode::FlightRecordBatchStream,
flight_service_server::{FlightService, FlightServiceServer},
sql::{
- server::FlightSqlService, ActionBeginSavepointRequest,
- ActionBeginSavepointResult, ActionBeginTransactionRequest,
- ActionBeginTransactionResult, ActionCancelQueryRequest, ActionCancelQueryResult,
+ server::{FlightSqlService, PeekableFlightDataStream},
+ ActionBeginSavepointRequest, ActionBeginSavepointResult,
+ ActionBeginTransactionRequest, ActionBeginTransactionResult,
+ ActionCancelQueryRequest, ActionCancelQueryResult,
ActionClosePreparedStatementRequest, ActionCreatePreparedStatementRequest,
ActionCreatePreparedStatementResult, ActionCreatePreparedSubstraitPlanRequest,
ActionEndSavepointRequest, ActionEndTransactionRequest, Any, CommandGetCatalogs,
@@ -36,18 +38,20 @@ use arrow_flight::{
},
utils::batches_to_flight_data,
Action, FlightData, FlightDescriptor, FlightEndpoint, FlightInfo, HandshakeRequest,
- HandshakeResponse, Ticket,
+ HandshakeResponse, IpcMessage, PutResult, SchemaAsIpc, Ticket,
};
+use arrow_ipc::writer::IpcWriteOptions;
use arrow_schema::{ArrowError, DataType, Field, Schema};
use assert_cmd::Command;
-use futures::Stream;
+use bytes::Bytes;
+use futures::{Stream, StreamExt, TryStreamExt};
use prost::Message;
use tokio::{net::TcpListener, task::JoinHandle};
use tonic::{Request, Response, Status, Streaming};
const QUERY: &str = "SELECT * FROM table;";
-#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
+#[tokio::test]
async fn test_simple() {
let test_server = FlightSqlServiceImpl {};
let fixture = TestFixture::new(&test_server).await;
@@ -63,6 +67,7 @@ async fn test_simple() {
.arg(addr.ip().to_string())
.arg("--port")
.arg(addr.port().to_string())
+ .arg("statement-query")
.arg(QUERY)
.assert()
.success()
@@ -87,10 +92,56 @@ async fn test_simple() {
);
}
+const PREPARED_QUERY: &str = "SELECT * FROM table WHERE field = $1";
+const PREPARED_STATEMENT_HANDLE: &str = "prepared_statement_handle";
+
+#[tokio::test]
+async fn test_do_put_prepared_statement() {
+ let test_server = FlightSqlServiceImpl {};
+ let fixture = TestFixture::new(&test_server).await;
+ let addr = fixture.addr;
+
+ let stdout = tokio::task::spawn_blocking(move || {
+ Command::cargo_bin("flight_sql_client")
+ .unwrap()
+ .env_clear()
+ .env("RUST_BACKTRACE", "1")
+ .env("RUST_LOG", "warn")
+ .arg("--host")
+ .arg(addr.ip().to_string())
+ .arg("--port")
+ .arg(addr.port().to_string())
+ .arg("prepared-statement-query")
+ .arg(PREPARED_QUERY)
+ .args(["-p", "$1=string"])
+ .args(["-p", "$2=64"])
+ .assert()
+ .success()
+ .get_output()
+ .stdout
+ .clone()
+ })
+ .await
+ .unwrap();
+
+ fixture.shutdown_and_wait().await;
+
+ assert_eq!(
+ std::str::from_utf8(&stdout).unwrap().trim(),
+ "+--------------+-----------+\
+ \n| field_string | field_int |\
+ \n+--------------+-----------+\
+ \n| Hello | 42 |\
+ \n| lovely | |\
+ \n| FlightSQL! | 1337 |\
+ \n+--------------+-----------+",
+ );
+}
+
/// All tests must complete within this many seconds or else the test server is shutdown
const DEFAULT_TIMEOUT_SECONDS: u64 = 30;
-#[derive(Clone)]
+#[derive(Clone, Default)]
pub struct FlightSqlServiceImpl {}
impl FlightSqlServiceImpl {
@@ -116,6 +167,59 @@ impl FlightSqlServiceImpl {
];
RecordBatch::try_new(Arc::new(schema), cols)
}
+
+ fn create_fake_prepared_stmt(
+ ) -> Result<ActionCreatePreparedStatementResult, ArrowError> {
+ let handle = PREPARED_STATEMENT_HANDLE.to_string();
+ let schema = Schema::new(vec![
+ Field::new("field_string", DataType::Utf8, false),
+ Field::new("field_int", DataType::Int64, true),
+ ]);
+
+ let parameter_schema = Schema::new(vec![
+ Field::new("$1", DataType::Utf8, false),
+ Field::new("$2", DataType::Int64, true),
+ ]);
+
+ Ok(ActionCreatePreparedStatementResult {
+ prepared_statement_handle: handle.into(),
+ dataset_schema: serialize_schema(&schema)?,
+ parameter_schema: serialize_schema(¶meter_schema)?,
+ })
+ }
+
+ fn fake_flight_info(&self) -> Result<FlightInfo, ArrowError> {
+ let batch = Self::fake_result()?;
+
+ Ok(FlightInfo::new()
+ .try_with_schema(&batch.schema())
+ .expect("encoding schema")
+ .with_endpoint(
+ FlightEndpoint::new().with_ticket(Ticket::new(
+ FetchResults {
+ handle: String::from("part_1"),
+ }
+ .as_any()
+ .encode_to_vec(),
+ )),
+ )
+ .with_endpoint(
+ FlightEndpoint::new().with_ticket(Ticket::new(
+ FetchResults {
+ handle: String::from("part_2"),
+ }
+ .as_any()
+ .encode_to_vec(),
+ )),
+ )
+ .with_total_records(batch.num_rows() as i64)
+ .with_total_bytes(batch.get_array_memory_size() as i64)
+ .with_ordered(false))
+ }
+}
+
+fn serialize_schema(schema: &Schema) -> Result<Bytes, ArrowError> {
+ Ok(IpcMessage::try_from(SchemaAsIpc::new(schema, &IpcWriteOptions::default()))?.0)
}
#[tonic::async_trait]
@@ -164,45 +268,21 @@ impl FlightSqlService for FlightSqlServiceImpl {
) -> Result<Response<FlightInfo>, Status> {
assert_eq!(query.query, QUERY);
- let batch = Self::fake_result().unwrap();
-
- let info = FlightInfo::new()
- .try_with_schema(&batch.schema())
- .expect("encoding schema")
- .with_endpoint(
- FlightEndpoint::new().with_ticket(Ticket::new(
- FetchResults {
- handle: String::from("part_1"),
- }
- .as_any()
- .encode_to_vec(),
- )),
- )
- .with_endpoint(
- FlightEndpoint::new().with_ticket(Ticket::new(
- FetchResults {
- handle: String::from("part_2"),
- }
- .as_any()
- .encode_to_vec(),
- )),
- )
- .with_total_records(batch.num_rows() as i64)
- .with_total_bytes(batch.get_array_memory_size() as i64)
- .with_ordered(false);
-
- let resp = Response::new(info);
+ let resp = Response::new(self.fake_flight_info().unwrap());
Ok(resp)
}
async fn get_flight_info_prepared_statement(
&self,
- _cmd: CommandPreparedStatementQuery,
+ cmd: CommandPreparedStatementQuery,
_request: Request<FlightDescriptor>,
) -> Result<Response<FlightInfo>, Status> {
- Err(Status::unimplemented(
- "get_flight_info_prepared_statement not implemented",
- ))
+ assert_eq!(
+ cmd.prepared_statement_handle,
+ PREPARED_STATEMENT_HANDLE.as_bytes()
+ );
+ let resp = Response::new(self.fake_flight_info().unwrap());
+ Ok(resp)
}
async fn get_flight_info_substrait_plan(
@@ -426,7 +506,7 @@ impl FlightSqlService for FlightSqlServiceImpl {
async fn do_put_statement_update(
&self,
_ticket: CommandStatementUpdate,
- _request: Request<Streaming<FlightData>>,
+ _request: Request<PeekableFlightDataStream>,
) -> Result<i64, Status> {
Err(Status::unimplemented(
"do_put_statement_update not implemented",
@@ -436,7 +516,7 @@ impl FlightSqlService for FlightSqlServiceImpl {
async fn do_put_substrait_plan(
&self,
_ticket: CommandStatementSubstraitPlan,
- _request: Request<Streaming<FlightData>>,
+ _request: Request<PeekableFlightDataStream>,
) -> Result<i64, Status> {
Err(Status::unimplemented(
"do_put_substrait_plan not implemented",
@@ -446,17 +526,36 @@ impl FlightSqlService for FlightSqlServiceImpl {
async fn do_put_prepared_statement_query(
&self,
_query: CommandPreparedStatementQuery,
- _request: Request<Streaming<FlightData>>,
+ request: Request<PeekableFlightDataStream>,
) -> Result<Response<<Self as FlightService>::DoPutStream>, Status> {
- Err(Status::unimplemented(
- "do_put_prepared_statement_query not implemented",
+ // just make sure decoding the parameters works
+ let parameters = FlightRecordBatchStream::new_from_flight_data(
+ request.into_inner().map_err(|e| e.into()),
+ )
+ .try_collect::<Vec<_>>()
+ .await?;
+
+ for (left, right) in parameters[0].schema().all_fields().iter().zip(vec![
+ Field::new("$1", DataType::Utf8, false),
+ Field::new("$2", DataType::Int64, true),
+ ]) {
+ if left.name() != right.name() || left.data_type() != right.data_type() {
+ return Err(Status::invalid_argument(format!(
+ "Parameters did not match parameter schema\ngot {}",
+ parameters[0].schema(),
+ )));
+ }
+ }
+
+ Ok(Response::new(
+ futures::stream::once(async { Ok(PutResult::default()) }).boxed(),
))
}
async fn do_put_prepared_statement_update(
&self,
_query: CommandPreparedStatementUpdate,
- _request: Request<Streaming<FlightData>>,
+ _request: Request<PeekableFlightDataStream>,
) -> Result<i64, Status> {
Err(Status::unimplemented(
"do_put_prepared_statement_update not implemented",
@@ -468,9 +567,8 @@ impl FlightSqlService for FlightSqlServiceImpl {
_query: ActionCreatePreparedStatementRequest,
_request: Request<Action>,
) -> Result<ActionCreatePreparedStatementResult, Status> {
- Err(Status::unimplemented(
- "do_action_create_prepared_statement not implemented",
- ))
+ Self::create_fake_prepared_stmt()
+ .map_err(|e| Status::internal(format!("Unable to serialize schema: {e}")))
}
async fn do_action_close_prepared_statement(
|
DoPut FlightSQL handler inadvertently consumes schema at start of Request<Streaming<FlightData>>
**Describe the bug**
When executing `DoPutPreparedStatementQuery` requests to bind parameters to a prepared statement, using the `DoPut` Flight RPC, one may receive an error like this:
```
rpc error: code = Internal desc = Received RecordBatch prior to Schema
```
This is because the implementation of `FlightService` for FlightSQL servers consumes the first flight batch by calling `.message()` on the `Request<Streaming<FlightData>>` handle:
```rust
async fn do_put(
&self,
mut request: Request<Streaming<FlightData>>,
) -> Result<Response<Self::DoPutStream>, Status> {
let cmd = request.get_mut().message().await?.unwrap();
```
It does this to inspect the type of the `FlightDescriptor`, which tells it which `DoPut` handler to dispatch to in the `FlightSqlService`. If the schema was encoded in the very first message together with the `FlightDescriptor`, calling `.message()` consumes both the `FlightDescriptor` and the schema, so that a `FlightSqlService` handler such as `do_put_prepared_statement_query` no longer can read the schema from the `Request<Streaming<FlightData>>`.
**To Reproduce**
Implement a `FlightSqlService` that handles any kind of `DoPut` request and decodes the flight stream, such as the following:
```rust
impl FlightSqlService for FlightSqlServer {
async fn do_put_prepared_statement_query(
&self,
query: CommandPreparedStatementQuery,
request: Request<Streaming<FlightData>>,
) -> Result<Response<<Self as FlightService>::DoPutStream>> {
info!("do_put_prepared_statement_query");
let parameters = FlightRecordBatchStream::new_from_flight_data(
request.into_inner().map_err(|e| e.into()),
)
.try_collect::<Vec<_>>()
.await?;
todo!()
}
}
```
then execute a `DoPut` using a raw `do_put` request on the `FlightSqlServiceClient`, sending the following batch:
```rust
let cmd = CommandPreparedStatementQuery {
prepared_statement_handle: handle.clone(),
};
let flight_stream = FlightDataEncoderBuilder::new()
.with_flight_descriptor(Some(FlightDescriptor::new_cmd(
cmd.as_any().encode_to_vec(),
)))
.with_schema(batch.schema())
.build(stream::once(async { Ok(batch) }));
client
.do_put(flight_stream.map(Result::unwrap))
.await
.context("submit DoPut request")?
.try_collect::<Vec<_>>()
.await
.context("read DoPut response")?;
```
**Expected behavior**
The server should be able to properly handle flight streams sent from a compliant FlightSQL client.
**Additional context**
This bug was uncovered while implementing and testing prepared statements for a Rust FlightSQL server. The same bug was observed when submitting queries from both Rust and Go FlightSQL clients (the server is a Rust FlightSQL server).
FlightSqlClient `parameter_binding` is write-only
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
I would like to run parameterized queries from the FlightSql client to integration test what users will be doing with the JDBC client. Unfortunately, I see that the `parameter_binding` field is written to, but never read-from - so these values must not be getting to the server where I need to implement support.
**Describe the solution you'd like**
1. Test with the JDBC client to see how these values are passed
2. Implement the necessary changes to the arrow-rs FlightSqlClient to reproduce the JDBC behavior
**Describe alternatives you've considered**
Continue to leave this important functionality unimplemented.
|
2023-09-07T21:04:59Z
|
46.0
|
878217b9e330b4f1ed13e798a214ea11fbeb2bbb
|
|
apache/arrow-rs
| 4,795
|
apache__arrow-rs-4795
|
[
"4794",
"4794"
] |
77455d48cd6609045a4728ba908123de9d0b62fd
|
diff --git a/arrow-csv/src/reader/mod.rs b/arrow-csv/src/reader/mod.rs
index 328c2cd41f3b..695e3d47965d 100644
--- a/arrow-csv/src/reader/mod.rs
+++ b/arrow-csv/src/reader/mod.rs
@@ -133,8 +133,8 @@ use arrow_schema::*;
use chrono::{TimeZone, Utc};
use csv::StringRecord;
use lazy_static::lazy_static;
-use regex::RegexSet;
-use std::fmt;
+use regex::{Regex, RegexSet};
+use std::fmt::{self, Debug};
use std::fs::File;
use std::io::{BufRead, BufReader as StdBufReader, Read, Seek, SeekFrom};
use std::sync::Arc;
@@ -157,6 +157,22 @@ lazy_static! {
]).unwrap();
}
+/// A wrapper over `Option<Regex>` to check if the value is `NULL`.
+#[derive(Debug, Clone, Default)]
+struct NullRegex(Option<Regex>);
+
+impl NullRegex {
+ /// Returns true if the value should be considered as `NULL` according to
+ /// the provided regular expression.
+ #[inline]
+ fn is_null(&self, s: &str) -> bool {
+ match &self.0 {
+ Some(r) => r.is_match(s),
+ None => s.is_empty(),
+ }
+ }
+}
+
#[derive(Default, Copy, Clone)]
struct InferredDataType {
/// Packed booleans indicating type
@@ -213,6 +229,7 @@ pub struct Format {
escape: Option<u8>,
quote: Option<u8>,
terminator: Option<u8>,
+ null_regex: NullRegex,
}
impl Format {
@@ -241,6 +258,12 @@ impl Format {
self
}
+ /// Provide a regex to match null values, defaults to `^$`
+ pub fn with_null_regex(mut self, null_regex: Regex) -> Self {
+ self.null_regex = NullRegex(Some(null_regex));
+ self
+ }
+
/// Infer schema of CSV records from the provided `reader`
///
/// If `max_records` is `None`, all records will be read, otherwise up to `max_records`
@@ -287,7 +310,7 @@ impl Format {
column_types.iter_mut().enumerate().take(header_length)
{
if let Some(string) = record.get(i) {
- if !string.is_empty() {
+ if !self.null_regex.is_null(string) {
column_type.update(string)
}
}
@@ -557,6 +580,9 @@ pub struct Decoder {
/// A decoder for [`StringRecords`]
record_decoder: RecordDecoder,
+
+ /// Check if the string matches this pattern for `NULL`.
+ null_regex: NullRegex,
}
impl Decoder {
@@ -603,6 +629,7 @@ impl Decoder {
Some(self.schema.metadata.clone()),
self.projection.as_ref(),
self.line_number,
+ &self.null_regex,
)?;
self.line_number += rows.len();
Ok(Some(batch))
@@ -621,6 +648,7 @@ fn parse(
metadata: Option<std::collections::HashMap<String, String>>,
projection: Option<&Vec<usize>>,
line_number: usize,
+ null_regex: &NullRegex,
) -> Result<RecordBatch, ArrowError> {
let projection: Vec<usize> = match projection {
Some(v) => v.clone(),
@@ -633,7 +661,9 @@ fn parse(
let i = *i;
let field = &fields[i];
match field.data_type() {
- DataType::Boolean => build_boolean_array(line_number, rows, i),
+ DataType::Boolean => {
+ build_boolean_array(line_number, rows, i, null_regex)
+ }
DataType::Decimal128(precision, scale) => {
build_decimal_array::<Decimal128Type>(
line_number,
@@ -641,6 +671,7 @@ fn parse(
i,
*precision,
*scale,
+ null_regex,
)
}
DataType::Decimal256(precision, scale) => {
@@ -650,53 +681,73 @@ fn parse(
i,
*precision,
*scale,
+ null_regex,
)
}
- DataType::Int8 => build_primitive_array::<Int8Type>(line_number, rows, i),
+ DataType::Int8 => {
+ build_primitive_array::<Int8Type>(line_number, rows, i, null_regex)
+ }
DataType::Int16 => {
- build_primitive_array::<Int16Type>(line_number, rows, i)
+ build_primitive_array::<Int16Type>(line_number, rows, i, null_regex)
}
DataType::Int32 => {
- build_primitive_array::<Int32Type>(line_number, rows, i)
+ build_primitive_array::<Int32Type>(line_number, rows, i, null_regex)
}
DataType::Int64 => {
- build_primitive_array::<Int64Type>(line_number, rows, i)
+ build_primitive_array::<Int64Type>(line_number, rows, i, null_regex)
}
DataType::UInt8 => {
- build_primitive_array::<UInt8Type>(line_number, rows, i)
+ build_primitive_array::<UInt8Type>(line_number, rows, i, null_regex)
}
DataType::UInt16 => {
- build_primitive_array::<UInt16Type>(line_number, rows, i)
+ build_primitive_array::<UInt16Type>(line_number, rows, i, null_regex)
}
DataType::UInt32 => {
- build_primitive_array::<UInt32Type>(line_number, rows, i)
+ build_primitive_array::<UInt32Type>(line_number, rows, i, null_regex)
}
DataType::UInt64 => {
- build_primitive_array::<UInt64Type>(line_number, rows, i)
+ build_primitive_array::<UInt64Type>(line_number, rows, i, null_regex)
}
DataType::Float32 => {
- build_primitive_array::<Float32Type>(line_number, rows, i)
+ build_primitive_array::<Float32Type>(line_number, rows, i, null_regex)
}
DataType::Float64 => {
- build_primitive_array::<Float64Type>(line_number, rows, i)
+ build_primitive_array::<Float64Type>(line_number, rows, i, null_regex)
}
DataType::Date32 => {
- build_primitive_array::<Date32Type>(line_number, rows, i)
+ build_primitive_array::<Date32Type>(line_number, rows, i, null_regex)
}
DataType::Date64 => {
- build_primitive_array::<Date64Type>(line_number, rows, i)
- }
- DataType::Time32(TimeUnit::Second) => {
- build_primitive_array::<Time32SecondType>(line_number, rows, i)
+ build_primitive_array::<Date64Type>(line_number, rows, i, null_regex)
}
+ DataType::Time32(TimeUnit::Second) => build_primitive_array::<
+ Time32SecondType,
+ >(
+ line_number, rows, i, null_regex
+ ),
DataType::Time32(TimeUnit::Millisecond) => {
- build_primitive_array::<Time32MillisecondType>(line_number, rows, i)
+ build_primitive_array::<Time32MillisecondType>(
+ line_number,
+ rows,
+ i,
+ null_regex,
+ )
}
DataType::Time64(TimeUnit::Microsecond) => {
- build_primitive_array::<Time64MicrosecondType>(line_number, rows, i)
+ build_primitive_array::<Time64MicrosecondType>(
+ line_number,
+ rows,
+ i,
+ null_regex,
+ )
}
DataType::Time64(TimeUnit::Nanosecond) => {
- build_primitive_array::<Time64NanosecondType>(line_number, rows, i)
+ build_primitive_array::<Time64NanosecondType>(
+ line_number,
+ rows,
+ i,
+ null_regex,
+ )
}
DataType::Timestamp(TimeUnit::Second, tz) => {
build_timestamp_array::<TimestampSecondType>(
@@ -704,6 +755,7 @@ fn parse(
rows,
i,
tz.as_deref(),
+ null_regex,
)
}
DataType::Timestamp(TimeUnit::Millisecond, tz) => {
@@ -712,6 +764,7 @@ fn parse(
rows,
i,
tz.as_deref(),
+ null_regex,
)
}
DataType::Timestamp(TimeUnit::Microsecond, tz) => {
@@ -720,6 +773,7 @@ fn parse(
rows,
i,
tz.as_deref(),
+ null_regex,
)
}
DataType::Timestamp(TimeUnit::Nanosecond, tz) => {
@@ -728,6 +782,7 @@ fn parse(
rows,
i,
tz.as_deref(),
+ null_regex,
)
}
DataType::Utf8 => Ok(Arc::new(
@@ -827,11 +882,12 @@ fn build_decimal_array<T: DecimalType>(
col_idx: usize,
precision: u8,
scale: i8,
+ null_regex: &NullRegex,
) -> Result<ArrayRef, ArrowError> {
let mut decimal_builder = PrimitiveBuilder::<T>::with_capacity(rows.len());
for row in rows.iter() {
let s = row.get(col_idx);
- if s.is_empty() {
+ if null_regex.is_null(s) {
// append null
decimal_builder.append_null();
} else {
@@ -859,12 +915,13 @@ fn build_primitive_array<T: ArrowPrimitiveType + Parser>(
line_number: usize,
rows: &StringRecords<'_>,
col_idx: usize,
+ null_regex: &NullRegex,
) -> Result<ArrayRef, ArrowError> {
rows.iter()
.enumerate()
.map(|(row_index, row)| {
let s = row.get(col_idx);
- if s.is_empty() {
+ if null_regex.is_null(s) {
return Ok(None);
}
@@ -888,14 +945,27 @@ fn build_timestamp_array<T: ArrowTimestampType>(
rows: &StringRecords<'_>,
col_idx: usize,
timezone: Option<&str>,
+ null_regex: &NullRegex,
) -> Result<ArrayRef, ArrowError> {
Ok(Arc::new(match timezone {
Some(timezone) => {
let tz: Tz = timezone.parse()?;
- build_timestamp_array_impl::<T, _>(line_number, rows, col_idx, &tz)?
- .with_timezone(timezone)
+ build_timestamp_array_impl::<T, _>(
+ line_number,
+ rows,
+ col_idx,
+ &tz,
+ null_regex,
+ )?
+ .with_timezone(timezone)
}
- None => build_timestamp_array_impl::<T, _>(line_number, rows, col_idx, &Utc)?,
+ None => build_timestamp_array_impl::<T, _>(
+ line_number,
+ rows,
+ col_idx,
+ &Utc,
+ null_regex,
+ )?,
}))
}
@@ -904,12 +974,13 @@ fn build_timestamp_array_impl<T: ArrowTimestampType, Tz: TimeZone>(
rows: &StringRecords<'_>,
col_idx: usize,
timezone: &Tz,
+ null_regex: &NullRegex,
) -> Result<PrimitiveArray<T>, ArrowError> {
rows.iter()
.enumerate()
.map(|(row_index, row)| {
let s = row.get(col_idx);
- if s.is_empty() {
+ if null_regex.is_null(s) {
return Ok(None);
}
@@ -936,12 +1007,13 @@ fn build_boolean_array(
line_number: usize,
rows: &StringRecords<'_>,
col_idx: usize,
+ null_regex: &NullRegex,
) -> Result<ArrayRef, ArrowError> {
rows.iter()
.enumerate()
.map(|(row_index, row)| {
let s = row.get(col_idx);
- if s.is_empty() {
+ if null_regex.is_null(s) {
return Ok(None);
}
let parsed = parse_bool(s);
@@ -1042,6 +1114,12 @@ impl ReaderBuilder {
self
}
+ /// Provide a regex to match null values, defaults to `^$`
+ pub fn with_null_regex(mut self, null_regex: Regex) -> Self {
+ self.format.null_regex = NullRegex(Some(null_regex));
+ self
+ }
+
/// Set the batch size (number of records to load at one time)
pub fn with_batch_size(mut self, batch_size: usize) -> Self {
self.batch_size = batch_size;
@@ -1100,6 +1178,7 @@ impl ReaderBuilder {
end,
projection: self.projection,
batch_size: self.batch_size,
+ null_regex: self.format.null_regex,
}
}
}
@@ -1426,6 +1505,36 @@ mod tests {
assert!(!batch.column(1).is_null(4));
}
+ #[test]
+ fn test_custom_nulls() {
+ let schema = Arc::new(Schema::new(vec![
+ Field::new("c_int", DataType::UInt64, true),
+ Field::new("c_float", DataType::Float32, true),
+ Field::new("c_string", DataType::Utf8, true),
+ Field::new("c_bool", DataType::Boolean, true),
+ ]));
+
+ let file = File::open("test/data/custom_null_test.csv").unwrap();
+
+ let null_regex = Regex::new("^nil$").unwrap();
+
+ let mut csv = ReaderBuilder::new(schema)
+ .has_header(true)
+ .with_null_regex(null_regex)
+ .build(file)
+ .unwrap();
+
+ let batch = csv.next().unwrap().unwrap();
+
+ // "nil"s should be NULL
+ assert!(batch.column(0).is_null(1));
+ assert!(batch.column(1).is_null(2));
+ assert!(batch.column(3).is_null(4));
+ // String won't be empty
+ assert!(!batch.column(2).is_null(3));
+ assert!(!batch.column(2).is_null(4));
+ }
+
#[test]
fn test_nulls_with_inference() {
let mut file = File::open("test/data/various_types.csv").unwrap();
@@ -1485,6 +1594,42 @@ mod tests {
assert!(!batch.column(1).is_null(4));
}
+ #[test]
+ fn test_custom_nulls_with_inference() {
+ let mut file = File::open("test/data/custom_null_test.csv").unwrap();
+
+ let null_regex = Regex::new("^nil$").unwrap();
+
+ let format = Format::default()
+ .with_header(true)
+ .with_null_regex(null_regex);
+
+ let (schema, _) = format.infer_schema(&mut file, None).unwrap();
+ file.rewind().unwrap();
+
+ let expected_schema = Schema::new(vec![
+ Field::new("c_int", DataType::Int64, true),
+ Field::new("c_float", DataType::Float64, true),
+ Field::new("c_string", DataType::Utf8, true),
+ Field::new("c_bool", DataType::Boolean, true),
+ ]);
+
+ assert_eq!(schema, expected_schema);
+
+ let builder = ReaderBuilder::new(Arc::new(schema))
+ .with_format(format)
+ .with_batch_size(512)
+ .with_projection(vec![0, 1, 2, 3]);
+
+ let mut csv = builder.build(file).unwrap();
+ let batch = csv.next().unwrap().unwrap();
+
+ assert_eq!(5, batch.num_rows());
+ assert_eq!(4, batch.num_columns());
+
+ assert_eq!(batch.schema().as_ref(), &expected_schema);
+ }
+
#[test]
fn test_parse_invalid_csv() {
let file = File::open("test/data/various_types_invalid.csv").unwrap();
|
diff --git a/arrow-csv/test/data/custom_null_test.csv b/arrow-csv/test/data/custom_null_test.csv
new file mode 100644
index 000000000000..39f9fc4b3eff
--- /dev/null
+++ b/arrow-csv/test/data/custom_null_test.csv
@@ -0,0 +1,6 @@
+c_int,c_float,c_string,c_bool
+1,1.1,"1.11",True
+nil,2.2,"2.22",TRUE
+3,nil,"3.33",true
+4,4.4,nil,False
+5,6.6,"",nil
|
Add option to specify custom null values for CSV reader
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
<!--
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
(This section helps Arrow developers understand the context and *why* for this feature, in addition to the *what*)
-->
Add an option to the CSV reader to specify custom null values that might be used in CSV files as placeholders.
Helps in parsing of file such as:
```csv
a,b,c
1,2,NA
3,NA,5
```
where `NA` is a placeholder for `NULL`
**Describe the solution you'd like**
<!--
A clear and concise description of what you want to happen.
-->
**Describe alternatives you've considered**
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
Add option to specify custom null values for CSV reader
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
<!--
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
(This section helps Arrow developers understand the context and *why* for this feature, in addition to the *what*)
-->
Add an option to the CSV reader to specify custom null values that might be used in CSV files as placeholders.
Helps in parsing of file such as:
```csv
a,b,c
1,2,NA
3,NA,5
```
where `NA` is a placeholder for `NULL`
**Describe the solution you'd like**
<!--
A clear and concise description of what you want to happen.
-->
**Describe alternatives you've considered**
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
|
2023-09-07T17:45:56Z
|
46.0
|
878217b9e330b4f1ed13e798a214ea11fbeb2bbb
|
|
apache/arrow-rs
| 4,773
|
apache__arrow-rs-4773
|
[
"4772"
] |
03d0505fc864c09e6dcd208d3cdddeecefb90345
|
diff --git a/parquet/src/record/mod.rs b/parquet/src/record/mod.rs
index 771d8058c9c1..f40e91418da1 100644
--- a/parquet/src/record/mod.rs
+++ b/parquet/src/record/mod.rs
@@ -19,6 +19,7 @@
mod api;
pub mod reader;
+mod record_reader;
mod record_writer;
mod triplet;
@@ -26,5 +27,6 @@ pub use self::{
api::{
Field, List, ListAccessor, Map, MapAccessor, Row, RowAccessor, RowColumnIter, RowFormatter,
},
+ record_reader::RecordReader,
record_writer::RecordWriter,
};
diff --git a/parquet/src/record/record_reader.rs b/parquet/src/record/record_reader.rs
new file mode 100644
index 000000000000..bcfeb95dcdf4
--- /dev/null
+++ b/parquet/src/record/record_reader.rs
@@ -0,0 +1,30 @@
+// 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.
+
+use super::super::errors::ParquetError;
+use super::super::file::reader::RowGroupReader;
+
+/// read up to `max_records` records from `row_group_reader` into `self`
+/// The type parameter `T` is used to work around the rust orphan rule
+/// when implementing on types such as `Vec<T>`.
+pub trait RecordReader<T> {
+ fn read_from_row_group(
+ &mut self,
+ row_group_reader: &mut dyn RowGroupReader,
+ num_records: usize,
+ ) -> Result<(), ParquetError>;
+}
diff --git a/parquet/src/record/record_writer.rs b/parquet/src/record/record_writer.rs
index 62099051f513..0b2b95ef7dea 100644
--- a/parquet/src/record/record_writer.rs
+++ b/parquet/src/record/record_writer.rs
@@ -20,6 +20,10 @@ use crate::schema::types::TypePtr;
use super::super::errors::ParquetError;
use super::super::file::writer::SerializedRowGroupWriter;
+/// `write_to_row_group` writes from `self` into `row_group_writer`
+/// `schema` builds the schema used by `row_group_writer`
+/// The type parameter `T` is used to work around the rust orphan rule
+/// when implementing on types such as `&[T]`.
pub trait RecordWriter<T> {
fn write_to_row_group<W: std::io::Write + Send>(
&self,
diff --git a/parquet_derive/README.md b/parquet_derive/README.md
index b20721079c2d..c267a92430e0 100644
--- a/parquet_derive/README.md
+++ b/parquet_derive/README.md
@@ -19,9 +19,9 @@
# Parquet Derive
-A crate for deriving `RecordWriter` for arbitrary, _simple_ structs. This does not generate writers for arbitrarily nested
-structures. It only works for primitives and a few generic structures and
-various levels of reference. Please see features checklist for what is currently
+A crate for deriving `RecordWriter` and `RecordReader` for arbitrary, _simple_ structs. This does not
+generate readers or writers for arbitrarily nested structures. It only works for primitives and a few
+generic structures and various levels of reference. Please see features checklist for what is currently
supported.
Derive also has some support for the chrono time library. You must must enable the `chrono` feature to get this support.
@@ -77,16 +77,55 @@ writer.close_row_group(row_group).unwrap();
writer.close().unwrap();
```
+Example usage of deriving a `RecordReader` for your struct:
+
+```rust
+use parquet::file::{serialized_reader::SerializedFileReader, reader::FileReader};
+use parquet_derive::ParquetRecordReader;
+
+#[derive(ParquetRecordReader)]
+struct ACompleteRecord {
+ pub a_bool: bool,
+ pub a_string: String,
+ pub i16: i16,
+ pub i32: i32,
+ pub u64: u64,
+ pub isize: isize,
+ pub float: f32,
+ pub double: f64,
+ pub now: chrono::NaiveDateTime,
+ pub byte_vec: Vec<u8>,
+}
+
+// Initialize your parquet file
+let reader = SerializedFileReader::new(file).unwrap();
+let mut row_group = reader.get_row_group(0).unwrap();
+
+// create your records vector to read into
+let mut chunks: Vec<ACompleteRecord> = Vec::new();
+
+// The derived `RecordReader` takes over here
+chunks.read_from_row_group(&mut *row_group, 1).unwrap();
+```
+
## Features
- [x] Support writing `String`, `&str`, `bool`, `i32`, `f32`, `f64`, `Vec<u8>`
- [ ] Support writing dictionaries
- [x] Support writing logical types like timestamp
-- [x] Derive definition_levels for `Option`
-- [ ] Derive definition levels for nested structures
+- [x] Derive definition_levels for `Option` for writing
+- [ ] Derive definition levels for nested structures for writing
- [ ] Derive writing tuple struct
- [ ] Derive writing `tuple` container types
+- [x] Support reading `String`, `&str`, `bool`, `i32`, `f32`, `f64`, `Vec<u8>`
+- [ ] Support reading/writing dictionaries
+- [x] Support reading/writing logical types like timestamp
+- [ ] Handle definition_levels for `Option` for reading
+- [ ] Handle definition levels for nested structures for reading
+- [ ] Derive reading/writing tuple struct
+- [ ] Derive reading/writing `tuple` container types
+
## Requirements
- Same as `parquet-rs`
@@ -103,4 +142,4 @@ To compile and view in the browser, run `cargo doc --no-deps --open`.
## License
-Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0.
+Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0.
\ No newline at end of file
diff --git a/parquet_derive/src/lib.rs b/parquet_derive/src/lib.rs
index c6641cd8091d..671a46db0f31 100644
--- a/parquet_derive/src/lib.rs
+++ b/parquet_derive/src/lib.rs
@@ -44,7 +44,7 @@ mod parquet_field;
/// use parquet::file::writer::SerializedFileWriter;
///
/// use std::sync::Arc;
-//
+///
/// #[derive(ParquetRecordWriter)]
/// struct ACompleteRecord<'a> {
/// pub a_bool: bool,
@@ -137,3 +137,89 @@ pub fn parquet_record_writer(input: proc_macro::TokenStream) -> proc_macro::Toke
}
}).into()
}
+
+/// Derive flat, simple RecordReader implementations. Works by parsing
+/// a struct tagged with `#[derive(ParquetRecordReader)]` and emitting
+/// the correct writing code for each field of the struct. Column readers
+/// are generated in the order they are defined.
+///
+/// It is up to the programmer to keep the order of the struct
+/// fields lined up with the schema.
+///
+/// Example:
+///
+/// ```ignore
+/// use parquet::file::{serialized_reader::SerializedFileReader, reader::FileReader};
+/// use parquet_derive::{ParquetRecordReader};
+///
+/// #[derive(ParquetRecordReader)]
+/// struct ACompleteRecord {
+/// pub a_bool: bool,
+/// pub a_string: String,
+/// }
+///
+/// pub fn read_some_records() -> Vec<ACompleteRecord> {
+/// let mut samples: Vec<ACompleteRecord> = Vec::new();
+///
+/// let reader = SerializedFileReader::new(file).unwrap();
+/// let mut row_group = reader.get_row_group(0).unwrap();
+/// samples.read_from_row_group(&mut *row_group, 1).unwrap();
+/// samples
+/// }
+/// ```
+///
+#[proc_macro_derive(ParquetRecordReader)]
+pub fn parquet_record_reader(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
+ let input: DeriveInput = parse_macro_input!(input as DeriveInput);
+ let fields = match input.data {
+ Data::Struct(DataStruct { fields, .. }) => fields,
+ Data::Enum(_) => unimplemented!("Enum currently is not supported"),
+ Data::Union(_) => unimplemented!("Union currently is not supported"),
+ };
+
+ let field_infos: Vec<_> = fields.iter().map(parquet_field::Field::from).collect();
+ let field_names: Vec<_> = fields.iter().map(|f| f.ident.clone()).collect();
+ let reader_snippets: Vec<proc_macro2::TokenStream> =
+ field_infos.iter().map(|x| x.reader_snippet()).collect();
+ let i: Vec<_> = (0..reader_snippets.len()).collect();
+
+ let derived_for = input.ident;
+ let generics = input.generics;
+
+ (quote! {
+
+ impl #generics ::parquet::record::RecordReader<#derived_for #generics> for Vec<#derived_for #generics> {
+ fn read_from_row_group(
+ &mut self,
+ row_group_reader: &mut dyn ::parquet::file::reader::RowGroupReader,
+ num_records: usize,
+ ) -> Result<(), ::parquet::errors::ParquetError> {
+ use ::parquet::column::reader::ColumnReader;
+
+ let mut row_group_reader = row_group_reader;
+
+ for _ in 0..num_records {
+ self.push(#derived_for {
+ #(
+ #field_names: Default::default()
+ ),*
+ })
+ }
+
+ let records = self; // Used by all the reader snippets to be more clear
+
+ #(
+ {
+ if let Ok(mut column_reader) = row_group_reader.get_column_reader(#i) {
+ #reader_snippets
+ } else {
+ return Err(::parquet::errors::ParquetError::General("Failed to get next column".into()))
+ }
+ }
+ );*
+
+ Ok(())
+ }
+ }
+ }).into()
+}
diff --git a/parquet_derive/src/parquet_field.rs b/parquet_derive/src/parquet_field.rs
index e629bfe757ab..0ac95c2864e5 100644
--- a/parquet_derive/src/parquet_field.rs
+++ b/parquet_derive/src/parquet_field.rs
@@ -219,6 +219,72 @@ impl Field {
}
}
+ /// Takes the parsed field of the struct and emits a valid
+ /// column reader snippet. Should match exactly what you
+ /// would write by hand.
+ ///
+ /// Can only generate writers for basic structs, for example:
+ ///
+ /// struct Record {
+ /// a_bool: bool
+ /// }
+ ///
+ /// but not
+ ///
+ /// struct UnsupportedNestedRecord {
+ /// a_property: bool,
+ /// nested_record: Record
+ /// }
+ ///
+ /// because this parsing logic is not sophisticated enough for definition
+ /// levels beyond 2.
+ ///
+ /// `Option` types and references not supported
+ pub fn reader_snippet(&self) -> proc_macro2::TokenStream {
+ let ident = &self.ident;
+ let column_reader = self.ty.column_reader();
+ let parquet_type = self.ty.physical_type_as_rust();
+
+ // generate the code to read the column into a vector `vals`
+ let write_batch_expr = quote! {
+ let mut vals_vec = Vec::new();
+ vals_vec.resize(num_records, Default::default());
+ let mut vals: &mut [#parquet_type] = vals_vec.as_mut_slice();
+ if let #column_reader(mut typed) = column_reader {
+ typed.read_records(num_records, None, None, vals)?;
+ } else {
+ panic!("Schema and struct disagree on type for {}", stringify!{#ident});
+ }
+ };
+
+ // generate the code to convert each element of `vals` to the correct type and then write
+ // it to its field in the corresponding struct
+ let vals_writer = match &self.ty {
+ Type::TypePath(_) => self.copied_direct_fields(),
+ Type::Reference(_, ref first_type) => match **first_type {
+ Type::TypePath(_) => self.copied_direct_fields(),
+ Type::Slice(ref second_type) => match **second_type {
+ Type::TypePath(_) => self.copied_direct_fields(),
+ ref f => unimplemented!("Unsupported: {:#?}", f),
+ },
+ ref f => unimplemented!("Unsupported: {:#?}", f),
+ },
+ Type::Vec(ref first_type) => match **first_type {
+ Type::TypePath(_) => self.copied_direct_fields(),
+ ref f => unimplemented!("Unsupported: {:#?}", f),
+ },
+ f => unimplemented!("Unsupported: {:#?}", f),
+ };
+
+ quote! {
+ {
+ #write_batch_expr
+
+ #vals_writer
+ }
+ }
+ }
+
pub fn parquet_type(&self) -> proc_macro2::TokenStream {
// TODO: Support group types
// TODO: Add length if dealing with fixedlenbinary
@@ -319,27 +385,31 @@ impl Field {
}
}
+ // generates code to read `field_name` from each record into a vector `vals`
fn copied_direct_vals(&self) -> proc_macro2::TokenStream {
let field_name = &self.ident;
- let is_a_byte_buf = self.is_a_byte_buf;
- let is_a_timestamp = self.third_party_type == Some(ThirdPartyType::ChronoNaiveDateTime);
- let is_a_date = self.third_party_type == Some(ThirdPartyType::ChronoNaiveDate);
- let is_a_uuid = self.third_party_type == Some(ThirdPartyType::Uuid);
- let access = if is_a_timestamp {
- quote! { rec.#field_name.timestamp_millis() }
- } else if is_a_date {
- quote! { rec.#field_name.signed_duration_since(::chrono::NaiveDate::from_ymd(1970, 1, 1)).num_days() as i32 }
- } else if is_a_uuid {
- quote! { (&rec.#field_name.to_string()[..]).into() }
- } else if is_a_byte_buf {
- quote! { (&rec.#field_name[..]).into() }
- } else {
- // Type might need converting to a physical type
- match self.ty.physical_type() {
- parquet::basic::Type::INT32 => quote! { rec.#field_name as i32 },
- parquet::basic::Type::INT64 => quote! { rec.#field_name as i64 },
- _ => quote! { rec.#field_name },
+ let access = match self.third_party_type {
+ Some(ThirdPartyType::ChronoNaiveDateTime) => {
+ quote! { rec.#field_name.timestamp_millis() }
+ }
+ Some(ThirdPartyType::ChronoNaiveDate) => {
+ quote! { rec.#field_name.signed_duration_since(::chrono::NaiveDate::from_ymd(1970, 1, 1)).num_days() as i32 }
+ }
+ Some(ThirdPartyType::Uuid) => {
+ quote! { (&rec.#field_name.to_string()[..]).into() }
+ }
+ _ => {
+ if self.is_a_byte_buf {
+ quote! { (&rec.#field_name[..]).into() }
+ } else {
+ // Type might need converting to a physical type
+ match self.ty.physical_type() {
+ parquet::basic::Type::INT32 => quote! { rec.#field_name as i32 },
+ parquet::basic::Type::INT64 => quote! { rec.#field_name as i64 },
+ _ => quote! { rec.#field_name },
+ }
+ }
}
};
@@ -348,6 +418,48 @@ impl Field {
}
}
+ // generates code to read a vector `records` into `field_name` for each record
+ fn copied_direct_fields(&self) -> proc_macro2::TokenStream {
+ let field_name = &self.ident;
+
+ let value = match self.third_party_type {
+ Some(ThirdPartyType::ChronoNaiveDateTime) => {
+ quote! { ::chrono::naive::NaiveDateTime::from_timestamp_millis(vals[i]).unwrap() }
+ }
+ Some(ThirdPartyType::ChronoNaiveDate) => {
+ quote! {
+ ::chrono::naive::NaiveDate::from_num_days_from_ce_opt(vals[i]
+ + ((::chrono::naive::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap()
+ .signed_duration_since(
+ ::chrono::naive::NaiveDate::from_ymd_opt(0, 12, 31).unwrap()
+ )
+ ).num_days()) as i32).unwrap()
+ }
+ }
+ Some(ThirdPartyType::Uuid) => {
+ quote! { ::uuid::Uuid::parse_str(vals[i].data().convert()).unwrap() }
+ }
+ _ => match &self.ty {
+ Type::TypePath(_) => match self.ty.last_part().as_str() {
+ "String" => quote! { String::from(std::str::from_utf8(vals[i].data())
+ .expect("invalid UTF-8 sequence")) },
+ t => {
+ let s: proc_macro2::TokenStream = t.parse().unwrap();
+ quote! { vals[i] as #s }
+ }
+ },
+ Type::Vec(_) => quote! { vals[i].data().to_vec() },
+ f => unimplemented!("Unsupported: {:#?}", f),
+ },
+ };
+
+ quote! {
+ for (i, r) in &mut records[..num_records].iter_mut().enumerate() {
+ r.#field_name = #value;
+ }
+ }
+ }
+
fn optional_definition_levels(&self) -> proc_macro2::TokenStream {
let field_name = &self.ident;
@@ -396,6 +508,29 @@ impl Type {
}
}
+ /// Takes a rust type and returns the appropriate
+ /// parquet-rs column reader
+ fn column_reader(&self) -> syn::TypePath {
+ use parquet::basic::Type as BasicType;
+
+ match self.physical_type() {
+ BasicType::BOOLEAN => {
+ syn::parse_quote!(ColumnReader::BoolColumnReader)
+ }
+ BasicType::INT32 => syn::parse_quote!(ColumnReader::Int32ColumnReader),
+ BasicType::INT64 => syn::parse_quote!(ColumnReader::Int64ColumnReader),
+ BasicType::INT96 => syn::parse_quote!(ColumnReader::Int96ColumnReader),
+ BasicType::FLOAT => syn::parse_quote!(ColumnReader::FloatColumnReader),
+ BasicType::DOUBLE => syn::parse_quote!(ColumnReader::DoubleColumnReader),
+ BasicType::BYTE_ARRAY => {
+ syn::parse_quote!(ColumnReader::ByteArrayColumnReader)
+ }
+ BasicType::FIXED_LEN_BYTE_ARRAY => {
+ syn::parse_quote!(ColumnReader::FixedLenByteArrayColumnReader)
+ }
+ }
+ }
+
/// Helper to simplify a nested field definition to its leaf type
///
/// Ex:
@@ -515,6 +650,23 @@ impl Type {
}
}
+ fn physical_type_as_rust(&self) -> proc_macro2::TokenStream {
+ use parquet::basic::Type as BasicType;
+
+ match self.physical_type() {
+ BasicType::BOOLEAN => quote! { bool },
+ BasicType::INT32 => quote! { i32 },
+ BasicType::INT64 => quote! { i64 },
+ BasicType::INT96 => unimplemented!("96-bit int currently is not supported"),
+ BasicType::FLOAT => quote! { f32 },
+ BasicType::DOUBLE => quote! { f64 },
+ BasicType::BYTE_ARRAY => quote! { ::parquet::data_type::ByteArray },
+ BasicType::FIXED_LEN_BYTE_ARRAY => {
+ quote! { ::parquet::data_type::FixedLenByteArray }
+ }
+ }
+ }
+
fn logical_type(&self) -> proc_macro2::TokenStream {
let last_part = self.last_part();
let leaf_type = self.leaf_type_recursive();
@@ -713,6 +865,39 @@ mod test {
)
}
+ #[test]
+ fn test_generating_a_simple_reader_snippet() {
+ let snippet: proc_macro2::TokenStream = quote! {
+ struct ABoringStruct {
+ counter: usize,
+ }
+ };
+
+ let fields = extract_fields(snippet);
+ let counter = Field::from(&fields[0]);
+
+ let snippet = counter.reader_snippet().to_string();
+ assert_eq!(
+ snippet,
+ (quote! {
+ {
+ let mut vals_vec = Vec::new();
+ vals_vec.resize(num_records, Default::default());
+ let mut vals: &mut[i64] = vals_vec.as_mut_slice();
+ if let ColumnReader::Int64ColumnReader(mut typed) = column_reader {
+ typed.read_records(num_records, None, None, vals)?;
+ } else {
+ panic!("Schema and struct disagree on type for {}", stringify!{ counter });
+ }
+ for (i, r) in &mut records[..num_records].iter_mut().enumerate() {
+ r.counter = vals[i] as usize;
+ }
+ }
+ })
+ .to_string()
+ )
+ }
+
#[test]
fn test_optional_to_writer_snippet() {
let struct_def: proc_macro2::TokenStream = quote! {
@@ -822,6 +1007,32 @@ mod test {
);
}
+ #[test]
+ fn test_converting_to_column_reader_type() {
+ let snippet: proc_macro2::TokenStream = quote! {
+ struct ABasicStruct {
+ yes_no: bool,
+ name: String,
+ }
+ };
+
+ let fields = extract_fields(snippet);
+ let processed: Vec<_> = fields.iter().map(Field::from).collect();
+
+ let column_readers: Vec<_> = processed
+ .iter()
+ .map(|field| field.ty.column_reader())
+ .collect();
+
+ assert_eq!(
+ column_readers,
+ vec![
+ syn::parse_quote!(ColumnReader::BoolColumnReader),
+ syn::parse_quote!(ColumnReader::ByteArrayColumnReader)
+ ]
+ );
+ }
+
#[test]
fn convert_basic_struct() {
let snippet: proc_macro2::TokenStream = quote! {
@@ -995,7 +1206,7 @@ mod test {
}
#[test]
- fn test_chrono_timestamp_millis() {
+ fn test_chrono_timestamp_millis_write() {
let snippet: proc_macro2::TokenStream = quote! {
struct ATimestampStruct {
henceforth: chrono::NaiveDateTime,
@@ -1038,7 +1249,34 @@ mod test {
}
#[test]
- fn test_chrono_date() {
+ fn test_chrono_timestamp_millis_read() {
+ let snippet: proc_macro2::TokenStream = quote! {
+ struct ATimestampStruct {
+ henceforth: chrono::NaiveDateTime,
+ }
+ };
+
+ let fields = extract_fields(snippet);
+ let when = Field::from(&fields[0]);
+ assert_eq!(when.reader_snippet().to_string(),(quote!{
+ {
+ let mut vals_vec = Vec::new();
+ vals_vec.resize(num_records, Default::default());
+ let mut vals: &mut[i64] = vals_vec.as_mut_slice();
+ if let ColumnReader::Int64ColumnReader(mut typed) = column_reader {
+ typed.read_records(num_records, None, None, vals)?;
+ } else {
+ panic!("Schema and struct disagree on type for {}", stringify!{ henceforth });
+ }
+ for (i, r) in &mut records[..num_records].iter_mut().enumerate() {
+ r.henceforth = ::chrono::naive::NaiveDateTime::from_timestamp_millis(vals[i]).unwrap();
+ }
+ }
+ }).to_string());
+ }
+
+ #[test]
+ fn test_chrono_date_write() {
let snippet: proc_macro2::TokenStream = quote! {
struct ATimestampStruct {
henceforth: chrono::NaiveDate,
@@ -1081,7 +1319,38 @@ mod test {
}
#[test]
- fn test_uuid() {
+ fn test_chrono_date_read() {
+ let snippet: proc_macro2::TokenStream = quote! {
+ struct ATimestampStruct {
+ henceforth: chrono::NaiveDate,
+ }
+ };
+
+ let fields = extract_fields(snippet);
+ let when = Field::from(&fields[0]);
+ assert_eq!(when.reader_snippet().to_string(),(quote!{
+ {
+ let mut vals_vec = Vec::new();
+ vals_vec.resize(num_records, Default::default());
+ let mut vals: &mut [i32] = vals_vec.as_mut_slice();
+ if let ColumnReader::Int32ColumnReader(mut typed) = column_reader {
+ typed.read_records(num_records, None, None, vals)?;
+ } else {
+ panic!("Schema and struct disagree on type for {}", stringify!{ henceforth });
+ }
+ for (i, r) in &mut records[..num_records].iter_mut().enumerate() {
+ r.henceforth = ::chrono::naive::NaiveDate::from_num_days_from_ce_opt(vals[i]
+ + ((::chrono::naive::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap()
+ .signed_duration_since(
+ ::chrono::naive::NaiveDate::from_ymd_opt(0, 12, 31).unwrap()
+ )).num_days()) as i32).unwrap();
+ }
+ }
+ }).to_string());
+ }
+
+ #[test]
+ fn test_uuid_write() {
let snippet: proc_macro2::TokenStream = quote! {
struct AUuidStruct {
unique_id: uuid::Uuid,
@@ -1123,6 +1392,33 @@ mod test {
}).to_string());
}
+ #[test]
+ fn test_uuid_read() {
+ let snippet: proc_macro2::TokenStream = quote! {
+ struct AUuidStruct {
+ unique_id: uuid::Uuid,
+ }
+ };
+
+ let fields = extract_fields(snippet);
+ let when = Field::from(&fields[0]);
+ assert_eq!(when.reader_snippet().to_string(),(quote!{
+ {
+ let mut vals_vec = Vec::new();
+ vals_vec.resize(num_records, Default::default());
+ let mut vals: &mut [::parquet::data_type::ByteArray] = vals_vec.as_mut_slice();
+ if let ColumnReader::ByteArrayColumnReader(mut typed) = column_reader {
+ typed.read_records(num_records, None, None, vals)?;
+ } else {
+ panic!("Schema and struct disagree on type for {}", stringify!{ unique_id });
+ }
+ for (i, r) in &mut records[..num_records].iter_mut().enumerate() {
+ r.unique_id = ::uuid::Uuid::parse_str(vals[i].data().convert()).unwrap();
+ }
+ }
+ }).to_string());
+ }
+
#[test]
fn test_converted_type() {
let snippet: proc_macro2::TokenStream = quote! {
|
diff --git a/parquet_derive_test/src/lib.rs b/parquet_derive_test/src/lib.rs
index d377fb0a62af..a8b631ecc024 100644
--- a/parquet_derive_test/src/lib.rs
+++ b/parquet_derive_test/src/lib.rs
@@ -17,7 +17,7 @@
#![allow(clippy::approx_constant)]
-use parquet_derive::ParquetRecordWriter;
+use parquet_derive::{ParquetRecordReader, ParquetRecordWriter};
#[derive(ParquetRecordWriter)]
struct ACompleteRecord<'a> {
@@ -49,6 +49,21 @@ struct ACompleteRecord<'a> {
pub borrowed_maybe_borrowed_byte_vec: &'a Option<&'a [u8]>,
}
+#[derive(PartialEq, ParquetRecordWriter, ParquetRecordReader, Debug)]
+struct APartiallyCompleteRecord {
+ pub bool: bool,
+ pub string: String,
+ pub i16: i16,
+ pub i32: i32,
+ pub u64: u64,
+ pub isize: isize,
+ pub float: f32,
+ pub double: f64,
+ pub now: chrono::NaiveDateTime,
+ pub date: chrono::NaiveDate,
+ pub byte_vec: Vec<u8>,
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -56,7 +71,8 @@ mod tests {
use std::{env, fs, io::Write, sync::Arc};
use parquet::{
- file::writer::SerializedFileWriter, record::RecordWriter,
+ file::writer::SerializedFileWriter,
+ record::{RecordReader, RecordWriter},
schema::parser::parse_message_type,
};
@@ -147,6 +163,56 @@ mod tests {
writer.close().unwrap();
}
+ #[test]
+ fn test_parquet_derive_read_write_combined() {
+ let file = get_temp_file("test_parquet_derive_combined", &[]);
+
+ let mut drs: Vec<APartiallyCompleteRecord> = vec![APartiallyCompleteRecord {
+ bool: true,
+ string: "a string".into(),
+ i16: -45,
+ i32: 456,
+ u64: 4563424,
+ isize: -365,
+ float: 3.5,
+ double: std::f64::NAN,
+ now: chrono::Utc::now().naive_local(),
+ date: chrono::naive::NaiveDate::from_ymd_opt(2015, 3, 14).unwrap(),
+ byte_vec: vec![0x65, 0x66, 0x67],
+ }];
+
+ let mut out: Vec<APartiallyCompleteRecord> = Vec::new();
+
+ use parquet::file::{reader::FileReader, serialized_reader::SerializedFileReader};
+
+ let generated_schema = drs.as_slice().schema().unwrap();
+
+ let props = Default::default();
+ let mut writer =
+ SerializedFileWriter::new(file.try_clone().unwrap(), generated_schema, props).unwrap();
+
+ let mut row_group = writer.next_row_group().unwrap();
+ drs.as_slice().write_to_row_group(&mut row_group).unwrap();
+ row_group.close().unwrap();
+ writer.close().unwrap();
+
+ let reader = SerializedFileReader::new(file).unwrap();
+
+ let mut row_group = reader.get_row_group(0).unwrap();
+ out.read_from_row_group(&mut *row_group, 1).unwrap();
+
+ // correct for rounding error when writing milliseconds
+ drs[0].now =
+ chrono::naive::NaiveDateTime::from_timestamp_millis(drs[0].now.timestamp_millis())
+ .unwrap();
+
+ assert!(out[0].double.is_nan()); // these three lines are necessary because NAN != NAN
+ out[0].double = 0.;
+ drs[0].double = 0.;
+
+ assert_eq!(drs[0], out[0]);
+ }
+
/// Returns file handle for a temp file in 'target' directory with a provided content
pub fn get_temp_file(file_name: &str, content: &[u8]) -> fs::File {
// build tmp path to a file in "target/debug/testdata"
|
There exists a `ParquetRecordWriter` proc macro in `parquet_derive`, but `ParquetRecordReader` is missing
## Is your feature request related to a problem or challenge? Please describe what you are trying to do.
Reading parquet files into slices of structs can take quite a lot of code. There exists a `parquet_derive::ParquetRecordWriter` derive macro to write from a slice of structs to a parquet file, but there is no equivalent `parquet_derive::ParquetRecordReader` macro.
## Describe the solution you'd like
A `parquet_derive::ParquetRecordReader` macro that does the same as `parquet_derive::ParquetRecordWriter` but for reading.
There already exists a `parquet::record::RecordWriter` trait:
https://github.com/apache/arrow-rs/blob/587250c8e0f9707cc102bd04573395c153249ced/parquet/src/record/record_writer.rs#L23-L31
I would like there to be a similar `parquet::record::RecordReader` trait such as:
```rust
pub trait RecordReader<T> {
fn read_from_row_group(
&mut self,
row_group_reader: &mut dyn RowGroupReader,
max_records: usize,
) -> Result<(), ParquetError>;
}
```
There also exists a `parquet_derive::ParquetRecordWriter` proc macro to implement this trait for slices of structs:
https://github.com/apache/arrow-rs/blob/587250c8e0f9707cc102bd04573395c153249ced/parquet_derive/src/lib.rs#L77-L78
Generates code to implement trait here:
https://github.com/apache/arrow-rs/blob/587250c8e0f9707cc102bd04573395c153249ced/parquet_derive/src/lib.rs#L98
So I would again like there to be a similar `parquet_derive::ParquetRecordReader` that implements something like:
```rust
impl #generics ::parquet::record::RecordReader<#derived_for #generics> for &mut [#derived_for #generics] {
```
## Describe alternatives you've considered
The alternative is for the user to write this code by hand. However, for large structs a macro is necessary and then quickly becomes quite a lot of code ontop of the existing parquet library.
## Additional context
I have already implemented a possible solution which I will make a PR for.
|
2023-09-04T16:10:38Z
|
48.0
|
e78d1409c265ae5c216fc62e51a0f20aa55f6415
|
|
apache/arrow-rs
| 4,752
|
apache__arrow-rs-4752
|
[
"4750"
] |
32e973d7fd90a6f94799177a6d3735c6e3201689
|
diff --git a/arrow/src/ffi_stream.rs b/arrow/src/ffi_stream.rs
index 7005cadc623c..865a8d0e0a29 100644
--- a/arrow/src/ffi_stream.rs
+++ b/arrow/src/ffi_stream.rs
@@ -281,7 +281,7 @@ fn get_stream_schema(stream_ptr: *mut FFI_ArrowArrayStream) -> Result<SchemaRef>
let ret_code = unsafe { (*stream_ptr).get_schema.unwrap()(stream_ptr, &mut schema) };
if ret_code == 0 {
- let schema = Schema::try_from(&schema).unwrap();
+ let schema = Schema::try_from(&schema)?;
Ok(Arc::new(schema))
} else {
Err(ArrowError::CDataInterface(format!(
|
diff --git a/arrow-pyarrow-integration-testing/tests/test_sql.py b/arrow-pyarrow-integration-testing/tests/test_sql.py
index 92782b9ed473..e2e8d66c0f29 100644
--- a/arrow-pyarrow-integration-testing/tests/test_sql.py
+++ b/arrow-pyarrow-integration-testing/tests/test_sql.py
@@ -421,6 +421,14 @@ def iter_batches():
with pytest.raises(ValueError, match="test error"):
rust.reader_return_errors(reader)
+ # Due to a long-standing oversight, PyArrow allows binary values in schema
+ # metadata that are not valid UTF-8. This is not allowed in Rust, but we
+ # make sure we error and not panic here.
+ schema = schema.with_metadata({"key": b"\xff"})
+ reader = pa.RecordBatchReader.from_batches(schema, iter_batches())
+ with pytest.raises(ValueError, match="invalid utf-8"):
+ rust.round_trip_record_batch_reader(reader)
+
def test_reject_other_classes():
# Arbitrary type that is not a PyArrow type
not_pyarrow = ["hello"]
|
stream ffi panics if schema metadata values aren't valid utf8
**Describe the bug**
The values in schema and field metadata should be valid UTF-8 according to the flatbuffers files but, due to a long-standing oversight, the C++ / Python implementations use binary and not string values. So it would be nicer to them if we returned an error instead of panicking when we encounter invalid utf8 imported over ffi.
**To Reproduce**
Unwrap occurs here:
https://github.com/apache/arrow-rs/blob/32e973d7fd90a6f94799177a6d3735c6e3201689/arrow/src/ffi_stream.rs#L284-L284
**Expected behavior**
<!--
A clear and concise description of what you expected to happen.
-->
**Additional context**
[Arrow dev ML thread](https://lists.apache.org/thread/y08fl9qztm4zg79bl2jttz9yzy89mlcn)
|
2023-08-30T03:38:46Z
|
46.0
|
878217b9e330b4f1ed13e798a214ea11fbeb2bbb
|
|
apache/arrow-rs
| 4,751
|
apache__arrow-rs-4751
|
[
"4730"
] |
eeba0a3792a2774dee1d10a25340b2741cf95c9e
|
diff --git a/arrow/src/lib.rs b/arrow/src/lib.rs
index fb904c1908e6..f4d0585fa6b5 100644
--- a/arrow/src/lib.rs
+++ b/arrow/src/lib.rs
@@ -375,7 +375,8 @@ pub mod pyarrow;
pub mod record_batch {
pub use arrow_array::{
- RecordBatch, RecordBatchOptions, RecordBatchReader, RecordBatchWriter,
+ RecordBatch, RecordBatchIterator, RecordBatchOptions, RecordBatchReader,
+ RecordBatchWriter,
};
}
pub use arrow_array::temporal_conversions;
diff --git a/arrow/src/pyarrow.rs b/arrow/src/pyarrow.rs
index 0e9669c5e9fa..6063ae763228 100644
--- a/arrow/src/pyarrow.rs
+++ b/arrow/src/pyarrow.rs
@@ -15,15 +15,51 @@
// specific language governing permissions and limitations
// under the License.
-//! Pass Arrow objects from and to Python, using Arrow's
+//! Pass Arrow objects from and to PyArrow, using Arrow's
//! [C Data Interface](https://arrow.apache.org/docs/format/CDataInterface.html)
//! and [pyo3](https://docs.rs/pyo3/latest/pyo3/).
//! For underlying implementation, see the [ffi] module.
+//!
+//! One can use these to write Python functions that take and return PyArrow
+//! objects, with automatic conversion to corresponding arrow-rs types.
+//!
+//! ```ignore
+//! #[pyfunction]
+//! fn double_array(array: PyArrowType<ArrayData>) -> PyResult<PyArrowType<ArrayData>> {
+//! let array = array.0; // Extract from PyArrowType wrapper
+//! let array: Arc<dyn Array> = make_array(array); // Convert ArrayData to ArrayRef
+//! let array: &Int32Array = array.as_any().downcast_ref()
+//! .ok_or_else(|| PyValueError::new_err("expected int32 array"))?;
+//! let array: Int32Array = array.iter().map(|x| x.map(|x| x * 2)).collect();
+//! Ok(PyArrowType(array.into_data()))
+//! }
+//! ```
+//!
+//! | pyarrow type | arrow-rs type |
+//! |-----------------------------|--------------------------------------------------------------------|
+//! | `pyarrow.DataType` | [DataType] |
+//! | `pyarrow.Field` | [Field] |
+//! | `pyarrow.Schema` | [Schema] |
+//! | `pyarrow.Array` | [ArrayData] |
+//! | `pyarrow.RecordBatch` | [RecordBatch] |
+//! | `pyarrow.RecordBatchReader` | [ArrowArrayStreamReader] / `Box<dyn RecordBatchReader + Send>` (1) |
+//!
+//! (1) `pyarrow.RecordBatchReader` can be imported as [ArrowArrayStreamReader]. Either
+//! [ArrowArrayStreamReader] or `Box<dyn RecordBatchReader + Send>` can be exported
+//! as `pyarrow.RecordBatchReader`. (`Box<dyn RecordBatchReader + Send>` is typically
+//! easier to create.)
+//!
+//! PyArrow has the notion of chunked arrays and tables, but arrow-rs doesn't
+//! have these same concepts. A chunked table is instead represented with
+//! `Vec<RecordBatch>`. A `pyarrow.Table` can be imported to Rust by calling
+//! [pyarrow.Table.to_reader()](https://arrow.apache.org/docs/python/generated/pyarrow.Table.html#pyarrow.Table.to_reader)
+//! and then importing the reader as a [ArrowArrayStreamReader].
use std::convert::{From, TryFrom};
use std::ptr::{addr_of, addr_of_mut};
use std::sync::Arc;
+use arrow_array::RecordBatchReader;
use pyo3::exceptions::{PyTypeError, PyValueError};
use pyo3::ffi::Py_uintptr_t;
use pyo3::import_exception;
@@ -256,6 +292,7 @@ impl ToPyArrow for RecordBatch {
}
}
+/// Supports conversion from `pyarrow.RecordBatchReader` to [ArrowArrayStreamReader].
impl FromPyArrow for ArrowArrayStreamReader {
fn from_pyarrow(value: &PyAny) -> PyResult<Self> {
validate_class("RecordBatchReader", value)?;
@@ -277,10 +314,13 @@ impl FromPyArrow for ArrowArrayStreamReader {
}
}
-impl IntoPyArrow for ArrowArrayStreamReader {
+/// Convert a [`RecordBatchReader`] into a `pyarrow.RecordBatchReader`.
+impl IntoPyArrow for Box<dyn RecordBatchReader + Send> {
+ // We can't implement `ToPyArrow` for `T: RecordBatchReader + Send` because
+ // there is already a blanket implementation for `T: ToPyArrow`.
fn into_pyarrow(self, py: Python) -> PyResult<PyObject> {
let mut stream = FFI_ArrowArrayStream::empty();
- unsafe { export_reader_into_raw(Box::new(self), &mut stream) };
+ unsafe { export_reader_into_raw(self, &mut stream) };
let stream_ptr = (&mut stream) as *mut FFI_ArrowArrayStream;
let module = py.import("pyarrow")?;
@@ -292,8 +332,17 @@ impl IntoPyArrow for ArrowArrayStreamReader {
}
}
-/// A newtype wrapper around a `T: PyArrowConvert` that implements
-/// [`FromPyObject`] and [`IntoPy`] allowing usage with pyo3 macros
+/// Convert a [`ArrowArrayStreamReader`] into a `pyarrow.RecordBatchReader`.
+impl IntoPyArrow for ArrowArrayStreamReader {
+ fn into_pyarrow(self, py: Python) -> PyResult<PyObject> {
+ let boxed: Box<dyn RecordBatchReader + Send> = Box::new(self);
+ boxed.into_pyarrow(py)
+ }
+}
+
+/// A newtype wrapper. When wrapped around a type `T: FromPyArrow`, it
+/// implements `FromPyObject` for the PyArrow objects. When wrapped around a
+/// `T: IntoPyArrow`, it implements `IntoPy<PyObject>` for the wrapped type.
#[derive(Debug)]
pub struct PyArrowType<T>(pub T);
|
diff --git a/arrow-pyarrow-integration-testing/src/lib.rs b/arrow-pyarrow-integration-testing/src/lib.rs
index adcec769f247..a53447b53c31 100644
--- a/arrow-pyarrow-integration-testing/src/lib.rs
+++ b/arrow-pyarrow-integration-testing/src/lib.rs
@@ -21,6 +21,7 @@
use std::sync::Arc;
use arrow::array::new_empty_array;
+use arrow::record_batch::{RecordBatchIterator, RecordBatchReader};
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use pyo3::wrap_pyfunction;
@@ -152,6 +153,20 @@ fn reader_return_errors(obj: PyArrowType<ArrowArrayStreamReader>) -> PyResult<()
}
}
+#[pyfunction]
+fn boxed_reader_roundtrip(
+ obj: PyArrowType<ArrowArrayStreamReader>,
+) -> PyArrowType<Box<dyn RecordBatchReader + Send>> {
+ let schema = obj.0.schema();
+ let batches = obj
+ .0
+ .collect::<Result<Vec<RecordBatch>, ArrowError>>()
+ .unwrap();
+ let reader = RecordBatchIterator::new(batches.into_iter().map(Ok), schema);
+ let reader: Box<dyn RecordBatchReader + Send> = Box::new(reader);
+ PyArrowType(reader)
+}
+
#[pymodule]
fn arrow_pyarrow_integration_testing(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_wrapped(wrap_pyfunction!(double))?;
@@ -166,5 +181,6 @@ fn arrow_pyarrow_integration_testing(_py: Python, m: &PyModule) -> PyResult<()>
m.add_wrapped(wrap_pyfunction!(round_trip_record_batch))?;
m.add_wrapped(wrap_pyfunction!(round_trip_record_batch_reader))?;
m.add_wrapped(wrap_pyfunction!(reader_return_errors))?;
+ m.add_wrapped(wrap_pyfunction!(boxed_reader_roundtrip))?;
Ok(())
}
diff --git a/arrow-pyarrow-integration-testing/tests/test_sql.py b/arrow-pyarrow-integration-testing/tests/test_sql.py
index e2e8d66c0f29..3be5b9ec52fe 100644
--- a/arrow-pyarrow-integration-testing/tests/test_sql.py
+++ b/arrow-pyarrow-integration-testing/tests/test_sql.py
@@ -409,6 +409,13 @@ def test_record_batch_reader():
got_batches = list(b)
assert got_batches == batches
+ # Also try the boxed reader variant
+ a = pa.RecordBatchReader.from_batches(schema, batches)
+ b = rust.boxed_reader_roundtrip(a)
+ assert b.schema == schema
+ got_batches = list(b)
+ assert got_batches == batches
+
def test_record_batch_reader_error():
schema = pa.schema([('ints', pa.list_(pa.int32()))])
|
Support IntoPyArrow for impl RecordBatchReader
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
It's a little awkward to export RBR, since you have to export them manually like:
```
let batch_reader = ...
let stream = FFI_ArrowArrayStream::new(Box::new(batch_reader));
let stream_reader = ArrowArrayStreamReader::try_new(stream).unwrap();
Ok(PyArrowType(stream_reader))
```
**Describe the solution you'd like**
As a convenience, we can implement `IntoPyArrow` for `RecordBatchReader`.
**Describe alternatives you've considered**
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
|
2023-08-30T03:21:34Z
|
46.0
|
878217b9e330b4f1ed13e798a214ea11fbeb2bbb
|
|
apache/arrow-rs
| 4,681
|
apache__arrow-rs-4681
|
[
"4255"
] |
c6184389241a0c85823aa494e8b5d93343771666
|
diff --git a/arrow-array/src/array/list_array.rs b/arrow-array/src/array/list_array.rs
index 05628084c844..e50f2eb0941d 100644
--- a/arrow-array/src/array/list_array.rs
+++ b/arrow-array/src/array/list_array.rs
@@ -1037,13 +1037,17 @@ mod tests {
#[should_panic(
expected = "Memory pointer is not aligned with the specified scalar type"
)]
+ // Different error messages, so skip for now
+ // https://github.com/apache/arrow-rs/issues/1545
+ #[cfg(not(feature = "force_validate"))]
fn test_primitive_array_alignment() {
let buf = Buffer::from_slice_ref([0_u64]);
let buf2 = buf.slice(1);
- let array_data = ArrayData::builder(DataType::Int32)
- .add_buffer(buf2)
- .build()
- .unwrap();
+ let array_data = unsafe {
+ ArrayData::builder(DataType::Int32)
+ .add_buffer(buf2)
+ .build_unchecked()
+ };
drop(Int32Array::from(array_data));
}
diff --git a/arrow-array/src/types.rs b/arrow-array/src/types.rs
index 769dbf974b93..d79b32a991ed 100644
--- a/arrow-array/src/types.rs
+++ b/arrow-array/src/types.rs
@@ -1494,7 +1494,6 @@ pub type LargeBinaryType = GenericBinaryType<i64>;
mod tests {
use super::*;
use arrow_data::{layout, BufferSpec};
- use std::mem::size_of;
#[test]
fn month_day_nano_should_roundtrip() {
@@ -1541,7 +1540,8 @@ mod tests {
assert_eq!(
spec,
&BufferSpec::FixedWidth {
- byte_width: size_of::<T::Native>()
+ byte_width: std::mem::size_of::<T::Native>(),
+ alignment: std::mem::align_of::<T::Native>(),
}
);
}
diff --git a/arrow-data/src/data.rs b/arrow-data/src/data.rs
index 6ff8a824b2ff..0417e1d357c7 100644
--- a/arrow-data/src/data.rs
+++ b/arrow-data/src/data.rs
@@ -20,7 +20,7 @@
use crate::bit_iterator::BitSliceIterator;
use arrow_buffer::buffer::{BooleanBuffer, NullBuffer};
-use arrow_buffer::{bit_util, ArrowNativeType, Buffer, MutableBuffer};
+use arrow_buffer::{bit_util, i256, ArrowNativeType, Buffer, MutableBuffer};
use arrow_schema::{ArrowError, DataType, UnionMode};
use std::convert::TryInto;
use std::mem;
@@ -451,7 +451,7 @@ impl ArrayData {
for spec in layout.buffers.iter() {
match spec {
- BufferSpec::FixedWidth { byte_width } => {
+ BufferSpec::FixedWidth { byte_width, .. } => {
let buffer_size =
self.len.checked_mul(*byte_width).ok_or_else(|| {
ArrowError::ComputeError(
@@ -699,6 +699,23 @@ impl ArrayData {
Self::new_null(data_type, 0)
}
+ /// Verifies that the buffers meet the minimum alignment requirements for the data type
+ ///
+ /// Buffers that are not adequately aligned will be copied to a new aligned allocation
+ ///
+ /// This can be useful for when interacting with data sent over IPC or FFI, that may
+ /// not meet the minimum alignment requirements
+ fn align_buffers(&mut self) {
+ let layout = layout(&self.data_type);
+ for (buffer, spec) in self.buffers.iter_mut().zip(&layout.buffers) {
+ if let BufferSpec::FixedWidth { alignment, .. } = spec {
+ if buffer.as_ptr().align_offset(*alignment) != 0 {
+ *buffer = Buffer::from_slice_ref(buffer.as_ref())
+ }
+ }
+ }
+ }
+
/// "cheap" validation of an `ArrayData`. Ensures buffers are
/// sufficiently sized to store `len` + `offset` total elements of
/// `data_type` and performs other inexpensive consistency checks.
@@ -736,10 +753,11 @@ impl ArrayData {
self.buffers.iter().zip(layout.buffers.iter()).enumerate()
{
match spec {
- BufferSpec::FixedWidth { byte_width } => {
- let min_buffer_size = len_plus_offset
- .checked_mul(*byte_width)
- .expect("integer overflow computing min buffer size");
+ BufferSpec::FixedWidth {
+ byte_width,
+ alignment,
+ } => {
+ let min_buffer_size = len_plus_offset.saturating_mul(*byte_width);
if buffer.len() < min_buffer_size {
return Err(ArrowError::InvalidArgumentError(format!(
@@ -747,6 +765,14 @@ impl ArrayData {
min_buffer_size, i, self.data_type, buffer.len()
)));
}
+
+ let align_offset = buffer.as_ptr().align_offset(*alignment);
+ if align_offset != 0 {
+ return Err(ArrowError::InvalidArgumentError(format!(
+ "Misaligned buffers[{i}] in array of type {:?}, offset from expected alignment of {alignment} by {}",
+ self.data_type, align_offset.min(alignment - align_offset)
+ )));
+ }
}
BufferSpec::VariableWidth => {
// not cheap to validate (need to look at the
@@ -1493,7 +1519,8 @@ impl ArrayData {
pub fn layout(data_type: &DataType) -> DataTypeLayout {
// based on C/C++ implementation in
// https://github.com/apache/arrow/blob/661c7d749150905a63dd3b52e0a04dac39030d95/cpp/src/arrow/type.h (and .cc)
- use std::mem::size_of;
+ use arrow_schema::IntervalUnit::*;
+
match data_type {
DataType::Null => DataTypeLayout {
buffers: vec![],
@@ -1503,44 +1530,52 @@ pub fn layout(data_type: &DataType) -> DataTypeLayout {
buffers: vec![BufferSpec::BitMap],
can_contain_null_mask: true,
},
- DataType::Int8
- | DataType::Int16
- | DataType::Int32
- | DataType::Int64
- | DataType::UInt8
- | DataType::UInt16
- | DataType::UInt32
- | DataType::UInt64
- | DataType::Float16
- | DataType::Float32
- | DataType::Float64
- | DataType::Timestamp(_, _)
- | DataType::Date32
- | DataType::Date64
- | DataType::Time32(_)
- | DataType::Time64(_)
- | DataType::Interval(_) => {
- DataTypeLayout::new_fixed_width(data_type.primitive_width().unwrap())
- }
- DataType::Duration(_) => DataTypeLayout::new_fixed_width(size_of::<i64>()),
- DataType::Binary => DataTypeLayout::new_binary(size_of::<i32>()),
- DataType::FixedSizeBinary(bytes_per_value) => {
- let bytes_per_value: usize = (*bytes_per_value)
- .try_into()
- .expect("negative size for fixed size binary");
- DataTypeLayout::new_fixed_width(bytes_per_value)
+ DataType::Int8 => DataTypeLayout::new_fixed_width::<i8>(),
+ DataType::Int16 => DataTypeLayout::new_fixed_width::<i16>(),
+ DataType::Int32 => DataTypeLayout::new_fixed_width::<i32>(),
+ DataType::Int64 => DataTypeLayout::new_fixed_width::<i64>(),
+ DataType::UInt8 => DataTypeLayout::new_fixed_width::<u8>(),
+ DataType::UInt16 => DataTypeLayout::new_fixed_width::<u16>(),
+ DataType::UInt32 => DataTypeLayout::new_fixed_width::<u32>(),
+ DataType::UInt64 => DataTypeLayout::new_fixed_width::<u64>(),
+ DataType::Float16 => DataTypeLayout::new_fixed_width::<half::f16>(),
+ DataType::Float32 => DataTypeLayout::new_fixed_width::<f32>(),
+ DataType::Float64 => DataTypeLayout::new_fixed_width::<f64>(),
+ DataType::Timestamp(_, _) => DataTypeLayout::new_fixed_width::<i64>(),
+ DataType::Date32 => DataTypeLayout::new_fixed_width::<i32>(),
+ DataType::Date64 => DataTypeLayout::new_fixed_width::<i64>(),
+ DataType::Time32(_) => DataTypeLayout::new_fixed_width::<i32>(),
+ DataType::Time64(_) => DataTypeLayout::new_fixed_width::<i64>(),
+ DataType::Interval(YearMonth) => DataTypeLayout::new_fixed_width::<i32>(),
+ DataType::Interval(DayTime) => DataTypeLayout::new_fixed_width::<i64>(),
+ DataType::Interval(MonthDayNano) => DataTypeLayout::new_fixed_width::<i128>(),
+ DataType::Duration(_) => DataTypeLayout::new_fixed_width::<i64>(),
+ DataType::Decimal128(_, _) => DataTypeLayout::new_fixed_width::<i128>(),
+ DataType::Decimal256(_, _) => DataTypeLayout::new_fixed_width::<i256>(),
+ DataType::FixedSizeBinary(size) => {
+ let spec = BufferSpec::FixedWidth {
+ byte_width: (*size).try_into().unwrap(),
+ alignment: mem::align_of::<u8>(),
+ };
+ DataTypeLayout {
+ buffers: vec![spec],
+ can_contain_null_mask: true,
+ }
}
- DataType::LargeBinary => DataTypeLayout::new_binary(size_of::<i64>()),
- DataType::Utf8 => DataTypeLayout::new_binary(size_of::<i32>()),
- DataType::LargeUtf8 => DataTypeLayout::new_binary(size_of::<i64>()),
- DataType::List(_) => DataTypeLayout::new_fixed_width(size_of::<i32>()),
+ DataType::Binary => DataTypeLayout::new_binary::<i32>(),
+ DataType::LargeBinary => DataTypeLayout::new_binary::<i64>(),
+ DataType::Utf8 => DataTypeLayout::new_binary::<i32>(),
+ DataType::LargeUtf8 => DataTypeLayout::new_binary::<i64>(),
DataType::FixedSizeList(_, _) => DataTypeLayout::new_empty(), // all in child data
- DataType::LargeList(_) => DataTypeLayout::new_fixed_width(size_of::<i64>()),
+ DataType::List(_) => DataTypeLayout::new_fixed_width::<i32>(),
+ DataType::LargeList(_) => DataTypeLayout::new_fixed_width::<i64>(),
+ DataType::Map(_, _) => DataTypeLayout::new_fixed_width::<i32>(),
DataType::Struct(_) => DataTypeLayout::new_empty(), // all in child data,
DataType::RunEndEncoded(_, _) => DataTypeLayout::new_empty(), // all in child data,
DataType::Union(_, mode) => {
let type_ids = BufferSpec::FixedWidth {
- byte_width: size_of::<i8>(),
+ byte_width: mem::size_of::<i8>(),
+ alignment: mem::align_of::<i8>(),
};
DataTypeLayout {
@@ -1552,7 +1587,8 @@ pub fn layout(data_type: &DataType) -> DataTypeLayout {
vec![
type_ids,
BufferSpec::FixedWidth {
- byte_width: size_of::<i32>(),
+ byte_width: mem::size_of::<i32>(),
+ alignment: mem::align_of::<i32>(),
},
]
}
@@ -1561,19 +1597,6 @@ pub fn layout(data_type: &DataType) -> DataTypeLayout {
}
}
DataType::Dictionary(key_type, _value_type) => layout(key_type),
- DataType::Decimal128(_, _) => {
- // Decimals are always some fixed width; The rust implementation
- // always uses 16 bytes / size of i128
- DataTypeLayout::new_fixed_width(size_of::<i128>())
- }
- DataType::Decimal256(_, _) => {
- // Decimals are always some fixed width.
- DataTypeLayout::new_fixed_width(32)
- }
- DataType::Map(_, _) => {
- // same as ListType
- DataTypeLayout::new_fixed_width(size_of::<i32>())
- }
}
}
@@ -1589,10 +1612,13 @@ pub struct DataTypeLayout {
}
impl DataTypeLayout {
- /// Describes a basic numeric array where each element has a fixed width
- pub fn new_fixed_width(byte_width: usize) -> Self {
+ /// Describes a basic numeric array where each element has type `T`
+ pub fn new_fixed_width<T>() -> Self {
Self {
- buffers: vec![BufferSpec::FixedWidth { byte_width }],
+ buffers: vec![BufferSpec::FixedWidth {
+ byte_width: mem::size_of::<T>(),
+ alignment: mem::align_of::<T>(),
+ }],
can_contain_null_mask: true,
}
}
@@ -1608,14 +1634,15 @@ impl DataTypeLayout {
}
/// Describes a basic numeric array where each element has a fixed
- /// with offset buffer of `offset_byte_width` bytes, followed by a
+ /// with offset buffer of type `T`, followed by a
/// variable width data buffer
- pub fn new_binary(offset_byte_width: usize) -> Self {
+ pub fn new_binary<T>() -> Self {
Self {
buffers: vec![
// offsets
BufferSpec::FixedWidth {
- byte_width: offset_byte_width,
+ byte_width: mem::size_of::<T>(),
+ alignment: mem::align_of::<T>(),
},
// values
BufferSpec::VariableWidth,
@@ -1628,8 +1655,18 @@ impl DataTypeLayout {
/// Layout specification for a single data type buffer
#[derive(Debug, PartialEq, Eq)]
pub enum BufferSpec {
- /// each element has a fixed width
- FixedWidth { byte_width: usize },
+ /// Each element is a fixed width primitive, with the given `byte_width` and `alignment`
+ ///
+ /// `alignment` is the alignment required by Rust for an array of the corresponding primitive,
+ /// see [`Layout::array`](std::alloc::Layout::array) and [`std::mem::align_of`].
+ ///
+ /// Arrow-rs requires that all buffers are have at least this alignment, to allow for
+ /// [slice](std::slice) based APIs. We do not require alignment in excess of this to allow
+ /// for array slicing, and interoperability with `Vec` which in the absence of support
+ /// for custom allocators, cannot be over-aligned.
+ ///
+ /// Note that these alignment requirements will vary between architectures
+ FixedWidth { byte_width: usize, alignment: usize },
/// Variable width, such as string data for utf8 data
VariableWidth,
/// Buffer holds a bitmap.
@@ -1741,6 +1778,15 @@ impl ArrayDataBuilder {
/// apply.
#[allow(clippy::let_and_return)]
pub unsafe fn build_unchecked(self) -> ArrayData {
+ let data = self.build_impl();
+ // Provide a force_validate mode
+ #[cfg(feature = "force_validate")]
+ data.validate_data().unwrap();
+ data
+ }
+
+ /// Same as [`Self::build_unchecked`] but ignoring `force_validate` feature flag
+ unsafe fn build_impl(self) -> ArrayData {
let nulls = self.nulls.or_else(|| {
let buffer = self.null_bit_buffer?;
let buffer = BooleanBuffer::new(buffer, self.offset, self.len);
@@ -1750,26 +1796,41 @@ impl ArrayDataBuilder {
})
});
- let data = ArrayData {
+ ArrayData {
data_type: self.data_type,
len: self.len,
offset: self.offset,
buffers: self.buffers,
child_data: self.child_data,
nulls: nulls.filter(|b| b.null_count() != 0),
- };
-
- // Provide a force_validate mode
- #[cfg(feature = "force_validate")]
- data.validate_data().unwrap();
- data
+ }
}
/// Creates an array data, validating all inputs
- #[allow(clippy::let_and_return)]
pub fn build(self) -> Result<ArrayData, ArrowError> {
- let data = unsafe { self.build_unchecked() };
- #[cfg(not(feature = "force_validate"))]
+ let data = unsafe { self.build_impl() };
+ data.validate_data()?;
+ Ok(data)
+ }
+
+ /// Creates an array data, validating all inputs, and aligning any buffers
+ ///
+ /// Rust requires that arrays are aligned to their corresponding primitive,
+ /// see [`Layout::array`](std::alloc::Layout::array) and [`std::mem::align_of`].
+ ///
+ /// [`ArrayData`] therefore requires that all buffers are have at least this alignment,
+ /// to allow for [slice](std::slice) based APIs. See [`BufferSpec::FixedWidth`].
+ ///
+ /// As this alignment is architecture specific, and not guaranteed by all arrow implementations,
+ /// this method is provided to automatically copy buffers to a new correctly aligned allocation
+ /// when necessary, making it useful when interacting with buffers produced by other systems,
+ /// e.g. IPC or FFI.
+ ///
+ /// This is unlike `[Self::build`] which will instead return an error on encountering
+ /// insufficiently aligned buffers.
+ pub fn build_aligned(self) -> Result<ArrayData, ArrowError> {
+ let mut data = unsafe { self.build_impl() };
+ data.align_buffers();
data.validate_data()?;
Ok(data)
}
@@ -2057,4 +2118,31 @@ mod tests {
assert_eq!(buffers.len(), layout.buffers.len());
}
}
+
+ #[test]
+ fn test_alignment() {
+ let buffer = Buffer::from_vec(vec![1_i32, 2_i32, 3_i32]);
+ let sliced = buffer.slice(1);
+
+ let mut data = ArrayData {
+ data_type: DataType::Int32,
+ len: 0,
+ offset: 0,
+ buffers: vec![buffer],
+ child_data: vec![],
+ nulls: None,
+ };
+ data.validate_full().unwrap();
+
+ data.buffers[0] = sliced;
+ let err = data.validate().unwrap_err();
+
+ assert_eq!(
+ err.to_string(),
+ "Invalid argument error: Misaligned buffers[0] in array of type Int32, offset from expected alignment of 4 by 1"
+ );
+
+ data.align_buffers();
+ data.validate_full().unwrap();
+ }
}
diff --git a/arrow-ipc/src/reader.rs b/arrow-ipc/src/reader.rs
index 0908d580d59a..b7d328977d1c 100644
--- a/arrow-ipc/src/reader.rs
+++ b/arrow-ipc/src/reader.rs
@@ -20,7 +20,6 @@
//! The `FileReader` and `StreamReader` have similar interfaces,
//! however the `FileReader` expects a reader that supports `Seek`ing
-use arrow_buffer::i256;
use flatbuffers::VectorIter;
use std::collections::HashMap;
use std::fmt;
@@ -129,7 +128,7 @@ fn create_array(reader: &mut ArrayReader, field: &Field) -> Result<ArrayRef, Arr
.offset(0)
.add_child_data(run_ends.into_data())
.add_child_data(values.into_data())
- .build()?;
+ .build_aligned()?;
Ok(make_array(data))
}
@@ -202,7 +201,7 @@ fn create_array(reader: &mut ArrayReader, field: &Field) -> Result<ArrayRef, Arr
let data = ArrayData::builder(data_type.clone())
.len(length as usize)
.offset(0)
- .build()
+ .build_aligned()
.unwrap();
// no buffer increases
Ok(Arc::new(NullArray::from(data)))
@@ -231,54 +230,17 @@ fn create_primitive_array(
.len(length)
.buffers(buffers[1..3].to_vec())
.null_bit_buffer(null_buffer)
- .build()?
+ .build_aligned()?
}
- Int8
- | Int16
- | Int32
- | UInt8
- | UInt16
- | UInt32
- | Time32(_)
- | Date32
- | Interval(IntervalUnit::YearMonth)
- | Interval(IntervalUnit::DayTime)
- | FixedSizeBinary(_)
- | Boolean
- | Int64
- | UInt64
- | Float32
- | Float64
- | Time64(_)
- | Timestamp(_, _)
- | Date64
- | Duration(_) => {
+ _ if data_type.is_primitive()
+ || matches!(data_type, Boolean | FixedSizeBinary(_)) =>
+ {
// read 2 buffers: null buffer (optional) and data buffer
ArrayData::builder(data_type.clone())
.len(length)
.add_buffer(buffers[1].clone())
.null_bit_buffer(null_buffer)
- .build()?
- }
- Interval(IntervalUnit::MonthDayNano) | Decimal128(_, _) => {
- let buffer = get_aligned_buffer::<i128>(&buffers[1], length);
-
- // read 2 buffers: null buffer (optional) and data buffer
- ArrayData::builder(data_type.clone())
- .len(length)
- .add_buffer(buffer)
- .null_bit_buffer(null_buffer)
- .build()?
- }
- Decimal256(_, _) => {
- let buffer = get_aligned_buffer::<i256>(&buffers[1], length);
-
- // read 2 buffers: null buffer (optional) and data buffer
- ArrayData::builder(data_type.clone())
- .len(length)
- .add_buffer(buffer)
- .null_bit_buffer(null_buffer)
- .build()?
+ .build_aligned()?
}
t => unreachable!("Data type {:?} either unsupported or not primitive", t),
};
@@ -286,28 +248,10 @@ fn create_primitive_array(
Ok(make_array(array_data))
}
-/// Checks if given `Buffer` is properly aligned with `T`.
-/// If not, copying the data and padded it for alignment.
-fn get_aligned_buffer<T>(buffer: &Buffer, length: usize) -> Buffer {
- let ptr = buffer.as_ptr();
- let align_req = std::mem::align_of::<T>();
- let align_offset = ptr.align_offset(align_req);
- // The buffer is not aligned properly. The writer might use a smaller alignment
- // e.g. 8 bytes, but on some platform (e.g. ARM) i128 requires 16 bytes alignment.
- // We need to copy the buffer as fallback.
- if align_offset != 0 {
- let len_in_bytes = (length * std::mem::size_of::<T>()).min(buffer.len());
- let slice = &buffer.as_slice()[0..len_in_bytes];
- Buffer::from_slice_ref(slice)
- } else {
- buffer.clone()
- }
-}
-
/// Reads the correct number of buffers based on list type and null_count, and creates a
/// list array ref
fn create_list_array(
- field_node: &crate::FieldNode,
+ field_node: &FieldNode,
data_type: &DataType,
buffers: &[Buffer],
child_array: ArrayRef,
@@ -329,13 +273,13 @@ fn create_list_array(
_ => unreachable!("Cannot create list or map array from {:?}", data_type),
};
- Ok(make_array(builder.build()?))
+ Ok(make_array(builder.build_aligned()?))
}
/// Reads the correct number of buffers based on list type and null_count, and creates a
/// list array ref
fn create_dictionary_array(
- field_node: &crate::FieldNode,
+ field_node: &FieldNode,
data_type: &DataType,
buffers: &[Buffer],
value_array: ArrayRef,
@@ -348,7 +292,7 @@ fn create_dictionary_array(
.add_child_data(value_array.into_data())
.null_bit_buffer(null_buffer);
- Ok(make_array(builder.build()?))
+ Ok(make_array(builder.build_aligned()?))
} else {
unreachable!("Cannot create dictionary array from {:?}", data_type)
}
@@ -1097,10 +1041,11 @@ impl<R: Read> RecordBatchReader for StreamReader<R> {
#[cfg(test)]
mod tests {
- use crate::writer::unslice_run_array;
+ use crate::writer::{unslice_run_array, DictionaryTracker, IpcDataGenerator};
use super::*;
+ use crate::root_as_message;
use arrow_array::builder::{PrimitiveRunBuilder, UnionBuilder};
use arrow_array::types::*;
use arrow_buffer::ArrowNativeType;
@@ -1357,8 +1302,7 @@ mod tests {
writer.finish().unwrap();
drop(writer);
- let mut reader =
- crate::reader::FileReader::try_new(std::io::Cursor::new(buf), None).unwrap();
+ let mut reader = FileReader::try_new(std::io::Cursor::new(buf), None).unwrap();
reader.next().unwrap().unwrap()
}
@@ -1704,4 +1648,40 @@ mod tests {
let output_batch = roundtrip_ipc_stream(&input_batch);
assert_eq!(input_batch, output_batch);
}
+
+ #[test]
+ fn test_unaligned() {
+ let batch = RecordBatch::try_from_iter(vec![(
+ "i32",
+ Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _,
+ )])
+ .unwrap();
+
+ let gen = IpcDataGenerator {};
+ let mut dict_tracker = DictionaryTracker::new(false);
+ let (_, encoded) = gen
+ .encoded_batch(&batch, &mut dict_tracker, &Default::default())
+ .unwrap();
+
+ let message = root_as_message(&encoded.ipc_message).unwrap();
+
+ // Construct an unaligned buffer
+ let mut buffer = MutableBuffer::with_capacity(encoded.arrow_data.len() + 1);
+ buffer.push(0_u8);
+ buffer.extend_from_slice(&encoded.arrow_data);
+ let b = Buffer::from(buffer).slice(1);
+ assert_ne!(b.as_ptr().align_offset(8), 0);
+
+ let ipc_batch = message.header_as_record_batch().unwrap();
+ let roundtrip = read_record_batch(
+ &b,
+ ipc_batch,
+ batch.schema(),
+ &Default::default(),
+ None,
+ &message.version(),
+ )
+ .unwrap();
+ assert_eq!(batch, roundtrip);
+ }
}
diff --git a/arrow-ipc/src/writer.rs b/arrow-ipc/src/writer.rs
index 59657bc4be09..1c56613d8f24 100644
--- a/arrow-ipc/src/writer.rs
+++ b/arrow-ipc/src/writer.rs
@@ -1146,7 +1146,7 @@ fn buffer_need_truncate(
#[inline]
fn get_buffer_element_width(spec: &BufferSpec) -> usize {
match spec {
- BufferSpec::FixedWidth { byte_width } => *byte_width,
+ BufferSpec::FixedWidth { byte_width, .. } => *byte_width,
_ => 0,
}
}
|
diff --git a/arrow/tests/array_validation.rs b/arrow/tests/array_validation.rs
index 0d3652a0473a..fa80db1860cd 100644
--- a/arrow/tests/array_validation.rs
+++ b/arrow/tests/array_validation.rs
@@ -56,7 +56,9 @@ fn test_bad_number_of_buffers() {
}
#[test]
-#[should_panic(expected = "integer overflow computing min buffer size")]
+#[should_panic(
+ expected = "Need at least 18446744073709551615 bytes in buffers[0] in array of type Int64, but got 8"
+)]
fn test_fixed_width_overflow() {
let buffer = Buffer::from_slice_ref([0i32, 2i32]);
ArrayData::try_new(DataType::Int64, usize::MAX, None, 0, vec![buffer], vec![])
|
Handle Misaligned IPC Buffers
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
<!--
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
(This section helps Arrow developers understand the context and *why* for this feature, in addition to the *what*)
-->
The flatbuffer specification recommends that buffers are aligned to 64-bit boundaries, however, this is not mandated. Additionally when loading a flatbuffer from an in-memory source, it is possible the source buffer itself isn't aligned.
We already re-align interval buffers, we should do this consistently
**Describe the solution you'd like**
<!--
A clear and concise description of what you want to happen.
-->
We should automatically re-align mis-aligned IPC buffers
**Describe alternatives you've considered**
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
Relates to #4254 which would likely produce mis-aligned buffers
|
2023-08-11T11:00:40Z
|
45.0
|
c6184389241a0c85823aa494e8b5d93343771666
|
|
apache/arrow-rs
| 4,670
|
apache__arrow-rs-4670
|
[
"4637"
] |
5023ea8438e3143bf711a89a3a2ffb8838a18e9e
|
diff --git a/arrow-data/src/equal/fixed_binary.rs b/arrow-data/src/equal/fixed_binary.rs
index 9e0e77ff7eca..40dacdddd3a0 100644
--- a/arrow-data/src/equal/fixed_binary.rs
+++ b/arrow-data/src/equal/fixed_binary.rs
@@ -80,7 +80,7 @@ pub(super) fn fixed_binary_equal(
lhs_start + lhs_nulls.offset(),
len,
);
- let rhs_nulls = lhs.nulls().unwrap();
+ let rhs_nulls = rhs.nulls().unwrap();
let rhs_slices_iter = BitSliceIterator::new(
rhs_nulls.validity(),
rhs_start + rhs_nulls.offset(),
|
diff --git a/arrow/tests/array_equal.rs b/arrow/tests/array_equal.rs
index 83a280db67b8..4abe31a36cf5 100644
--- a/arrow/tests/array_equal.rs
+++ b/arrow/tests/array_equal.rs
@@ -1295,3 +1295,25 @@ fn test_struct_equal_slice() {
test_equal(&a, &b, true);
}
+
+#[test]
+fn test_list_excess_children_equal() {
+ let mut a = ListBuilder::new(FixedSizeBinaryBuilder::new(5));
+ a.values().append_value(b"11111").unwrap(); // Masked value
+ a.append_null();
+ a.values().append_value(b"22222").unwrap();
+ a.values().append_null();
+ a.append(true);
+ let a = a.finish();
+
+ let mut b = ListBuilder::new(FixedSizeBinaryBuilder::new(5));
+ b.append_null();
+ b.values().append_value(b"22222").unwrap();
+ b.values().append_null();
+ b.append(true);
+ let b = b.finish();
+
+ assert_eq!(a.value_offsets(), &[0, 1, 3]);
+ assert_eq!(b.value_offsets(), &[0, 0, 2]);
+ assert_eq!(a, b);
+}
|
`List(FixedSizeBinary)` array equality check may return wrong result
**Describe the bug**
`<ListArray as PartialEq>::eq` returns `false` for two arrays of datatype `List(FixedSizeBinary(5))` containing identical values but physically differ.
**To Reproduce**
```rust
#[test]
fn test_list_excess_children_equal() {
let a_values = create_fixed_size_binary_array([Some(b"11111"), Some(b"22222"), None]);
// ^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^
// a[0] a[1]
let a: ListArray = ArrayDataBuilder::new(DataType::List(Arc::new(Field::new(
"item",
a_values.data_type().clone(),
true,
))))
.len(2)
.add_buffer(Buffer::from(vec![0i32, 1, 3].to_byte_slice()))
.add_child_data(a_values.into_data())
.null_bit_buffer(Some(Buffer::from(&[0b00000010])))
.build()
.unwrap()
.into();
let b_values = create_fixed_size_binary_array([Some(b"22222"), None]);
// ^^^^^^^^^^^^^^^^^^^^
// a[1]
let b: ListArray = ArrayDataBuilder::new(DataType::List(Arc::new(Field::new(
"item",
b_values.data_type().clone(),
true,
))))
.len(2)
.add_buffer(Buffer::from(vec![0i32, 0, 2].to_byte_slice()))
.add_child_data(b_values.into_data())
.null_bit_buffer(Some(Buffer::from(&[0b00000010])))
.build()
.unwrap()
.into();
a.to_data().validate_full().unwrap();
b.to_data().validate_full().unwrap();
assert_eq!(a, b);
}
// from `arrow/tests/array_equal.rs`
fn create_fixed_size_binary_array<U: AsRef<[u8]>, T: AsRef<[Option<U>]>>(
data: T,
) -> FixedSizeBinaryArray {
let mut builder = FixedSizeBinaryBuilder::with_capacity(data.as_ref().len(), 5);
for d in data.as_ref() {
if let Some(v) = d {
builder.append_value(v.as_ref()).unwrap();
} else {
builder.append_null();
}
}
builder.finish()
}
```
```
thread 'test_list_excess_children_equal' panicked at 'assertion failed: `(left == right)`
left: `ListArray
[
null,
FixedSizeBinaryArray<5>
[
[50, 50, 50, 50, 50],
null,
],
]`,
right: `ListArray
[
null,
FixedSizeBinaryArray<5>
[
[50, 50, 50, 50, 50],
null,
],
]`', arrow\tests\array_equal.rs:399:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
```
**Expected behavior**
Returning `true` because they both contain `[null, [[50, 50, 50, 50, 50], null]]` as shown by the debug printing
**Additional context**
<!--
Add any other context about the problem here.
-->
|
These two array isn't equal in fact.
```
values: [
[49, 49, 49, 49, 49],
[50, 50, 50, 50, 50],
null,
]
value_offsets: [0, 1, 3]
values [
[50, 50, 50, 50, 50],
null,
]
value_offsets [0, 0, 2]
```
|
2023-08-09T15:59:12Z
|
45.0
|
c6184389241a0c85823aa494e8b5d93343771666
|
apache/arrow-rs
| 4,665
|
apache__arrow-rs-4665
|
[
"4656"
] |
696cbdbb72e821613f44a09e2b547d2f85c06089
|
diff --git a/arrow-flight/examples/flight_sql_server.rs b/arrow-flight/examples/flight_sql_server.rs
index f717d9b621b2..08a36bc49ea8 100644
--- a/arrow-flight/examples/flight_sql_server.rs
+++ b/arrow-flight/examples/flight_sql_server.rs
@@ -196,9 +196,9 @@ impl FlightSqlService for FlightSqlServiceImpl {
self.check_token(&request)?;
let batch =
Self::fake_result().map_err(|e| status!("Could not fake a result", e))?;
- let schema = (*batch.schema()).clone();
+ let schema = batch.schema();
let batches = vec![batch];
- let flight_data = batches_to_flight_data(schema, batches)
+ let flight_data = batches_to_flight_data(schema.as_ref(), batches)
.map_err(|e| status!("Could not convert batches", e))?
.into_iter()
.map(Ok);
diff --git a/arrow-flight/src/utils.rs b/arrow-flight/src/utils.rs
index ccf1e73866e1..8baf5ed7232a 100644
--- a/arrow-flight/src/utils.rs
+++ b/arrow-flight/src/utils.rs
@@ -147,11 +147,11 @@ pub fn ipc_message_from_arrow_schema(
/// Convert `RecordBatch`es to wire protocol `FlightData`s
pub fn batches_to_flight_data(
- schema: Schema,
+ schema: &Schema,
batches: Vec<RecordBatch>,
) -> Result<Vec<FlightData>, ArrowError> {
let options = IpcWriteOptions::default();
- let schema_flight_data: FlightData = SchemaAsIpc::new(&schema, &options).into();
+ let schema_flight_data: FlightData = SchemaAsIpc::new(schema, &options).into();
let mut dictionaries = vec![];
let mut flight_data = vec![];
|
diff --git a/arrow-flight/tests/flight_sql_client_cli.rs b/arrow-flight/tests/flight_sql_client_cli.rs
index c4ae9280c898..912bcc75a9df 100644
--- a/arrow-flight/tests/flight_sql_client_cli.rs
+++ b/arrow-flight/tests/flight_sql_client_cli.rs
@@ -144,9 +144,9 @@ impl FlightSqlService for FlightSqlServiceImpl {
"part_2" => batch.slice(2, 1),
ticket => panic!("Invalid ticket: {ticket:?}"),
};
- let schema = (*batch.schema()).clone();
+ let schema = batch.schema();
let batches = vec![batch];
- let flight_data = batches_to_flight_data(schema, batches)
+ let flight_data = batches_to_flight_data(schema.as_ref(), batches)
.unwrap()
.into_iter()
.map(Ok);
|
API improvement: `batches_to_flight_data` forces clone
The API is pretty inconsistent, sometimes requiring a `Schema` and sometimes a `SchemaRef`.
For example I hold a `SchemaRef`, but `batches_to_flight_data` requires a `Schema`, forcing me to create a clone of the ref counted object.
Instead, the function should just take a `&Schema`.
```rust
pub fn batches_to_flight_data(
schema: Schema,
batches: Vec<RecordBatch>,
) -> Result<Vec<FlightData>, ArrowError> {
let options = IpcWriteOptions::default();
let schema_flight_data: FlightData = SchemaAsIpc::new(&schema, &options).into();
^___ it's borrowed later anyways!
```
|
Make sense to me
|
2023-08-08T06:08:51Z
|
45.0
|
c6184389241a0c85823aa494e8b5d93343771666
|
apache/arrow-rs
| 4,660
|
apache__arrow-rs-4660
|
[
"4659"
] |
f16ceedf981c7230167ff858eabb9a8cdc87ffda
|
diff --git a/arrow/src/ffi_stream.rs b/arrow/src/ffi_stream.rs
index 7d6689a89058..a9d2e8ab6bf2 100644
--- a/arrow/src/ffi_stream.rs
+++ b/arrow/src/ffi_stream.rs
@@ -54,6 +54,7 @@
//! }
//! ```
+use std::ffi::CStr;
use std::ptr::addr_of;
use std::{
convert::TryFrom,
@@ -120,7 +121,7 @@ unsafe extern "C" fn release_stream(stream: *mut FFI_ArrowArrayStream) {
struct StreamPrivateData {
batch_reader: Box<dyn RecordBatchReader + Send>,
- last_error: String,
+ last_error: Option<CString>,
}
// The callback used to get array schema
@@ -142,8 +143,12 @@ unsafe extern "C" fn get_next(
// The callback used to get the error from last operation on the `FFI_ArrowArrayStream`
unsafe extern "C" fn get_last_error(stream: *mut FFI_ArrowArrayStream) -> *const c_char {
let mut ffi_stream = ExportedArrayStream { stream };
- let last_error = ffi_stream.get_last_error();
- CString::new(last_error.as_str()).unwrap().into_raw()
+ // The consumer should not take ownership of this string, we should return
+ // a const pointer to it.
+ match ffi_stream.get_last_error() {
+ Some(err_string) => err_string.as_ptr(),
+ None => std::ptr::null(),
+ }
}
impl Drop for FFI_ArrowArrayStream {
@@ -160,7 +165,7 @@ impl FFI_ArrowArrayStream {
pub fn new(batch_reader: Box<dyn RecordBatchReader + Send>) -> Self {
let private_data = Box::new(StreamPrivateData {
batch_reader,
- last_error: String::new(),
+ last_error: None,
});
Self {
@@ -206,7 +211,10 @@ impl ExportedArrayStream {
0
}
Err(ref err) => {
- private_data.last_error = err.to_string();
+ private_data.last_error = Some(
+ CString::new(err.to_string())
+ .expect("Error string has a null byte in it."),
+ );
get_error_code(err)
}
}
@@ -231,15 +239,18 @@ impl ExportedArrayStream {
0
} else {
let err = &next_batch.unwrap_err();
- private_data.last_error = err.to_string();
+ private_data.last_error = Some(
+ CString::new(err.to_string())
+ .expect("Error string has a null byte in it."),
+ );
get_error_code(err)
}
}
}
}
- pub fn get_last_error(&mut self) -> &String {
- &self.get_private_data().last_error
+ pub fn get_last_error(&mut self) -> Option<&CString> {
+ self.get_private_data().last_error.as_ref()
}
}
@@ -312,19 +323,15 @@ impl ArrowArrayStreamReader {
/// Get the last error from `ArrowArrayStreamReader`
fn get_stream_last_error(&mut self) -> Option<String> {
- self.stream.get_last_error?;
-
- let error_str = unsafe {
- let c_str =
- self.stream.get_last_error.unwrap()(&mut self.stream) as *mut c_char;
- CString::from_raw(c_str).into_string()
- };
+ let get_last_error = self.stream.get_last_error?;
- if let Err(err) = error_str {
- Some(err.to_string())
- } else {
- Some(error_str.unwrap())
+ let error_str = unsafe { get_last_error(&mut self.stream) };
+ if error_str.is_null() {
+ return None;
}
+
+ let error_str = unsafe { CStr::from_ptr(error_str) };
+ Some(error_str.to_string_lossy().to_string())
}
}
@@ -381,6 +388,8 @@ pub unsafe fn export_reader_into_raw(
#[cfg(test)]
mod tests {
+ use arrow_schema::DataType;
+
use super::*;
use crate::array::Int32Array;
@@ -503,4 +512,32 @@ mod tests {
_test_round_trip_import(vec![array.clone(), array.clone(), array])
}
+
+ #[test]
+ fn test_error_import() -> Result<()> {
+ let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, true)]));
+
+ let iter =
+ Box::new(vec![Err(ArrowError::MemoryError("".to_string()))].into_iter());
+
+ let reader = TestRecordBatchReader::new(schema.clone(), iter);
+
+ // Import through `FFI_ArrowArrayStream` as `ArrowArrayStreamReader`
+ let stream = FFI_ArrowArrayStream::new(reader);
+ let stream_reader = ArrowArrayStreamReader::try_new(stream).unwrap();
+
+ let imported_schema = stream_reader.schema();
+ assert_eq!(imported_schema, schema);
+
+ let mut produced_batches = vec![];
+ for batch in stream_reader {
+ produced_batches.push(batch);
+ }
+
+ // The results should outlive the lifetime of the stream itself.
+ assert_eq!(produced_batches.len(), 1);
+ assert!(produced_batches[0].is_err());
+
+ Ok(())
+ }
}
|
diff --git a/arrow-pyarrow-integration-testing/src/lib.rs b/arrow-pyarrow-integration-testing/src/lib.rs
index 89395bd2ed08..adcec769f247 100644
--- a/arrow-pyarrow-integration-testing/src/lib.rs
+++ b/arrow-pyarrow-integration-testing/src/lib.rs
@@ -21,6 +21,7 @@
use std::sync::Arc;
use arrow::array::new_empty_array;
+use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use pyo3::wrap_pyfunction;
@@ -140,6 +141,17 @@ fn round_trip_record_batch_reader(
Ok(obj)
}
+#[pyfunction]
+fn reader_return_errors(obj: PyArrowType<ArrowArrayStreamReader>) -> PyResult<()> {
+ // This makes sure we can correctly consume a RBR and return the error,
+ // ensuring the error can live beyond the lifetime of the RBR.
+ let batches = obj.0.collect::<Result<Vec<RecordBatch>, ArrowError>>();
+ match batches {
+ Ok(_) => Ok(()),
+ Err(err) => Err(PyValueError::new_err(err.to_string())),
+ }
+}
+
#[pymodule]
fn arrow_pyarrow_integration_testing(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_wrapped(wrap_pyfunction!(double))?;
@@ -153,5 +165,6 @@ fn arrow_pyarrow_integration_testing(_py: Python, m: &PyModule) -> PyResult<()>
m.add_wrapped(wrap_pyfunction!(round_trip_array))?;
m.add_wrapped(wrap_pyfunction!(round_trip_record_batch))?;
m.add_wrapped(wrap_pyfunction!(round_trip_record_batch_reader))?;
+ m.add_wrapped(wrap_pyfunction!(reader_return_errors))?;
Ok(())
}
diff --git a/arrow-pyarrow-integration-testing/tests/test_sql.py b/arrow-pyarrow-integration-testing/tests/test_sql.py
index a7c6b34a4474..92782b9ed473 100644
--- a/arrow-pyarrow-integration-testing/tests/test_sql.py
+++ b/arrow-pyarrow-integration-testing/tests/test_sql.py
@@ -409,6 +409,18 @@ def test_record_batch_reader():
got_batches = list(b)
assert got_batches == batches
+def test_record_batch_reader_error():
+ schema = pa.schema([('ints', pa.list_(pa.int32()))])
+
+ def iter_batches():
+ yield pa.record_batch([[[1], [2, 42]]], schema)
+ raise ValueError("test error")
+
+ reader = pa.RecordBatchReader.from_batches(schema, iter_batches())
+
+ with pytest.raises(ValueError, match="test error"):
+ rust.reader_return_errors(reader)
+
def test_reject_other_classes():
# Arbitrary type that is not a PyArrow type
not_pyarrow = ["hello"]
|
Double free in C Stream Interface
**Describe the bug**
Got a double free when consuming a stream and trying to return the error. Right now the C Stream Interface import tries to take ownership of the error string, but once the release callback is called that string gets freed.
https://github.com/apache/arrow-rs/blob/f16ceedf981c7230167ff858eabb9a8cdc87ffda/arrow/src/ffi_stream.rs#L317-L327
From [the C stream interface docs](https://arrow.apache.org/docs/format/CStreamInterface.html#c.ArrowArrayStream.get_last_error):
> The returned pointer is only guaranteed to be valid until the next call of one of the stream’s callbacks. The character string it points to should be copied to consumer-managed storage if it is intended to survive longer.
**To Reproduce**
<!--
Steps to reproduce the behavior:
-->
**Expected behavior**
We should probably clone the string as suggested by the interface docs.
**Additional context**
<!--
Add any other context about the problem here.
-->
|
2023-08-07T20:07:26Z
|
45.0
|
c6184389241a0c85823aa494e8b5d93343771666
|
|
apache/arrow-rs
| 4,598
|
apache__arrow-rs-4598
|
[
"4578"
] |
95683439fa4108c036e48b334f8bed898b87a9b9
|
diff --git a/arrow-data/src/transform/union.rs b/arrow-data/src/transform/union.rs
index 8d1ea34c314d..d7083588d782 100644
--- a/arrow-data/src/transform/union.rs
+++ b/arrow-data/src/transform/union.rs
@@ -39,6 +39,9 @@ pub(super) fn build_extend_sparse(array: &ArrayData) -> Extend {
pub(super) fn build_extend_dense(array: &ArrayData) -> Extend {
let type_ids = array.buffer::<i8>(0);
let offsets = array.buffer::<i32>(1);
+ let arrow_schema::DataType::Union(src_fields, _) = array.data_type() else {
+ unreachable!();
+ };
Box::new(
move |mutable: &mut _MutableArrayData, index: usize, start: usize, len: usize| {
@@ -48,14 +51,18 @@ pub(super) fn build_extend_dense(array: &ArrayData) -> Extend {
.extend_from_slice(&type_ids[start..start + len]);
(start..start + len).for_each(|i| {
- let type_id = type_ids[i] as usize;
+ let type_id = type_ids[i];
+ let child_index = src_fields
+ .iter()
+ .position(|(r, _)| r == type_id)
+ .expect("invalid union type ID");
let src_offset = offsets[i] as usize;
- let child_data = &mut mutable.child_data[type_id];
+ let child_data = &mut mutable.child_data[child_index];
let dst_offset = child_data.len();
// Extend offsets
mutable.buffer2.push(dst_offset as i32);
- mutable.child_data[type_id].extend(index, src_offset, src_offset + 1)
+ mutable.child_data[child_index].extend(index, src_offset, src_offset + 1)
})
},
)
|
diff --git a/arrow/tests/array_transform.rs b/arrow/tests/array_transform.rs
index ebbadc00aecd..15141eb208e4 100644
--- a/arrow/tests/array_transform.rs
+++ b/arrow/tests/array_transform.rs
@@ -19,7 +19,7 @@ use arrow::array::{
Array, ArrayRef, BooleanArray, Decimal128Array, DictionaryArray,
FixedSizeBinaryArray, Int16Array, Int32Array, Int64Array, Int64Builder, ListArray,
ListBuilder, MapBuilder, NullArray, StringArray, StringBuilder,
- StringDictionaryBuilder, StructArray, UInt8Array,
+ StringDictionaryBuilder, StructArray, UInt8Array, UnionArray,
};
use arrow::datatypes::Int16Type;
use arrow_buffer::Buffer;
@@ -488,6 +488,63 @@ fn test_struct_many() {
assert_eq!(array, expected)
}
+#[test]
+fn test_union_dense() {
+ // Input data
+ let strings: ArrayRef = Arc::new(StringArray::from(vec![
+ Some("joe"),
+ Some("mark"),
+ Some("doe"),
+ ]));
+ let ints: ArrayRef = Arc::new(Int32Array::from(vec![
+ Some(1),
+ Some(2),
+ Some(3),
+ Some(4),
+ Some(5),
+ ]));
+ let offsets = Buffer::from_slice_ref([0, 0, 1, 1, 2, 2, 3, 4i32]);
+ let type_ids = Buffer::from_slice_ref([42, 84, 42, 84, 84, 42, 84, 84i8]);
+
+ let array = UnionArray::try_new(
+ &[84, 42],
+ type_ids,
+ Some(offsets),
+ vec![
+ (Field::new("int", DataType::Int32, false), ints),
+ (Field::new("string", DataType::Utf8, false), strings),
+ ],
+ )
+ .unwrap()
+ .into_data();
+ let arrays = vec![&array];
+ let mut mutable = MutableArrayData::new(arrays, false, 0);
+
+ // Slice it by `MutableArrayData`
+ mutable.extend(0, 4, 7);
+ let data = mutable.freeze();
+ let array = UnionArray::from(data);
+
+ // Expected data
+ let strings: ArrayRef = Arc::new(StringArray::from(vec![Some("doe")]));
+ let ints: ArrayRef = Arc::new(Int32Array::from(vec![Some(3), Some(4)]));
+ let offsets = Buffer::from_slice_ref([0, 0, 1i32]);
+ let type_ids = Buffer::from_slice_ref([84, 42, 84i8]);
+
+ let expected = UnionArray::try_new(
+ &[84, 42],
+ type_ids,
+ Some(offsets),
+ vec![
+ (Field::new("int", DataType::Int32, false), ints),
+ (Field::new("string", DataType::Utf8, false), strings),
+ ],
+ )
+ .unwrap();
+
+ assert_eq!(array.to_data(), expected.to_data());
+}
+
#[test]
fn test_binary_fixed_sized_offsets() {
let array = FixedSizeBinaryArray::try_from_iter(
|
`arrow::compute::concat` panics for dense union arrays with non-trivial type IDs
**Describe the bug**
`arrow::compute::concat` panics when called with dense union arrays with type IDs that don't start at zero.
```
thread 'proptest::tests::qc_row' panicked at 'index out of bounds: the len is 1 but the index is 35', ...\.cargo\registry\src\index.crates.io-6f17d22bba15001f\arrow-data-43.0.0\src\transform\union.rs:53:39
stack backtrace:
...
3: arrow_data::transform::union::build_extend_dense::{{closure}}::{{closure}}
4: core::iter::traits::iterator::Iterator::for_each::call::{{closure}}
at /rustc/864bdf7843e1ceabc824ed86d97006acad6af643\library\core\src\iter\traits/iterator.rs:853:29
5: core::iter::traits::iterator::Iterator::fold
at /rustc/864bdf7843e1ceabc824ed86d97006acad6af643\library\core\src\iter\traits/iterator.rs:2481:21
6: core::iter::traits::iterator::Iterator::for_each
at /rustc/864bdf7843e1ceabc824ed86d97006acad6af643\library\core\src\iter\traits/iterator.rs:856:9
7: arrow_data::transform::union::build_extend_dense::{{closure}}
at ...\.cargo\registry\src\index.crates.io-6f17d22bba15001f\arrow-data-43.0.0\src\transform\union.rs:50:13
8: <alloc::boxed::Box<F,A> as core::ops::function::Fn<Args>>::call
at /rustc/864bdf7843e1ceabc824ed86d97006acad6af643\library\alloc\src/boxed.rs:2021:9
9: arrow_data::transform::MutableArrayData::extend
at ...\.cargo\registry\src\index.crates.io-6f17d22bba15001f\arrow-data-43.0.0\src\transform\mod.rs:631:9
10: arrow_select::concat::concat
at ...\.cargo\registry\src\index.crates.io-6f17d22bba15001f\arrow-select-43.0.0\src\concat.rs:89:9
```
**To Reproduce**
Call `arrow::compute::concat` and pass the following arrays:
[
UnionArray(Dense)
[
-- type id buffer:
ScalarBuffer([35])
-- offsets buffer:
ScalarBuffer([0])
-- child 35: "" (Null)
NullArray(1)
],
UnionArray(Dense)
[
-- type id buffer:
ScalarBuffer([35])
-- offsets buffer:
ScalarBuffer([0])
-- child 35: "" (Null)
NullArray(1)
],
]
of the following data type:
```
Union(
[
(
35,
Field {
name: "",
data_type: Null,
nullable: false,
dict_id: 0,
dict_is_ordered: false,
metadata: {},
},
),
],
Dense,
)
```
**Expected behavior**
Producing the following array:
```
UnionArray(Dense)
[
-- type id buffer:
ScalarBuffer([35, 35])
-- offsets buffer:
ScalarBuffer([0, 1])
-- child 35: "" (Null)
NullArray(2)
]
```
**Additional context**
<!--
Add any other context about the problem here.
-->
|
MutableArrayData likely needs to be updated to properly understand UnionArray with non-trivial type ids
|
2023-07-31T04:27:18Z
|
45.0
|
c6184389241a0c85823aa494e8b5d93343771666
|
apache/arrow-rs
| 4,594
|
apache__arrow-rs-4594
|
[
"4481"
] |
16744e5ac08d9ead6c51ff6e08d8b91e87460c52
|
diff --git a/arrow-arith/src/arithmetic.rs b/arrow-arith/src/arithmetic.rs
index f8c855af0183..8635ce0ddd80 100644
--- a/arrow-arith/src/arithmetic.rs
+++ b/arrow-arith/src/arithmetic.rs
@@ -31,552 +31,6 @@ use arrow_schema::*;
use std::cmp::min;
use std::sync::Arc;
-/// Helper function to perform math lambda function on values from two arrays. If either
-/// left or right value is null then the output value is also null, so `1 + null` is
-/// `null`.
-///
-/// # Errors
-///
-/// This function errors if the arrays have different lengths
-#[deprecated(note = "Use arrow_arith::arity::binary")]
-pub fn math_op<LT, RT, F>(
- left: &PrimitiveArray<LT>,
- right: &PrimitiveArray<RT>,
- op: F,
-) -> Result<PrimitiveArray<LT>, ArrowError>
-where
- LT: ArrowNumericType,
- RT: ArrowNumericType,
- F: Fn(LT::Native, RT::Native) -> LT::Native,
-{
- binary(left, right, op)
-}
-
-/// Calculates the modulus operation `left % right` on two SIMD inputs.
-/// The lower-most bits of `valid_mask` specify which vector lanes are considered as valid.
-///
-/// # Errors
-///
-/// This function returns a [`ArrowError::DivideByZero`] if a valid element in `right` is `0`
-#[cfg(feature = "simd")]
-#[inline]
-fn simd_checked_modulus<T: ArrowNumericType>(
- valid_mask: Option<u64>,
- left: T::Simd,
- right: T::Simd,
-) -> Result<T::Simd, ArrowError> {
- let zero = T::init(T::Native::ZERO);
- let one = T::init(T::Native::ONE);
-
- let right_no_invalid_zeros = match valid_mask {
- Some(mask) => {
- let simd_mask = T::mask_from_u64(mask);
- // select `1` for invalid lanes, which will be a no-op during division later
- T::mask_select(simd_mask, right, one)
- }
- None => right,
- };
-
- let zero_mask = T::eq(right_no_invalid_zeros, zero);
-
- if T::mask_any(zero_mask) {
- Err(ArrowError::DivideByZero)
- } else {
- Ok(T::bin_op(left, right_no_invalid_zeros, |a, b| a % b))
- }
-}
-
-/// Calculates the division operation `left / right` on two SIMD inputs.
-/// The lower-most bits of `valid_mask` specify which vector lanes are considered as valid.
-///
-/// # Errors
-///
-/// This function returns a [`ArrowError::DivideByZero`] if a valid element in `right` is `0`
-#[cfg(feature = "simd")]
-#[inline]
-fn simd_checked_divide<T: ArrowNumericType>(
- valid_mask: Option<u64>,
- left: T::Simd,
- right: T::Simd,
-) -> Result<T::Simd, ArrowError> {
- let zero = T::init(T::Native::ZERO);
- let one = T::init(T::Native::ONE);
-
- let right_no_invalid_zeros = match valid_mask {
- Some(mask) => {
- let simd_mask = T::mask_from_u64(mask);
- // select `1` for invalid lanes, which will be a no-op during division later
- T::mask_select(simd_mask, right, one)
- }
- None => right,
- };
-
- let zero_mask = T::eq(right_no_invalid_zeros, zero);
-
- if T::mask_any(zero_mask) {
- Err(ArrowError::DivideByZero)
- } else {
- Ok(T::bin_op(left, right_no_invalid_zeros, |a, b| a / b))
- }
-}
-
-/// Applies `op` on the remainder elements of two input chunks and writes the result into
-/// the remainder elements of `result_chunks`.
-/// The lower-most bits of `valid_mask` specify which elements are considered as valid.
-///
-/// # Errors
-///
-/// This function returns a [`ArrowError::DivideByZero`] if a valid element in `right` is `0`
-#[cfg(feature = "simd")]
-#[inline]
-fn simd_checked_divide_op_remainder<T, F>(
- valid_mask: Option<u64>,
- left_chunks: std::slice::ChunksExact<T::Native>,
- right_chunks: std::slice::ChunksExact<T::Native>,
- result_chunks: std::slice::ChunksExactMut<T::Native>,
- op: F,
-) -> Result<(), ArrowError>
-where
- T: ArrowNumericType,
- F: Fn(T::Native, T::Native) -> T::Native,
-{
- let result_remainder = result_chunks.into_remainder();
- let left_remainder = left_chunks.remainder();
- let right_remainder = right_chunks.remainder();
-
- result_remainder
- .iter_mut()
- .zip(left_remainder.iter().zip(right_remainder.iter()))
- .enumerate()
- .try_for_each(|(i, (result_scalar, (left_scalar, right_scalar)))| {
- if valid_mask.map(|mask| mask & (1 << i) != 0).unwrap_or(true) {
- if right_scalar.is_zero() {
- return Err(ArrowError::DivideByZero);
- }
- *result_scalar = op(*left_scalar, *right_scalar);
- } else {
- *result_scalar = T::default_value();
- }
- Ok(())
- })?;
-
- Ok(())
-}
-
-/// Creates a new PrimitiveArray by applying `simd_op` to the `left` and `right` input array.
-/// If the length of the arrays is not multiple of the number of vector lanes
-/// then the remainder of the array will be calculated using `scalar_op`.
-/// Any operation on a `NULL` value will result in a `NULL` value in the output.
-///
-/// # Errors
-///
-/// This function errors if:
-/// * the arrays have different lengths
-/// * there is an element where both left and right values are valid and the right value is `0`
-#[cfg(feature = "simd")]
-fn simd_checked_divide_op<T, SI, SC>(
- left: &PrimitiveArray<T>,
- right: &PrimitiveArray<T>,
- simd_op: SI,
- scalar_op: SC,
-) -> Result<PrimitiveArray<T>, ArrowError>
-where
- T: ArrowNumericType,
- SI: Fn(Option<u64>, T::Simd, T::Simd) -> Result<T::Simd, ArrowError>,
- SC: Fn(T::Native, T::Native) -> T::Native,
-{
- if left.len() != right.len() {
- return Err(ArrowError::ComputeError(
- "Cannot perform math operation on arrays of different length".to_string(),
- ));
- }
-
- // Create the combined `Bitmap`
- let nulls = arrow_buffer::NullBuffer::union(left.nulls(), right.nulls());
-
- let lanes = T::lanes();
- let buffer_size = left.len() * std::mem::size_of::<T::Native>();
- let mut result =
- arrow_buffer::MutableBuffer::new(buffer_size).with_bitset(buffer_size, false);
-
- match &nulls {
- Some(b) => {
- let valid_chunks = b.inner().bit_chunks();
-
- // process data in chunks of 64 elements since we also get 64 bits of validity information at a time
-
- let mut result_chunks = result.typed_data_mut().chunks_exact_mut(64);
- let mut left_chunks = left.values().chunks_exact(64);
- let mut right_chunks = right.values().chunks_exact(64);
-
- valid_chunks
- .iter()
- .zip((&mut result_chunks).zip((&mut left_chunks).zip(&mut right_chunks)))
- .try_for_each(
- |(mut mask, (result_slice, (left_slice, right_slice)))| {
- // split chunks further into slices corresponding to the vector length
- // the compiler is able to unroll this inner loop and remove bounds checks
- // since the outer chunk size (64) is always a multiple of the number of lanes
- result_slice
- .chunks_exact_mut(lanes)
- .zip(left_slice.chunks_exact(lanes).zip(right_slice.chunks_exact(lanes)))
- .try_for_each(|(result_slice, (left_slice, right_slice))| -> Result<(), ArrowError> {
- let simd_left = T::load(left_slice);
- let simd_right = T::load(right_slice);
-
- let simd_result = simd_op(Some(mask), simd_left, simd_right)?;
-
- T::write(simd_result, result_slice);
-
- // skip the shift and avoid overflow for u8 type, which uses 64 lanes.
- mask >>= T::lanes() % 64;
-
- Ok(())
- })
- },
- )?;
-
- let valid_remainder = valid_chunks.remainder_bits();
-
- simd_checked_divide_op_remainder::<T, _>(
- Some(valid_remainder),
- left_chunks,
- right_chunks,
- result_chunks,
- scalar_op,
- )?;
- }
- None => {
- let mut result_chunks = result.typed_data_mut().chunks_exact_mut(lanes);
- let mut left_chunks = left.values().chunks_exact(lanes);
- let mut right_chunks = right.values().chunks_exact(lanes);
-
- (&mut result_chunks)
- .zip((&mut left_chunks).zip(&mut right_chunks))
- .try_for_each(
- |(result_slice, (left_slice, right_slice))| -> Result<(), ArrowError> {
- let simd_left = T::load(left_slice);
- let simd_right = T::load(right_slice);
-
- let simd_result = simd_op(None, simd_left, simd_right)?;
-
- T::write(simd_result, result_slice);
-
- Ok(())
- },
- )?;
-
- simd_checked_divide_op_remainder::<T, _>(
- None,
- left_chunks,
- right_chunks,
- result_chunks,
- scalar_op,
- )?;
- }
- }
-
- Ok(PrimitiveArray::new(result.into(), nulls))
-}
-
-fn math_safe_divide_op<LT, RT, F>(
- left: &PrimitiveArray<LT>,
- right: &PrimitiveArray<RT>,
- op: F,
-) -> Result<ArrayRef, ArrowError>
-where
- LT: ArrowNumericType,
- RT: ArrowNumericType,
- F: Fn(LT::Native, RT::Native) -> Option<LT::Native>,
-{
- let array: PrimitiveArray<LT> = binary_opt::<_, _, _, LT>(left, right, op)?;
- Ok(Arc::new(array) as ArrayRef)
-}
-
-/// Perform `left + right` operation on two arrays. If either left or right value is null
-/// then the result is also null.
-///
-/// This doesn't detect overflow. Once overflowing, the result will wrap around.
-/// For an overflow-checking variant, use `add_checked` instead.
-#[deprecated(note = "Use arrow_arith::numeric::add_wrapping")]
-pub fn add<T: ArrowNumericType>(
- left: &PrimitiveArray<T>,
- right: &PrimitiveArray<T>,
-) -> Result<PrimitiveArray<T>, ArrowError> {
- binary(left, right, |a, b| a.add_wrapping(b))
-}
-
-/// Perform `left + right` operation on two arrays. If either left or right value is null
-/// then the result is also null.
-///
-/// This detects overflow and returns an `Err` for that. For an non-overflow-checking variant,
-/// use `add` instead.
-#[deprecated(note = "Use arrow_arith::numeric::add")]
-pub fn add_checked<T: ArrowNumericType>(
- left: &PrimitiveArray<T>,
- right: &PrimitiveArray<T>,
-) -> Result<PrimitiveArray<T>, ArrowError> {
- try_binary(left, right, |a, b| a.add_checked(b))
-}
-
-/// Perform `left + right` operation on two arrays. If either left or right value is null
-/// then the result is also null.
-///
-/// This doesn't detect overflow. Once overflowing, the result will wrap around.
-/// For an overflow-checking variant, use `add_dyn_checked` instead.
-#[deprecated(note = "Use arrow_arith::numeric::add_wrapping")]
-pub fn add_dyn(left: &dyn Array, right: &dyn Array) -> Result<ArrayRef, ArrowError> {
- crate::numeric::add_wrapping(&left, &right)
-}
-
-/// Perform `left + right` operation on two arrays. If either left or right value is null
-/// then the result is also null.
-///
-/// This detects overflow and returns an `Err` for that. For an non-overflow-checking variant,
-/// use `add_dyn` instead.
-#[deprecated(note = "Use arrow_arith::numeric::add")]
-pub fn add_dyn_checked(
- left: &dyn Array,
- right: &dyn Array,
-) -> Result<ArrayRef, ArrowError> {
- crate::numeric::add(&left, &right)
-}
-
-/// Add every value in an array by a scalar. If any value in the array is null then the
-/// result is also null.
-///
-/// This doesn't detect overflow. Once overflowing, the result will wrap around.
-/// For an overflow-checking variant, use `add_scalar_checked` instead.
-#[deprecated(note = "Use arrow_arith::numeric::add_wrapping")]
-pub fn add_scalar<T: ArrowNumericType>(
- array: &PrimitiveArray<T>,
- scalar: T::Native,
-) -> Result<PrimitiveArray<T>, ArrowError> {
- Ok(unary(array, |value| value.add_wrapping(scalar)))
-}
-
-/// Add every value in an array by a scalar. If any value in the array is null then the
-/// result is also null.
-///
-/// This detects overflow and returns an `Err` for that. For an non-overflow-checking variant,
-/// use `add_scalar` instead.
-#[deprecated(note = "Use arrow_arith::numeric::add")]
-pub fn add_scalar_checked<T: ArrowNumericType>(
- array: &PrimitiveArray<T>,
- scalar: T::Native,
-) -> Result<PrimitiveArray<T>, ArrowError> {
- try_unary(array, |value| value.add_checked(scalar))
-}
-
-/// Add every value in an array by a scalar. If any value in the array is null then the
-/// result is also null. The given array must be a `PrimitiveArray` of the type same as
-/// the scalar, or a `DictionaryArray` of the value type same as the scalar.
-///
-/// This doesn't detect overflow. Once overflowing, the result will wrap around.
-/// For an overflow-checking variant, use `add_scalar_checked_dyn` instead.
-///
-/// This returns an `Err` when the input array is not supported for adding operation.
-#[deprecated(note = "Use arrow_arith::numeric::add_wrapping")]
-pub fn add_scalar_dyn<T: ArrowNumericType>(
- array: &dyn Array,
- scalar: T::Native,
-) -> Result<ArrayRef, ArrowError> {
- unary_dyn::<_, T>(array, |value| value.add_wrapping(scalar))
-}
-
-/// Add every value in an array by a scalar. If any value in the array is null then the
-/// result is also null. The given array must be a `PrimitiveArray` of the type same as
-/// the scalar, or a `DictionaryArray` of the value type same as the scalar.
-///
-/// This detects overflow and returns an `Err` for that. For an non-overflow-checking variant,
-/// use `add_scalar_dyn` instead.
-///
-/// As this kernel has the branching costs and also prevents LLVM from vectorising it correctly,
-/// it is usually much slower than non-checking variant.
-#[deprecated(note = "Use arrow_arith::numeric::add")]
-pub fn add_scalar_checked_dyn<T: ArrowNumericType>(
- array: &dyn Array,
- scalar: T::Native,
-) -> Result<ArrayRef, ArrowError> {
- try_unary_dyn::<_, T>(array, |value| value.add_checked(scalar))
- .map(|a| Arc::new(a) as ArrayRef)
-}
-
-/// Perform `left - right` operation on two arrays. If either left or right value is null
-/// then the result is also null.
-///
-/// This doesn't detect overflow. Once overflowing, the result will wrap around.
-/// For an overflow-checking variant, use `subtract_checked` instead.
-#[deprecated(note = "Use arrow_arith::numeric::sub_wrapping")]
-pub fn subtract<T: ArrowNumericType>(
- left: &PrimitiveArray<T>,
- right: &PrimitiveArray<T>,
-) -> Result<PrimitiveArray<T>, ArrowError> {
- binary(left, right, |a, b| a.sub_wrapping(b))
-}
-
-/// Perform `left - right` operation on two arrays. If either left or right value is null
-/// then the result is also null.
-///
-/// This detects overflow and returns an `Err` for that. For an non-overflow-checking variant,
-/// use `subtract` instead.
-#[deprecated(note = "Use arrow_arith::numeric::sub")]
-pub fn subtract_checked<T: ArrowNumericType>(
- left: &PrimitiveArray<T>,
- right: &PrimitiveArray<T>,
-) -> Result<PrimitiveArray<T>, ArrowError> {
- try_binary(left, right, |a, b| a.sub_checked(b))
-}
-
-/// Perform `left - right` operation on two arrays. If either left or right value is null
-/// then the result is also null.
-///
-/// This doesn't detect overflow. Once overflowing, the result will wrap around.
-/// For an overflow-checking variant, use `subtract_dyn_checked` instead.
-#[deprecated(note = "Use arrow_arith::numeric::sub_wrapping")]
-pub fn subtract_dyn(left: &dyn Array, right: &dyn Array) -> Result<ArrayRef, ArrowError> {
- crate::numeric::sub_wrapping(&left, &right)
-}
-
-/// Perform `left - right` operation on two arrays. If either left or right value is null
-/// then the result is also null.
-///
-/// This detects overflow and returns an `Err` for that. For an non-overflow-checking variant,
-/// use `subtract_dyn` instead.
-#[deprecated(note = "Use arrow_arith::numeric::sub")]
-pub fn subtract_dyn_checked(
- left: &dyn Array,
- right: &dyn Array,
-) -> Result<ArrayRef, ArrowError> {
- crate::numeric::sub(&left, &right)
-}
-
-/// Subtract every value in an array by a scalar. If any value in the array is null then the
-/// result is also null.
-///
-/// This doesn't detect overflow. Once overflowing, the result will wrap around.
-/// For an overflow-checking variant, use `subtract_scalar_checked` instead.
-#[deprecated(note = "Use arrow_arith::numeric::sub_wrapping")]
-pub fn subtract_scalar<T: ArrowNumericType>(
- array: &PrimitiveArray<T>,
- scalar: T::Native,
-) -> Result<PrimitiveArray<T>, ArrowError> {
- Ok(unary(array, |value| value.sub_wrapping(scalar)))
-}
-
-/// Subtract every value in an array by a scalar. If any value in the array is null then the
-/// result is also null.
-///
-/// This detects overflow and returns an `Err` for that. For an non-overflow-checking variant,
-/// use `subtract_scalar` instead.
-#[deprecated(note = "Use arrow_arith::numeric::sub")]
-pub fn subtract_scalar_checked<T: ArrowNumericType>(
- array: &PrimitiveArray<T>,
- scalar: T::Native,
-) -> Result<PrimitiveArray<T>, ArrowError> {
- try_unary(array, |value| value.sub_checked(scalar))
-}
-
-/// Subtract every value in an array by a scalar. If any value in the array is null then the
-/// result is also null. The given array must be a `PrimitiveArray` of the type same as
-/// the scalar, or a `DictionaryArray` of the value type same as the scalar.
-///
-/// This doesn't detect overflow. Once overflowing, the result will wrap around.
-/// For an overflow-checking variant, use `subtract_scalar_checked_dyn` instead.
-#[deprecated(note = "Use arrow_arith::numeric::sub_wrapping")]
-pub fn subtract_scalar_dyn<T: ArrowNumericType>(
- array: &dyn Array,
- scalar: T::Native,
-) -> Result<ArrayRef, ArrowError> {
- unary_dyn::<_, T>(array, |value| value.sub_wrapping(scalar))
-}
-
-/// Subtract every value in an array by a scalar. If any value in the array is null then the
-/// result is also null. The given array must be a `PrimitiveArray` of the type same as
-/// the scalar, or a `DictionaryArray` of the value type same as the scalar.
-///
-/// This detects overflow and returns an `Err` for that. For an non-overflow-checking variant,
-/// use `subtract_scalar_dyn` instead.
-#[deprecated(note = "Use arrow_arith::numeric::sub")]
-pub fn subtract_scalar_checked_dyn<T: ArrowNumericType>(
- array: &dyn Array,
- scalar: T::Native,
-) -> Result<ArrayRef, ArrowError> {
- try_unary_dyn::<_, T>(array, |value| value.sub_checked(scalar))
- .map(|a| Arc::new(a) as ArrayRef)
-}
-
-/// Perform `-` operation on an array. If value is null then the result is also null.
-///
-/// This doesn't detect overflow. Once overflowing, the result will wrap around.
-/// For an overflow-checking variant, use `negate_checked` instead.
-#[deprecated(note = "Use arrow_arith::numeric::neg_wrapping")]
-pub fn negate<T: ArrowNumericType>(
- array: &PrimitiveArray<T>,
-) -> Result<PrimitiveArray<T>, ArrowError> {
- Ok(unary(array, |x| x.neg_wrapping()))
-}
-
-/// Perform `-` operation on an array. If value is null then the result is also null.
-///
-/// This detects overflow and returns an `Err` for that. For an non-overflow-checking variant,
-/// use `negate` instead.
-#[deprecated(note = "Use arrow_arith::numeric::neg")]
-pub fn negate_checked<T: ArrowNumericType>(
- array: &PrimitiveArray<T>,
-) -> Result<PrimitiveArray<T>, ArrowError> {
- try_unary(array, |value| value.neg_checked())
-}
-
-/// Perform `left * right` operation on two arrays. If either left or right value is null
-/// then the result is also null.
-///
-/// This doesn't detect overflow. Once overflowing, the result will wrap around.
-/// For an overflow-checking variant, use `multiply_check` instead.
-#[deprecated(note = "Use arrow_arith::numeric::mul_wrapping")]
-pub fn multiply<T: ArrowNumericType>(
- left: &PrimitiveArray<T>,
- right: &PrimitiveArray<T>,
-) -> Result<PrimitiveArray<T>, ArrowError> {
- binary(left, right, |a, b| a.mul_wrapping(b))
-}
-
-/// Perform `left * right` operation on two arrays. If either left or right value is null
-/// then the result is also null.
-///
-/// This detects overflow and returns an `Err` for that. For an non-overflow-checking variant,
-/// use `multiply` instead.
-#[deprecated(note = "Use arrow_arith::numeric::mul")]
-pub fn multiply_checked<T: ArrowNumericType>(
- left: &PrimitiveArray<T>,
- right: &PrimitiveArray<T>,
-) -> Result<PrimitiveArray<T>, ArrowError> {
- try_binary(left, right, |a, b| a.mul_checked(b))
-}
-
-/// Perform `left * right` operation on two arrays. If either left or right value is null
-/// then the result is also null.
-///
-/// This doesn't detect overflow. Once overflowing, the result will wrap around.
-/// For an overflow-checking variant, use `multiply_dyn_checked` instead.
-#[deprecated(note = "Use arrow_arith::numeric::mul_wrapping")]
-pub fn multiply_dyn(left: &dyn Array, right: &dyn Array) -> Result<ArrayRef, ArrowError> {
- crate::numeric::mul_wrapping(&left, &right)
-}
-
-/// Perform `left * right` operation on two arrays. If either left or right value is null
-/// then the result is also null.
-///
-/// This detects overflow and returns an `Err` for that. For an non-overflow-checking variant,
-/// use `multiply_dyn` instead.
-#[deprecated(note = "Use arrow_arith::numeric::mul")]
-pub fn multiply_dyn_checked(
- left: &dyn Array,
- right: &dyn Array,
-) -> Result<ArrayRef, ArrowError> {
- crate::numeric::mul(&left, &right)
-}
-
/// Returns the precision and scale of the result of a multiplication of two decimal types,
/// and the divisor for fixed point multiplication.
fn get_fixed_point_info(
@@ -740,1861 +194,81 @@ where
}
}
-/// Multiply every value in an array by a scalar. If any value in the array is null then the
-/// result is also null.
-///
-/// This doesn't detect overflow. Once overflowing, the result will wrap around.
-/// For an overflow-checking variant, use `multiply_scalar_checked` instead.
-#[deprecated(note = "Use arrow_arith::numeric::mul_wrapping")]
-pub fn multiply_scalar<T: ArrowNumericType>(
- array: &PrimitiveArray<T>,
- scalar: T::Native,
-) -> Result<PrimitiveArray<T>, ArrowError> {
- Ok(unary(array, |value| value.mul_wrapping(scalar)))
-}
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::numeric::mul;
-/// Multiply every value in an array by a scalar. If any value in the array is null then the
-/// result is also null.
-///
-/// This detects overflow and returns an `Err` for that. For an non-overflow-checking variant,
-/// use `multiply_scalar` instead.
-#[deprecated(note = "Use arrow_arith::numeric::mul")]
-pub fn multiply_scalar_checked<T: ArrowNumericType>(
- array: &PrimitiveArray<T>,
- scalar: T::Native,
-) -> Result<PrimitiveArray<T>, ArrowError> {
- try_unary(array, |value| value.mul_checked(scalar))
-}
+ #[test]
+ fn test_decimal_multiply_allow_precision_loss() {
+ // Overflow happening as i128 cannot hold multiplying result.
+ // [123456789]
+ let a = Decimal128Array::from(vec![123456789000000000000000000])
+ .with_precision_and_scale(38, 18)
+ .unwrap();
-/// Multiply every value in an array by a scalar. If any value in the array is null then the
-/// result is also null. The given array must be a `PrimitiveArray` of the type same as
-/// the scalar, or a `DictionaryArray` of the value type same as the scalar.
-///
-/// This doesn't detect overflow. Once overflowing, the result will wrap around.
-/// For an overflow-checking variant, use `multiply_scalar_checked_dyn` instead.
-#[deprecated(note = "Use arrow_arith::numeric::mul_wrapping")]
-pub fn multiply_scalar_dyn<T: ArrowNumericType>(
- array: &dyn Array,
- scalar: T::Native,
-) -> Result<ArrayRef, ArrowError> {
- unary_dyn::<_, T>(array, |value| value.mul_wrapping(scalar))
-}
+ // [10]
+ let b = Decimal128Array::from(vec![10000000000000000000])
+ .with_precision_and_scale(38, 18)
+ .unwrap();
-/// Subtract every value in an array by a scalar. If any value in the array is null then the
-/// result is also null. The given array must be a `PrimitiveArray` of the type same as
-/// the scalar, or a `DictionaryArray` of the value type same as the scalar.
-///
-/// This detects overflow and returns an `Err` for that. For an non-overflow-checking variant,
-/// use `multiply_scalar_dyn` instead.
-#[deprecated(note = "Use arrow_arith::numeric::mul")]
-pub fn multiply_scalar_checked_dyn<T: ArrowNumericType>(
- array: &dyn Array,
- scalar: T::Native,
-) -> Result<ArrayRef, ArrowError> {
- try_unary_dyn::<_, T>(array, |value| value.mul_checked(scalar))
- .map(|a| Arc::new(a) as ArrayRef)
-}
+ let err = mul(&a, &b).unwrap_err();
+ assert!(err.to_string().contains(
+ "Overflow happened on: 123456789000000000000000000 * 10000000000000000000"
+ ));
-/// Perform `left % right` operation on two arrays. If either left or right value is null
-/// then the result is also null. If any right hand value is zero then the result of this
-/// operation will be `Err(ArrowError::DivideByZero)`.
-#[deprecated(note = "Use arrow_arith::numeric::rem")]
-pub fn modulus<T: ArrowNumericType>(
- left: &PrimitiveArray<T>,
- right: &PrimitiveArray<T>,
-) -> Result<PrimitiveArray<T>, ArrowError> {
- #[cfg(feature = "simd")]
- return simd_checked_divide_op(&left, &right, simd_checked_modulus::<T>, |a, b| {
- a.mod_wrapping(b)
- });
- #[cfg(not(feature = "simd"))]
- return try_binary(left, right, |a, b| {
- if b.is_zero() {
- Err(ArrowError::DivideByZero)
- } else {
- Ok(a.mod_wrapping(b))
- }
- });
-}
+ // Allow precision loss.
+ let result = multiply_fixed_point_checked(&a, &b, 28).unwrap();
+ // [1234567890]
+ let expected =
+ Decimal128Array::from(vec![12345678900000000000000000000000000000])
+ .with_precision_and_scale(38, 28)
+ .unwrap();
-/// Perform `left % right` operation on two arrays. If either left or right value is null
-/// then the result is also null. If any right hand value is zero then the result of this
-/// operation will be `Err(ArrowError::DivideByZero)`.
-#[deprecated(note = "Use arrow_arith::numeric::rem")]
-pub fn modulus_dyn(left: &dyn Array, right: &dyn Array) -> Result<ArrayRef, ArrowError> {
- crate::numeric::rem(&left, &right)
-}
+ assert_eq!(&expected, &result);
+ assert_eq!(
+ result.value_as_string(0),
+ "1234567890.0000000000000000000000000000"
+ );
-/// Perform `left / right` operation on two arrays. If either left or right value is null
-/// then the result is also null. If any right hand value is zero then the result of this
-/// operation will be `Err(ArrowError::DivideByZero)`.
-///
-/// When `simd` feature is not enabled. This detects overflow and returns an `Err` for that.
-/// For an non-overflow-checking variant, use `divide` instead.
-#[deprecated(note = "Use arrow_arith::numeric::div")]
-pub fn divide_checked<T: ArrowNumericType>(
- left: &PrimitiveArray<T>,
- right: &PrimitiveArray<T>,
-) -> Result<PrimitiveArray<T>, ArrowError> {
- #[cfg(feature = "simd")]
- return simd_checked_divide_op(&left, &right, simd_checked_divide::<T>, |a, b| {
- a.div_wrapping(b)
- });
- #[cfg(not(feature = "simd"))]
- return try_binary(left, right, |a, b| a.div_checked(b));
-}
+ // Rounding case
+ // [0.000000000000000001, 123456789.555555555555555555, 1.555555555555555555]
+ let a = Decimal128Array::from(vec![
+ 1,
+ 123456789555555555555555555,
+ 1555555555555555555,
+ ])
+ .with_precision_and_scale(38, 18)
+ .unwrap();
-/// Perform `left / right` operation on two arrays. If either left or right value is null
-/// then the result is also null.
-///
-/// If any right hand value is zero, the operation value will be replaced with null in the
-/// result.
-///
-/// Unlike [`divide`] or [`divide_checked`], division by zero will yield a null value in the
-/// result instead of returning an `Err`.
-///
-/// For floating point types overflow will saturate at INF or -INF
-/// preserving the expected sign value.
-///
-/// For integer types overflow will wrap around.
-///
-#[deprecated(note = "Use arrow_arith::numeric::div")]
-pub fn divide_opt<T: ArrowNumericType>(
- left: &PrimitiveArray<T>,
- right: &PrimitiveArray<T>,
-) -> Result<PrimitiveArray<T>, ArrowError> {
- binary_opt(left, right, |a, b| {
- if b.is_zero() {
- None
- } else {
- Some(a.div_wrapping(b))
- }
- })
-}
+ // [1.555555555555555555, 11.222222222222222222, 0.000000000000000001]
+ let b = Decimal128Array::from(vec![1555555555555555555, 11222222222222222222, 1])
+ .with_precision_and_scale(38, 18)
+ .unwrap();
-/// Perform `left / right` operation on two arrays. If either left or right value is null
-/// then the result is also null. If any right hand value is zero then the result of this
-/// operation will be `Err(ArrowError::DivideByZero)`.
-///
-/// This doesn't detect overflow. Once overflowing, the result will wrap around.
-/// For an overflow-checking variant, use `divide_dyn_checked` instead.
-#[deprecated(note = "Use arrow_arith::numeric::div")]
-pub fn divide_dyn(left: &dyn Array, right: &dyn Array) -> Result<ArrayRef, ArrowError> {
- fn divide_op<T: ArrowPrimitiveType>(
- left: &PrimitiveArray<T>,
- right: &PrimitiveArray<T>,
- ) -> Result<PrimitiveArray<T>, ArrowError> {
- try_binary(left, right, |a, b| {
- if b.is_zero() {
- Err(ArrowError::DivideByZero)
- } else {
- Ok(a.div_wrapping(b))
- }
- })
- }
+ let result = multiply_fixed_point_checked(&a, &b, 28).unwrap();
+ // [
+ // 0.0000000000000000015555555556,
+ // 1385459527.2345679012071330528765432099,
+ // 0.0000000000000000015555555556
+ // ]
+ let expected = Decimal128Array::from(vec![
+ 15555555556,
+ 13854595272345679012071330528765432099,
+ 15555555556,
+ ])
+ .with_precision_and_scale(38, 28)
+ .unwrap();
- downcast_primitive_array!(
- (left, right) => divide_op(left, right).map(|a| Arc::new(a) as ArrayRef),
- _ => Err(ArrowError::CastError(format!(
- "Unsupported data type {}, {}",
- left.data_type(), right.data_type()
- )))
- )
-}
+ assert_eq!(&expected, &result);
-/// Perform `left / right` operation on two arrays. If either left or right value is null
-/// then the result is also null. If any right hand value is zero then the result of this
-/// operation will be `Err(ArrowError::DivideByZero)`.
-///
-/// This detects overflow and returns an `Err` for that. For an non-overflow-checking variant,
-/// use `divide_dyn` instead.
-#[deprecated(note = "Use arrow_arith::numeric::div")]
-pub fn divide_dyn_checked(
- left: &dyn Array,
- right: &dyn Array,
-) -> Result<ArrayRef, ArrowError> {
- crate::numeric::div(&left, &right)
-}
-
-/// Perform `left / right` operation on two arrays. If either left or right value is null
-/// then the result is also null.
-///
-/// If any right hand value is zero, the operation value will be replaced with null in the
-/// result.
-///
-/// Unlike `divide_dyn` or `divide_dyn_checked`, division by zero will get a null value instead
-/// returning an `Err`, this also doesn't check overflowing, overflowing will just wrap
-/// the result around.
-#[deprecated(note = "Use arrow_arith::numeric::div")]
-pub fn divide_dyn_opt(
- left: &dyn Array,
- right: &dyn Array,
-) -> Result<ArrayRef, ArrowError> {
- downcast_primitive_array!(
- (left, right) => {
- math_safe_divide_op(left, right, |a, b| {
- if b.is_zero() {
- None
- } else {
- Some(a.div_wrapping(b))
- }
- })
- }
- _ => Err(ArrowError::CastError(format!(
- "Unsupported data type {}, {}",
- left.data_type(), right.data_type()
- )))
- )
-}
-
-/// Perform `left / right` operation on two arrays without checking for
-/// division by zero or overflow.
-///
-/// For floating point types, overflow and division by zero follows normal floating point rules
-///
-/// For integer types overflow will wrap around. Division by zero will currently panic, although
-/// this may be subject to change see <https://github.com/apache/arrow-rs/issues/2647>
-///
-/// If either left or right value is null then the result is also null.
-///
-/// For an overflow-checking variant, use `divide_checked` instead.
-#[deprecated(note = "Use arrow_arith::numeric::div")]
-pub fn divide<T: ArrowNumericType>(
- left: &PrimitiveArray<T>,
- right: &PrimitiveArray<T>,
-) -> Result<PrimitiveArray<T>, ArrowError> {
- // TODO: This is incorrect as div_wrapping has side-effects for integer types
- // and so may panic on null values (#2647)
- binary(left, right, |a, b| a.div_wrapping(b))
-}
-
-/// Modulus every value in an array by a scalar. If any value in the array is null then the
-/// result is also null. If the scalar is zero then the result of this operation will be
-/// `Err(ArrowError::DivideByZero)`.
-#[deprecated(note = "Use arrow_arith::numeric::rem")]
-pub fn modulus_scalar<T: ArrowNumericType>(
- array: &PrimitiveArray<T>,
- modulo: T::Native,
-) -> Result<PrimitiveArray<T>, ArrowError> {
- if modulo.is_zero() {
- return Err(ArrowError::DivideByZero);
- }
-
- Ok(unary(array, |a| a.mod_wrapping(modulo)))
-}
-
-/// Modulus every value in an array by a scalar. If any value in the array is null then the
-/// result is also null. If the scalar is zero then the result of this operation will be
-/// `Err(ArrowError::DivideByZero)`.
-#[deprecated(note = "Use arrow_arith::numeric::rem")]
-pub fn modulus_scalar_dyn<T: ArrowNumericType>(
- array: &dyn Array,
- modulo: T::Native,
-) -> Result<ArrayRef, ArrowError> {
- if modulo.is_zero() {
- return Err(ArrowError::DivideByZero);
- }
- unary_dyn::<_, T>(array, |value| value.mod_wrapping(modulo))
-}
-
-/// Divide every value in an array by a scalar. If any value in the array is null then the
-/// result is also null. If the scalar is zero then the result of this operation will be
-/// `Err(ArrowError::DivideByZero)`.
-#[deprecated(note = "Use arrow_arith::numeric::div")]
-pub fn divide_scalar<T: ArrowNumericType>(
- array: &PrimitiveArray<T>,
- divisor: T::Native,
-) -> Result<PrimitiveArray<T>, ArrowError> {
- if divisor.is_zero() {
- return Err(ArrowError::DivideByZero);
- }
- Ok(unary(array, |a| a.div_wrapping(divisor)))
-}
-
-/// Divide every value in an array by a scalar. If any value in the array is null then the
-/// result is also null. If the scalar is zero then the result of this operation will be
-/// `Err(ArrowError::DivideByZero)`. The given array must be a `PrimitiveArray` of the type
-/// same as the scalar, or a `DictionaryArray` of the value type same as the scalar.
-///
-/// This doesn't detect overflow. Once overflowing, the result will wrap around.
-/// For an overflow-checking variant, use `divide_scalar_checked_dyn` instead.
-#[deprecated(note = "Use arrow_arith::numeric::div")]
-pub fn divide_scalar_dyn<T: ArrowNumericType>(
- array: &dyn Array,
- divisor: T::Native,
-) -> Result<ArrayRef, ArrowError> {
- if divisor.is_zero() {
- return Err(ArrowError::DivideByZero);
- }
- unary_dyn::<_, T>(array, |value| value.div_wrapping(divisor))
-}
-
-/// Divide every value in an array by a scalar. If any value in the array is null then the
-/// result is also null. If the scalar is zero then the result of this operation will be
-/// `Err(ArrowError::DivideByZero)`. The given array must be a `PrimitiveArray` of the type
-/// same as the scalar, or a `DictionaryArray` of the value type same as the scalar.
-///
-/// This detects overflow and returns an `Err` for that. For an non-overflow-checking variant,
-/// use `divide_scalar_dyn` instead.
-#[deprecated(note = "Use arrow_arith::numeric::div")]
-pub fn divide_scalar_checked_dyn<T: ArrowNumericType>(
- array: &dyn Array,
- divisor: T::Native,
-) -> Result<ArrayRef, ArrowError> {
- if divisor.is_zero() {
- return Err(ArrowError::DivideByZero);
- }
-
- try_unary_dyn::<_, T>(array, |value| value.div_checked(divisor))
- .map(|a| Arc::new(a) as ArrayRef)
-}
-
-/// Divide every value in an array by a scalar. If any value in the array is null then the
-/// result is also null. The given array must be a `PrimitiveArray` of the type
-/// same as the scalar, or a `DictionaryArray` of the value type same as the scalar.
-///
-/// If any right hand value is zero, the operation value will be replaced with null in the
-/// result.
-///
-/// Unlike `divide_scalar_dyn` or `divide_scalar_checked_dyn`, division by zero will get a
-/// null value instead returning an `Err`, this also doesn't check overflowing, overflowing
-/// will just wrap the result around.
-#[deprecated(note = "Use arrow_arith::numeric::div")]
-pub fn divide_scalar_opt_dyn<T: ArrowNumericType>(
- array: &dyn Array,
- divisor: T::Native,
-) -> Result<ArrayRef, ArrowError> {
- if divisor.is_zero() {
- match array.data_type() {
- DataType::Dictionary(_, value_type) => {
- return Ok(new_null_array(value_type.as_ref(), array.len()))
- }
- _ => return Ok(new_null_array(array.data_type(), array.len())),
- }
- }
-
- unary_dyn::<_, T>(array, |value| value.div_wrapping(divisor))
-}
-
-#[cfg(test)]
-#[allow(deprecated)]
-mod tests {
- use super::*;
- use arrow_array::builder::{
- BooleanBufferBuilder, BufferBuilder, PrimitiveDictionaryBuilder,
- };
- use arrow_array::cast::AsArray;
- use arrow_array::temporal_conversions::SECONDS_IN_DAY;
- use arrow_buffer::buffer::NullBuffer;
- use arrow_buffer::i256;
- use arrow_data::ArrayDataBuilder;
- use chrono::NaiveDate;
- use half::f16;
-
- #[test]
- fn test_primitive_array_add() {
- let a = Int32Array::from(vec![5, 6, 7, 8, 9]);
- let b = Int32Array::from(vec![6, 7, 8, 9, 8]);
- let c = add(&a, &b).unwrap();
- assert_eq!(11, c.value(0));
- assert_eq!(13, c.value(1));
- assert_eq!(15, c.value(2));
- assert_eq!(17, c.value(3));
- assert_eq!(17, c.value(4));
- }
-
- #[test]
- fn test_date32_month_add() {
- let a = Date32Array::from(vec![Date32Type::from_naive_date(
- NaiveDate::from_ymd_opt(2000, 1, 1).unwrap(),
- )]);
- let b =
- IntervalYearMonthArray::from(vec![IntervalYearMonthType::make_value(1, 2)]);
- let c = add_dyn(&a, &b).unwrap();
- let c = c.as_any().downcast_ref::<Date32Array>().unwrap();
- assert_eq!(
- c.value(0),
- Date32Type::from_naive_date(NaiveDate::from_ymd_opt(2001, 3, 1).unwrap())
- );
-
- let c = add_dyn(&b, &a).unwrap();
- let c = c.as_any().downcast_ref::<Date32Array>().unwrap();
- assert_eq!(
- c.value(0),
- Date32Type::from_naive_date(NaiveDate::from_ymd_opt(2001, 3, 1).unwrap())
- );
- }
-
- #[test]
- fn test_date32_day_time_add() {
- let a = Date32Array::from(vec![Date32Type::from_naive_date(
- NaiveDate::from_ymd_opt(2000, 1, 1).unwrap(),
- )]);
- let b = IntervalDayTimeArray::from(vec![IntervalDayTimeType::make_value(1, 2)]);
- let c = add_dyn(&a, &b).unwrap();
- assert_eq!(
- c.as_primitive::<Date32Type>().value(0),
- Date32Type::from_naive_date(NaiveDate::from_ymd_opt(2000, 1, 2).unwrap())
- );
-
- let c = add_dyn(&b, &a).unwrap();
- assert_eq!(
- c.as_primitive::<Date32Type>().value(0),
- Date32Type::from_naive_date(NaiveDate::from_ymd_opt(2000, 1, 2).unwrap())
- );
- }
-
- #[test]
- fn test_date32_month_day_nano_add() {
- let a = Date32Array::from(vec![Date32Type::from_naive_date(
- NaiveDate::from_ymd_opt(2000, 1, 1).unwrap(),
- )]);
- let b =
- IntervalMonthDayNanoArray::from(vec![IntervalMonthDayNanoType::make_value(
- 1, 2, 3,
- )]);
- let c = add_dyn(&a, &b).unwrap();
- assert_eq!(
- c.as_primitive::<Date32Type>().value(0),
- Date32Type::from_naive_date(NaiveDate::from_ymd_opt(2000, 2, 3).unwrap())
- );
-
- let c = add_dyn(&b, &a).unwrap();
- assert_eq!(
- c.as_primitive::<Date32Type>().value(0),
- Date32Type::from_naive_date(NaiveDate::from_ymd_opt(2000, 2, 3).unwrap())
- );
- }
-
- #[test]
- fn test_date64_month_add() {
- let a = Date64Array::from(vec![Date64Type::from_naive_date(
- NaiveDate::from_ymd_opt(2000, 1, 1).unwrap(),
- )]);
- let b =
- IntervalYearMonthArray::from(vec![IntervalYearMonthType::make_value(1, 2)]);
- let c = add_dyn(&a, &b).unwrap();
- assert_eq!(
- c.as_primitive::<Date64Type>().value(0),
- Date64Type::from_naive_date(NaiveDate::from_ymd_opt(2001, 3, 1).unwrap())
- );
-
- let c = add_dyn(&b, &a).unwrap();
- assert_eq!(
- c.as_primitive::<Date64Type>().value(0),
- Date64Type::from_naive_date(NaiveDate::from_ymd_opt(2001, 3, 1).unwrap())
- );
- }
-
- #[test]
- fn test_date64_day_time_add() {
- let a = Date64Array::from(vec![Date64Type::from_naive_date(
- NaiveDate::from_ymd_opt(2000, 1, 1).unwrap(),
- )]);
- let b = IntervalDayTimeArray::from(vec![IntervalDayTimeType::make_value(1, 2)]);
- let c = add_dyn(&a, &b).unwrap();
- assert_eq!(
- c.as_primitive::<Date64Type>().value(0),
- Date64Type::from_naive_date(NaiveDate::from_ymd_opt(2000, 1, 2).unwrap())
- );
-
- let c = add_dyn(&b, &a).unwrap();
- assert_eq!(
- c.as_primitive::<Date64Type>().value(0),
- Date64Type::from_naive_date(NaiveDate::from_ymd_opt(2000, 1, 2).unwrap())
- );
- }
-
- #[test]
- fn test_date64_month_day_nano_add() {
- let a = Date64Array::from(vec![Date64Type::from_naive_date(
- NaiveDate::from_ymd_opt(2000, 1, 1).unwrap(),
- )]);
- let b =
- IntervalMonthDayNanoArray::from(vec![IntervalMonthDayNanoType::make_value(
- 1, 2, 3,
- )]);
- let c = add_dyn(&a, &b).unwrap();
- assert_eq!(
- c.as_primitive::<Date64Type>().value(0),
- Date64Type::from_naive_date(NaiveDate::from_ymd_opt(2000, 2, 3).unwrap())
- );
-
- let c = add_dyn(&b, &a).unwrap();
- assert_eq!(
- c.as_primitive::<Date64Type>().value(0),
- Date64Type::from_naive_date(NaiveDate::from_ymd_opt(2000, 2, 3).unwrap())
- );
- }
-
- #[test]
- fn test_primitive_array_add_dyn() {
- let a = Int32Array::from(vec![Some(5), Some(6), Some(7), Some(8), Some(9)]);
- let b = Int32Array::from(vec![Some(6), Some(7), Some(8), None, Some(8)]);
- let c = add_dyn(&a, &b).unwrap();
- let c = c.as_any().downcast_ref::<Int32Array>().unwrap();
- assert_eq!(11, c.value(0));
- assert_eq!(13, c.value(1));
- assert_eq!(15, c.value(2));
- assert!(c.is_null(3));
- assert_eq!(17, c.value(4));
- }
-
- #[test]
- fn test_primitive_array_add_scalar_dyn() {
- let a = Int32Array::from(vec![Some(5), Some(6), Some(7), None, Some(9)]);
- let b = 1_i32;
- let c = add_scalar_dyn::<Int32Type>(&a, b).unwrap();
- let c = c.as_any().downcast_ref::<Int32Array>().unwrap();
- assert_eq!(6, c.value(0));
- assert_eq!(7, c.value(1));
- assert_eq!(8, c.value(2));
- assert!(c.is_null(3));
- assert_eq!(10, c.value(4));
-
- let mut builder = PrimitiveDictionaryBuilder::<Int8Type, Int32Type>::new();
- builder.append(5).unwrap();
- builder.append_null();
- builder.append(7).unwrap();
- builder.append(8).unwrap();
- builder.append(9).unwrap();
- let a = builder.finish();
- let b = -1_i32;
-
- let c = add_scalar_dyn::<Int32Type>(&a, b).unwrap();
- let c = c
- .as_any()
- .downcast_ref::<DictionaryArray<Int8Type>>()
- .unwrap();
- let values = c
- .values()
- .as_any()
- .downcast_ref::<PrimitiveArray<Int32Type>>()
- .unwrap();
- assert_eq!(4, values.value(c.key(0).unwrap()));
- assert!(c.is_null(1));
- assert_eq!(6, values.value(c.key(2).unwrap()));
- assert_eq!(7, values.value(c.key(3).unwrap()));
- assert_eq!(8, values.value(c.key(4).unwrap()));
- }
-
- #[test]
- fn test_primitive_array_subtract_dyn() {
- let a = Int32Array::from(vec![Some(51), Some(6), Some(15), Some(8), Some(9)]);
- let b = Int32Array::from(vec![Some(6), Some(7), Some(8), None, Some(8)]);
- let c = subtract_dyn(&a, &b).unwrap();
- let c = c.as_any().downcast_ref::<Int32Array>().unwrap();
- assert_eq!(45, c.value(0));
- assert_eq!(-1, c.value(1));
- assert_eq!(7, c.value(2));
- assert!(c.is_null(3));
- assert_eq!(1, c.value(4));
- }
-
- #[test]
- fn test_date32_month_subtract() {
- let a = Date32Array::from(vec![Date32Type::from_naive_date(
- NaiveDate::from_ymd_opt(2000, 7, 1).unwrap(),
- )]);
- let b =
- IntervalYearMonthArray::from(vec![IntervalYearMonthType::make_value(6, 3)]);
- let c = subtract_dyn(&a, &b).unwrap();
- let c = c.as_any().downcast_ref::<Date32Array>().unwrap();
- assert_eq!(
- c.value(0),
- Date32Type::from_naive_date(NaiveDate::from_ymd_opt(1994, 4, 1).unwrap())
- );
- }
-
- #[test]
- fn test_date32_day_time_subtract() {
- let a = Date32Array::from(vec![Date32Type::from_naive_date(
- NaiveDate::from_ymd_opt(2023, 3, 29).unwrap(),
- )]);
- let b =
- IntervalDayTimeArray::from(vec![IntervalDayTimeType::make_value(1, 86500)]);
- let c = subtract_dyn(&a, &b).unwrap();
- let c = c.as_any().downcast_ref::<Date32Array>().unwrap();
- assert_eq!(
- c.value(0),
- Date32Type::from_naive_date(NaiveDate::from_ymd_opt(2023, 3, 28).unwrap())
- );
- }
-
- #[test]
- fn test_date32_month_day_nano_subtract() {
- let a = Date32Array::from(vec![Date32Type::from_naive_date(
- NaiveDate::from_ymd_opt(2023, 3, 15).unwrap(),
- )]);
- let b =
- IntervalMonthDayNanoArray::from(vec![IntervalMonthDayNanoType::make_value(
- 1, 2, 0,
- )]);
- let c = subtract_dyn(&a, &b).unwrap();
- let c = c.as_any().downcast_ref::<Date32Array>().unwrap();
- assert_eq!(
- c.value(0),
- Date32Type::from_naive_date(NaiveDate::from_ymd_opt(2023, 2, 13).unwrap())
- );
- }
-
- #[test]
- fn test_date64_month_subtract() {
- let a = Date64Array::from(vec![Date64Type::from_naive_date(
- NaiveDate::from_ymd_opt(2000, 7, 1).unwrap(),
- )]);
- let b =
- IntervalYearMonthArray::from(vec![IntervalYearMonthType::make_value(6, 3)]);
- let c = subtract_dyn(&a, &b).unwrap();
- let c = c.as_any().downcast_ref::<Date64Array>().unwrap();
- assert_eq!(
- c.value(0),
- Date64Type::from_naive_date(NaiveDate::from_ymd_opt(1994, 4, 1).unwrap())
- );
- }
-
- #[test]
- fn test_date64_day_time_subtract() {
- let a = Date64Array::from(vec![Date64Type::from_naive_date(
- NaiveDate::from_ymd_opt(2023, 3, 29).unwrap(),
- )]);
- let b =
- IntervalDayTimeArray::from(vec![IntervalDayTimeType::make_value(1, 86500)]);
- let c = subtract_dyn(&a, &b).unwrap();
- let c = c.as_any().downcast_ref::<Date64Array>().unwrap();
- assert_eq!(
- c.value(0),
- Date64Type::from_naive_date(NaiveDate::from_ymd_opt(2023, 3, 28).unwrap())
- );
- }
-
- #[test]
- fn test_date64_month_day_nano_subtract() {
- let a = Date64Array::from(vec![Date64Type::from_naive_date(
- NaiveDate::from_ymd_opt(2023, 3, 15).unwrap(),
- )]);
- let b =
- IntervalMonthDayNanoArray::from(vec![IntervalMonthDayNanoType::make_value(
- 1, 2, 0,
- )]);
- let c = subtract_dyn(&a, &b).unwrap();
- let c = c.as_any().downcast_ref::<Date64Array>().unwrap();
- assert_eq!(
- c.value(0),
- Date64Type::from_naive_date(NaiveDate::from_ymd_opt(2023, 2, 13).unwrap())
- );
- }
-
- #[test]
- fn test_primitive_array_subtract_scalar_dyn() {
- let a = Int32Array::from(vec![Some(5), Some(6), Some(7), None, Some(9)]);
- let b = 1_i32;
- let c = subtract_scalar_dyn::<Int32Type>(&a, b).unwrap();
- let c = c.as_any().downcast_ref::<Int32Array>().unwrap();
- assert_eq!(4, c.value(0));
- assert_eq!(5, c.value(1));
- assert_eq!(6, c.value(2));
- assert!(c.is_null(3));
- assert_eq!(8, c.value(4));
-
- let mut builder = PrimitiveDictionaryBuilder::<Int8Type, Int32Type>::new();
- builder.append(5).unwrap();
- builder.append_null();
- builder.append(7).unwrap();
- builder.append(8).unwrap();
- builder.append(9).unwrap();
- let a = builder.finish();
- let b = -1_i32;
-
- let c = subtract_scalar_dyn::<Int32Type>(&a, b).unwrap();
- let c = c
- .as_any()
- .downcast_ref::<DictionaryArray<Int8Type>>()
- .unwrap();
- let values = c
- .values()
- .as_any()
- .downcast_ref::<PrimitiveArray<Int32Type>>()
- .unwrap();
- assert_eq!(6, values.value(c.key(0).unwrap()));
- assert!(c.is_null(1));
- assert_eq!(8, values.value(c.key(2).unwrap()));
- assert_eq!(9, values.value(c.key(3).unwrap()));
- assert_eq!(10, values.value(c.key(4).unwrap()));
- }
-
- #[test]
- fn test_primitive_array_multiply_dyn() {
- let a = Int32Array::from(vec![Some(5), Some(6), Some(7), Some(8), Some(9)]);
- let b = Int32Array::from(vec![Some(6), Some(7), Some(8), None, Some(8)]);
- let c = multiply_dyn(&a, &b).unwrap();
- let c = c.as_any().downcast_ref::<Int32Array>().unwrap();
- assert_eq!(30, c.value(0));
- assert_eq!(42, c.value(1));
- assert_eq!(56, c.value(2));
- assert!(c.is_null(3));
- assert_eq!(72, c.value(4));
- }
-
- #[test]
- fn test_primitive_array_divide_dyn() {
- let a = Int32Array::from(vec![Some(15), Some(6), Some(1), Some(8), Some(9)]);
- let b = Int32Array::from(vec![Some(5), Some(3), Some(1), None, Some(3)]);
- let c = divide_dyn(&a, &b).unwrap();
- let c = c.as_any().downcast_ref::<Int32Array>().unwrap();
- assert_eq!(3, c.value(0));
- assert_eq!(2, c.value(1));
- assert_eq!(1, c.value(2));
- assert!(c.is_null(3));
- assert_eq!(3, c.value(4));
- }
-
- #[test]
- fn test_primitive_array_multiply_scalar_dyn() {
- let a = Int32Array::from(vec![Some(5), Some(6), Some(7), None, Some(9)]);
- let b = 2_i32;
- let c = multiply_scalar_dyn::<Int32Type>(&a, b).unwrap();
- let c = c.as_any().downcast_ref::<Int32Array>().unwrap();
- assert_eq!(10, c.value(0));
- assert_eq!(12, c.value(1));
- assert_eq!(14, c.value(2));
- assert!(c.is_null(3));
- assert_eq!(18, c.value(4));
-
- let mut builder = PrimitiveDictionaryBuilder::<Int8Type, Int32Type>::new();
- builder.append(5).unwrap();
- builder.append_null();
- builder.append(7).unwrap();
- builder.append(8).unwrap();
- builder.append(9).unwrap();
- let a = builder.finish();
- let b = -1_i32;
-
- let c = multiply_scalar_dyn::<Int32Type>(&a, b).unwrap();
- let c = c
- .as_any()
- .downcast_ref::<DictionaryArray<Int8Type>>()
- .unwrap();
- let values = c
- .values()
- .as_any()
- .downcast_ref::<PrimitiveArray<Int32Type>>()
- .unwrap();
- assert_eq!(-5, values.value(c.key(0).unwrap()));
- assert!(c.is_null(1));
- assert_eq!(-7, values.value(c.key(2).unwrap()));
- assert_eq!(-8, values.value(c.key(3).unwrap()));
- assert_eq!(-9, values.value(c.key(4).unwrap()));
- }
-
- #[test]
- fn test_primitive_array_add_sliced() {
- let a = Int32Array::from(vec![0, 0, 0, 5, 6, 7, 8, 9, 0]);
- let b = Int32Array::from(vec![0, 0, 0, 6, 7, 8, 9, 8, 0]);
- let a = a.slice(3, 5);
- let b = b.slice(3, 5);
- let a = a.as_any().downcast_ref::<Int32Array>().unwrap();
- let b = b.as_any().downcast_ref::<Int32Array>().unwrap();
-
- assert_eq!(5, a.value(0));
- assert_eq!(6, b.value(0));
-
- let c = add(a, b).unwrap();
- assert_eq!(5, c.len());
- assert_eq!(11, c.value(0));
- assert_eq!(13, c.value(1));
- assert_eq!(15, c.value(2));
- assert_eq!(17, c.value(3));
- assert_eq!(17, c.value(4));
- }
-
- #[test]
- fn test_primitive_array_add_mismatched_length() {
- let a = Int32Array::from(vec![5, 6, 7, 8, 9]);
- let b = Int32Array::from(vec![6, 7, 8]);
- let e = add(&a, &b).expect_err("should have failed due to different lengths");
- assert_eq!(
- "ComputeError(\"Cannot perform binary operation on arrays of different length\")",
- format!("{e:?}")
- );
- }
-
- #[test]
- fn test_primitive_array_add_scalar() {
- let a = Int32Array::from(vec![15, 14, 9, 8, 1]);
- let b = 3;
- let c = add_scalar(&a, b).unwrap();
- let expected = Int32Array::from(vec![18, 17, 12, 11, 4]);
- assert_eq!(c, expected);
- }
-
- #[test]
- fn test_primitive_array_add_scalar_sliced() {
- let a = Int32Array::from(vec![Some(15), None, Some(9), Some(8), None]);
- let a = a.slice(1, 4);
- let actual = add_scalar(&a, 3).unwrap();
- let expected = Int32Array::from(vec![None, Some(12), Some(11), None]);
- assert_eq!(actual, expected);
- }
-
- #[test]
- fn test_primitive_array_subtract() {
- let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
- let b = Int32Array::from(vec![5, 4, 3, 2, 1]);
- let c = subtract(&a, &b).unwrap();
- assert_eq!(-4, c.value(0));
- assert_eq!(-2, c.value(1));
- assert_eq!(0, c.value(2));
- assert_eq!(2, c.value(3));
- assert_eq!(4, c.value(4));
- }
-
- #[test]
- fn test_primitive_array_subtract_scalar() {
- let a = Int32Array::from(vec![15, 14, 9, 8, 1]);
- let b = 3;
- let c = subtract_scalar(&a, b).unwrap();
- let expected = Int32Array::from(vec![12, 11, 6, 5, -2]);
- assert_eq!(c, expected);
- }
-
- #[test]
- fn test_primitive_array_subtract_scalar_sliced() {
- let a = Int32Array::from(vec![Some(15), None, Some(9), Some(8), None]);
- let a = a.slice(1, 4);
- let actual = subtract_scalar(&a, 3).unwrap();
- let expected = Int32Array::from(vec![None, Some(6), Some(5), None]);
- assert_eq!(actual, expected);
- }
-
- #[test]
- fn test_primitive_array_multiply() {
- let a = Int32Array::from(vec![5, 6, 7, 8, 9]);
- let b = Int32Array::from(vec![6, 7, 8, 9, 8]);
- let c = multiply(&a, &b).unwrap();
- assert_eq!(30, c.value(0));
- assert_eq!(42, c.value(1));
- assert_eq!(56, c.value(2));
- assert_eq!(72, c.value(3));
- assert_eq!(72, c.value(4));
- }
-
- #[test]
- fn test_primitive_array_multiply_scalar() {
- let a = Int32Array::from(vec![15, 14, 9, 8, 1]);
- let b = 3;
- let c = multiply_scalar(&a, b).unwrap();
- let expected = Int32Array::from(vec![45, 42, 27, 24, 3]);
- assert_eq!(c, expected);
- }
-
- #[test]
- fn test_primitive_array_multiply_scalar_sliced() {
- let a = Int32Array::from(vec![Some(15), None, Some(9), Some(8), None]);
- let a = a.slice(1, 4);
- let actual = multiply_scalar(&a, 3).unwrap();
- let expected = Int32Array::from(vec![None, Some(27), Some(24), None]);
- assert_eq!(actual, expected);
- }
-
- #[test]
- fn test_primitive_array_divide() {
- let a = Int32Array::from(vec![15, 15, 8, 1, 9]);
- let b = Int32Array::from(vec![5, 6, 8, 9, 1]);
- let c = divide(&a, &b).unwrap();
- assert_eq!(3, c.value(0));
- assert_eq!(2, c.value(1));
- assert_eq!(1, c.value(2));
- assert_eq!(0, c.value(3));
- assert_eq!(9, c.value(4));
- }
-
- #[test]
- fn test_int_array_modulus() {
- let a = Int32Array::from(vec![15, 15, 8, 1, 9]);
- let b = Int32Array::from(vec![5, 6, 8, 9, 1]);
- let c = modulus(&a, &b).unwrap();
- assert_eq!(0, c.value(0));
- assert_eq!(3, c.value(1));
- assert_eq!(0, c.value(2));
- assert_eq!(1, c.value(3));
- assert_eq!(0, c.value(4));
-
- let c = modulus_dyn(&a, &b).unwrap();
- let c = c.as_primitive::<Int32Type>();
- assert_eq!(0, c.value(0));
- assert_eq!(3, c.value(1));
- assert_eq!(0, c.value(2));
- assert_eq!(1, c.value(3));
- assert_eq!(0, c.value(4));
- }
-
- #[test]
- #[should_panic(
- expected = "called `Result::unwrap()` on an `Err` value: DivideByZero"
- )]
- fn test_int_array_modulus_divide_by_zero() {
- let a = Int32Array::from(vec![1]);
- let b = Int32Array::from(vec![0]);
- modulus(&a, &b).unwrap();
- }
-
- #[test]
- #[should_panic(
- expected = "called `Result::unwrap()` on an `Err` value: DivideByZero"
- )]
- fn test_int_array_modulus_dyn_divide_by_zero() {
- let a = Int32Array::from(vec![1]);
- let b = Int32Array::from(vec![0]);
- modulus_dyn(&a, &b).unwrap();
- }
-
- #[test]
- fn test_int_array_modulus_overflow_wrapping() {
- let a = Int32Array::from(vec![i32::MIN]);
- let b = Int32Array::from(vec![-1]);
- let result = modulus(&a, &b).unwrap();
- assert_eq!(0, result.value(0))
- }
-
- #[test]
- fn test_primitive_array_divide_scalar() {
- let a = Int32Array::from(vec![15, 14, 9, 8, 1]);
- let b = 3;
- let c = divide_scalar(&a, b).unwrap();
- let expected = Int32Array::from(vec![5, 4, 3, 2, 0]);
- assert_eq!(c, expected);
- }
-
- #[test]
- fn test_primitive_array_divide_scalar_dyn() {
- let a = Int32Array::from(vec![Some(5), Some(6), Some(7), None, Some(9)]);
- let b = 2_i32;
- let c = divide_scalar_dyn::<Int32Type>(&a, b).unwrap();
- let c = c.as_any().downcast_ref::<Int32Array>().unwrap();
- assert_eq!(2, c.value(0));
- assert_eq!(3, c.value(1));
- assert_eq!(3, c.value(2));
- assert!(c.is_null(3));
- assert_eq!(4, c.value(4));
-
- let mut builder = PrimitiveDictionaryBuilder::<Int8Type, Int32Type>::new();
- builder.append(5).unwrap();
- builder.append_null();
- builder.append(7).unwrap();
- builder.append(8).unwrap();
- builder.append(9).unwrap();
- let a = builder.finish();
- let b = -2_i32;
-
- let c = divide_scalar_dyn::<Int32Type>(&a, b).unwrap();
- let c = c
- .as_any()
- .downcast_ref::<DictionaryArray<Int8Type>>()
- .unwrap();
- let values = c
- .values()
- .as_any()
- .downcast_ref::<PrimitiveArray<Int32Type>>()
- .unwrap();
- assert_eq!(-2, values.value(c.key(0).unwrap()));
- assert!(c.is_null(1));
- assert_eq!(-3, values.value(c.key(2).unwrap()));
- assert_eq!(-4, values.value(c.key(3).unwrap()));
- assert_eq!(-4, values.value(c.key(4).unwrap()));
-
- let e = divide_scalar_dyn::<Int32Type>(&a, 0_i32)
- .expect_err("should have failed due to divide by zero");
- assert_eq!("DivideByZero", format!("{e:?}"));
- }
-
- #[test]
- fn test_primitive_array_divide_scalar_sliced() {
- let a = Int32Array::from(vec![Some(15), None, Some(9), Some(8), None]);
- let a = a.slice(1, 4);
- let actual = divide_scalar(&a, 3).unwrap();
- let expected = Int32Array::from(vec![None, Some(3), Some(2), None]);
- assert_eq!(actual, expected);
- }
-
- #[test]
- fn test_int_array_modulus_scalar() {
- let a = Int32Array::from(vec![15, 14, 9, 8, 1]);
- let b = 3;
- let c = modulus_scalar(&a, b).unwrap();
- let expected = Int32Array::from(vec![0, 2, 0, 2, 1]);
- assert_eq!(c, expected);
-
- let c = modulus_scalar_dyn::<Int32Type>(&a, b).unwrap();
- let c = c.as_primitive::<Int32Type>();
- let expected = Int32Array::from(vec![0, 2, 0, 2, 1]);
- assert_eq!(c, &expected);
- }
-
- #[test]
- fn test_int_array_modulus_scalar_sliced() {
- let a = Int32Array::from(vec![Some(15), None, Some(9), Some(8), None]);
- let a = a.slice(1, 4);
- let actual = modulus_scalar(&a, 3).unwrap();
- let expected = Int32Array::from(vec![None, Some(0), Some(2), None]);
- assert_eq!(actual, expected);
-
- let actual = modulus_scalar_dyn::<Int32Type>(&a, 3).unwrap();
- let actual = actual.as_primitive::<Int32Type>();
- let expected = Int32Array::from(vec![None, Some(0), Some(2), None]);
- assert_eq!(actual, &expected);
- }
-
- #[test]
- #[should_panic(
- expected = "called `Result::unwrap()` on an `Err` value: DivideByZero"
- )]
- fn test_int_array_modulus_scalar_divide_by_zero() {
- let a = Int32Array::from(vec![1]);
- modulus_scalar(&a, 0).unwrap();
- }
-
- #[test]
- fn test_int_array_modulus_scalar_overflow_wrapping() {
- let a = Int32Array::from(vec![i32::MIN]);
- let result = modulus_scalar(&a, -1).unwrap();
- assert_eq!(0, result.value(0));
-
- let result = modulus_scalar_dyn::<Int32Type>(&a, -1).unwrap();
- let result = result.as_primitive::<Int32Type>();
- assert_eq!(0, result.value(0));
- }
-
- #[test]
- fn test_primitive_array_divide_sliced() {
- let a = Int32Array::from(vec![0, 0, 0, 15, 15, 8, 1, 9, 0]);
- let b = Int32Array::from(vec![0, 0, 0, 5, 6, 8, 9, 1, 0]);
- let a = a.slice(3, 5);
- let b = b.slice(3, 5);
- let a = a.as_any().downcast_ref::<Int32Array>().unwrap();
- let b = b.as_any().downcast_ref::<Int32Array>().unwrap();
-
- let c = divide(a, b).unwrap();
- assert_eq!(5, c.len());
- assert_eq!(3, c.value(0));
- assert_eq!(2, c.value(1));
- assert_eq!(1, c.value(2));
- assert_eq!(0, c.value(3));
- assert_eq!(9, c.value(4));
- }
-
- #[test]
- fn test_primitive_array_modulus_sliced() {
- let a = Int32Array::from(vec![0, 0, 0, 15, 15, 8, 1, 9, 0]);
- let b = Int32Array::from(vec![0, 0, 0, 5, 6, 8, 9, 1, 0]);
- let a = a.slice(3, 5);
- let b = b.slice(3, 5);
- let a = a.as_any().downcast_ref::<Int32Array>().unwrap();
- let b = b.as_any().downcast_ref::<Int32Array>().unwrap();
-
- let c = modulus(a, b).unwrap();
- assert_eq!(5, c.len());
- assert_eq!(0, c.value(0));
- assert_eq!(3, c.value(1));
- assert_eq!(0, c.value(2));
- assert_eq!(1, c.value(3));
- assert_eq!(0, c.value(4));
- }
-
- #[test]
- fn test_primitive_array_divide_with_nulls() {
- let a = Int32Array::from(vec![Some(15), None, Some(8), Some(1), Some(9), None]);
- let b = Int32Array::from(vec![Some(5), Some(6), Some(8), Some(9), None, None]);
- let c = divide_checked(&a, &b).unwrap();
- assert_eq!(3, c.value(0));
- assert!(c.is_null(1));
- assert_eq!(1, c.value(2));
- assert_eq!(0, c.value(3));
- assert!(c.is_null(4));
- assert!(c.is_null(5));
- }
-
- #[test]
- fn test_primitive_array_modulus_with_nulls() {
- let a = Int32Array::from(vec![Some(15), None, Some(8), Some(1), Some(9), None]);
- let b = Int32Array::from(vec![Some(5), Some(6), Some(8), Some(9), None, None]);
- let c = modulus(&a, &b).unwrap();
- assert_eq!(0, c.value(0));
- assert!(c.is_null(1));
- assert_eq!(0, c.value(2));
- assert_eq!(1, c.value(3));
- assert!(c.is_null(4));
- assert!(c.is_null(5));
- }
-
- #[test]
- fn test_primitive_array_divide_scalar_with_nulls() {
- let a = Int32Array::from(vec![Some(15), None, Some(8), Some(1), Some(9), None]);
- let b = 3;
- let c = divide_scalar(&a, b).unwrap();
- let expected =
- Int32Array::from(vec![Some(5), None, Some(2), Some(0), Some(3), None]);
- assert_eq!(c, expected);
- }
-
- #[test]
- fn test_primitive_array_modulus_scalar_with_nulls() {
- let a = Int32Array::from(vec![Some(15), None, Some(8), Some(1), Some(9), None]);
- let b = 3;
- let c = modulus_scalar(&a, b).unwrap();
- let expected =
- Int32Array::from(vec![Some(0), None, Some(2), Some(1), Some(0), None]);
- assert_eq!(c, expected);
- }
-
- #[test]
- fn test_primitive_array_divide_with_nulls_sliced() {
- let a = Int32Array::from(vec![
- None,
- None,
- None,
- None,
- None,
- None,
- None,
- None,
- Some(15),
- None,
- Some(8),
- Some(1),
- Some(9),
- None,
- None,
- ]);
- let b = Int32Array::from(vec![
- None,
- None,
- None,
- None,
- None,
- None,
- None,
- None,
- Some(5),
- Some(6),
- Some(8),
- Some(9),
- None,
- None,
- None,
- ]);
-
- let a = a.slice(8, 6);
- let a = a.as_any().downcast_ref::<Int32Array>().unwrap();
-
- let b = b.slice(8, 6);
- let b = b.as_any().downcast_ref::<Int32Array>().unwrap();
-
- let c = divide_checked(a, b).unwrap();
- assert_eq!(6, c.len());
- assert_eq!(3, c.value(0));
- assert!(c.is_null(1));
- assert_eq!(1, c.value(2));
- assert_eq!(0, c.value(3));
- assert!(c.is_null(4));
- assert!(c.is_null(5));
- }
-
- #[test]
- fn test_primitive_array_modulus_with_nulls_sliced() {
- let a = Int32Array::from(vec![
- None,
- None,
- None,
- None,
- None,
- None,
- None,
- None,
- Some(15),
- None,
- Some(8),
- Some(1),
- Some(9),
- None,
- None,
- ]);
- let b = Int32Array::from(vec![
- None,
- None,
- None,
- None,
- None,
- None,
- None,
- None,
- Some(5),
- Some(6),
- Some(8),
- Some(9),
- None,
- None,
- None,
- ]);
-
- let a = a.slice(8, 6);
- let a = a.as_any().downcast_ref::<Int32Array>().unwrap();
-
- let b = b.slice(8, 6);
- let b = b.as_any().downcast_ref::<Int32Array>().unwrap();
-
- let c = modulus(a, b).unwrap();
- assert_eq!(6, c.len());
- assert_eq!(0, c.value(0));
- assert!(c.is_null(1));
- assert_eq!(0, c.value(2));
- assert_eq!(1, c.value(3));
- assert!(c.is_null(4));
- assert!(c.is_null(5));
- }
-
- #[test]
- #[should_panic(expected = "DivideByZero")]
- fn test_int_array_divide_by_zero_with_checked() {
- let a = Int32Array::from(vec![15]);
- let b = Int32Array::from(vec![0]);
- divide_checked(&a, &b).unwrap();
- }
-
- #[test]
- #[should_panic(expected = "DivideByZero")]
- fn test_f32_array_divide_by_zero_with_checked() {
- let a = Float32Array::from(vec![15.0]);
- let b = Float32Array::from(vec![0.0]);
- divide_checked(&a, &b).unwrap();
- }
-
- #[test]
- #[should_panic(expected = "attempt to divide by zero")]
- fn test_int_array_divide_by_zero() {
- let a = Int32Array::from(vec![15]);
- let b = Int32Array::from(vec![0]);
- divide(&a, &b).unwrap();
- }
-
- #[test]
- fn test_f32_array_divide_by_zero() {
- let a = Float32Array::from(vec![1.5, 0.0, -1.5]);
- let b = Float32Array::from(vec![0.0, 0.0, 0.0]);
- let result = divide(&a, &b).unwrap();
- assert_eq!(result.value(0), f32::INFINITY);
- assert!(result.value(1).is_nan());
- assert_eq!(result.value(2), f32::NEG_INFINITY);
- }
-
- #[test]
- #[should_panic(expected = "DivideByZero")]
- fn test_int_array_divide_dyn_by_zero() {
- let a = Int32Array::from(vec![15]);
- let b = Int32Array::from(vec![0]);
- divide_dyn(&a, &b).unwrap();
- }
-
- #[test]
- #[should_panic(expected = "DivideByZero")]
- fn test_f32_array_divide_dyn_by_zero() {
- let a = Float32Array::from(vec![1.5]);
- let b = Float32Array::from(vec![0.0]);
- divide_dyn(&a, &b).unwrap();
- }
-
- #[test]
- #[should_panic(expected = "DivideByZero")]
- fn test_i32_array_modulus_by_zero() {
- let a = Int32Array::from(vec![15]);
- let b = Int32Array::from(vec![0]);
- modulus(&a, &b).unwrap();
- }
-
- #[test]
- #[should_panic(expected = "DivideByZero")]
- fn test_i32_array_modulus_dyn_by_zero() {
- let a = Int32Array::from(vec![15]);
- let b = Int32Array::from(vec![0]);
- modulus_dyn(&a, &b).unwrap();
- }
-
- #[test]
- #[should_panic(expected = "DivideByZero")]
- fn test_f32_array_modulus_by_zero() {
- let a = Float32Array::from(vec![1.5]);
- let b = Float32Array::from(vec![0.0]);
- modulus(&a, &b).unwrap();
- }
-
- #[test]
- fn test_f32_array_modulus_dyn_by_zero() {
- let a = Float32Array::from(vec![1.5]);
- let b = Float32Array::from(vec![0.0]);
- let result = modulus_dyn(&a, &b).unwrap();
- assert!(result.as_primitive::<Float32Type>().value(0).is_nan());
- }
-
- #[test]
- fn test_f64_array_divide() {
- let a = Float64Array::from(vec![15.0, 15.0, 8.0]);
- let b = Float64Array::from(vec![5.0, 6.0, 8.0]);
- let c = divide(&a, &b).unwrap();
- assert_eq!(3.0, c.value(0));
- assert_eq!(2.5, c.value(1));
- assert_eq!(1.0, c.value(2));
- }
-
- #[test]
- fn test_primitive_array_add_with_nulls() {
- let a = Int32Array::from(vec![Some(5), None, Some(7), None]);
- let b = Int32Array::from(vec![None, None, Some(6), Some(7)]);
- let c = add(&a, &b).unwrap();
- assert!(c.is_null(0));
- assert!(c.is_null(1));
- assert!(!c.is_null(2));
- assert!(c.is_null(3));
- assert_eq!(13, c.value(2));
- }
-
- #[test]
- fn test_primitive_array_negate() {
- let a: Int64Array = (0..100).map(Some).collect();
- let actual = negate(&a).unwrap();
- let expected: Int64Array = (0..100).map(|i| Some(-i)).collect();
- assert_eq!(expected, actual);
- }
-
- #[test]
- fn test_primitive_array_negate_checked_overflow() {
- let a = Int32Array::from(vec![i32::MIN]);
- let actual = negate(&a).unwrap();
- let expected = Int32Array::from(vec![i32::MIN]);
- assert_eq!(expected, actual);
-
- let err = negate_checked(&a);
- err.expect_err("negate_checked should detect overflow");
- }
-
- #[test]
- fn test_arithmetic_kernel_should_not_rely_on_padding() {
- let a: UInt8Array = (0..128_u8).map(Some).collect();
- let a = a.slice(63, 65);
- let a = a.as_any().downcast_ref::<UInt8Array>().unwrap();
-
- let b: UInt8Array = (0..128_u8).map(Some).collect();
- let b = b.slice(63, 65);
- let b = b.as_any().downcast_ref::<UInt8Array>().unwrap();
-
- let actual = add(a, b).unwrap();
- let actual: Vec<Option<u8>> = actual.iter().collect();
- let expected: Vec<Option<u8>> =
- (63..63_u8 + 65_u8).map(|i| Some(i + i)).collect();
- assert_eq!(expected, actual);
- }
-
- #[test]
- fn test_primitive_add_wrapping_overflow() {
- let a = Int32Array::from(vec![i32::MAX, i32::MIN]);
- let b = Int32Array::from(vec![1, 1]);
-
- let wrapped = add(&a, &b);
- let expected = Int32Array::from(vec![-2147483648, -2147483647]);
- assert_eq!(expected, wrapped.unwrap());
-
- let overflow = add_checked(&a, &b);
- overflow.expect_err("overflow should be detected");
- }
-
- #[test]
- fn test_primitive_subtract_wrapping_overflow() {
- let a = Int32Array::from(vec![-2]);
- let b = Int32Array::from(vec![i32::MAX]);
-
- let wrapped = subtract(&a, &b);
- let expected = Int32Array::from(vec![i32::MAX]);
- assert_eq!(expected, wrapped.unwrap());
-
- let overflow = subtract_checked(&a, &b);
- overflow.expect_err("overflow should be detected");
- }
-
- #[test]
- fn test_primitive_mul_wrapping_overflow() {
- let a = Int32Array::from(vec![10]);
- let b = Int32Array::from(vec![i32::MAX]);
-
- let wrapped = multiply(&a, &b);
- let expected = Int32Array::from(vec![-10]);
- assert_eq!(expected, wrapped.unwrap());
-
- let overflow = multiply_checked(&a, &b);
- overflow.expect_err("overflow should be detected");
- }
-
- #[test]
- #[cfg(not(feature = "simd"))]
- fn test_primitive_div_wrapping_overflow() {
- let a = Int32Array::from(vec![i32::MIN]);
- let b = Int32Array::from(vec![-1]);
-
- let wrapped = divide(&a, &b);
- let expected = Int32Array::from(vec![-2147483648]);
- assert_eq!(expected, wrapped.unwrap());
-
- let overflow = divide_checked(&a, &b);
- overflow.expect_err("overflow should be detected");
- }
-
- #[test]
- fn test_primitive_add_scalar_wrapping_overflow() {
- let a = Int32Array::from(vec![i32::MAX, i32::MIN]);
-
- let wrapped = add_scalar(&a, 1);
- let expected = Int32Array::from(vec![-2147483648, -2147483647]);
- assert_eq!(expected, wrapped.unwrap());
-
- let overflow = add_scalar_checked(&a, 1);
- overflow.expect_err("overflow should be detected");
- }
-
- #[test]
- fn test_primitive_subtract_scalar_wrapping_overflow() {
- let a = Int32Array::from(vec![-2]);
-
- let wrapped = subtract_scalar(&a, i32::MAX);
- let expected = Int32Array::from(vec![i32::MAX]);
- assert_eq!(expected, wrapped.unwrap());
-
- let overflow = subtract_scalar_checked(&a, i32::MAX);
- overflow.expect_err("overflow should be detected");
- }
-
- #[test]
- fn test_primitive_mul_scalar_wrapping_overflow() {
- let a = Int32Array::from(vec![10]);
-
- let wrapped = multiply_scalar(&a, i32::MAX);
- let expected = Int32Array::from(vec![-10]);
- assert_eq!(expected, wrapped.unwrap());
-
- let overflow = multiply_scalar_checked(&a, i32::MAX);
- overflow.expect_err("overflow should be detected");
- }
-
- #[test]
- fn test_primitive_add_scalar_dyn_wrapping_overflow() {
- let a = Int32Array::from(vec![i32::MAX, i32::MIN]);
-
- let wrapped = add_scalar_dyn::<Int32Type>(&a, 1).unwrap();
- let expected =
- Arc::new(Int32Array::from(vec![-2147483648, -2147483647])) as ArrayRef;
- assert_eq!(&expected, &wrapped);
-
- let overflow = add_scalar_checked_dyn::<Int32Type>(&a, 1);
- overflow.expect_err("overflow should be detected");
- }
-
- #[test]
- fn test_primitive_subtract_scalar_dyn_wrapping_overflow() {
- let a = Int32Array::from(vec![-2]);
-
- let wrapped = subtract_scalar_dyn::<Int32Type>(&a, i32::MAX).unwrap();
- let expected = Arc::new(Int32Array::from(vec![i32::MAX])) as ArrayRef;
- assert_eq!(&expected, &wrapped);
-
- let overflow = subtract_scalar_checked_dyn::<Int32Type>(&a, i32::MAX);
- overflow.expect_err("overflow should be detected");
- }
-
- #[test]
- fn test_primitive_mul_scalar_dyn_wrapping_overflow() {
- let a = Int32Array::from(vec![10]);
-
- let wrapped = multiply_scalar_dyn::<Int32Type>(&a, i32::MAX).unwrap();
- let expected = Arc::new(Int32Array::from(vec![-10])) as ArrayRef;
- assert_eq!(&expected, &wrapped);
-
- let overflow = multiply_scalar_checked_dyn::<Int32Type>(&a, i32::MAX);
- overflow.expect_err("overflow should be detected");
- }
-
- #[test]
- fn test_primitive_div_scalar_dyn_wrapping_overflow() {
- let a = Int32Array::from(vec![i32::MIN]);
-
- let wrapped = divide_scalar_dyn::<Int32Type>(&a, -1).unwrap();
- let expected = Arc::new(Int32Array::from(vec![-2147483648])) as ArrayRef;
- assert_eq!(&expected, &wrapped);
-
- let overflow = divide_scalar_checked_dyn::<Int32Type>(&a, -1);
- overflow.expect_err("overflow should be detected");
- }
-
- #[test]
- fn test_primitive_div_opt_overflow_division_by_zero() {
- let a = Int32Array::from(vec![i32::MIN]);
- let b = Int32Array::from(vec![-1]);
-
- let wrapped = divide(&a, &b);
- let expected = Int32Array::from(vec![-2147483648]);
- assert_eq!(expected, wrapped.unwrap());
-
- let overflow = divide_opt(&a, &b);
- let expected = Int32Array::from(vec![-2147483648]);
- assert_eq!(expected, overflow.unwrap());
-
- let b = Int32Array::from(vec![0]);
- let overflow = divide_opt(&a, &b);
- let expected = Int32Array::from(vec![None]);
- assert_eq!(expected, overflow.unwrap());
- }
-
- #[test]
- fn test_primitive_add_dyn_wrapping_overflow() {
- let a = Int32Array::from(vec![i32::MAX, i32::MIN]);
- let b = Int32Array::from(vec![1, 1]);
-
- let wrapped = add_dyn(&a, &b).unwrap();
- let expected =
- Arc::new(Int32Array::from(vec![-2147483648, -2147483647])) as ArrayRef;
- assert_eq!(&expected, &wrapped);
-
- let overflow = add_dyn_checked(&a, &b);
- overflow.expect_err("overflow should be detected");
- }
-
- #[test]
- fn test_primitive_subtract_dyn_wrapping_overflow() {
- let a = Int32Array::from(vec![-2]);
- let b = Int32Array::from(vec![i32::MAX]);
-
- let wrapped = subtract_dyn(&a, &b).unwrap();
- let expected = Arc::new(Int32Array::from(vec![i32::MAX])) as ArrayRef;
- assert_eq!(&expected, &wrapped);
-
- let overflow = subtract_dyn_checked(&a, &b);
- overflow.expect_err("overflow should be detected");
- }
-
- #[test]
- fn test_primitive_mul_dyn_wrapping_overflow() {
- let a = Int32Array::from(vec![10]);
- let b = Int32Array::from(vec![i32::MAX]);
-
- let wrapped = multiply_dyn(&a, &b).unwrap();
- let expected = Arc::new(Int32Array::from(vec![-10])) as ArrayRef;
- assert_eq!(&expected, &wrapped);
-
- let overflow = multiply_dyn_checked(&a, &b);
- overflow.expect_err("overflow should be detected");
- }
-
- #[test]
- fn test_primitive_div_dyn_wrapping_overflow() {
- let a = Int32Array::from(vec![i32::MIN]);
- let b = Int32Array::from(vec![-1]);
-
- let wrapped = divide_dyn(&a, &b).unwrap();
- let expected = Arc::new(Int32Array::from(vec![-2147483648])) as ArrayRef;
- assert_eq!(&expected, &wrapped);
-
- let overflow = divide_dyn_checked(&a, &b);
- overflow.expect_err("overflow should be detected");
- }
-
- #[test]
- fn test_decimal128() {
- let a = Decimal128Array::from_iter_values([1, 2, 4, 5]);
- let b = Decimal128Array::from_iter_values([7, -3, 6, 3]);
- let e = Decimal128Array::from_iter_values([8, -1, 10, 8]);
- let r = add(&a, &b).unwrap();
- assert_eq!(e, r);
-
- let e = Decimal128Array::from_iter_values([-6, 5, -2, 2]);
- let r = subtract(&a, &b).unwrap();
- assert_eq!(e, r);
-
- let e = Decimal128Array::from_iter_values([7, -6, 24, 15]);
- let r = multiply(&a, &b).unwrap();
- assert_eq!(e, r);
-
- let a = Decimal128Array::from_iter_values([23, 56, 32, 55]);
- let b = Decimal128Array::from_iter_values([1, -2, 4, 5]);
- let e = Decimal128Array::from_iter_values([23, -28, 8, 11]);
- let r = divide(&a, &b).unwrap();
- assert_eq!(e, r);
- }
-
- #[test]
- fn test_decimal256() {
- let a = Decimal256Array::from_iter_values(
- [1, 2, 4, 5].into_iter().map(i256::from_i128),
- );
- let b = Decimal256Array::from_iter_values(
- [7, -3, 6, 3].into_iter().map(i256::from_i128),
- );
- let e = Decimal256Array::from_iter_values(
- [8, -1, 10, 8].into_iter().map(i256::from_i128),
- );
- let r = add(&a, &b).unwrap();
- assert_eq!(e, r);
-
- let e = Decimal256Array::from_iter_values(
- [-6, 5, -2, 2].into_iter().map(i256::from_i128),
- );
- let r = subtract(&a, &b).unwrap();
- assert_eq!(e, r);
-
- let e = Decimal256Array::from_iter_values(
- [7, -6, 24, 15].into_iter().map(i256::from_i128),
- );
- let r = multiply(&a, &b).unwrap();
- assert_eq!(e, r);
-
- let a = Decimal256Array::from_iter_values(
- [23, 56, 32, 55].into_iter().map(i256::from_i128),
- );
- let b = Decimal256Array::from_iter_values(
- [1, -2, 4, 5].into_iter().map(i256::from_i128),
- );
- let e = Decimal256Array::from_iter_values(
- [23, -28, 8, 11].into_iter().map(i256::from_i128),
- );
- let r = divide(&a, &b).unwrap();
- assert_eq!(e, r);
- }
-
- #[test]
- fn test_div_scalar_dyn_opt_overflow_division_by_zero() {
- let a = Int32Array::from(vec![i32::MIN]);
-
- let division_by_zero = divide_scalar_opt_dyn::<Int32Type>(&a, 0);
- let expected = Arc::new(Int32Array::from(vec![None])) as ArrayRef;
- assert_eq!(&expected, &division_by_zero.unwrap());
-
- let mut builder =
- PrimitiveDictionaryBuilder::<Int8Type, Int32Type>::with_capacity(1, 1);
- builder.append(i32::MIN).unwrap();
- let a = builder.finish();
-
- let division_by_zero = divide_scalar_opt_dyn::<Int32Type>(&a, 0);
- assert_eq!(&expected, &division_by_zero.unwrap());
- }
-
- #[test]
- fn test_sum_f16() {
- let a = Float16Array::from_iter_values([
- f16::from_f32(0.1),
- f16::from_f32(0.2),
- f16::from_f32(1.5),
- f16::from_f32(-0.1),
- ]);
- let b = Float16Array::from_iter_values([
- f16::from_f32(5.1),
- f16::from_f32(6.2),
- f16::from_f32(-1.),
- f16::from_f32(-2.1),
- ]);
- let expected = Float16Array::from_iter_values(
- a.values().iter().zip(b.values()).map(|(a, b)| a + b),
- );
-
- let c = add(&a, &b).unwrap();
- assert_eq!(c, expected);
- }
-
- #[test]
- fn test_resize_builder() {
- let mut null_buffer_builder = BooleanBufferBuilder::new(16);
- null_buffer_builder.append_slice(&[
- false, false, false, false, false, false, false, false, false, false, false,
- false, false, true, true, true,
- ]);
- // `resize` resizes the buffer length to the ceil of byte numbers.
- // So the underlying buffer is not changed.
- null_buffer_builder.resize(13);
- assert_eq!(null_buffer_builder.len(), 13);
-
- let nulls = null_buffer_builder.finish();
- assert_eq!(nulls.count_set_bits(), 0);
- let nulls = NullBuffer::new(nulls);
- assert_eq!(nulls.null_count(), 13);
-
- let mut data_buffer_builder = BufferBuilder::<i32>::new(13);
- data_buffer_builder.append_slice(&[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
- let data_buffer = data_buffer_builder.finish();
-
- let arg1: Int32Array = ArrayDataBuilder::new(DataType::Int32)
- .len(13)
- .nulls(Some(nulls))
- .buffers(vec![data_buffer])
- .build()
- .unwrap()
- .into();
-
- assert_eq!(arg1.null_count(), 13);
-
- let mut data_buffer_builder = BufferBuilder::<i32>::new(13);
- data_buffer_builder.append_slice(&[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
- let data_buffer = data_buffer_builder.finish();
-
- let arg2: Int32Array = ArrayDataBuilder::new(DataType::Int32)
- .len(13)
- .buffers(vec![data_buffer])
- .build()
- .unwrap()
- .into();
-
- assert_eq!(arg2.null_count(), 0);
-
- let result_dyn = add_dyn(&arg1, &arg2).unwrap();
- let result = result_dyn.as_any().downcast_ref::<Int32Array>().unwrap();
-
- assert_eq!(result.len(), 13);
- assert_eq!(result.null_count(), 13);
- }
-
- #[test]
- fn test_primitive_array_add_mut_by_binary_mut() {
- let a = Int32Array::from(vec![15, 14, 9, 8, 1]);
- let b = Int32Array::from(vec![Some(1), None, Some(3), None, Some(5)]);
-
- let c = binary_mut(a, &b, |a, b| a.add_wrapping(b))
- .unwrap()
- .unwrap();
- let expected = Int32Array::from(vec![Some(16), None, Some(12), None, Some(6)]);
- assert_eq!(c, expected);
- }
-
- #[test]
- fn test_primitive_add_mut_wrapping_overflow_by_try_binary_mut() {
- let a = Int32Array::from(vec![i32::MAX, i32::MIN]);
- let b = Int32Array::from(vec![1, 1]);
-
- let wrapped = binary_mut(a, &b, |a, b| a.add_wrapping(b))
- .unwrap()
- .unwrap();
- let expected = Int32Array::from(vec![-2147483648, -2147483647]);
- assert_eq!(expected, wrapped);
-
- let a = Int32Array::from(vec![i32::MAX, i32::MIN]);
- let b = Int32Array::from(vec![1, 1]);
- let overflow = try_binary_mut(a, &b, |a, b| a.add_checked(b));
- let _ = overflow.unwrap().expect_err("overflow should be detected");
- }
-
- #[test]
- fn test_primitive_add_scalar_by_unary_mut() {
- let a = Int32Array::from(vec![15, 14, 9, 8, 1]);
- let b = 3;
- let c = unary_mut(a, |value| value.add_wrapping(b)).unwrap();
- let expected = Int32Array::from(vec![18, 17, 12, 11, 4]);
- assert_eq!(c, expected);
- }
-
- #[test]
- fn test_primitive_add_scalar_overflow_by_try_unary_mut() {
- let a = Int32Array::from(vec![i32::MAX, i32::MIN]);
-
- let wrapped = unary_mut(a, |value| value.add_wrapping(1)).unwrap();
- let expected = Int32Array::from(vec![-2147483648, -2147483647]);
- assert_eq!(expected, wrapped);
-
- let a = Int32Array::from(vec![i32::MAX, i32::MIN]);
- let overflow = try_unary_mut(a, |value| value.add_checked(1));
- let _ = overflow.unwrap().expect_err("overflow should be detected");
- }
-
- #[test]
- fn test_decimal_add_scalar_dyn() {
- let a = Decimal128Array::from(vec![100, 210, 320])
- .with_precision_and_scale(38, 2)
- .unwrap();
-
- let result = add_scalar_dyn::<Decimal128Type>(&a, 1).unwrap();
- let result = result
- .as_primitive::<Decimal128Type>()
- .clone()
- .with_precision_and_scale(38, 2)
- .unwrap();
- let expected = Decimal128Array::from(vec![101, 211, 321])
- .with_precision_and_scale(38, 2)
- .unwrap();
-
- assert_eq!(&expected, &result);
- }
-
- #[test]
- fn test_decimal_multiply_allow_precision_loss() {
- // Overflow happening as i128 cannot hold multiplying result.
- // [123456789]
- let a = Decimal128Array::from(vec![123456789000000000000000000])
- .with_precision_and_scale(38, 18)
- .unwrap();
-
- // [10]
- let b = Decimal128Array::from(vec![10000000000000000000])
- .with_precision_and_scale(38, 18)
- .unwrap();
-
- let err = multiply_dyn_checked(&a, &b).unwrap_err();
- assert!(err.to_string().contains(
- "Overflow happened on: 123456789000000000000000000 * 10000000000000000000"
- ));
-
- // Allow precision loss.
- let result = multiply_fixed_point_checked(&a, &b, 28).unwrap();
- // [1234567890]
- let expected =
- Decimal128Array::from(vec![12345678900000000000000000000000000000])
- .with_precision_and_scale(38, 28)
- .unwrap();
-
- assert_eq!(&expected, &result);
- assert_eq!(
- result.value_as_string(0),
- "1234567890.0000000000000000000000000000"
- );
-
- // Rounding case
- // [0.000000000000000001, 123456789.555555555555555555, 1.555555555555555555]
- let a = Decimal128Array::from(vec![
- 1,
- 123456789555555555555555555,
- 1555555555555555555,
- ])
- .with_precision_and_scale(38, 18)
- .unwrap();
-
- // [1.555555555555555555, 11.222222222222222222, 0.000000000000000001]
- let b = Decimal128Array::from(vec![1555555555555555555, 11222222222222222222, 1])
- .with_precision_and_scale(38, 18)
- .unwrap();
-
- let result = multiply_fixed_point_checked(&a, &b, 28).unwrap();
- // [
- // 0.0000000000000000015555555556,
- // 1385459527.2345679012071330528765432099,
- // 0.0000000000000000015555555556
- // ]
- let expected = Decimal128Array::from(vec![
- 15555555556,
- 13854595272345679012071330528765432099,
- 15555555556,
- ])
- .with_precision_and_scale(38, 28)
- .unwrap();
-
- assert_eq!(&expected, &result);
-
- // Rounded the value "1385459527.234567901207133052876543209876543210".
- assert_eq!(
- result.value_as_string(1),
- "1385459527.2345679012071330528765432099"
- );
- assert_eq!(result.value_as_string(0), "0.0000000000000000015555555556");
- assert_eq!(result.value_as_string(2), "0.0000000000000000015555555556");
+ // Rounded the value "1385459527.234567901207133052876543209876543210".
+ assert_eq!(
+ result.value_as_string(1),
+ "1385459527.2345679012071330528765432099"
+ );
+ assert_eq!(result.value_as_string(0), "0.0000000000000000015555555556");
+ assert_eq!(result.value_as_string(2), "0.0000000000000000015555555556");
let a = Decimal128Array::from(vec![1230])
.with_precision_and_scale(4, 2)
@@ -2609,11 +283,8 @@ mod tests {
assert_eq!(result.precision(), 9);
assert_eq!(result.scale(), 4);
- let expected = multiply_checked(&a, &b)
- .unwrap()
- .with_precision_and_scale(9, 4)
- .unwrap();
- assert_eq!(&expected, &result);
+ let expected = mul(&a, &b).unwrap();
+ assert_eq!(expected.as_ref(), &result);
// Required scale cannot be larger than the product of the input scales.
let result = multiply_fixed_point_checked(&a, &b, 5).unwrap_err();
@@ -2661,12 +332,8 @@ mod tests {
.unwrap();
// `multiply` overflows on this case.
- let result = multiply(&a, &b).unwrap();
- let expected =
- Decimal128Array::from(vec![-16672482290199102048610367863168958464])
- .with_precision_and_scale(38, 10)
- .unwrap();
- assert_eq!(&expected, &result);
+ let err = mul(&a, &b).unwrap_err();
+ assert_eq!(err.to_string(), "Compute error: Overflow happened on: 123456789000000000000000000 * 10000000000000000000");
// Avoid overflow by reducing the scale.
let result = multiply_fixed_point(&a, &b, 28).unwrap();
@@ -2682,693 +349,4 @@ mod tests {
"1234567890.0000000000000000000000000000"
);
}
-
- #[test]
- fn test_timestamp_second_add_interval() {
- // timestamp second + interval year month
- let a = TimestampSecondArray::from(vec![1, 2, 3, 4, 5]);
- let b = IntervalYearMonthArray::from(vec![
- Some(IntervalYearMonthType::make_value(1, 2)),
- Some(IntervalYearMonthType::make_value(1, 2)),
- Some(IntervalYearMonthType::make_value(1, 2)),
- Some(IntervalYearMonthType::make_value(1, 2)),
- Some(IntervalYearMonthType::make_value(1, 2)),
- ]);
-
- let result = add_dyn(&a, &b).unwrap();
- let result = result.as_primitive::<TimestampSecondType>();
-
- let expected = TimestampSecondArray::from(vec![
- 1 + SECONDS_IN_DAY * (365 + 31 + 28),
- 2 + SECONDS_IN_DAY * (365 + 31 + 28),
- 3 + SECONDS_IN_DAY * (365 + 31 + 28),
- 4 + SECONDS_IN_DAY * (365 + 31 + 28),
- 5 + SECONDS_IN_DAY * (365 + 31 + 28),
- ]);
- assert_eq!(result, &expected);
-
- let result = add_dyn(&b, &a).unwrap();
- let result = result.as_primitive::<TimestampSecondType>();
- assert_eq!(result, &expected);
-
- // timestamp second + interval day time
- let a = TimestampSecondArray::from(vec![1, 2, 3, 4, 5]);
- let b = IntervalDayTimeArray::from(vec![
- Some(IntervalDayTimeType::make_value(1, 0)),
- Some(IntervalDayTimeType::make_value(1, 0)),
- Some(IntervalDayTimeType::make_value(1, 0)),
- Some(IntervalDayTimeType::make_value(1, 0)),
- Some(IntervalDayTimeType::make_value(1, 0)),
- ]);
- let result = add_dyn(&a, &b).unwrap();
- let result = result.as_primitive::<TimestampSecondType>();
-
- let expected = TimestampSecondArray::from(vec![
- 1 + SECONDS_IN_DAY,
- 2 + SECONDS_IN_DAY,
- 3 + SECONDS_IN_DAY,
- 4 + SECONDS_IN_DAY,
- 5 + SECONDS_IN_DAY,
- ]);
- assert_eq!(&expected, result);
- let result = add_dyn(&b, &a).unwrap();
- let result = result.as_primitive::<TimestampSecondType>();
- assert_eq!(result, &expected);
-
- // timestamp second + interval month day nanosecond
- let a = TimestampSecondArray::from(vec![1, 2, 3, 4, 5]);
- let b = IntervalMonthDayNanoArray::from(vec![
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- ]);
- let result = add_dyn(&a, &b).unwrap();
- let result = result.as_primitive::<TimestampSecondType>();
-
- let expected = TimestampSecondArray::from(vec![
- 1 + SECONDS_IN_DAY,
- 2 + SECONDS_IN_DAY,
- 3 + SECONDS_IN_DAY,
- 4 + SECONDS_IN_DAY,
- 5 + SECONDS_IN_DAY,
- ]);
- assert_eq!(&expected, result);
- let result = add_dyn(&b, &a).unwrap();
- let result = result.as_primitive::<TimestampSecondType>();
- assert_eq!(result, &expected);
- }
-
- #[test]
- fn test_timestamp_second_subtract_interval() {
- // timestamp second + interval year month
- let a = TimestampSecondArray::from(vec![1, 2, 3, 4, 5]);
- let b = IntervalYearMonthArray::from(vec![
- Some(IntervalYearMonthType::make_value(1, 2)),
- Some(IntervalYearMonthType::make_value(1, 2)),
- Some(IntervalYearMonthType::make_value(1, 2)),
- Some(IntervalYearMonthType::make_value(1, 2)),
- Some(IntervalYearMonthType::make_value(1, 2)),
- ]);
-
- let result = subtract_dyn(&a, &b).unwrap();
- let result = result.as_primitive::<TimestampSecondType>();
-
- let expected = TimestampSecondArray::from(vec![
- 1 - SECONDS_IN_DAY * (31 + 30 + 365),
- 2 - SECONDS_IN_DAY * (31 + 30 + 365),
- 3 - SECONDS_IN_DAY * (31 + 30 + 365),
- 4 - SECONDS_IN_DAY * (31 + 30 + 365),
- 5 - SECONDS_IN_DAY * (31 + 30 + 365),
- ]);
- assert_eq!(&expected, result);
-
- // timestamp second + interval day time
- let a = TimestampSecondArray::from(vec![1, 2, 3, 4, 5]);
- let b = IntervalDayTimeArray::from(vec![
- Some(IntervalDayTimeType::make_value(1, 0)),
- Some(IntervalDayTimeType::make_value(1, 0)),
- Some(IntervalDayTimeType::make_value(1, 0)),
- Some(IntervalDayTimeType::make_value(1, 0)),
- Some(IntervalDayTimeType::make_value(1, 0)),
- ]);
- let result = subtract_dyn(&a, &b).unwrap();
- let result = result.as_primitive::<TimestampSecondType>();
-
- let expected = TimestampSecondArray::from(vec![
- 1 - SECONDS_IN_DAY,
- 2 - SECONDS_IN_DAY,
- 3 - SECONDS_IN_DAY,
- 4 - SECONDS_IN_DAY,
- 5 - SECONDS_IN_DAY,
- ]);
- assert_eq!(&expected, result);
-
- // timestamp second + interval month day nanosecond
- let a = TimestampSecondArray::from(vec![1, 2, 3, 4, 5]);
- let b = IntervalMonthDayNanoArray::from(vec![
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- ]);
- let result = subtract_dyn(&a, &b).unwrap();
- let result = result.as_primitive::<TimestampSecondType>();
-
- let expected = TimestampSecondArray::from(vec![
- 1 - SECONDS_IN_DAY,
- 2 - SECONDS_IN_DAY,
- 3 - SECONDS_IN_DAY,
- 4 - SECONDS_IN_DAY,
- 5 - SECONDS_IN_DAY,
- ]);
- assert_eq!(&expected, result);
- }
-
- #[test]
- fn test_timestamp_millisecond_add_interval() {
- // timestamp millisecond + interval year month
- let a = TimestampMillisecondArray::from(vec![1, 2, 3, 4, 5]);
- let b = IntervalYearMonthArray::from(vec![
- Some(IntervalYearMonthType::make_value(1, 2)),
- Some(IntervalYearMonthType::make_value(1, 2)),
- Some(IntervalYearMonthType::make_value(1, 2)),
- Some(IntervalYearMonthType::make_value(1, 2)),
- Some(IntervalYearMonthType::make_value(1, 2)),
- ]);
-
- let result = add_dyn(&a, &b).unwrap();
- let result = result.as_primitive::<TimestampMillisecondType>();
-
- let expected = TimestampMillisecondArray::from(vec![
- 1 + SECONDS_IN_DAY * (31 + 28 + 365) * 1_000,
- 2 + SECONDS_IN_DAY * (31 + 28 + 365) * 1_000,
- 3 + SECONDS_IN_DAY * (31 + 28 + 365) * 1_000,
- 4 + SECONDS_IN_DAY * (31 + 28 + 365) * 1_000,
- 5 + SECONDS_IN_DAY * (31 + 28 + 365) * 1_000,
- ]);
- assert_eq!(result, &expected);
- let result = add_dyn(&b, &a).unwrap();
- let result = result.as_primitive::<TimestampMillisecondType>();
- assert_eq!(result, &expected);
-
- // timestamp millisecond + interval day time
- let a = TimestampMillisecondArray::from(vec![1, 2, 3, 4, 5]);
- let b = IntervalDayTimeArray::from(vec![
- Some(IntervalDayTimeType::make_value(1, 0)),
- Some(IntervalDayTimeType::make_value(1, 0)),
- Some(IntervalDayTimeType::make_value(1, 0)),
- Some(IntervalDayTimeType::make_value(1, 0)),
- Some(IntervalDayTimeType::make_value(1, 0)),
- ]);
- let result = add_dyn(&a, &b).unwrap();
- let result = result.as_primitive::<TimestampMillisecondType>();
-
- let expected = TimestampMillisecondArray::from(vec![
- 1 + SECONDS_IN_DAY * 1_000,
- 2 + SECONDS_IN_DAY * 1_000,
- 3 + SECONDS_IN_DAY * 1_000,
- 4 + SECONDS_IN_DAY * 1_000,
- 5 + SECONDS_IN_DAY * 1_000,
- ]);
- assert_eq!(&expected, result);
- let result = add_dyn(&b, &a).unwrap();
- let result = result.as_primitive::<TimestampMillisecondType>();
- assert_eq!(result, &expected);
-
- // timestamp millisecond + interval month day nanosecond
- let a = TimestampMillisecondArray::from(vec![1, 2, 3, 4, 5]);
- let b = IntervalMonthDayNanoArray::from(vec![
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- ]);
- let result = add_dyn(&a, &b).unwrap();
- let result = result.as_primitive::<TimestampMillisecondType>();
-
- let expected = TimestampMillisecondArray::from(vec![
- 1 + SECONDS_IN_DAY * 1_000,
- 2 + SECONDS_IN_DAY * 1_000,
- 3 + SECONDS_IN_DAY * 1_000,
- 4 + SECONDS_IN_DAY * 1_000,
- 5 + SECONDS_IN_DAY * 1_000,
- ]);
- assert_eq!(&expected, result);
- let result = add_dyn(&b, &a).unwrap();
- let result = result.as_primitive::<TimestampMillisecondType>();
- assert_eq!(result, &expected);
- }
-
- #[test]
- fn test_timestamp_millisecond_subtract_interval() {
- // timestamp millisecond + interval year month
- let a = TimestampMillisecondArray::from(vec![1, 2, 3, 4, 5]);
- let b = IntervalYearMonthArray::from(vec![
- Some(IntervalYearMonthType::make_value(1, 2)),
- Some(IntervalYearMonthType::make_value(1, 2)),
- Some(IntervalYearMonthType::make_value(1, 2)),
- Some(IntervalYearMonthType::make_value(1, 2)),
- Some(IntervalYearMonthType::make_value(1, 2)),
- ]);
-
- let result = subtract_dyn(&a, &b).unwrap();
- let result = result.as_primitive::<TimestampMillisecondType>();
-
- let expected = TimestampMillisecondArray::from(vec![
- 1 - SECONDS_IN_DAY * (31 + 30 + 365) * 1_000,
- 2 - SECONDS_IN_DAY * (31 + 30 + 365) * 1_000,
- 3 - SECONDS_IN_DAY * (31 + 30 + 365) * 1_000,
- 4 - SECONDS_IN_DAY * (31 + 30 + 365) * 1_000,
- 5 - SECONDS_IN_DAY * (31 + 30 + 365) * 1_000,
- ]);
- assert_eq!(&expected, result);
-
- // timestamp millisecond + interval day time
- let a = TimestampMillisecondArray::from(vec![1, 2, 3, 4, 5]);
- let b = IntervalDayTimeArray::from(vec![
- Some(IntervalDayTimeType::make_value(1, 0)),
- Some(IntervalDayTimeType::make_value(1, 0)),
- Some(IntervalDayTimeType::make_value(1, 0)),
- Some(IntervalDayTimeType::make_value(1, 0)),
- Some(IntervalDayTimeType::make_value(1, 0)),
- ]);
- let result = subtract_dyn(&a, &b).unwrap();
- let result = result.as_primitive::<TimestampMillisecondType>();
-
- let expected = TimestampMillisecondArray::from(vec![
- 1 - SECONDS_IN_DAY * 1_000,
- 2 - SECONDS_IN_DAY * 1_000,
- 3 - SECONDS_IN_DAY * 1_000,
- 4 - SECONDS_IN_DAY * 1_000,
- 5 - SECONDS_IN_DAY * 1_000,
- ]);
- assert_eq!(&expected, result);
-
- // timestamp millisecond + interval month day nanosecond
- let a = TimestampMillisecondArray::from(vec![1, 2, 3, 4, 5]);
- let b = IntervalMonthDayNanoArray::from(vec![
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- ]);
- let result = subtract_dyn(&a, &b).unwrap();
- let result = result.as_primitive::<TimestampMillisecondType>();
-
- let expected = TimestampMillisecondArray::from(vec![
- 1 - SECONDS_IN_DAY * 1_000,
- 2 - SECONDS_IN_DAY * 1_000,
- 3 - SECONDS_IN_DAY * 1_000,
- 4 - SECONDS_IN_DAY * 1_000,
- 5 - SECONDS_IN_DAY * 1_000,
- ]);
- assert_eq!(&expected, result);
- }
-
- #[test]
- fn test_timestamp_microsecond_add_interval() {
- // timestamp microsecond + interval year month
- let a = TimestampMicrosecondArray::from(vec![1, 2, 3, 4, 5]);
- let b = IntervalYearMonthArray::from(vec![
- Some(IntervalYearMonthType::make_value(1, 2)),
- Some(IntervalYearMonthType::make_value(1, 2)),
- Some(IntervalYearMonthType::make_value(1, 2)),
- Some(IntervalYearMonthType::make_value(1, 2)),
- Some(IntervalYearMonthType::make_value(1, 2)),
- ]);
-
- let result = add_dyn(&a, &b).unwrap();
- let result = result.as_primitive::<TimestampMicrosecondType>();
-
- let expected = TimestampMicrosecondArray::from(vec![
- 1 + SECONDS_IN_DAY * (31 + 28 + 365) * 1_000_000,
- 2 + SECONDS_IN_DAY * (31 + 28 + 365) * 1_000_000,
- 3 + SECONDS_IN_DAY * (31 + 28 + 365) * 1_000_000,
- 4 + SECONDS_IN_DAY * (31 + 28 + 365) * 1_000_000,
- 5 + SECONDS_IN_DAY * (31 + 28 + 365) * 1_000_000,
- ]);
- assert_eq!(result, &expected);
- let result = add_dyn(&b, &a).unwrap();
- let result = result.as_primitive::<TimestampMicrosecondType>();
- assert_eq!(result, &expected);
-
- // timestamp microsecond + interval day time
- let a = TimestampMicrosecondArray::from(vec![1, 2, 3, 4, 5]);
- let b = IntervalDayTimeArray::from(vec![
- Some(IntervalDayTimeType::make_value(1, 0)),
- Some(IntervalDayTimeType::make_value(1, 0)),
- Some(IntervalDayTimeType::make_value(1, 0)),
- Some(IntervalDayTimeType::make_value(1, 0)),
- Some(IntervalDayTimeType::make_value(1, 0)),
- ]);
- let result = add_dyn(&a, &b).unwrap();
- let result = result.as_primitive::<TimestampMicrosecondType>();
-
- let expected = TimestampMicrosecondArray::from(vec![
- 1 + SECONDS_IN_DAY * 1_000_000,
- 2 + SECONDS_IN_DAY * 1_000_000,
- 3 + SECONDS_IN_DAY * 1_000_000,
- 4 + SECONDS_IN_DAY * 1_000_000,
- 5 + SECONDS_IN_DAY * 1_000_000,
- ]);
- assert_eq!(&expected, result);
- let result = add_dyn(&b, &a).unwrap();
- let result = result.as_primitive::<TimestampMicrosecondType>();
- assert_eq!(result, &expected);
-
- // timestamp microsecond + interval month day nanosecond
- let a = TimestampMicrosecondArray::from(vec![1, 2, 3, 4, 5]);
- let b = IntervalMonthDayNanoArray::from(vec![
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- ]);
- let result = add_dyn(&a, &b).unwrap();
- let result = result.as_primitive::<TimestampMicrosecondType>();
-
- let expected = TimestampMicrosecondArray::from(vec![
- 1 + SECONDS_IN_DAY * 1_000_000,
- 2 + SECONDS_IN_DAY * 1_000_000,
- 3 + SECONDS_IN_DAY * 1_000_000,
- 4 + SECONDS_IN_DAY * 1_000_000,
- 5 + SECONDS_IN_DAY * 1_000_000,
- ]);
- assert_eq!(&expected, result);
- let result = add_dyn(&b, &a).unwrap();
- let result = result.as_primitive::<TimestampMicrosecondType>();
- assert_eq!(result, &expected);
- }
-
- #[test]
- fn test_timestamp_microsecond_subtract_interval() {
- // timestamp microsecond + interval year month
- let a = TimestampMicrosecondArray::from(vec![1, 2, 3, 4, 5]);
- let b = IntervalYearMonthArray::from(vec![
- Some(IntervalYearMonthType::make_value(1, 2)),
- Some(IntervalYearMonthType::make_value(1, 2)),
- Some(IntervalYearMonthType::make_value(1, 2)),
- Some(IntervalYearMonthType::make_value(1, 2)),
- Some(IntervalYearMonthType::make_value(1, 2)),
- ]);
-
- let result = subtract_dyn(&a, &b).unwrap();
- let result = result.as_primitive::<TimestampMicrosecondType>();
-
- let expected = TimestampMicrosecondArray::from(vec![
- 1 - SECONDS_IN_DAY * (31 + 30 + 365) * 1_000_000,
- 2 - SECONDS_IN_DAY * (31 + 30 + 365) * 1_000_000,
- 3 - SECONDS_IN_DAY * (31 + 30 + 365) * 1_000_000,
- 4 - SECONDS_IN_DAY * (31 + 30 + 365) * 1_000_000,
- 5 - SECONDS_IN_DAY * (31 + 30 + 365) * 1_000_000,
- ]);
- assert_eq!(&expected, result);
-
- // timestamp microsecond + interval day time
- let a = TimestampMicrosecondArray::from(vec![1, 2, 3, 4, 5]);
- let b = IntervalDayTimeArray::from(vec![
- Some(IntervalDayTimeType::make_value(1, 0)),
- Some(IntervalDayTimeType::make_value(1, 0)),
- Some(IntervalDayTimeType::make_value(1, 0)),
- Some(IntervalDayTimeType::make_value(1, 0)),
- Some(IntervalDayTimeType::make_value(1, 0)),
- ]);
- let result = subtract_dyn(&a, &b).unwrap();
- let result = result.as_primitive::<TimestampMicrosecondType>();
-
- let expected = TimestampMicrosecondArray::from(vec![
- 1 - SECONDS_IN_DAY * 1_000_000,
- 2 - SECONDS_IN_DAY * 1_000_000,
- 3 - SECONDS_IN_DAY * 1_000_000,
- 4 - SECONDS_IN_DAY * 1_000_000,
- 5 - SECONDS_IN_DAY * 1_000_000,
- ]);
- assert_eq!(&expected, result);
-
- // timestamp microsecond + interval month day nanosecond
- let a = TimestampMicrosecondArray::from(vec![1, 2, 3, 4, 5]);
- let b = IntervalMonthDayNanoArray::from(vec![
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- ]);
- let result = subtract_dyn(&a, &b).unwrap();
- let result = result.as_primitive::<TimestampMicrosecondType>();
-
- let expected = TimestampMicrosecondArray::from(vec![
- 1 - SECONDS_IN_DAY * 1_000_000,
- 2 - SECONDS_IN_DAY * 1_000_000,
- 3 - SECONDS_IN_DAY * 1_000_000,
- 4 - SECONDS_IN_DAY * 1_000_000,
- 5 - SECONDS_IN_DAY * 1_000_000,
- ]);
- assert_eq!(&expected, result);
- }
-
- #[test]
- fn test_timestamp_nanosecond_add_interval() {
- // timestamp nanosecond + interval year month
- let a = TimestampNanosecondArray::from(vec![1, 2, 3, 4, 5]);
- let b = IntervalYearMonthArray::from(vec![
- Some(IntervalYearMonthType::make_value(1, 2)),
- Some(IntervalYearMonthType::make_value(1, 2)),
- Some(IntervalYearMonthType::make_value(1, 2)),
- Some(IntervalYearMonthType::make_value(1, 2)),
- Some(IntervalYearMonthType::make_value(1, 2)),
- ]);
-
- let result = add_dyn(&a, &b).unwrap();
- let result = result.as_primitive::<TimestampNanosecondType>();
-
- let expected = TimestampNanosecondArray::from(vec![
- 1 + SECONDS_IN_DAY * (31 + 28 + 365) * 1_000_000_000,
- 2 + SECONDS_IN_DAY * (31 + 28 + 365) * 1_000_000_000,
- 3 + SECONDS_IN_DAY * (31 + 28 + 365) * 1_000_000_000,
- 4 + SECONDS_IN_DAY * (31 + 28 + 365) * 1_000_000_000,
- 5 + SECONDS_IN_DAY * (31 + 28 + 365) * 1_000_000_000,
- ]);
- assert_eq!(result, &expected);
- let result = add_dyn(&b, &a).unwrap();
- let result = result.as_primitive::<TimestampNanosecondType>();
- assert_eq!(result, &expected);
-
- // timestamp nanosecond + interval day time
- let a = TimestampNanosecondArray::from(vec![1, 2, 3, 4, 5]);
- let b = IntervalDayTimeArray::from(vec![
- Some(IntervalDayTimeType::make_value(1, 0)),
- Some(IntervalDayTimeType::make_value(1, 0)),
- Some(IntervalDayTimeType::make_value(1, 0)),
- Some(IntervalDayTimeType::make_value(1, 0)),
- Some(IntervalDayTimeType::make_value(1, 0)),
- ]);
- let result = add_dyn(&a, &b).unwrap();
- let result = result.as_primitive::<TimestampNanosecondType>();
-
- let expected = TimestampNanosecondArray::from(vec![
- 1 + SECONDS_IN_DAY * 1_000_000_000,
- 2 + SECONDS_IN_DAY * 1_000_000_000,
- 3 + SECONDS_IN_DAY * 1_000_000_000,
- 4 + SECONDS_IN_DAY * 1_000_000_000,
- 5 + SECONDS_IN_DAY * 1_000_000_000,
- ]);
- assert_eq!(&expected, result);
- let result = add_dyn(&b, &a).unwrap();
- let result = result.as_primitive::<TimestampNanosecondType>();
- assert_eq!(result, &expected);
-
- // timestamp nanosecond + interval month day nanosecond
- let a = TimestampNanosecondArray::from(vec![1, 2, 3, 4, 5]);
- let b = IntervalMonthDayNanoArray::from(vec![
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- ]);
- let result = add_dyn(&a, &b).unwrap();
- let result = result.as_primitive::<TimestampNanosecondType>();
-
- let expected = TimestampNanosecondArray::from(vec![
- 1 + SECONDS_IN_DAY * 1_000_000_000,
- 2 + SECONDS_IN_DAY * 1_000_000_000,
- 3 + SECONDS_IN_DAY * 1_000_000_000,
- 4 + SECONDS_IN_DAY * 1_000_000_000,
- 5 + SECONDS_IN_DAY * 1_000_000_000,
- ]);
- assert_eq!(&expected, result);
- let result = add_dyn(&b, &a).unwrap();
- let result = result.as_primitive::<TimestampNanosecondType>();
- assert_eq!(result, &expected);
- }
-
- #[test]
- fn test_timestamp_nanosecond_subtract_interval() {
- // timestamp nanosecond + interval year month
- let a = TimestampNanosecondArray::from(vec![1, 2, 3, 4, 5]);
- let b = IntervalYearMonthArray::from(vec![
- Some(IntervalYearMonthType::make_value(1, 2)),
- Some(IntervalYearMonthType::make_value(1, 2)),
- Some(IntervalYearMonthType::make_value(1, 2)),
- Some(IntervalYearMonthType::make_value(1, 2)),
- Some(IntervalYearMonthType::make_value(1, 2)),
- ]);
-
- let result = subtract_dyn(&a, &b).unwrap();
- let result = result.as_primitive::<TimestampNanosecondType>();
-
- let expected = TimestampNanosecondArray::from(vec![
- 1 - SECONDS_IN_DAY * (31 + 30 + 365) * 1_000_000_000,
- 2 - SECONDS_IN_DAY * (31 + 30 + 365) * 1_000_000_000,
- 3 - SECONDS_IN_DAY * (31 + 30 + 365) * 1_000_000_000,
- 4 - SECONDS_IN_DAY * (31 + 30 + 365) * 1_000_000_000,
- 5 - SECONDS_IN_DAY * (31 + 30 + 365) * 1_000_000_000,
- ]);
- assert_eq!(&expected, result);
-
- // timestamp nanosecond + interval day time
- let a = TimestampNanosecondArray::from(vec![1, 2, 3, 4, 5]);
- let b = IntervalDayTimeArray::from(vec![
- Some(IntervalDayTimeType::make_value(1, 0)),
- Some(IntervalDayTimeType::make_value(1, 0)),
- Some(IntervalDayTimeType::make_value(1, 0)),
- Some(IntervalDayTimeType::make_value(1, 0)),
- Some(IntervalDayTimeType::make_value(1, 0)),
- ]);
- let result = subtract_dyn(&a, &b).unwrap();
- let result = result.as_primitive::<TimestampNanosecondType>();
-
- let expected = TimestampNanosecondArray::from(vec![
- 1 - SECONDS_IN_DAY * 1_000_000_000,
- 2 - SECONDS_IN_DAY * 1_000_000_000,
- 3 - SECONDS_IN_DAY * 1_000_000_000,
- 4 - SECONDS_IN_DAY * 1_000_000_000,
- 5 - SECONDS_IN_DAY * 1_000_000_000,
- ]);
- assert_eq!(&expected, result);
-
- // timestamp nanosecond + interval month day nanosecond
- let a = TimestampNanosecondArray::from(vec![1, 2, 3, 4, 5]);
- let b = IntervalMonthDayNanoArray::from(vec![
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- Some(IntervalMonthDayNanoType::make_value(0, 1, 0)),
- ]);
- let result = subtract_dyn(&a, &b).unwrap();
- let result = result.as_primitive::<TimestampNanosecondType>();
-
- let expected = TimestampNanosecondArray::from(vec![
- 1 - SECONDS_IN_DAY * 1_000_000_000,
- 2 - SECONDS_IN_DAY * 1_000_000_000,
- 3 - SECONDS_IN_DAY * 1_000_000_000,
- 4 - SECONDS_IN_DAY * 1_000_000_000,
- 5 - SECONDS_IN_DAY * 1_000_000_000,
- ]);
- assert_eq!(&expected, result);
- }
-
- #[test]
- fn test_timestamp_second_subtract_timestamp() {
- let a = TimestampSecondArray::from(vec![0, 2, 4, 6, 8]);
- let b = TimestampSecondArray::from(vec![1, 2, 3, 4, 5]);
- let expected = DurationSecondArray::from(vec![-1, 0, 1, 2, 3]);
-
- // unchecked
- let result = subtract_dyn(&a, &b).unwrap();
- let result = result.as_primitive::<DurationSecondType>();
- assert_eq!(&expected, result);
-
- // checked
- let result = subtract_dyn_checked(&a, &b).unwrap();
- let result = result.as_primitive::<DurationSecondType>();
- assert_eq!(&expected, result);
- }
-
- #[test]
- fn test_timestamp_second_subtract_timestamp_overflow() {
- let a = TimestampSecondArray::from(vec![
- <TimestampSecondType as ArrowPrimitiveType>::Native::MAX,
- ]);
- let b = TimestampSecondArray::from(vec![
- <TimestampSecondType as ArrowPrimitiveType>::Native::MIN,
- ]);
-
- // checked
- let result = subtract_dyn_checked(&a, &b);
- assert!(&result.is_err());
- }
-
- #[test]
- fn test_timestamp_microsecond_subtract_timestamp() {
- let a = TimestampMicrosecondArray::from(vec![0, 2, 4, 6, 8]);
- let b = TimestampMicrosecondArray::from(vec![1, 2, 3, 4, 5]);
- let expected = DurationMicrosecondArray::from(vec![-1, 0, 1, 2, 3]);
-
- // unchecked
- let result = subtract_dyn(&a, &b).unwrap();
- let result = result.as_primitive::<DurationMicrosecondType>();
- assert_eq!(&expected, result);
-
- // checked
- let result = subtract_dyn_checked(&a, &b).unwrap();
- let result = result.as_primitive::<DurationMicrosecondType>();
- assert_eq!(&expected, result);
- }
-
- #[test]
- fn test_timestamp_microsecond_subtract_timestamp_overflow() {
- let a = TimestampMicrosecondArray::from(vec![i64::MAX]);
- let b = TimestampMicrosecondArray::from(vec![i64::MIN]);
-
- // checked
- let result = subtract_dyn_checked(&a, &b);
- assert!(&result.is_err());
- }
-
- #[test]
- fn test_timestamp_millisecond_subtract_timestamp() {
- let a = TimestampMillisecondArray::from(vec![0, 2, 4, 6, 8]);
- let b = TimestampMillisecondArray::from(vec![1, 2, 3, 4, 5]);
- let expected = DurationMillisecondArray::from(vec![-1, 0, 1, 2, 3]);
-
- // unchecked
- let result = subtract_dyn(&a, &b).unwrap();
- let result = result.as_primitive::<DurationMillisecondType>();
- assert_eq!(&expected, result);
-
- // checked
- let result = subtract_dyn_checked(&a, &b).unwrap();
- let result = result.as_primitive::<DurationMillisecondType>();
- assert_eq!(&expected, result);
- }
-
- #[test]
- fn test_timestamp_millisecond_subtract_timestamp_overflow() {
- let a = TimestampMillisecondArray::from(vec![i64::MAX]);
- let b = TimestampMillisecondArray::from(vec![i64::MIN]);
-
- // checked
- let result = subtract_dyn_checked(&a, &b);
- assert!(&result.is_err());
- }
-
- #[test]
- fn test_timestamp_nanosecond_subtract_timestamp() {
- let a = TimestampNanosecondArray::from(vec![0, 2, 4, 6, 8]);
- let b = TimestampNanosecondArray::from(vec![1, 2, 3, 4, 5]);
- let expected = DurationNanosecondArray::from(vec![-1, 0, 1, 2, 3]);
-
- // unchecked
- let result = subtract_dyn(&a, &b).unwrap();
- let result = result.as_primitive::<DurationNanosecondType>();
- assert_eq!(&expected, result);
-
- // checked
- let result = subtract_dyn_checked(&a, &b).unwrap();
- let result = result.as_primitive::<DurationNanosecondType>();
- assert_eq!(&expected, result);
- }
-
- #[test]
- fn test_timestamp_nanosecond_subtract_timestamp_overflow() {
- let a = TimestampNanosecondArray::from(vec![
- <TimestampNanosecondType as ArrowPrimitiveType>::Native::MAX,
- ]);
- let b = TimestampNanosecondArray::from(vec![
- <TimestampNanosecondType as ArrowPrimitiveType>::Native::MIN,
- ]);
-
- // checked
- let result = subtract_dyn_checked(&a, &b);
- assert!(&result.is_err());
- }
}
diff --git a/arrow-arith/src/arity.rs b/arrow-arith/src/arity.rs
index ce766aff66f7..2dac33a4f28b 100644
--- a/arrow-arith/src/arity.rs
+++ b/arrow-arith/src/arity.rs
@@ -18,7 +18,6 @@
//! Defines kernels suitable to perform operations to primitive arrays.
use arrow_array::builder::BufferBuilder;
-use arrow_array::iterator::ArrayIter;
use arrow_array::types::ArrowDictionaryKeyType;
use arrow_array::*;
use arrow_buffer::buffer::NullBuffer;
@@ -425,76 +424,6 @@ where
Ok(Ok(builder.finish()))
}
-#[inline(never)]
-fn try_binary_opt_no_nulls<A: ArrayAccessor, B: ArrayAccessor, F, O>(
- len: usize,
- a: A,
- b: B,
- op: F,
-) -> Result<PrimitiveArray<O>, ArrowError>
-where
- O: ArrowPrimitiveType,
- F: Fn(A::Item, B::Item) -> Option<O::Native>,
-{
- let mut buffer = Vec::with_capacity(10);
- for idx in 0..len {
- unsafe {
- buffer.push(op(a.value_unchecked(idx), b.value_unchecked(idx)));
- };
- }
- Ok(buffer.iter().collect())
-}
-
-/// Applies the provided binary operation across `a` and `b`, collecting the optional results
-/// into a [`PrimitiveArray`]. If any index is null in either `a` or `b`, the corresponding
-/// index in the result will also be null. The binary operation could return `None` which
-/// results in a new null in the collected [`PrimitiveArray`].
-///
-/// The function is only evaluated for non-null indices
-///
-/// # Error
-///
-/// This function gives error if the arrays have different lengths
-pub(crate) fn binary_opt<A: ArrayAccessor + Array, B: ArrayAccessor + Array, F, O>(
- a: A,
- b: B,
- op: F,
-) -> Result<PrimitiveArray<O>, ArrowError>
-where
- O: ArrowPrimitiveType,
- F: Fn(A::Item, B::Item) -> Option<O::Native>,
-{
- if a.len() != b.len() {
- return Err(ArrowError::ComputeError(
- "Cannot perform binary operation on arrays of different length".to_string(),
- ));
- }
-
- if a.is_empty() {
- return Ok(PrimitiveArray::from(ArrayData::new_empty(&O::DATA_TYPE)));
- }
-
- if a.null_count() == 0 && b.null_count() == 0 {
- return try_binary_opt_no_nulls(a.len(), a, b, op);
- }
-
- let iter_a = ArrayIter::new(a);
- let iter_b = ArrayIter::new(b);
-
- let values = iter_a
- .into_iter()
- .zip(iter_b.into_iter())
- .map(|(item_a, item_b)| {
- if let (Some(a), Some(b)) = (item_a, item_b) {
- op(a, b)
- } else {
- None
- }
- });
-
- Ok(values.collect())
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/arrow/src/ffi.rs b/arrow/src/ffi.rs
index a392d1deec86..7fbbaa7a3907 100644
--- a/arrow/src/ffi.rs
+++ b/arrow/src/ffi.rs
@@ -31,10 +31,11 @@
//! # use std::sync::Arc;
//! # use arrow::array::{Int32Array, Array, ArrayData, make_array};
//! # use arrow::error::Result;
-//! # use arrow::compute::kernels::arithmetic;
+//! # use arrow_arith::numeric::add;
//! # use arrow::ffi::{to_ffi, from_ffi};
//! # fn main() -> Result<()> {
//! // create an array natively
+//!
//! let array = Int32Array::from(vec![Some(1), None, Some(3)]);
//! let data = array.into_data();
//!
@@ -46,10 +47,10 @@
//! let array = Int32Array::from(data);
//!
//! // perform some operation
-//! let array = arithmetic::add(&array, &array)?;
+//! let array = add(&array, &array)?;
//!
//! // verify
-//! assert_eq!(array, Int32Array::from(vec![Some(2), None, Some(6)]));
+//! assert_eq!(array.as_ref(), &Int32Array::from(vec![Some(2), None, Some(6)]));
//! #
//! # Ok(())
//! # }
@@ -948,10 +949,10 @@ mod tests {
// perform some operation
let array = array.as_any().downcast_ref::<Int32Array>().unwrap();
- let array = kernels::arithmetic::add(array, array).unwrap();
+ let array = kernels::numeric::add(array, array).unwrap();
// verify
- assert_eq!(array, Int32Array::from(vec![2, 4, 6]));
+ assert_eq!(array.as_ref(), &Int32Array::from(vec![2, 4, 6]));
Ok(())
}
diff --git a/arrow/src/lib.rs b/arrow/src/lib.rs
index bf39bae530b9..6d340b4dd6ba 100644
--- a/arrow/src/lib.rs
+++ b/arrow/src/lib.rs
@@ -184,7 +184,7 @@
//!
//! This module also implements many common vertical operations:
//!
-//! * All mathematical binary operators, such as [`subtract`](compute::kernels::arithmetic::subtract)
+//! * All mathematical binary operators, such as [`sub`](compute::kernels::numeric::sub)
//! * All boolean binary operators such as [`equality`](compute::kernels::comparison::eq)
//! * [`cast`](compute::kernels::cast::cast)
//! * [`filter`](compute::kernels::filter::filter)
|
diff --git a/arrow-pyarrow-integration-testing/src/lib.rs b/arrow-pyarrow-integration-testing/src/lib.rs
index 730409b3777e..89395bd2ed08 100644
--- a/arrow-pyarrow-integration-testing/src/lib.rs
+++ b/arrow-pyarrow-integration-testing/src/lib.rs
@@ -49,7 +49,7 @@ fn double(array: &PyAny, py: Python) -> PyResult<PyObject> {
.ok_or_else(|| ArrowError::ParseError("Expects an int64".to_string()))
.map_err(to_py_err)?;
- let array = kernels::arithmetic::add(array, array).map_err(to_py_err)?;
+ let array = kernels::numeric::add(array, array).map_err(to_py_err)?;
// export
array.to_data().to_pyarrow(py)
|
Remove Deprecated Arithmetic Kernels
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
<!--
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
(This section helps Arrow developers understand the context and *why* for this feature, in addition to the *what*)
-->
https://github.com/apache/arrow-rs/pull/4465 deprecated a large number of arithmetic kernels
**Describe the solution you'd like**
<!--
A clear and concise description of what you want to happen.
-->
Once a sufficient amount of time has passed, e.g. 2 releases, we should remove the old kernels
**Describe alternatives you've considered**
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
|
2023-07-30T20:17:13Z
|
45.0
|
c6184389241a0c85823aa494e8b5d93343771666
|
|
apache/arrow-rs
| 4,351
|
apache__arrow-rs-4351
|
[
"4350"
] |
008cf9c27424d581a67ba97f338a22b6eace9cc1
|
diff --git a/object_store/Cargo.toml b/object_store/Cargo.toml
index 28bf29f7f1e0..4002a1865fa6 100644
--- a/object_store/Cargo.toml
+++ b/object_store/Cargo.toml
@@ -75,3 +75,7 @@ tempfile = "3.1.0"
futures-test = "0.3"
rand = "0.8"
hyper = { version = "0.14.24", features = ["server"] }
+
+[[test]]
+name = "get_range_file"
+path = "tests/get_range_file.rs"
diff --git a/object_store/src/lib.rs b/object_store/src/lib.rs
index 98bbb7adceb9..864cabc4a8c0 100644
--- a/object_store/src/lib.rs
+++ b/object_store/src/lib.rs
@@ -359,10 +359,20 @@ pub trait ObjectStore: std::fmt::Display + Send + Sync + Debug + 'static {
/// in the given byte range
async fn get_range(&self, location: &Path, range: Range<usize>) -> Result<Bytes> {
let options = GetOptions {
- range: Some(range),
+ range: Some(range.clone()),
..Default::default()
};
- self.get_opts(location, options).await?.bytes().await
+ // Temporary until GetResult::File supports range (#4352)
+ match self.get_opts(location, options).await? {
+ GetResult::Stream(s) => collect_bytes(s, None).await,
+ #[cfg(not(target_arch = "wasm32"))]
+ GetResult::File(mut file, path) => {
+ maybe_spawn_blocking(move || local::read_range(&mut file, &path, range))
+ .await
+ }
+ #[cfg(target_arch = "wasm32")]
+ _ => unimplemented!("File IO not implemented on wasm32."),
+ }
}
/// Return the bytes that are stored at the specified location
diff --git a/object_store/src/local.rs b/object_store/src/local.rs
index 6039f8dbadf3..ffff6a5739d5 100644
--- a/object_store/src/local.rs
+++ b/object_store/src/local.rs
@@ -863,7 +863,7 @@ impl AsyncWrite for LocalUpload {
}
}
-fn read_range(file: &mut File, path: &PathBuf, range: Range<usize>) -> Result<Bytes> {
+pub(crate) fn read_range(file: &mut File, path: &PathBuf, range: Range<usize>) -> Result<Bytes> {
let to_read = range.end - range.start;
file.seek(SeekFrom::Start(range.start as u64))
.context(SeekSnafu { path })?;
|
diff --git a/object_store/tests/get_range_file.rs b/object_store/tests/get_range_file.rs
new file mode 100644
index 000000000000..f926e3b07f2a
--- /dev/null
+++ b/object_store/tests/get_range_file.rs
@@ -0,0 +1,116 @@
+// 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.
+
+//! Tests the default implementation of get_range handles GetResult::File correctly (#4350)
+
+use async_trait::async_trait;
+use bytes::Bytes;
+use futures::stream::BoxStream;
+use object_store::local::LocalFileSystem;
+use object_store::path::Path;
+use object_store::{
+ GetOptions, GetResult, ListResult, MultipartId, ObjectMeta, ObjectStore,
+};
+use std::fmt::Formatter;
+use tempfile::tempdir;
+use tokio::io::AsyncWrite;
+
+#[derive(Debug)]
+struct MyStore(LocalFileSystem);
+
+impl std::fmt::Display for MyStore {
+ fn fmt(&self, _: &mut Formatter<'_>) -> std::fmt::Result {
+ todo!()
+ }
+}
+
+#[async_trait]
+impl ObjectStore for MyStore {
+ async fn put(&self, path: &Path, data: Bytes) -> object_store::Result<()> {
+ self.0.put(path, data).await
+ }
+
+ async fn put_multipart(
+ &self,
+ _: &Path,
+ ) -> object_store::Result<(MultipartId, Box<dyn AsyncWrite + Unpin + Send>)> {
+ todo!()
+ }
+
+ async fn abort_multipart(
+ &self,
+ _: &Path,
+ _: &MultipartId,
+ ) -> object_store::Result<()> {
+ todo!()
+ }
+
+ async fn get_opts(
+ &self,
+ location: &Path,
+ options: GetOptions,
+ ) -> object_store::Result<GetResult> {
+ self.0.get_opts(location, options).await
+ }
+
+ async fn head(&self, _: &Path) -> object_store::Result<ObjectMeta> {
+ todo!()
+ }
+
+ async fn delete(&self, _: &Path) -> object_store::Result<()> {
+ todo!()
+ }
+
+ async fn list(
+ &self,
+ _: Option<&Path>,
+ ) -> object_store::Result<BoxStream<'_, object_store::Result<ObjectMeta>>> {
+ todo!()
+ }
+
+ async fn list_with_delimiter(
+ &self,
+ _: Option<&Path>,
+ ) -> object_store::Result<ListResult> {
+ todo!()
+ }
+
+ async fn copy(&self, _: &Path, _: &Path) -> object_store::Result<()> {
+ todo!()
+ }
+
+ async fn copy_if_not_exists(&self, _: &Path, _: &Path) -> object_store::Result<()> {
+ todo!()
+ }
+}
+
+#[tokio::test]
+async fn test_get_range() {
+ let tmp = tempdir().unwrap();
+ let store = MyStore(LocalFileSystem::new_with_prefix(tmp.path()).unwrap());
+ let path = Path::from("foo");
+
+ let expected = Bytes::from_static(b"hello world");
+ store.put(&path, expected.clone()).await.unwrap();
+ let fetched = store.get(&path).await.unwrap().bytes().await.unwrap();
+ assert_eq!(expected, fetched);
+
+ for range in [0..10, 3..5, 0..expected.len()] {
+ let data = store.get_range(&path, range.clone()).await.unwrap();
+ assert_eq!(&data[..], &expected[range])
+ }
+}
|
Default ObjectStore::get_range Doesn't Apply Range to GetResult::File
**Describe the bug**
<!--
A clear and concise description of what the bug is.
-->
The default implementation of `ObjectStore::get_range` added in #4212 incorrectly handles if `GetResult::File` is returned, instead returning the entire byte range. This is incorrect
**To Reproduce**
<!--
Steps to reproduce the behavior:
-->
**Expected behavior**
<!--
A clear and concise description of what you expected to happen.
-->
**Additional context**
<!--
Add any other context about the problem here.
-->
|
2023-06-02T16:36:39Z
|
40.0
|
008cf9c27424d581a67ba97f338a22b6eace9cc1
|
|
apache/arrow-rs
| 4,343
|
apache__arrow-rs-4343
|
[
"4324"
] |
795259502d8d19f1e929d8ebf1b2819b6ab145c4
|
diff --git a/arrow-data/src/transform/mod.rs b/arrow-data/src/transform/mod.rs
index c74875072233..f4b2b46d1723 100644
--- a/arrow-data/src/transform/mod.rs
+++ b/arrow-data/src/transform/mod.rs
@@ -53,7 +53,7 @@ struct _MutableArrayData<'a> {
pub null_count: usize,
pub len: usize,
- pub null_buffer: MutableBuffer,
+ pub null_buffer: Option<MutableBuffer>,
// arrow specification only allows up to 3 buffers (2 ignoring the nulls above).
// Thus, we place them in the stack to avoid bound checks and greater data locality.
@@ -63,6 +63,12 @@ struct _MutableArrayData<'a> {
}
impl<'a> _MutableArrayData<'a> {
+ fn null_buffer(&mut self) -> &mut MutableBuffer {
+ self.null_buffer
+ .as_mut()
+ .expect("MutableArrayData not nullable")
+ }
+
fn freeze(self, dictionary: Option<ArrayData>) -> ArrayDataBuilder {
let buffers = into_buffers(&self.data_type, self.buffer1, self.buffer2);
@@ -77,10 +83,13 @@ impl<'a> _MutableArrayData<'a> {
}
};
- let nulls = (self.null_count > 0).then(|| {
- let bools = BooleanBuffer::new(self.null_buffer.into(), 0, self.len);
- unsafe { NullBuffer::new_unchecked(bools, self.null_count) }
- });
+ let nulls = self
+ .null_buffer
+ .map(|nulls| {
+ let bools = BooleanBuffer::new(nulls.into(), 0, self.len);
+ unsafe { NullBuffer::new_unchecked(bools, self.null_count) }
+ })
+ .filter(|n| n.null_count() > 0);
ArrayDataBuilder::new(self.data_type)
.offset(0)
@@ -95,22 +104,25 @@ fn build_extend_null_bits(array: &ArrayData, use_nulls: bool) -> ExtendNullBits
if let Some(nulls) = array.nulls() {
let bytes = nulls.validity();
Box::new(move |mutable, start, len| {
- utils::resize_for_bits(&mut mutable.null_buffer, mutable.len + len);
+ let mutable_len = mutable.len;
+ let out = mutable.null_buffer();
+ utils::resize_for_bits(out, mutable_len + len);
mutable.null_count += set_bits(
- mutable.null_buffer.as_slice_mut(),
+ out.as_slice_mut(),
bytes,
- mutable.len,
+ mutable_len,
nulls.offset() + start,
len,
);
})
} else if use_nulls {
Box::new(|mutable, _, len| {
- utils::resize_for_bits(&mut mutable.null_buffer, mutable.len + len);
- let write_data = mutable.null_buffer.as_slice_mut();
- let offset = mutable.len;
+ let mutable_len = mutable.len;
+ let out = mutable.null_buffer();
+ utils::resize_for_bits(out, mutable_len + len);
+ let write_data = out.as_slice_mut();
(0..len).for_each(|i| {
- bit_util::set_bit(write_data, offset + i);
+ bit_util::set_bit(write_data, mutable_len + i);
});
})
} else {
@@ -555,13 +567,10 @@ impl<'a> MutableArrayData<'a> {
.map(|array| build_extend_null_bits(array, use_nulls))
.collect();
- let null_buffer = if use_nulls {
+ let null_buffer = use_nulls.then(|| {
let null_bytes = bit_util::ceil(array_capacity, 8);
MutableBuffer::from_len_zeroed(null_bytes)
- } else {
- // create 0 capacity mutable buffer with the intention that it won't be used
- MutableBuffer::with_capacity(0)
- };
+ });
let extend_values = match &data_type {
DataType::Dictionary(_, _) => {
@@ -624,13 +633,18 @@ impl<'a> MutableArrayData<'a> {
}
/// Extends this [MutableArrayData] with null elements, disregarding the bound arrays
+ ///
+ /// # Panics
+ ///
+ /// Panics if [`MutableArrayData`] not created with `use_nulls` or nullable source arrays
+ ///
pub fn extend_nulls(&mut self, len: usize) {
- // TODO: null_buffer should probably be extended here as well
- // otherwise is_valid() could later panic
- // add test to confirm
+ self.data.len += len;
+ let bit_len = bit_util::ceil(self.data.len, 8);
+ let nulls = self.data.null_buffer();
+ nulls.resize(bit_len, 0);
self.data.null_count += len;
(self.extend_nulls)(&mut self.data, len);
- self.data.len += len;
}
/// Returns the current length
|
diff --git a/arrow/tests/array_transform.rs b/arrow/tests/array_transform.rs
index 40938c80f4c3..ebbadc00aecd 100644
--- a/arrow/tests/array_transform.rs
+++ b/arrow/tests/array_transform.rs
@@ -922,6 +922,29 @@ fn test_fixed_size_binary_append() {
assert_eq!(result, expected);
}
+#[test]
+fn test_extend_nulls() {
+ let int = Int32Array::from(vec![1, 2, 3, 4]).into_data();
+ let mut mutable = MutableArrayData::new(vec![&int], true, 4);
+ mutable.extend(0, 2, 3);
+ mutable.extend_nulls(2);
+
+ let data = mutable.freeze();
+ data.validate_full().unwrap();
+ let out = Int32Array::from(data);
+
+ assert_eq!(out.null_count(), 2);
+ assert_eq!(out.iter().collect::<Vec<_>>(), vec![Some(3), None, None]);
+}
+
+#[test]
+#[should_panic(expected = "MutableArrayData not nullable")]
+fn test_extend_nulls_panic() {
+ let int = Int32Array::from(vec![1, 2, 3, 4]).into_data();
+ let mut mutable = MutableArrayData::new(vec![&int], false, 4);
+ mutable.extend_nulls(2);
+}
+
/*
// this is an old test used on a meanwhile removed dead code
// that is still useful when `MutableArrayData` supports fixed-size lists.
|
concat_batches panics with total_len <= bit_len assertion for records with lists
**Describe the bug**
`concat`, used by `concat_batches`, does not appear to allocate sufficient `capacities` when constructing the `MutableArrayData`. Concatenating records that contain lists of structs results in the following panic:
```
assertion failed: total_len <= bit_len
thread 'concat_test' panicked at 'assertion failed: total_len <= bit_len', /Users/x/.cargo/registry/src/index.crates.io-6f17d22bba15001f/arrow-buffer-40.0.0/src/buffer/boolean.rs:55:9
stack backtrace:
0: rust_begin_unwind
at /rustc/84c898d65adf2f39a5a98507f1fe0ce10a2b8dbc/library/std/src/panicking.rs:579:5
1: core::panicking::panic_fmt
at /rustc/84c898d65adf2f39a5a98507f1fe0ce10a2b8dbc/library/core/src/panicking.rs:64:14
2: core::panicking::panic
at /rustc/84c898d65adf2f39a5a98507f1fe0ce10a2b8dbc/library/core/src/panicking.rs:114:5
3: arrow_buffer::buffer::boolean::BooleanBuffer::new
at /Users/x/.cargo/registry/src/index.crates.io-6f17d22bba15001f/arrow-buffer-40.0.0/src/buffer/boolean.rs:55:9
4: arrow_data::transform::_MutableArrayData::freeze::{{closure}}
at /Users/x/.cargo/registry/src/index.crates.io-6f17d22bba15001f/arrow-data-40.0.0/src/transform/mod.rs:81:25
5: core::bool::<impl bool>::then
at /rustc/84c898d65adf2f39a5a98507f1fe0ce10a2b8dbc/library/core/src/bool.rs:71:24
6: arrow_data::transform::_MutableArrayData::freeze
at /Users/x/.cargo/registry/src/index.crates.io-6f17d22bba15001f/arrow-data-40.0.0/src/transform/mod.rs:80:21
7: arrow_data::transform::MutableArrayData::freeze
at /Users/x/.cargo/registry/src/index.crates.io-6f17d22bba15001f/arrow-data-40.0.0/src/transform/mod.rs:656:18
8: arrow_data::transform::_MutableArrayData::freeze
at /Users/x/.cargo/registry/src/index.crates.io-6f17d22bba15001f/arrow-data-40.0.0/src/transform/mod.rs:74:37
9: arrow_data::transform::MutableArrayData::freeze
at /Users/x/.cargo/registry/src/index.crates.io-6f17d22bba15001f/arrow-data-40.0.0/src/transform/mod.rs:656:18
10: arrow_data::transform::_MutableArrayData::freeze
at /Users/x/.cargo/registry/src/index.crates.io-6f17d22bba15001f/arrow-data-40.0.0/src/transform/mod.rs:74:37
11: arrow_data::transform::MutableArrayData::freeze
at /Users/x/.cargo/registry/src/index.crates.io-6f17d22bba15001f/arrow-data-40.0.0/src/transform/mod.rs:656:18
12: arrow_data::transform::_MutableArrayData::freeze
at /Users/x/.cargo/registry/src/index.crates.io-6f17d22bba15001f/arrow-data-40.0.0/src/transform/mod.rs:74:37
13: arrow_data::transform::MutableArrayData::freeze
at /Users/x/.cargo/registry/src/index.crates.io-6f17d22bba15001f/arrow-data-40.0.0/src/transform/mod.rs:656:18
```
**To Reproduce**
Call `concat_batches` with `RecordBatch`s that contain lists of structs (on the order of 20–50 structs in the list per `RecordBatch`). If I modify [the capacity calculation in concat](https://github.com/apache/arrow-rs/blob/c295b172b37902d5fa41ef275ff5b86caf9fde75/arrow-select/src/concat.rs#L76-L82) to add a constant factor for lists, the error does not occur:
```rust
let capacity = match d {
DataType::Utf8 => binary_capacity::<Utf8Type>(arrays),
DataType::LargeUtf8 => binary_capacity::<LargeUtf8Type>(arrays),
DataType::Binary => binary_capacity::<BinaryType>(arrays),
DataType::LargeBinary => binary_capacity::<LargeBinaryType>(arrays),
DataType::List(_) => {
Capacities::Array(arrays.iter().map(|a| a.len()).sum::<usize>() + 500) // <- 500 added here
}
_ => Capacities::Array(arrays.iter().map(|a| a.len()).sum()),
};
```
**Expected behavior**
No panics when concatenating `RecordBatch`s with lists.
**Additional context**
Reproduced with Arrow versions 37–40.
|
Possibly related to https://github.com/apache/arrow-rs/issues/1230. The error would suggest that the validity buffer is not the correct length. I'll take a look in a bit, MutableArrayData is overdue some TLC in this regard (#1225)
Are you able to share a reproducer for this?
Sure, see https://github.com/ElementalCognition/arrow-bug.
Thank you, very helpful. It looks like this is https://github.com/apache/arrow-rs/issues/1230, which I will fix now
As a happy accident https://github.com/apache/arrow-rs/pull/4333 fixed your reproducer as it removed the use of extend_nulls when appending structs
|
2023-06-02T07:51:43Z
|
40.0
|
008cf9c27424d581a67ba97f338a22b6eace9cc1
|
apache/arrow-rs
| 4,342
|
apache__arrow-rs-4342
|
[
"4289"
] |
a121e0969ee83d3396c59603717333864acc52fa
|
diff --git a/arrow-ord/src/comparison.rs b/arrow-ord/src/comparison.rs
index c771182f7917..b9274f0eaefb 100644
--- a/arrow-ord/src/comparison.rs
+++ b/arrow-ord/src/comparison.rs
@@ -2700,7 +2700,7 @@ where
}
/// Checks if a [`GenericListArray`] contains a value in the [`PrimitiveArray`]
-pub fn contains<T, OffsetSize>(
+pub fn in_list<T, OffsetSize>(
left: &PrimitiveArray<T>,
right: &GenericListArray<OffsetSize>,
) -> Result<BooleanArray, ArrowError>
@@ -2742,7 +2742,7 @@ where
}
/// Checks if a [`GenericListArray`] contains a value in the [`GenericStringArray`]
-pub fn contains_utf8<OffsetSize>(
+pub fn in_list_utf8<OffsetSize>(
left: &GenericStringArray<OffsetSize>,
right: &ListArray,
) -> Result<BooleanArray, ArrowError>
@@ -3425,7 +3425,7 @@ mod tests {
let list_array = LargeListArray::from(list_data);
let nulls = Int32Array::from(vec![None, None, None, None]);
- let nulls_result = contains(&nulls, &list_array).unwrap();
+ let nulls_result = in_list(&nulls, &list_array).unwrap();
assert_eq!(
nulls_result
.as_any()
@@ -3435,7 +3435,7 @@ mod tests {
);
let values = Int32Array::from(vec![Some(0), Some(0), Some(0), Some(0)]);
- let values_result = contains(&values, &list_array).unwrap();
+ let values_result = in_list(&values, &list_array).unwrap();
assert_eq!(
values_result
.as_any()
@@ -3695,7 +3695,7 @@ mod tests {
let v: Vec<Option<&str>> = vec![None, None, None, None];
let nulls = StringArray::from(v);
- let nulls_result = contains_utf8(&nulls, &list_array).unwrap();
+ let nulls_result = in_list_utf8(&nulls, &list_array).unwrap();
assert_eq!(
nulls_result
.as_any()
@@ -3710,7 +3710,7 @@ mod tests {
Some("Lorem"),
Some("Lorem"),
]);
- let values_result = contains_utf8(&values, &list_array).unwrap();
+ let values_result = in_list_utf8(&values, &list_array).unwrap();
assert_eq!(
values_result
.as_any()
diff --git a/arrow/examples/builders.rs b/arrow/examples/builders.rs
index a6d8c563b4ca..250f5c39af10 100644
--- a/arrow/examples/builders.rs
+++ b/arrow/examples/builders.rs
@@ -15,8 +15,7 @@
// specific language governing permissions and limitations
// under the License.
-///! Many builders are available to easily create different types of arrow arrays
-extern crate arrow;
+//! Many builders are available to easily create different types of arrow arrays
use std::sync::Arc;
diff --git a/arrow/examples/collect.rs b/arrow/examples/collect.rs
index 5581186dbe7a..ced4640d600f 100644
--- a/arrow/examples/collect.rs
+++ b/arrow/examples/collect.rs
@@ -15,8 +15,9 @@
// specific language governing permissions and limitations
// under the License.
-///! `FromIterator` API is implemented for different array types to easily create them
-/// from values.
+//! `FromIterator` API is implemented for different array types to easily create them
+//! from values.
+
use arrow::array::Array;
use arrow_array::types::Int32Type;
use arrow_array::{Float32Array, Int32Array, Int8Array, ListArray};
diff --git a/arrow/examples/dynamic_types.rs b/arrow/examples/dynamic_types.rs
index 5470131d6d41..8ec473c76d56 100644
--- a/arrow/examples/dynamic_types.rs
+++ b/arrow/examples/dynamic_types.rs
@@ -15,7 +15,7 @@
// specific language governing permissions and limitations
// under the License.
-///! This example demonstrates dealing with mixed types dynamically at runtime
+//! This example demonstrates dealing with mixed types dynamically at runtime
use std::sync::Arc;
extern crate arrow;
diff --git a/arrow/examples/tensor_builder.rs b/arrow/examples/tensor_builder.rs
index ca31679e250d..90ad1b4868f7 100644
--- a/arrow/examples/tensor_builder.rs
+++ b/arrow/examples/tensor_builder.rs
@@ -15,8 +15,7 @@
// specific language governing permissions and limitations
// under the License.
-///! Tensor builder example
-extern crate arrow;
+//! Tensor builder example
use arrow::array::*; //{Int32BufferBuilder, Float32BufferBuilder};
use arrow::buffer::Buffer;
diff --git a/parquet/src/data_type.rs b/parquet/src/data_type.rs
index 2e7f73bf0a4f..67d0bad98202 100644
--- a/parquet/src/data_type.rs
+++ b/parquet/src/data_type.rs
@@ -483,7 +483,7 @@ macro_rules! gen_as_bytes {
unsafe {
std::slice::from_raw_parts(
self_.as_ptr() as *const u8,
- std::mem::size_of::<$source_ty>() * self_.len(),
+ std::mem::size_of_val(self_),
)
}
}
@@ -493,7 +493,7 @@ macro_rules! gen_as_bytes {
unsafe fn slice_as_bytes_mut(self_: &mut [Self]) -> &mut [u8] {
std::slice::from_raw_parts_mut(
self_.as_mut_ptr() as *mut u8,
- std::mem::size_of::<$source_ty>() * self_.len(),
+ std::mem::size_of_val(self_),
)
}
}
@@ -735,7 +735,7 @@ pub(crate) mod private {
let raw = unsafe {
std::slice::from_raw_parts(
values.as_ptr() as *const u8,
- std::mem::size_of::<$ty>() * values.len(),
+ std::mem::size_of_val(values),
)
};
writer.write_all(raw)?;
|
diff --git a/arrow/tests/array_validation.rs b/arrow/tests/array_validation.rs
index 67960ada6c98..0d3652a0473a 100644
--- a/arrow/tests/array_validation.rs
+++ b/arrow/tests/array_validation.rs
@@ -948,8 +948,7 @@ fn test_try_new_sliced_struct() {
let struct_array = builder.finish();
let struct_array_slice = struct_array.slice(1, 3);
- let cloned = struct_array_slice.clone();
- assert_eq!(&struct_array_slice, &cloned);
+ assert_eq!(struct_array_slice, struct_array_slice);
}
#[test]
|
ambiguous glob re-exports of contains_utf8
**Describe the bug**
<!--
A clear and concise description of what the bug is.
-->
```
warning: ambiguous glob re-exports
--> arrow/src/compute/kernels/mod.rs:31:13
|
31 | pub use arrow_ord::comparison::*;
| ^^^^^^^^^^^^^^^^^^^^^^^^ the name `contains_utf8` in the value namespace is first re-exported here
32 | pub use arrow_string::like::*;
| --------------------- but the name `contains_utf8` in the value namespace is also re-exported here
|
= note: `#[warn(ambiguous_glob_reexports)]` on by default
```
**To Reproduce**
<!--
Steps to reproduce the behavior:
-->
```
cargo check
```
**Expected behavior**
<!--
A clear and concise description of what you expected to happen.
-->
**Additional context**
<!--
Add any other context about the problem here.
-->
```
> rustc -vV
rustc 1.71.0-nightly (c4190f2d3 2023-05-07)
binary: rustc
commit-hash: c4190f2d3a46a59f435f7b42f58bc22b2f4d6917
commit-date: 2023-05-07
host: aarch64-apple-darwin
release: 1.71.0-nightly
LLVM version: 16.0.2
```
|
2023-06-02T06:18:55Z
|
40.0
|
008cf9c27424d581a67ba97f338a22b6eace9cc1
|
|
apache/arrow-rs
| 4,327
|
apache__arrow-rs-4327
|
[
"3680"
] |
30196d89bfab698c50bcde6c304f0599011a1100
|
diff --git a/parquet/src/column/writer/mod.rs b/parquet/src/column/writer/mod.rs
index 310519f4a39c..fc5e29b03256 100644
--- a/parquet/src/column/writer/mod.rs
+++ b/parquet/src/column/writer/mod.rs
@@ -308,6 +308,17 @@ impl<'a, E: ColumnValueEncoder> GenericColumnWriter<'a, E> {
max: Option<&E::T>,
distinct_count: Option<u64>,
) -> Result<usize> {
+ // Check if number of definition levels is the same as number of repetition levels.
+ if let (Some(def), Some(rep)) = (def_levels, rep_levels) {
+ if def.len() != rep.len() {
+ return Err(general_err!(
+ "Inconsistent length of definition and repetition levels: {} != {}",
+ def.len(),
+ rep.len()
+ ));
+ }
+ }
+
// We check for DataPage limits only after we have inserted the values. If a user
// writes a large number of values, the DataPage size can be well above the limit.
//
@@ -323,10 +334,6 @@ impl<'a, E: ColumnValueEncoder> GenericColumnWriter<'a, E> {
None => values.len(),
};
- // Find out number of batches to process.
- let write_batch_size = self.props.write_batch_size();
- let num_batches = num_levels / write_batch_size;
-
// If only computing chunk-level statistics compute them here, page-level statistics
// are computed in [`Self::write_mini_batch`] and used to update chunk statistics in
// [`Self::add_data_page`]
@@ -374,27 +381,28 @@ impl<'a, E: ColumnValueEncoder> GenericColumnWriter<'a, E> {
let mut values_offset = 0;
let mut levels_offset = 0;
- for _ in 0..num_batches {
+ let base_batch_size = self.props.write_batch_size();
+ while levels_offset < num_levels {
+ let mut end_offset = num_levels.min(levels_offset + base_batch_size);
+
+ // Split at record boundary
+ if let Some(r) = rep_levels {
+ while end_offset < r.len() && r[end_offset] != 0 {
+ end_offset += 1;
+ }
+ }
+
values_offset += self.write_mini_batch(
values,
values_offset,
value_indices,
- write_batch_size,
- def_levels.map(|lv| &lv[levels_offset..levels_offset + write_batch_size]),
- rep_levels.map(|lv| &lv[levels_offset..levels_offset + write_batch_size]),
+ end_offset - levels_offset,
+ def_levels.map(|lv| &lv[levels_offset..end_offset]),
+ rep_levels.map(|lv| &lv[levels_offset..end_offset]),
)?;
- levels_offset += write_batch_size;
+ levels_offset = end_offset;
}
- values_offset += self.write_mini_batch(
- values,
- values_offset,
- value_indices,
- num_levels - levels_offset,
- def_levels.map(|lv| &lv[levels_offset..]),
- rep_levels.map(|lv| &lv[levels_offset..]),
- )?;
-
// Return total number of values processed.
Ok(values_offset)
}
@@ -522,18 +530,6 @@ impl<'a, E: ColumnValueEncoder> GenericColumnWriter<'a, E> {
def_levels: Option<&[i16]>,
rep_levels: Option<&[i16]>,
) -> Result<usize> {
- // Check if number of definition levels is the same as number of repetition
- // levels.
- if let (Some(def), Some(rep)) = (def_levels, rep_levels) {
- if def.len() != rep.len() {
- return Err(general_err!(
- "Inconsistent length of definition and repetition levels: {} != {}",
- def.len(),
- rep.len()
- ));
- }
- }
-
// Process definition levels and determine how many values to write.
let values_to_write = if self.descr.max_def_level() > 0 {
let levels = def_levels.ok_or_else(|| {
@@ -569,6 +565,13 @@ impl<'a, E: ColumnValueEncoder> GenericColumnWriter<'a, E> {
)
})?;
+ if !levels.is_empty() && levels[0] != 0 {
+ return Err(general_err!(
+ "Write must start at a record boundary, got non-zero repetition level of {}",
+ levels[0]
+ ));
+ }
+
// Count the occasions where we start a new row
for &level in levels {
self.page_metrics.num_buffered_rows += (level == 0) as u32
@@ -2255,6 +2258,7 @@ mod tests {
let mut buf: Vec<i16> = Vec::new();
let rep_levels = if max_rep_level > 0 {
random_numbers_range(max_size, 0, max_rep_level + 1, &mut buf);
+ buf[0] = 0; // Must start on record boundary
Some(&buf[..])
} else {
None
|
diff --git a/parquet/tests/arrow_writer_layout.rs b/parquet/tests/arrow_writer_layout.rs
index 142112b7b686..3142c8c52063 100644
--- a/parquet/tests/arrow_writer_layout.rs
+++ b/parquet/tests/arrow_writer_layout.rs
@@ -19,6 +19,7 @@
use arrow::array::{Int32Array, StringArray};
use arrow::record_batch::RecordBatch;
+use arrow_array::builder::{Int32Builder, ListBuilder};
use bytes::Bytes;
use parquet::arrow::arrow_reader::{ArrowReaderOptions, ParquetRecordBatchReaderBuilder};
use parquet::arrow::ArrowWriter;
@@ -502,3 +503,45 @@ fn test_string() {
},
});
}
+
+#[test]
+fn test_list() {
+ let mut list = ListBuilder::new(Int32Builder::new());
+ for _ in 0..200 {
+ let values = list.values();
+ for i in 0..8 {
+ values.append_value(i);
+ }
+ list.append(true);
+ }
+ let array = Arc::new(list.finish()) as _;
+
+ let batch = RecordBatch::try_from_iter([("col", array)]).unwrap();
+ let props = WriterProperties::builder()
+ .set_dictionary_enabled(false)
+ .set_data_page_row_count_limit(20)
+ .set_write_batch_size(3)
+ .build();
+
+ // Test rows not split across pages
+ do_test(LayoutTest {
+ props,
+ batches: vec![batch],
+ layout: Layout {
+ row_groups: vec![RowGroup {
+ columns: vec![ColumnChunk {
+ pages: (0..10)
+ .map(|_| Page {
+ rows: 20,
+ page_header_size: 34,
+ compressed_size: 672,
+ encoding: Encoding::PLAIN,
+ page_type: PageType::DATA_PAGE,
+ })
+ .collect(),
+ dictionary_page: None,
+ }],
+ }],
+ },
+ });
+}
|
Should Parquet pages begin on the start of a row?
**Which part is this question about**
Parquet writer
<!--
Is it code base, library api, documentation or some other part?
-->
**Describe your question**
In #1777 it was brought up [here](https://github.com/apache/arrow-rs/issues/1777#issuecomment-1147686956) that the Parquet spec seems to require that pages begin on record boundaries when writing offset indices. Additionally, the same can be said for V2 page headers (see comment in the parquet-format [thrift](https://github.com/apache/parquet-format/blob/5205dc7b7c0b910ea6af33cadbd2963c0c47c726/src/main/thrift/parquet.thrift#L564) file). It appears that this reasoning was rejected, and the Parquet writer continues to write files where rows can span multiple pages. I'm wondering if this should still be considered a bug given how difficult finding individual rows is made with this behavior in place.
<!--
A clear and concise description of what the question is.
-->
**Additional context**
I've been working with the cuDF Parquet reader, and files with large nested rows can create havoc when rows span pages. Parquet-mr appears to hew to the "pages start with R=0" rule.
<!--
Add any other context about the problem here.
-->
|
I'm not sure it is a bug per se, but I definitely think the APIs shouldn't do it unilaterally as they currently do.
I would support making `GenericColumnWriter::write_batch_internal` call `write_mini_batch` treating the `WriterProperties::write_batch_size` as being a number of rows, as opposed to levels. Tbh this is probably what most people assume it does anyway. I'll try to get something up today
This should mean that if the user writes in a whole number of rows, the rows won't be split across multiple pages. Handling if the user writes partial rows would be significantly more complicated, and I think we can safely punt on it.
Edit: Ran out of time today, will do first thing tomorrow. Will try to ensure this makes the release slated for tomorrow, but will depend on reviews
> Will try to ensure this makes the release slated for tomorrow, but will depend on reviews
No rush, this might want some thought. One thing to consider is that this can lead to very uneven page sizes if the data is very "lumpy". That's the price to pay when using V2 headers or page indexes, but you may want to consider keeping the current behavior when neither of those is requested.
|
2023-05-31T19:17:10Z
|
40.0
|
008cf9c27424d581a67ba97f338a22b6eace9cc1
|
apache/arrow-rs
| 4,326
|
apache__arrow-rs-4326
|
[
"4321"
] |
0baf99a2244d39ff910ec09a0bc3a30b1138a577
|
diff --git a/parquet/src/arrow/arrow_reader/mod.rs b/parquet/src/arrow/arrow_reader/mod.rs
index 9cb09c9a5d7d..deca0c719551 100644
--- a/parquet/src/arrow/arrow_reader/mod.rs
+++ b/parquet/src/arrow/arrow_reader/mod.rs
@@ -2522,4 +2522,36 @@ mod tests {
assert_eq!(&written.slice(0, 8), &read[0]);
}
+
+ #[test]
+ fn test_list_skip() {
+ let mut list = ListBuilder::new(Int32Builder::new());
+ list.append_value([Some(1), Some(2)]);
+ list.append_value([Some(3)]);
+ list.append_value([Some(4)]);
+ let list = list.finish();
+ let batch = RecordBatch::try_from_iter([("l", Arc::new(list) as _)]).unwrap();
+
+ // First page contains 2 values but only 1 row
+ let props = WriterProperties::builder()
+ .set_data_page_row_count_limit(1)
+ .set_write_batch_size(2)
+ .build();
+
+ let mut buffer = Vec::with_capacity(1024);
+ let mut writer =
+ ArrowWriter::try_new(&mut buffer, batch.schema(), Some(props)).unwrap();
+ writer.write(&batch).unwrap();
+ writer.close().unwrap();
+
+ let selection = vec![RowSelector::skip(2), RowSelector::select(1)];
+ let mut reader = ParquetRecordBatchReaderBuilder::try_new(Bytes::from(buffer))
+ .unwrap()
+ .with_row_selection(selection.into())
+ .build()
+ .unwrap();
+ let out = reader.next().unwrap().unwrap();
+ assert_eq!(out.num_rows(), 1);
+ assert_eq!(out, batch.slice(2, 1));
+ }
}
diff --git a/parquet/src/column/page.rs b/parquet/src/column/page.rs
index 3b19734a2218..654cd0816039 100644
--- a/parquet/src/column/page.rs
+++ b/parquet/src/column/page.rs
@@ -265,9 +265,10 @@ impl PageWriteSpec {
/// Contains metadata for a page
#[derive(Clone)]
pub struct PageMetadata {
- /// The number of rows in this page
- pub num_rows: usize,
-
+ /// The number of rows within the page if known
+ pub num_rows: Option<usize>,
+ /// The number of levels within the page if known
+ pub num_levels: Option<usize>,
/// Returns true if the page is a dictionary page
pub is_dict: bool,
}
@@ -277,18 +278,27 @@ impl TryFrom<&PageHeader> for PageMetadata {
fn try_from(value: &PageHeader) -> std::result::Result<Self, Self::Error> {
match value.type_ {
- crate::format::PageType::DATA_PAGE => Ok(PageMetadata {
- num_rows: value.data_page_header.as_ref().unwrap().num_values as usize,
- is_dict: false,
- }),
+ crate::format::PageType::DATA_PAGE => {
+ let header = value.data_page_header.as_ref().unwrap();
+ Ok(PageMetadata {
+ num_rows: None,
+ num_levels: Some(header.num_values as _),
+ is_dict: false,
+ })
+ }
crate::format::PageType::DICTIONARY_PAGE => Ok(PageMetadata {
- num_rows: usize::MIN,
+ num_rows: None,
+ num_levels: None,
is_dict: true,
}),
- crate::format::PageType::DATA_PAGE_V2 => Ok(PageMetadata {
- num_rows: value.data_page_header_v2.as_ref().unwrap().num_rows as usize,
- is_dict: false,
- }),
+ crate::format::PageType::DATA_PAGE_V2 => {
+ let header = value.data_page_header_v2.as_ref().unwrap();
+ Ok(PageMetadata {
+ num_rows: Some(header.num_rows as _),
+ num_levels: Some(header.num_values as _),
+ is_dict: false,
+ })
+ }
other => Err(ParquetError::General(format!(
"page type {other:?} cannot be converted to PageMetadata"
))),
diff --git a/parquet/src/column/reader.rs b/parquet/src/column/reader.rs
index 3434eba69e50..991ec2c545a4 100644
--- a/parquet/src/column/reader.rs
+++ b/parquet/src/column/reader.rs
@@ -312,11 +312,20 @@ where
// If page has less rows than the remaining records to
// be skipped, skip entire page
- if metadata.num_rows <= remaining_records {
- self.page_reader.skip_next_page()?;
- remaining_records -= metadata.num_rows;
- continue;
- };
+ let rows = metadata.num_rows.or_else(|| {
+ // If no repetition levels, num_levels == num_rows
+ self.rep_level_decoder
+ .is_none()
+ .then_some(metadata.num_levels)?
+ });
+
+ if let Some(rows) = rows {
+ if rows <= remaining_records {
+ self.page_reader.skip_next_page()?;
+ remaining_records -= rows;
+ continue;
+ }
+ }
// because self.num_buffered_values == self.num_decoded_values means
// we need reads a new page and set up the decoders for levels
if !self.read_new_page()? {
@@ -533,12 +542,7 @@ where
if self.num_buffered_values == 0
|| self.num_buffered_values == self.num_decoded_values
{
- // TODO: should we return false if read_new_page() = true and
- // num_buffered_values = 0?
- match self.page_reader.peek_next_page()? {
- Some(next_page) => Ok(next_page.num_rows != 0),
- None => Ok(false),
- }
+ Ok(self.page_reader.peek_next_page()?.is_some())
} else {
Ok(true)
}
diff --git a/parquet/src/file/serialized_reader.rs b/parquet/src/file/serialized_reader.rs
index 782394942df4..2b3536904bb9 100644
--- a/parquet/src/file/serialized_reader.rs
+++ b/parquet/src/file/serialized_reader.rs
@@ -722,7 +722,8 @@ impl<R: ChunkReader> PageReader for SerializedPageReader<R> {
} => {
if dictionary_page.is_some() {
Ok(Some(PageMetadata {
- num_rows: 0,
+ num_rows: None,
+ num_levels: None,
is_dict: true,
}))
} else if let Some(page) = page_locations.front() {
@@ -732,7 +733,8 @@ impl<R: ChunkReader> PageReader for SerializedPageReader<R> {
.unwrap_or(*total_rows);
Ok(Some(PageMetadata {
- num_rows: next_rows - page.first_row_index as usize,
+ num_rows: Some(next_rows - page.first_row_index as usize),
+ num_levels: None,
is_dict: false,
}))
} else {
@@ -1644,11 +1646,11 @@ mod tests {
// have checked with `parquet-tools column-index -c string_col ./alltypes_tiny_pages.parquet`
// page meta has two scenarios(21, 20) of num_rows expect last page has 11 rows.
if i != 351 {
- assert!((meta.num_rows == 21) || (meta.num_rows == 20));
+ assert!((meta.num_rows == Some(21)) || (meta.num_rows == Some(20)));
} else {
// last page first row index is 7290, total row count is 7300
// because first row start with zero, last page row count should be 10.
- assert_eq!(meta.num_rows, 10);
+ assert_eq!(meta.num_rows, Some(10));
}
assert!(!meta.is_dict);
vec.push(meta);
@@ -1686,11 +1688,11 @@ mod tests {
// have checked with `parquet-tools column-index -c string_col ./alltypes_tiny_pages.parquet`
// page meta has two scenarios(21, 20) of num_rows expect last page has 11 rows.
if i != 351 {
- assert!((meta.num_rows == 21) || (meta.num_rows == 20));
+ assert!((meta.num_levels == Some(21)) || (meta.num_levels == Some(20)));
} else {
// last page first row index is 7290, total row count is 7300
// because first row start with zero, last page row count should be 10.
- assert_eq!(meta.num_rows, 10);
+ assert_eq!(meta.num_levels, Some(10));
}
assert!(!meta.is_dict);
vec.push(meta);
|
diff --git a/parquet/src/util/test_common/page_util.rs b/parquet/src/util/test_common/page_util.rs
index ab5287462c8c..c51c5158cd42 100644
--- a/parquet/src/util/test_common/page_util.rs
+++ b/parquet/src/util/test_common/page_util.rs
@@ -170,15 +170,22 @@ impl<P: Iterator<Item = Page> + Send> PageReader for InMemoryPageReader<P> {
if let Some(x) = self.page_iter.peek() {
match x {
Page::DataPage { num_values, .. } => Ok(Some(PageMetadata {
- num_rows: *num_values as usize,
+ num_rows: None,
+ num_levels: Some(*num_values as _),
is_dict: false,
})),
- Page::DataPageV2 { num_rows, .. } => Ok(Some(PageMetadata {
- num_rows: *num_rows as usize,
+ Page::DataPageV2 {
+ num_rows,
+ num_values,
+ ..
+ } => Ok(Some(PageMetadata {
+ num_rows: Some(*num_rows as _),
+ num_levels: Some(*num_values as _),
is_dict: false,
})),
Page::DictionaryPage { .. } => Ok(Some(PageMetadata {
- num_rows: 0,
+ num_rows: None,
+ num_levels: None,
is_dict: true,
})),
}
|
Incorrect PageMetadata Row Count returned for V1 DataPage
**Describe the bug**
<!--
A clear and concise description of what the bug is.
-->
`PageReader::peek_next_page` for `SerializedPageReader` and `InMemoryPageReader` returns num_values for DataPageV1. This is not the row count, and is instead the number of levels. For a column with repetition levels, this will therefore be incorrect.
This in turn will cause the skipping logic to misbehave
**To Reproduce**
<!--
Steps to reproduce the behavior:
-->
**Expected behavior**
<!--
A clear and concise description of what you expected to happen.
-->
**Additional context**
<!--
Add any other context about the problem here.
-->
|
2023-05-31T17:53:53Z
|
40.0
|
008cf9c27424d581a67ba97f338a22b6eace9cc1
|
|
apache/arrow-rs
| 4,316
|
apache__arrow-rs-4316
|
[
"4312"
] |
04ca2f2b0ad964ce8962b8b362da0df932c88091
|
diff --git a/arrow/src/pyarrow.rs b/arrow/src/pyarrow.rs
index ba8d606f2e1f..98e27ab30e09 100644
--- a/arrow/src/pyarrow.rs
+++ b/arrow/src/pyarrow.rs
@@ -24,7 +24,7 @@ use std::convert::{From, TryFrom};
use std::ptr::{addr_of, addr_of_mut};
use std::sync::Arc;
-use pyo3::exceptions::PyValueError;
+use pyo3::exceptions::{PyTypeError, PyValueError};
use pyo3::ffi::Py_uintptr_t;
use pyo3::import_exception;
use pyo3::prelude::*;
@@ -67,8 +67,27 @@ impl<T: ToPyArrow> IntoPyArrow for T {
}
}
+fn validate_class(expected: &str, value: &PyAny) -> PyResult<()> {
+ let pyarrow = PyModule::import(value.py(), "pyarrow")?;
+ let class = pyarrow.getattr(expected)?;
+ if !value.is_instance(class)? {
+ let expected_module = class.getattr("__module__")?.extract::<&str>()?;
+ let expected_name = class.getattr("__name__")?.extract::<&str>()?;
+ let found_class = value.get_type();
+ let found_module = found_class.getattr("__module__")?.extract::<&str>()?;
+ let found_name = found_class.getattr("__name__")?.extract::<&str>()?;
+ return Err(PyTypeError::new_err(format!(
+ "Expected instance of {}.{}, got {}.{}",
+ expected_module, expected_name, found_module, found_name
+ )));
+ }
+ Ok(())
+}
+
impl FromPyArrow for DataType {
fn from_pyarrow(value: &PyAny) -> PyResult<Self> {
+ validate_class("DataType", value)?;
+
let c_schema = FFI_ArrowSchema::empty();
let c_schema_ptr = &c_schema as *const FFI_ArrowSchema;
value.call_method1("_export_to_c", (c_schema_ptr as Py_uintptr_t,))?;
@@ -91,6 +110,8 @@ impl ToPyArrow for DataType {
impl FromPyArrow for Field {
fn from_pyarrow(value: &PyAny) -> PyResult<Self> {
+ validate_class("Field", value)?;
+
let c_schema = FFI_ArrowSchema::empty();
let c_schema_ptr = &c_schema as *const FFI_ArrowSchema;
value.call_method1("_export_to_c", (c_schema_ptr as Py_uintptr_t,))?;
@@ -113,6 +134,8 @@ impl ToPyArrow for Field {
impl FromPyArrow for Schema {
fn from_pyarrow(value: &PyAny) -> PyResult<Self> {
+ validate_class("Schema", value)?;
+
let c_schema = FFI_ArrowSchema::empty();
let c_schema_ptr = &c_schema as *const FFI_ArrowSchema;
value.call_method1("_export_to_c", (c_schema_ptr as Py_uintptr_t,))?;
@@ -135,6 +158,8 @@ impl ToPyArrow for Schema {
impl FromPyArrow for ArrayData {
fn from_pyarrow(value: &PyAny) -> PyResult<Self> {
+ validate_class("Array", value)?;
+
// prepare a pointer to receive the Array struct
let mut array = FFI_ArrowArray::empty();
let mut schema = FFI_ArrowSchema::empty();
@@ -194,6 +219,7 @@ impl<T: ToPyArrow> ToPyArrow for Vec<T> {
impl FromPyArrow for RecordBatch {
fn from_pyarrow(value: &PyAny) -> PyResult<Self> {
+ validate_class("RecordBatch", value)?;
// TODO(kszucs): implement the FFI conversions in arrow-rs for RecordBatches
let schema = value.getattr("schema")?;
let schema = Arc::new(Schema::from_pyarrow(schema)?);
@@ -235,6 +261,8 @@ impl ToPyArrow for RecordBatch {
impl FromPyArrow for ArrowArrayStreamReader {
fn from_pyarrow(value: &PyAny) -> PyResult<Self> {
+ validate_class("RecordBatchReader", value)?;
+
// prepare a pointer to receive the stream struct
let mut stream = FFI_ArrowArrayStream::empty();
let stream_ptr = &mut stream as *mut FFI_ArrowArrayStream;
|
diff --git a/arrow-pyarrow-integration-testing/tests/test_sql.py b/arrow-pyarrow-integration-testing/tests/test_sql.py
index f631f67cbfea..a7c6b34a4474 100644
--- a/arrow-pyarrow-integration-testing/tests/test_sql.py
+++ b/arrow-pyarrow-integration-testing/tests/test_sql.py
@@ -408,3 +408,25 @@ def test_record_batch_reader():
assert b.schema == schema
got_batches = list(b)
assert got_batches == batches
+
+def test_reject_other_classes():
+ # Arbitrary type that is not a PyArrow type
+ not_pyarrow = ["hello"]
+
+ with pytest.raises(TypeError, match="Expected instance of pyarrow.lib.Array, got builtins.list"):
+ rust.round_trip_array(not_pyarrow)
+
+ with pytest.raises(TypeError, match="Expected instance of pyarrow.lib.Schema, got builtins.list"):
+ rust.round_trip_schema(not_pyarrow)
+
+ with pytest.raises(TypeError, match="Expected instance of pyarrow.lib.Field, got builtins.list"):
+ rust.round_trip_field(not_pyarrow)
+
+ with pytest.raises(TypeError, match="Expected instance of pyarrow.lib.DataType, got builtins.list"):
+ rust.round_trip_type(not_pyarrow)
+
+ with pytest.raises(TypeError, match="Expected instance of pyarrow.lib.RecordBatch, got builtins.list"):
+ rust.round_trip_record_batch(not_pyarrow)
+
+ with pytest.raises(TypeError, match="Expected instance of pyarrow.lib.RecordBatchReader, got builtins.list"):
+ rust.round_trip_record_batch_reader(not_pyarrow)
|
PyArrow conversions could return TypeError if provided incorrect Python type
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
Right now, we bubble up an error like
```
AttributeError: 'XXX' object has no attribute '_export_to_c'
```
When we instead probably want something more like:
```
TypeError: expected `pyarrow.Schema` but got object of type 'XXX'
```
**Describe the solution you'd like**
Check for the correct Python type and return the TypeError if applicable.
**Describe alternatives you've considered**
We could support duck typing anything that supports `_export_to_c`, but I don't think that's safe right now. In the future, there may be an improved protocol that would allow better handling: https://github.com/apache/arrow/pull/35739
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
|
2023-05-31T03:33:23Z
|
40.0
|
008cf9c27424d581a67ba97f338a22b6eace9cc1
|
|
apache/arrow-rs
| 4,287
|
apache__arrow-rs-4287
|
[
"4286"
] |
3fd744b6913d12a9079db0bae1199cc80caff5d9
|
diff --git a/parquet/src/arrow/arrow_writer/mod.rs b/parquet/src/arrow/arrow_writer/mod.rs
index 08cfc7ea3ebf..616968bf6407 100644
--- a/parquet/src/arrow/arrow_writer/mod.rs
+++ b/parquet/src/arrow/arrow_writer/mod.rs
@@ -117,7 +117,7 @@ impl<W: Write> Debug for ArrowWriter<W> {
}
}
-impl<W: Write> ArrowWriter<W> {
+impl<W: Write + Send> ArrowWriter<W> {
/// Try to create a new Arrow writer
///
/// The writer will fail if:
@@ -273,7 +273,7 @@ impl<W: Write> ArrowWriter<W> {
}
}
-impl<W: Write> RecordBatchWriter for ArrowWriter<W> {
+impl<W: Write + Send> RecordBatchWriter for ArrowWriter<W> {
fn write(&mut self, batch: &RecordBatch) -> Result<(), ArrowError> {
self.write(batch).map_err(|e| e.into())
}
@@ -284,7 +284,7 @@ impl<W: Write> RecordBatchWriter for ArrowWriter<W> {
}
}
-fn write_leaves<W: Write>(
+fn write_leaves<W: Write + Send>(
row_group_writer: &mut SerializedRowGroupWriter<'_, W>,
arrays: &[ArrayRef],
levels: &mut [Vec<LevelInfo>],
diff --git a/parquet/src/column/page.rs b/parquet/src/column/page.rs
index bd3568d13cee..f854e5caca80 100644
--- a/parquet/src/column/page.rs
+++ b/parquet/src/column/page.rs
@@ -248,7 +248,7 @@ pub trait PageReader: Iterator<Item = Result<Page>> + Send {
///
/// It is reasonable to assume that all pages will be written in the correct order, e.g.
/// dictionary page followed by data pages, or a set of data pages, etc.
-pub trait PageWriter {
+pub trait PageWriter: Send {
/// Writes a page into the output stream/sink.
/// Returns `PageWriteSpec` that contains information about written page metrics,
/// including number of bytes, size, number of values, offset, etc.
diff --git a/parquet/src/column/writer/mod.rs b/parquet/src/column/writer/mod.rs
index 137893092405..c203fc02281a 100644
--- a/parquet/src/column/writer/mod.rs
+++ b/parquet/src/column/writer/mod.rs
@@ -2174,6 +2174,12 @@ mod tests {
);
}
+ #[test]
+ fn test_send() {
+ fn test<T: Send>() {}
+ test::<ColumnWriterImpl<Int32Type>>();
+ }
+
/// Performs write-read roundtrip with randomly generated values and levels.
/// `max_size` is maximum number of values or levels (if `max_def_level` > 0) to write
/// for a column.
diff --git a/parquet/src/encodings/encoding/mod.rs b/parquet/src/encodings/encoding/mod.rs
index b7e30c4ecf08..3088f332183b 100644
--- a/parquet/src/encodings/encoding/mod.rs
+++ b/parquet/src/encodings/encoding/mod.rs
@@ -40,7 +40,7 @@ mod dict_encoder;
///
/// Currently this allocates internal buffers for the encoded values. After done putting
/// values, caller should call `flush_buffer()` to get an immutable buffer pointer.
-pub trait Encoder<T: DataType> {
+pub trait Encoder<T: DataType>: Send {
/// Encodes data from `values`.
fn put(&mut self, values: &[T::T]) -> Result<()>;
diff --git a/parquet/src/file/writer.rs b/parquet/src/file/writer.rs
index 4b1c4bad92e1..1f71f9c67822 100644
--- a/parquet/src/file/writer.rs
+++ b/parquet/src/file/writer.rs
@@ -160,7 +160,7 @@ impl<W: Write> Debug for SerializedFileWriter<W> {
}
}
-impl<W: Write> SerializedFileWriter<W> {
+impl<W: Write + Send> SerializedFileWriter<W> {
/// Creates new file writer.
pub fn new(buf: W, schema: TypePtr, properties: WriterPropertiesPtr) -> Result<Self> {
let mut buf = TrackedWrite::new(buf);
@@ -406,7 +406,7 @@ pub struct SerializedRowGroupWriter<'a, W: Write> {
on_close: Option<OnCloseRowGroup<'a>>,
}
-impl<'a, W: Write> SerializedRowGroupWriter<'a, W> {
+impl<'a, W: Write + Send> SerializedRowGroupWriter<'a, W> {
/// Creates a new `SerializedRowGroupWriter` with:
///
/// - `schema_descr` - the schema to write
@@ -700,7 +700,7 @@ impl<'a, W: Write> SerializedPageWriter<'a, W> {
}
}
-impl<'a, W: Write> PageWriter for SerializedPageWriter<'a, W> {
+impl<'a, W: Write + Send> PageWriter for SerializedPageWriter<'a, W> {
fn write_page(&mut self, page: CompressedPage) -> Result<PageWriteSpec> {
let uncompressed_size = page.uncompressed_size();
let compressed_size = page.compressed_size();
@@ -1336,7 +1336,7 @@ mod tests {
compression: Compression,
) -> crate::format::FileMetaData
where
- W: Write,
+ W: Write + Send,
R: ChunkReader + From<W> + 'static,
{
test_roundtrip::<W, R, Int32Type, _>(
@@ -1356,7 +1356,7 @@ mod tests {
compression: Compression,
) -> crate::format::FileMetaData
where
- W: Write,
+ W: Write + Send,
R: ChunkReader + From<W> + 'static,
D: DataType,
F: Fn(Row) -> D::T,
diff --git a/parquet/src/record/record_writer.rs b/parquet/src/record/record_writer.rs
index fe803a7ff4ef..62099051f513 100644
--- a/parquet/src/record/record_writer.rs
+++ b/parquet/src/record/record_writer.rs
@@ -21,7 +21,7 @@ use super::super::errors::ParquetError;
use super::super::file::writer::SerializedRowGroupWriter;
pub trait RecordWriter<T> {
- fn write_to_row_group<W: std::io::Write>(
+ fn write_to_row_group<W: std::io::Write + Send>(
&self,
row_group_writer: &mut SerializedRowGroupWriter<W>,
) -> Result<(), ParquetError>;
diff --git a/parquet_derive/src/lib.rs b/parquet_derive/src/lib.rs
index a09b3b65233b..0f875401f0e9 100644
--- a/parquet_derive/src/lib.rs
+++ b/parquet_derive/src/lib.rs
@@ -96,7 +96,7 @@ pub fn parquet_record_writer(input: proc_macro::TokenStream) -> proc_macro::Toke
(quote! {
impl #generics ::parquet::record::RecordWriter<#derived_for #generics> for &[#derived_for #generics] {
- fn write_to_row_group<W: ::std::io::Write>(
+ fn write_to_row_group<W: ::std::io::Write + Send>(
&self,
row_group_writer: &mut ::parquet::file::writer::SerializedRowGroupWriter<'_, W>
) -> Result<(), ::parquet::errors::ParquetError> {
|
diff --git a/parquet_derive_test/src/lib.rs b/parquet_derive_test/src/lib.rs
index d2cf9efb1db6..f4f8be1e0d8c 100644
--- a/parquet_derive_test/src/lib.rs
+++ b/parquet_derive_test/src/lib.rs
@@ -56,8 +56,7 @@ mod tests {
use std::{env, fs, io::Write, sync::Arc};
use parquet::{
- file::{properties::WriterProperties, writer::SerializedFileWriter},
- record::RecordWriter,
+ file::writer::SerializedFileWriter, record::RecordWriter,
schema::parser::parse_message_type,
};
|
Make ColumnWriter Send
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
<!--
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
(This section helps Arrow developers understand the context and *why* for this feature, in addition to the *what*)
-->
`GenericColumnWriter` currently contains `Box<dyn PageWriter>`, as PageWriter lacks a `Send` bound this in turn makes `ColumnWriter` not send. This interferes with the use of column writer in multi-threaded code.
**Describe the solution you'd like**
<!--
A clear and concise description of what you want to happen.
-->
I would like `GenericColumnWriter: Send`
**Describe alternatives you've considered**
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
**Additional context**
Found as part of https://github.com/apache/arrow-rs/pull/4280
|
2023-05-26T09:48:13Z
|
40.0
|
008cf9c27424d581a67ba97f338a22b6eace9cc1
|
|
apache/arrow-rs
| 4,250
|
apache__arrow-rs-4250
|
[
"4249"
] |
25bfccca58ff219d9f59ba9f4d75550493238a4f
|
diff --git a/arrow-flight/examples/flight_sql_server.rs b/arrow-flight/examples/flight_sql_server.rs
index 23d71090ae47..01632285cf66 100644
--- a/arrow-flight/examples/flight_sql_server.rs
+++ b/arrow-flight/examples/flight_sql_server.rs
@@ -18,7 +18,11 @@
use arrow_array::builder::StringBuilder;
use arrow_array::{ArrayRef, RecordBatch};
use arrow_flight::sql::{
- ActionCreatePreparedStatementResult, Any, ProstMessageExt, SqlInfo,
+ ActionBeginSavepointRequest, ActionBeginSavepointResult,
+ ActionBeginTransactionResult, ActionCancelQueryRequest, ActionCancelQueryResult,
+ ActionCreatePreparedStatementResult, ActionEndSavepointRequest,
+ ActionEndTransactionRequest, Any, CommandStatementSubstraitPlan, ProstMessageExt,
+ SqlInfo,
};
use arrow_flight::{
Action, FlightData, FlightEndpoint, HandshakeRequest, HandshakeResponse, IpcMessage,
@@ -40,8 +44,9 @@ use arrow_flight::{
flight_service_server::FlightService,
flight_service_server::FlightServiceServer,
sql::{
- server::FlightSqlService, ActionClosePreparedStatementRequest,
- ActionCreatePreparedStatementRequest, CommandGetCatalogs,
+ server::FlightSqlService, ActionBeginTransactionRequest,
+ ActionClosePreparedStatementRequest, ActionCreatePreparedStatementRequest,
+ ActionCreatePreparedSubstraitPlanRequest, CommandGetCatalogs,
CommandGetCrossReference, CommandGetDbSchemas, CommandGetExportedKeys,
CommandGetImportedKeys, CommandGetPrimaryKeys, CommandGetSqlInfo,
CommandGetTableTypes, CommandGetTables, CommandGetXdbcTypeInfo,
@@ -177,6 +182,16 @@ impl FlightSqlService for FlightSqlServiceImpl {
))
}
+ async fn get_flight_info_substrait_plan(
+ &self,
+ _query: CommandStatementSubstraitPlan,
+ _request: Request<FlightDescriptor>,
+ ) -> Result<Response<FlightInfo>, Status> {
+ Err(Status::unimplemented(
+ "get_flight_info_substrait_plan not implemented",
+ ))
+ }
+
async fn get_flight_info_prepared_statement(
&self,
cmd: CommandPreparedStatementQuery,
@@ -220,6 +235,7 @@ impl FlightSqlService for FlightSqlServiceImpl {
endpoint: endpoints,
total_records: num_rows as i64,
total_bytes: num_bytes as i64,
+ ordered: false,
};
let resp = Response::new(info);
Ok(resp)
@@ -441,6 +457,16 @@ impl FlightSqlService for FlightSqlServiceImpl {
Ok(FAKE_UPDATE_RESULT)
}
+ async fn do_put_substrait_plan(
+ &self,
+ _ticket: CommandStatementSubstraitPlan,
+ _request: Request<Streaming<FlightData>>,
+ ) -> Result<i64, Status> {
+ Err(Status::unimplemented(
+ "do_put_substrait_plan not implemented",
+ ))
+ }
+
async fn do_put_prepared_statement_query(
&self,
_query: CommandPreparedStatementQuery,
@@ -486,8 +512,62 @@ impl FlightSqlService for FlightSqlServiceImpl {
&self,
_query: ActionClosePreparedStatementRequest,
_request: Request<Action>,
- ) {
- unimplemented!("Implement do_action_close_prepared_statement")
+ ) -> Result<(), Status> {
+ Err(Status::unimplemented(
+ "Implement do_action_close_prepared_statement",
+ ))
+ }
+
+ async fn do_action_create_prepared_substrait_plan(
+ &self,
+ _query: ActionCreatePreparedSubstraitPlanRequest,
+ _request: Request<Action>,
+ ) -> Result<ActionCreatePreparedStatementResult, Status> {
+ Err(Status::unimplemented(
+ "Implement do_action_create_prepared_substrait_plan",
+ ))
+ }
+
+ async fn do_action_begin_transaction(
+ &self,
+ _query: ActionBeginTransactionRequest,
+ _request: Request<Action>,
+ ) -> Result<ActionBeginTransactionResult, Status> {
+ Err(Status::unimplemented(
+ "Implement do_action_begin_transaction",
+ ))
+ }
+
+ async fn do_action_end_transaction(
+ &self,
+ _query: ActionEndTransactionRequest,
+ _request: Request<Action>,
+ ) -> Result<(), Status> {
+ Err(Status::unimplemented("Implement do_action_end_transaction"))
+ }
+
+ async fn do_action_begin_savepoint(
+ &self,
+ _query: ActionBeginSavepointRequest,
+ _request: Request<Action>,
+ ) -> Result<ActionBeginSavepointResult, Status> {
+ Err(Status::unimplemented("Implement do_action_begin_savepoint"))
+ }
+
+ async fn do_action_end_savepoint(
+ &self,
+ _query: ActionEndSavepointRequest,
+ _request: Request<Action>,
+ ) -> Result<(), Status> {
+ Err(Status::unimplemented("Implement do_action_end_savepoint"))
+ }
+
+ async fn do_action_cancel_query(
+ &self,
+ _query: ActionCancelQueryRequest,
+ _request: Request<Action>,
+ ) -> Result<ActionCancelQueryResult, Status> {
+ Err(Status::unimplemented("Implement do_action_cancel_query"))
}
async fn register_sql_info(&self, _id: i32, _result: &SqlInfo) {}
@@ -718,7 +798,7 @@ mod tests {
test_all_clients(|mut client| async move {
auth_client(&mut client).await;
- let mut stmt = client.prepare("select 1;".to_string()).await.unwrap();
+ let mut stmt = client.prepare("select 1;".to_string(), None).await.unwrap();
let flight_info = stmt.execute().await.unwrap();
@@ -746,7 +826,7 @@ mod tests {
test_all_clients(|mut client| async move {
auth_client(&mut client).await;
let res = client
- .execute_update("creat table test(a int);".to_string())
+ .execute_update("creat table test(a int);".to_string(), None)
.await
.unwrap();
assert_eq!(res, FAKE_UPDATE_RESULT);
@@ -759,7 +839,7 @@ mod tests {
test_all_clients(|mut client| async move {
// no handshake
assert!(client
- .prepare("select 1;".to_string())
+ .prepare("select 1;".to_string(), None)
.await
.unwrap_err()
.to_string()
@@ -776,7 +856,7 @@ mod tests {
// forget to set_token
client.handshake("admin", "password").await.unwrap();
assert!(client
- .prepare("select 1;".to_string())
+ .prepare("select 1;".to_string(), None)
.await
.unwrap_err()
.to_string()
@@ -786,7 +866,7 @@ mod tests {
client.handshake("admin", "password").await.unwrap();
client.set_token("wrong token".to_string());
assert!(client
- .prepare("select 1;".to_string())
+ .prepare("select 1;".to_string(), None)
.await
.unwrap_err()
.to_string()
diff --git a/arrow-flight/src/arrow.flight.protocol.rs b/arrow-flight/src/arrow.flight.protocol.rs
index 200c858cf5f1..10dc7ace0356 100644
--- a/arrow-flight/src/arrow.flight.protocol.rs
+++ b/arrow-flight/src/arrow.flight.protocol.rs
@@ -183,8 +183,21 @@ pub struct FlightInfo {
/// In other words, an application can use multiple endpoints to
/// represent partitioned data.
///
- /// There is no ordering defined on endpoints. Hence, if the returned
- /// data has an ordering, it should be returned in a single endpoint.
+ /// If the returned data has an ordering, an application can use
+ /// "FlightInfo.ordered = true" or should return the all data in a
+ /// single endpoint. Otherwise, there is no ordering defined on
+ /// endpoints or the data within.
+ ///
+ /// A client can read ordered data by reading data from returned
+ /// endpoints, in order, from front to back.
+ ///
+ /// Note that a client may ignore "FlightInfo.ordered = true". If an
+ /// ordering is important for an application, an application must
+ /// choose one of them:
+ ///
+ /// * An application requires that all clients must read data in
+ /// returned endpoints order.
+ /// * An application must return the all data in a single endpoint.
#[prost(message, repeated, tag = "3")]
pub endpoint: ::prost::alloc::vec::Vec<FlightEndpoint>,
/// Set these to -1 if unknown.
@@ -192,6 +205,10 @@ pub struct FlightInfo {
pub total_records: i64,
#[prost(int64, tag = "5")]
pub total_bytes: i64,
+ ///
+ /// FlightEndpoints are in the same order as the data.
+ #[prost(bool, tag = "6")]
+ pub ordered: bool,
}
///
/// A particular stream or split associated with a flight.
diff --git a/arrow-flight/src/bin/flight_sql_client.rs b/arrow-flight/src/bin/flight_sql_client.rs
index 1891a331be96..a787989bf6b4 100644
--- a/arrow-flight/src/bin/flight_sql_client.rs
+++ b/arrow-flight/src/bin/flight_sql_client.rs
@@ -108,7 +108,10 @@ async fn main() {
setup_logging();
let mut client = setup_client(args.client_args).await.expect("setup client");
- let info = client.execute(args.query).await.expect("prepare statement");
+ let info = client
+ .execute(args.query, None)
+ .await
+ .expect("prepare statement");
info!("got flight info");
let schema = Arc::new(Schema::try_from(info.clone()).expect("valid schema"));
diff --git a/arrow-flight/src/lib.rs b/arrow-flight/src/lib.rs
index a80358ff00c5..4960912ef8af 100644
--- a/arrow-flight/src/lib.rs
+++ b/arrow-flight/src/lib.rs
@@ -424,6 +424,7 @@ impl FlightInfo {
endpoint: Vec<FlightEndpoint>,
total_records: i64,
total_bytes: i64,
+ ordered: bool,
) -> Self {
let IpcMessage(vals) = message;
FlightInfo {
@@ -432,6 +433,7 @@ impl FlightInfo {
endpoint,
total_records,
total_bytes,
+ ordered,
}
}
diff --git a/arrow-flight/src/sql/arrow.flight.protocol.sql.rs b/arrow-flight/src/sql/arrow.flight.protocol.sql.rs
index 080156cce88e..b2137d8543d3 100644
--- a/arrow-flight/src/sql/arrow.flight.protocol.sql.rs
+++ b/arrow-flight/src/sql/arrow.flight.protocol.sql.rs
@@ -51,12 +51,12 @@ pub struct CommandGetSqlInfo {
/// The returned schema will be:
/// <
/// type_name: utf8 not null (The name of the data type, for example: VARCHAR, INTEGER, etc),
-/// data_type: int not null (The SQL data type),
-/// column_size: int (The maximum size supported by that column.
-/// In case of exact numeric types, this represents the maximum precision.
-/// In case of string types, this represents the character length.
-/// In case of datetime data types, this represents the length in characters of the string representation.
-/// NULL is returned for data types where column size is not applicable.),
+/// data_type: int32 not null (The SQL data type),
+/// column_size: int32 (The maximum size supported by that column.
+/// In case of exact numeric types, this represents the maximum precision.
+/// In case of string types, this represents the character length.
+/// In case of datetime data types, this represents the length in characters of the string representation.
+/// NULL is returned for data types where column size is not applicable.),
/// literal_prefix: utf8 (Character or characters used to prefix a literal, NULL is returned for
/// data types where a literal prefix is not applicable.),
/// literal_suffix: utf8 (Character or characters used to terminate a literal,
@@ -65,11 +65,11 @@ pub struct CommandGetSqlInfo {
/// (A list of keywords corresponding to which parameters can be used when creating
/// a column for that specific type.
/// NULL is returned if there are no parameters for the data type definition.),
-/// nullable: int not null (Shows if the data type accepts a NULL value. The possible values can be seen in the
-/// Nullable enum.),
+/// nullable: int32 not null (Shows if the data type accepts a NULL value. The possible values can be seen in the
+/// Nullable enum.),
/// case_sensitive: bool not null (Shows if a character data type is case-sensitive in collations and comparisons),
-/// searchable: int not null (Shows how the data type is used in a WHERE clause. The possible values can be seen in the
-/// Searchable enum.),
+/// searchable: int32 not null (Shows how the data type is used in a WHERE clause. The possible values can be seen in the
+/// Searchable enum.),
/// unsigned_attribute: bool (Shows if the data type is unsigned. NULL is returned if the attribute is
/// not applicable to the data type or the data type is not numeric.),
/// fixed_prec_scale: bool not null (Shows if the data type has predefined fixed precision and scale.),
@@ -77,26 +77,26 @@ pub struct CommandGetSqlInfo {
/// is not applicable to the data type or the data type is not numeric.),
/// local_type_name: utf8 (Localized version of the data source-dependent name of the data type. NULL
/// is returned if a localized name is not supported by the data source),
-/// minimum_scale: int (The minimum scale of the data type on the data source.
-/// If a data type has a fixed scale, the MINIMUM_SCALE and MAXIMUM_SCALE
-/// columns both contain this value. NULL is returned if scale is not applicable.),
-/// maximum_scale: int (The maximum scale of the data type on the data source.
-/// NULL is returned if scale is not applicable.),
-/// sql_data_type: int not null (The value of the SQL DATA TYPE which has the same values
-/// as data_type value. Except for interval and datetime, which
-/// uses generic values. More info about those types can be
-/// obtained through datetime_subcode. The possible values can be seen
-/// in the XdbcDataType enum.),
-/// datetime_subcode: int (Only used when the SQL DATA TYPE is interval or datetime. It contains
-/// its sub types. For type different from interval and datetime, this value
-/// is NULL. The possible values can be seen in the XdbcDatetimeSubcode enum.),
-/// num_prec_radix: int (If the data type is an approximate numeric type, this column contains
-/// the value 2 to indicate that COLUMN_SIZE specifies a number of bits. For
-/// exact numeric types, this column contains the value 10 to indicate that
-/// column size specifies a number of decimal digits. Otherwise, this column is NULL.),
-/// interval_precision: int (If the data type is an interval data type, then this column contains the value
-/// of the interval leading precision. Otherwise, this column is NULL. This fields
-/// is only relevant to be used by ODBC).
+/// minimum_scale: int32 (The minimum scale of the data type on the data source.
+/// If a data type has a fixed scale, the MINIMUM_SCALE and MAXIMUM_SCALE
+/// columns both contain this value. NULL is returned if scale is not applicable.),
+/// maximum_scale: int32 (The maximum scale of the data type on the data source.
+/// NULL is returned if scale is not applicable.),
+/// sql_data_type: int32 not null (The value of the SQL DATA TYPE which has the same values
+/// as data_type value. Except for interval and datetime, which
+/// uses generic values. More info about those types can be
+/// obtained through datetime_subcode. The possible values can be seen
+/// in the XdbcDataType enum.),
+/// datetime_subcode: int32 (Only used when the SQL DATA TYPE is interval or datetime. It contains
+/// its sub types. For type different from interval and datetime, this value
+/// is NULL. The possible values can be seen in the XdbcDatetimeSubcode enum.),
+/// num_prec_radix: int32 (If the data type is an approximate numeric type, this column contains
+/// the value 2 to indicate that COLUMN_SIZE specifies a number of bits. For
+/// exact numeric types, this column contains the value 10 to indicate that
+/// column size specifies a number of decimal digits. Otherwise, this column is NULL.),
+/// interval_precision: int32 (If the data type is an interval data type, then this column contains the value
+/// of the interval leading precision. Otherwise, this column is NULL. This fields
+/// is only relevant to be used by ODBC).
/// >
/// The returned data should be ordered by data_type and then by type_name.
#[allow(clippy::derive_partial_eq_without_eq)]
@@ -246,7 +246,7 @@ pub struct CommandGetTableTypes {}
/// table_name: utf8 not null,
/// column_name: utf8 not null,
/// key_name: utf8,
-/// key_sequence: int not null
+/// key_sequence: int32 not null
/// >
/// The returned data should be ordered by catalog_name, db_schema_name, table_name, key_name, then key_sequence.
#[allow(clippy::derive_partial_eq_without_eq)]
@@ -285,11 +285,11 @@ pub struct CommandGetPrimaryKeys {
/// fk_db_schema_name: utf8,
/// fk_table_name: utf8 not null,
/// fk_column_name: utf8 not null,
-/// key_sequence: int not null,
+/// key_sequence: int32 not null,
/// fk_key_name: utf8,
/// pk_key_name: utf8,
-/// update_rule: uint1 not null,
-/// delete_rule: uint1 not null
+/// update_rule: uint8 not null,
+/// delete_rule: uint8 not null
/// >
/// The returned data should be ordered by fk_catalog_name, fk_db_schema_name, fk_table_name, fk_key_name, then key_sequence.
/// update_rule and delete_rule returns a byte that is equivalent to actions declared on UpdateDeleteRules enum.
@@ -328,11 +328,11 @@ pub struct CommandGetExportedKeys {
/// fk_db_schema_name: utf8,
/// fk_table_name: utf8 not null,
/// fk_column_name: utf8 not null,
-/// key_sequence: int not null,
+/// key_sequence: int32 not null,
/// fk_key_name: utf8,
/// pk_key_name: utf8,
-/// update_rule: uint1 not null,
-/// delete_rule: uint1 not null
+/// update_rule: uint8 not null,
+/// delete_rule: uint8 not null
/// >
/// The returned data should be ordered by pk_catalog_name, pk_db_schema_name, pk_table_name, pk_key_name, then key_sequence.
/// update_rule and delete_rule returns a byte that is equivalent to actions:
@@ -378,11 +378,11 @@ pub struct CommandGetImportedKeys {
/// fk_db_schema_name: utf8,
/// fk_table_name: utf8 not null,
/// fk_column_name: utf8 not null,
-/// key_sequence: int not null,
+/// key_sequence: int32 not null,
/// fk_key_name: utf8,
/// pk_key_name: utf8,
-/// update_rule: uint1 not null,
-/// delete_rule: uint1 not null
+/// update_rule: uint8 not null,
+/// delete_rule: uint8 not null
/// >
/// The returned data should be ordered by pk_catalog_name, pk_db_schema_name, pk_table_name, pk_key_name, then key_sequence.
/// update_rule and delete_rule returns a byte that is equivalent to actions:
@@ -435,13 +435,49 @@ pub struct ActionCreatePreparedStatementRequest {
/// The valid SQL string to create a prepared statement for.
#[prost(string, tag = "1")]
pub query: ::prost::alloc::string::String,
+ /// Create/execute the prepared statement as part of this transaction (if
+ /// unset, executions of the prepared statement will be auto-committed).
+ #[prost(bytes = "bytes", optional, tag = "2")]
+ pub transaction_id: ::core::option::Option<::prost::bytes::Bytes>,
}
///
-/// Wrap the result of a "GetPreparedStatement" action.
+/// An embedded message describing a Substrait plan to execute.
+#[allow(clippy::derive_partial_eq_without_eq)]
+#[derive(Clone, PartialEq, ::prost::Message)]
+pub struct SubstraitPlan {
+ /// The serialized substrait.Plan to create a prepared statement for.
+ /// XXX(ARROW-16902): this is bytes instead of an embedded message
+ /// because Protobuf does not really support one DLL using Protobuf
+ /// definitions from another DLL.
+ #[prost(bytes = "bytes", tag = "1")]
+ pub plan: ::prost::bytes::Bytes,
+ /// The Substrait release, e.g. "0.12.0". This information is not
+ /// tracked in the plan itself, so this is the only way for consumers
+ /// to potentially know if they can handle the plan.
+ #[prost(string, tag = "2")]
+ pub version: ::prost::alloc::string::String,
+}
+///
+/// Request message for the "CreatePreparedSubstraitPlan" action on a Flight SQL enabled backend.
+#[allow(clippy::derive_partial_eq_without_eq)]
+#[derive(Clone, PartialEq, ::prost::Message)]
+pub struct ActionCreatePreparedSubstraitPlanRequest {
+ /// The serialized substrait.Plan to create a prepared statement for.
+ #[prost(message, optional, tag = "1")]
+ pub plan: ::core::option::Option<SubstraitPlan>,
+ /// Create/execute the prepared statement as part of this transaction (if
+ /// unset, executions of the prepared statement will be auto-committed).
+ #[prost(bytes = "bytes", optional, tag = "2")]
+ pub transaction_id: ::core::option::Option<::prost::bytes::Bytes>,
+}
+///
+/// Wrap the result of a "CreatePreparedStatement" or "CreatePreparedSubstraitPlan" action.
///
/// The resultant PreparedStatement can be closed either:
/// - Manually, through the "ClosePreparedStatement" action;
/// - Automatically, by a server timeout.
+///
+/// The result should be wrapped in a google.protobuf.Any message.
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct ActionCreatePreparedStatementResult {
@@ -468,6 +504,182 @@ pub struct ActionClosePreparedStatementRequest {
pub prepared_statement_handle: ::prost::bytes::Bytes,
}
///
+/// Request message for the "BeginTransaction" action.
+/// Begins a transaction.
+#[allow(clippy::derive_partial_eq_without_eq)]
+#[derive(Clone, PartialEq, ::prost::Message)]
+pub struct ActionBeginTransactionRequest {}
+///
+/// Request message for the "BeginSavepoint" action.
+/// Creates a savepoint within a transaction.
+///
+/// Only supported if FLIGHT_SQL_TRANSACTION is
+/// FLIGHT_SQL_TRANSACTION_SUPPORT_SAVEPOINT.
+#[allow(clippy::derive_partial_eq_without_eq)]
+#[derive(Clone, PartialEq, ::prost::Message)]
+pub struct ActionBeginSavepointRequest {
+ /// The transaction to which a savepoint belongs.
+ #[prost(bytes = "bytes", tag = "1")]
+ pub transaction_id: ::prost::bytes::Bytes,
+ /// Name for the savepoint.
+ #[prost(string, tag = "2")]
+ pub name: ::prost::alloc::string::String,
+}
+///
+/// The result of a "BeginTransaction" action.
+///
+/// The transaction can be manipulated with the "EndTransaction" action, or
+/// automatically via server timeout. If the transaction times out, then it is
+/// automatically rolled back.
+///
+/// The result should be wrapped in a google.protobuf.Any message.
+#[allow(clippy::derive_partial_eq_without_eq)]
+#[derive(Clone, PartialEq, ::prost::Message)]
+pub struct ActionBeginTransactionResult {
+ /// Opaque handle for the transaction on the server.
+ #[prost(bytes = "bytes", tag = "1")]
+ pub transaction_id: ::prost::bytes::Bytes,
+}
+///
+/// The result of a "BeginSavepoint" action.
+///
+/// The transaction can be manipulated with the "EndSavepoint" action.
+/// If the associated transaction is committed, rolled back, or times
+/// out, then the savepoint is also invalidated.
+///
+/// The result should be wrapped in a google.protobuf.Any message.
+#[allow(clippy::derive_partial_eq_without_eq)]
+#[derive(Clone, PartialEq, ::prost::Message)]
+pub struct ActionBeginSavepointResult {
+ /// Opaque handle for the savepoint on the server.
+ #[prost(bytes = "bytes", tag = "1")]
+ pub savepoint_id: ::prost::bytes::Bytes,
+}
+///
+/// Request message for the "EndTransaction" action.
+///
+/// Commit (COMMIT) or rollback (ROLLBACK) the transaction.
+///
+/// If the action completes successfully, the transaction handle is
+/// invalidated, as are all associated savepoints.
+#[allow(clippy::derive_partial_eq_without_eq)]
+#[derive(Clone, PartialEq, ::prost::Message)]
+pub struct ActionEndTransactionRequest {
+ /// Opaque handle for the transaction on the server.
+ #[prost(bytes = "bytes", tag = "1")]
+ pub transaction_id: ::prost::bytes::Bytes,
+ /// Whether to commit/rollback the given transaction.
+ #[prost(enumeration = "action_end_transaction_request::EndTransaction", tag = "2")]
+ pub action: i32,
+}
+/// Nested message and enum types in `ActionEndTransactionRequest`.
+pub mod action_end_transaction_request {
+ #[derive(
+ Clone,
+ Copy,
+ Debug,
+ PartialEq,
+ Eq,
+ Hash,
+ PartialOrd,
+ Ord,
+ ::prost::Enumeration
+ )]
+ #[repr(i32)]
+ pub enum EndTransaction {
+ Unspecified = 0,
+ /// Commit the transaction.
+ Commit = 1,
+ /// Roll back the transaction.
+ Rollback = 2,
+ }
+ impl EndTransaction {
+ /// String value of the enum field names used in the ProtoBuf definition.
+ ///
+ /// The values are not transformed in any way and thus are considered stable
+ /// (if the ProtoBuf definition does not change) and safe for programmatic use.
+ pub fn as_str_name(&self) -> &'static str {
+ match self {
+ EndTransaction::Unspecified => "END_TRANSACTION_UNSPECIFIED",
+ EndTransaction::Commit => "END_TRANSACTION_COMMIT",
+ EndTransaction::Rollback => "END_TRANSACTION_ROLLBACK",
+ }
+ }
+ /// Creates an enum from field names used in the ProtoBuf definition.
+ pub fn from_str_name(value: &str) -> ::core::option::Option<Self> {
+ match value {
+ "END_TRANSACTION_UNSPECIFIED" => Some(Self::Unspecified),
+ "END_TRANSACTION_COMMIT" => Some(Self::Commit),
+ "END_TRANSACTION_ROLLBACK" => Some(Self::Rollback),
+ _ => None,
+ }
+ }
+ }
+}
+///
+/// Request message for the "EndSavepoint" action.
+///
+/// Release (RELEASE) the savepoint or rollback (ROLLBACK) to the
+/// savepoint.
+///
+/// Releasing a savepoint invalidates that savepoint. Rolling back to
+/// a savepoint does not invalidate the savepoint, but invalidates all
+/// savepoints created after the current savepoint.
+#[allow(clippy::derive_partial_eq_without_eq)]
+#[derive(Clone, PartialEq, ::prost::Message)]
+pub struct ActionEndSavepointRequest {
+ /// Opaque handle for the savepoint on the server.
+ #[prost(bytes = "bytes", tag = "1")]
+ pub savepoint_id: ::prost::bytes::Bytes,
+ /// Whether to rollback/release the given savepoint.
+ #[prost(enumeration = "action_end_savepoint_request::EndSavepoint", tag = "2")]
+ pub action: i32,
+}
+/// Nested message and enum types in `ActionEndSavepointRequest`.
+pub mod action_end_savepoint_request {
+ #[derive(
+ Clone,
+ Copy,
+ Debug,
+ PartialEq,
+ Eq,
+ Hash,
+ PartialOrd,
+ Ord,
+ ::prost::Enumeration
+ )]
+ #[repr(i32)]
+ pub enum EndSavepoint {
+ Unspecified = 0,
+ /// Release the savepoint.
+ Release = 1,
+ /// Roll back to a savepoint.
+ Rollback = 2,
+ }
+ impl EndSavepoint {
+ /// String value of the enum field names used in the ProtoBuf definition.
+ ///
+ /// The values are not transformed in any way and thus are considered stable
+ /// (if the ProtoBuf definition does not change) and safe for programmatic use.
+ pub fn as_str_name(&self) -> &'static str {
+ match self {
+ EndSavepoint::Unspecified => "END_SAVEPOINT_UNSPECIFIED",
+ EndSavepoint::Release => "END_SAVEPOINT_RELEASE",
+ EndSavepoint::Rollback => "END_SAVEPOINT_ROLLBACK",
+ }
+ }
+ /// Creates an enum from field names used in the ProtoBuf definition.
+ pub fn from_str_name(value: &str) -> ::core::option::Option<Self> {
+ match value {
+ "END_SAVEPOINT_UNSPECIFIED" => Some(Self::Unspecified),
+ "END_SAVEPOINT_RELEASE" => Some(Self::Release),
+ "END_SAVEPOINT_ROLLBACK" => Some(Self::Rollback),
+ _ => None,
+ }
+ }
+ }
+}
+///
/// Represents a SQL query. Used in the command member of FlightDescriptor
/// for the following RPC calls:
/// - GetSchema: return the Arrow schema of the query.
@@ -489,6 +701,36 @@ pub struct CommandStatementQuery {
/// The SQL syntax.
#[prost(string, tag = "1")]
pub query: ::prost::alloc::string::String,
+ /// Include the query as part of this transaction (if unset, the query is auto-committed).
+ #[prost(bytes = "bytes", optional, tag = "2")]
+ pub transaction_id: ::core::option::Option<::prost::bytes::Bytes>,
+}
+///
+/// Represents a Substrait plan. Used in the command member of FlightDescriptor
+/// for the following RPC calls:
+/// - GetSchema: return the Arrow schema of the query.
+/// Fields on this schema may contain the following metadata:
+/// - ARROW:FLIGHT:SQL:CATALOG_NAME - Table's catalog name
+/// - ARROW:FLIGHT:SQL:DB_SCHEMA_NAME - Database schema name
+/// - ARROW:FLIGHT:SQL:TABLE_NAME - Table name
+/// - ARROW:FLIGHT:SQL:TYPE_NAME - The data source-specific name for the data type of the column.
+/// - ARROW:FLIGHT:SQL:PRECISION - Column precision/size
+/// - ARROW:FLIGHT:SQL:SCALE - Column scale/decimal digits if applicable
+/// - ARROW:FLIGHT:SQL:IS_AUTO_INCREMENT - "1" indicates if the column is auto incremented, "0" otherwise.
+/// - ARROW:FLIGHT:SQL:IS_CASE_SENSITIVE - "1" indicates if the column is case sensitive, "0" otherwise.
+/// - ARROW:FLIGHT:SQL:IS_READ_ONLY - "1" indicates if the column is read only, "0" otherwise.
+/// - ARROW:FLIGHT:SQL:IS_SEARCHABLE - "1" indicates if the column is searchable via WHERE clause, "0" otherwise.
+/// - GetFlightInfo: execute the query.
+/// - DoPut: execute the query.
+#[allow(clippy::derive_partial_eq_without_eq)]
+#[derive(Clone, PartialEq, ::prost::Message)]
+pub struct CommandStatementSubstraitPlan {
+ /// A serialized substrait.Plan
+ #[prost(message, optional, tag = "1")]
+ pub plan: ::core::option::Option<SubstraitPlan>,
+ /// Include the query as part of this transaction (if unset, the query is auto-committed).
+ #[prost(bytes = "bytes", optional, tag = "2")]
+ pub transaction_id: ::core::option::Option<::prost::bytes::Bytes>,
}
/// *
/// Represents a ticket resulting from GetFlightInfo with a CommandStatementQuery.
@@ -533,6 +775,9 @@ pub struct CommandStatementUpdate {
/// The SQL syntax.
#[prost(string, tag = "1")]
pub query: ::prost::alloc::string::String,
+ /// Include the query as part of this transaction (if unset, the query is auto-committed).
+ #[prost(bytes = "bytes", optional, tag = "2")]
+ pub transaction_id: ::core::option::Option<::prost::bytes::Bytes>,
}
///
/// Represents a SQL update query. Used in the command member of FlightDescriptor
@@ -557,6 +802,93 @@ pub struct DoPutUpdateResult {
#[prost(int64, tag = "1")]
pub record_count: i64,
}
+///
+/// Request message for the "CancelQuery" action.
+///
+/// Explicitly cancel a running query.
+///
+/// This lets a single client explicitly cancel work, no matter how many clients
+/// are involved/whether the query is distributed or not, given server support.
+/// The transaction/statement is not rolled back; it is the application's job to
+/// commit or rollback as appropriate. This only indicates the client no longer
+/// wishes to read the remainder of the query results or continue submitting
+/// data.
+///
+/// This command is idempotent.
+#[allow(clippy::derive_partial_eq_without_eq)]
+#[derive(Clone, PartialEq, ::prost::Message)]
+pub struct ActionCancelQueryRequest {
+ /// The result of the GetFlightInfo RPC that initiated the query.
+ /// XXX(ARROW-16902): this must be a serialized FlightInfo, but is
+ /// rendered as bytes because Protobuf does not really support one
+ /// DLL using Protobuf definitions from another DLL.
+ #[prost(bytes = "bytes", tag = "1")]
+ pub info: ::prost::bytes::Bytes,
+}
+///
+/// The result of cancelling a query.
+///
+/// The result should be wrapped in a google.protobuf.Any message.
+#[allow(clippy::derive_partial_eq_without_eq)]
+#[derive(Clone, PartialEq, ::prost::Message)]
+pub struct ActionCancelQueryResult {
+ #[prost(enumeration = "action_cancel_query_result::CancelResult", tag = "1")]
+ pub result: i32,
+}
+/// Nested message and enum types in `ActionCancelQueryResult`.
+pub mod action_cancel_query_result {
+ #[derive(
+ Clone,
+ Copy,
+ Debug,
+ PartialEq,
+ Eq,
+ Hash,
+ PartialOrd,
+ Ord,
+ ::prost::Enumeration
+ )]
+ #[repr(i32)]
+ pub enum CancelResult {
+ /// The cancellation status is unknown. Servers should avoid using
+ /// this value (send a NOT_FOUND error if the requested query is
+ /// not known). Clients can retry the request.
+ Unspecified = 0,
+ /// The cancellation request is complete. Subsequent requests with
+ /// the same payload may return CANCELLED or a NOT_FOUND error.
+ Cancelled = 1,
+ /// The cancellation request is in progress. The client may retry
+ /// the cancellation request.
+ Cancelling = 2,
+ /// The query is not cancellable. The client should not retry the
+ /// cancellation request.
+ NotCancellable = 3,
+ }
+ impl CancelResult {
+ /// String value of the enum field names used in the ProtoBuf definition.
+ ///
+ /// The values are not transformed in any way and thus are considered stable
+ /// (if the ProtoBuf definition does not change) and safe for programmatic use.
+ pub fn as_str_name(&self) -> &'static str {
+ match self {
+ CancelResult::Unspecified => "CANCEL_RESULT_UNSPECIFIED",
+ CancelResult::Cancelled => "CANCEL_RESULT_CANCELLED",
+ CancelResult::Cancelling => "CANCEL_RESULT_CANCELLING",
+ CancelResult::NotCancellable => "CANCEL_RESULT_NOT_CANCELLABLE",
+ }
+ }
+ /// Creates an enum from field names used in the ProtoBuf definition.
+ pub fn from_str_name(value: &str) -> ::core::option::Option<Self> {
+ match value {
+ "CANCEL_RESULT_UNSPECIFIED" => Some(Self::Unspecified),
+ "CANCEL_RESULT_CANCELLED" => Some(Self::Cancelled),
+ "CANCEL_RESULT_CANCELLING" => Some(Self::Cancelling),
+ "CANCEL_RESULT_NOT_CANCELLABLE" => Some(Self::NotCancellable),
+ _ => None,
+ }
+ }
+ }
+}
/// Options for CommandGetSqlInfo.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
#[repr(i32)]
@@ -575,6 +907,49 @@ pub enum SqlInfo {
/// - true: if read only
FlightSqlServerReadOnly = 3,
///
+ /// Retrieves a boolean value indicating whether the Flight SQL Server supports executing
+ /// SQL queries.
+ ///
+ /// Note that the absence of this info (as opposed to a false value) does not necessarily
+ /// mean that SQL is not supported, as this property was not originally defined.
+ FlightSqlServerSql = 4,
+ ///
+ /// Retrieves a boolean value indicating whether the Flight SQL Server supports executing
+ /// Substrait plans.
+ FlightSqlServerSubstrait = 5,
+ ///
+ /// Retrieves a string value indicating the minimum supported Substrait version, or null
+ /// if Substrait is not supported.
+ FlightSqlServerSubstraitMinVersion = 6,
+ ///
+ /// Retrieves a string value indicating the maximum supported Substrait version, or null
+ /// if Substrait is not supported.
+ FlightSqlServerSubstraitMaxVersion = 7,
+ ///
+ /// Retrieves an int32 indicating whether the Flight SQL Server supports the
+ /// BeginTransaction/EndTransaction/BeginSavepoint/EndSavepoint actions.
+ ///
+ /// Even if this is not supported, the database may still support explicit "BEGIN
+ /// TRANSACTION"/"COMMIT" SQL statements (see SQL_TRANSACTIONS_SUPPORTED); this property
+ /// is only about whether the server implements the Flight SQL API endpoints.
+ ///
+ /// The possible values are listed in `SqlSupportedTransaction`.
+ FlightSqlServerTransaction = 8,
+ ///
+ /// Retrieves a boolean value indicating whether the Flight SQL Server supports explicit
+ /// query cancellation (the CancelQuery action).
+ FlightSqlServerCancel = 9,
+ ///
+ /// Retrieves an int32 indicating the timeout (in milliseconds) for prepared statement handles.
+ ///
+ /// If 0, there is no timeout. Servers should reset the timeout when the handle is used in a command.
+ FlightSqlServerStatementTimeout = 100,
+ ///
+ /// Retrieves an int32 indicating the timeout (in milliseconds) for transactions, since transactions are not tied to a connection.
+ ///
+ /// If 0, there is no timeout. Servers should reset the timeout when the handle is used in a command.
+ FlightSqlServerTransactionTimeout = 101,
+ ///
/// Retrieves a boolean value indicating whether the Flight SQL Server supports CREATE and DROP of catalogs.
///
/// Returns:
@@ -1125,6 +1500,22 @@ impl SqlInfo {
SqlInfo::FlightSqlServerVersion => "FLIGHT_SQL_SERVER_VERSION",
SqlInfo::FlightSqlServerArrowVersion => "FLIGHT_SQL_SERVER_ARROW_VERSION",
SqlInfo::FlightSqlServerReadOnly => "FLIGHT_SQL_SERVER_READ_ONLY",
+ SqlInfo::FlightSqlServerSql => "FLIGHT_SQL_SERVER_SQL",
+ SqlInfo::FlightSqlServerSubstrait => "FLIGHT_SQL_SERVER_SUBSTRAIT",
+ SqlInfo::FlightSqlServerSubstraitMinVersion => {
+ "FLIGHT_SQL_SERVER_SUBSTRAIT_MIN_VERSION"
+ }
+ SqlInfo::FlightSqlServerSubstraitMaxVersion => {
+ "FLIGHT_SQL_SERVER_SUBSTRAIT_MAX_VERSION"
+ }
+ SqlInfo::FlightSqlServerTransaction => "FLIGHT_SQL_SERVER_TRANSACTION",
+ SqlInfo::FlightSqlServerCancel => "FLIGHT_SQL_SERVER_CANCEL",
+ SqlInfo::FlightSqlServerStatementTimeout => {
+ "FLIGHT_SQL_SERVER_STATEMENT_TIMEOUT"
+ }
+ SqlInfo::FlightSqlServerTransactionTimeout => {
+ "FLIGHT_SQL_SERVER_TRANSACTION_TIMEOUT"
+ }
SqlInfo::SqlDdlCatalog => "SQL_DDL_CATALOG",
SqlInfo::SqlDdlSchema => "SQL_DDL_SCHEMA",
SqlInfo::SqlDdlTable => "SQL_DDL_TABLE",
@@ -1241,6 +1632,22 @@ impl SqlInfo {
"FLIGHT_SQL_SERVER_VERSION" => Some(Self::FlightSqlServerVersion),
"FLIGHT_SQL_SERVER_ARROW_VERSION" => Some(Self::FlightSqlServerArrowVersion),
"FLIGHT_SQL_SERVER_READ_ONLY" => Some(Self::FlightSqlServerReadOnly),
+ "FLIGHT_SQL_SERVER_SQL" => Some(Self::FlightSqlServerSql),
+ "FLIGHT_SQL_SERVER_SUBSTRAIT" => Some(Self::FlightSqlServerSubstrait),
+ "FLIGHT_SQL_SERVER_SUBSTRAIT_MIN_VERSION" => {
+ Some(Self::FlightSqlServerSubstraitMinVersion)
+ }
+ "FLIGHT_SQL_SERVER_SUBSTRAIT_MAX_VERSION" => {
+ Some(Self::FlightSqlServerSubstraitMaxVersion)
+ }
+ "FLIGHT_SQL_SERVER_TRANSACTION" => Some(Self::FlightSqlServerTransaction),
+ "FLIGHT_SQL_SERVER_CANCEL" => Some(Self::FlightSqlServerCancel),
+ "FLIGHT_SQL_SERVER_STATEMENT_TIMEOUT" => {
+ Some(Self::FlightSqlServerStatementTimeout)
+ }
+ "FLIGHT_SQL_SERVER_TRANSACTION_TIMEOUT" => {
+ Some(Self::FlightSqlServerTransactionTimeout)
+ }
"SQL_DDL_CATALOG" => Some(Self::SqlDdlCatalog),
"SQL_DDL_SCHEMA" => Some(Self::SqlDdlSchema),
"SQL_DDL_TABLE" => Some(Self::SqlDdlTable),
@@ -1354,6 +1761,43 @@ impl SqlInfo {
}
}
}
+/// The level of support for Flight SQL transaction RPCs.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
+#[repr(i32)]
+pub enum SqlSupportedTransaction {
+ /// Unknown/not indicated/no support
+ None = 0,
+ /// Transactions, but not savepoints.
+ /// A savepoint is a mark within a transaction that can be individually
+ /// rolled back to. Not all databases support savepoints.
+ Transaction = 1,
+ /// Transactions and savepoints
+ Savepoint = 2,
+}
+impl SqlSupportedTransaction {
+ /// String value of the enum field names used in the ProtoBuf definition.
+ ///
+ /// The values are not transformed in any way and thus are considered stable
+ /// (if the ProtoBuf definition does not change) and safe for programmatic use.
+ pub fn as_str_name(&self) -> &'static str {
+ match self {
+ SqlSupportedTransaction::None => "SQL_SUPPORTED_TRANSACTION_NONE",
+ SqlSupportedTransaction::Transaction => {
+ "SQL_SUPPORTED_TRANSACTION_TRANSACTION"
+ }
+ SqlSupportedTransaction::Savepoint => "SQL_SUPPORTED_TRANSACTION_SAVEPOINT",
+ }
+ }
+ /// Creates an enum from field names used in the ProtoBuf definition.
+ pub fn from_str_name(value: &str) -> ::core::option::Option<Self> {
+ match value {
+ "SQL_SUPPORTED_TRANSACTION_NONE" => Some(Self::None),
+ "SQL_SUPPORTED_TRANSACTION_TRANSACTION" => Some(Self::Transaction),
+ "SQL_SUPPORTED_TRANSACTION_SAVEPOINT" => Some(Self::Savepoint),
+ _ => None,
+ }
+ }
+}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
#[repr(i32)]
pub enum SqlSupportedCaseSensitivity {
diff --git a/arrow-flight/src/sql/client.rs b/arrow-flight/src/sql/client.rs
index 15a896c109e1..c9adc2b98b12 100644
--- a/arrow-flight/src/sql/client.rs
+++ b/arrow-flight/src/sql/client.rs
@@ -116,8 +116,15 @@ impl FlightSqlServiceClient<Channel> {
}
/// Execute a query on the server.
- pub async fn execute(&mut self, query: String) -> Result<FlightInfo, ArrowError> {
- let cmd = CommandStatementQuery { query };
+ pub async fn execute(
+ &mut self,
+ query: String,
+ transaction_id: Option<Bytes>,
+ ) -> Result<FlightInfo, ArrowError> {
+ let cmd = CommandStatementQuery {
+ query,
+ transaction_id,
+ };
self.get_flight_info_for_command(cmd).await
}
@@ -170,8 +177,15 @@ impl FlightSqlServiceClient<Channel> {
}
/// Execute a update query on the server, and return the number of records affected
- pub async fn execute_update(&mut self, query: String) -> Result<i64, ArrowError> {
- let cmd = CommandStatementUpdate { query };
+ pub async fn execute_update(
+ &mut self,
+ query: String,
+ transaction_id: Option<Bytes>,
+ ) -> Result<i64, ArrowError> {
+ let cmd = CommandStatementUpdate {
+ query,
+ transaction_id,
+ };
let descriptor = FlightDescriptor::new_cmd(cmd.as_any().encode_to_vec());
let req = self.set_request_headers(
stream::iter(vec![FlightData {
@@ -325,8 +339,12 @@ impl FlightSqlServiceClient<Channel> {
pub async fn prepare(
&mut self,
query: String,
+ transaction_id: Option<Bytes>,
) -> Result<PreparedStatement<Channel>, ArrowError> {
- let cmd = ActionCreatePreparedStatementRequest { query };
+ let cmd = ActionCreatePreparedStatementRequest {
+ query,
+ transaction_id,
+ };
let action = Action {
r#type: CREATE_PREPARED_STATEMENT.to_string(),
body: cmd.as_any().encode_to_vec().into(),
diff --git a/arrow-flight/src/sql/mod.rs b/arrow-flight/src/sql/mod.rs
index ed26b38751c5..797ddfc9e4a6 100644
--- a/arrow-flight/src/sql/mod.rs
+++ b/arrow-flight/src/sql/mod.rs
@@ -46,9 +46,18 @@ mod gen {
include!("arrow.flight.protocol.sql.rs");
}
+pub use gen::ActionBeginSavepointRequest;
+pub use gen::ActionBeginSavepointResult;
+pub use gen::ActionBeginTransactionRequest;
+pub use gen::ActionBeginTransactionResult;
+pub use gen::ActionCancelQueryRequest;
+pub use gen::ActionCancelQueryResult;
pub use gen::ActionClosePreparedStatementRequest;
pub use gen::ActionCreatePreparedStatementRequest;
pub use gen::ActionCreatePreparedStatementResult;
+pub use gen::ActionCreatePreparedSubstraitPlanRequest;
+pub use gen::ActionEndSavepointRequest;
+pub use gen::ActionEndTransactionRequest;
pub use gen::CommandGetCatalogs;
pub use gen::CommandGetCrossReference;
pub use gen::CommandGetDbSchemas;
@@ -62,6 +71,7 @@ pub use gen::CommandGetXdbcTypeInfo;
pub use gen::CommandPreparedStatementQuery;
pub use gen::CommandPreparedStatementUpdate;
pub use gen::CommandStatementQuery;
+pub use gen::CommandStatementSubstraitPlan;
pub use gen::CommandStatementUpdate;
pub use gen::DoPutUpdateResult;
pub use gen::SqlInfo;
@@ -120,6 +130,7 @@ macro_rules! prost_message_ext {
/// # use arrow_flight::sql::{Any, CommandStatementQuery, Command};
/// let flightsql_message = CommandStatementQuery {
/// query: "SELECT * FROM foo".to_string(),
+ /// transaction_id: None,
/// };
///
/// // Given a packed FlightSQL Any message
@@ -203,9 +214,18 @@ macro_rules! prost_message_ext {
// Implement ProstMessageExt for all structs defined in FlightSql.proto
prost_message_ext!(
+ ActionBeginSavepointRequest,
+ ActionBeginSavepointResult,
+ ActionBeginTransactionRequest,
+ ActionBeginTransactionResult,
+ ActionCancelQueryRequest,
+ ActionCancelQueryResult,
ActionClosePreparedStatementRequest,
ActionCreatePreparedStatementRequest,
ActionCreatePreparedStatementResult,
+ ActionCreatePreparedSubstraitPlanRequest,
+ ActionEndSavepointRequest,
+ ActionEndTransactionRequest,
CommandGetCatalogs,
CommandGetCrossReference,
CommandGetDbSchemas,
@@ -219,6 +239,7 @@ prost_message_ext!(
CommandPreparedStatementQuery,
CommandPreparedStatementUpdate,
CommandStatementQuery,
+ CommandStatementSubstraitPlan,
CommandStatementUpdate,
DoPutUpdateResult,
TicketStatementQuery,
@@ -296,6 +317,7 @@ mod tests {
fn test_prost_any_pack_unpack() {
let query = CommandStatementQuery {
query: "select 1".to_string(),
+ transaction_id: None,
};
let any = Any::pack(&query).unwrap();
assert!(any.is::<CommandStatementQuery>());
@@ -307,6 +329,7 @@ mod tests {
fn test_command() {
let query = CommandStatementQuery {
query: "select 1".to_string(),
+ transaction_id: None,
};
let any = Any::pack(&query).unwrap();
let cmd: Command = any.try_into().unwrap();
diff --git a/arrow-flight/src/sql/server.rs b/arrow-flight/src/sql/server.rs
index 9a0183495434..89eb70e23b35 100644
--- a/arrow-flight/src/sql/server.rs
+++ b/arrow-flight/src/sql/server.rs
@@ -30,17 +30,28 @@ use super::{
FlightData, FlightDescriptor, FlightInfo, HandshakeRequest, HandshakeResponse,
PutResult, SchemaResult, Ticket,
},
+ ActionBeginSavepointRequest, ActionBeginSavepointResult,
+ ActionBeginTransactionRequest, ActionBeginTransactionResult,
+ ActionCancelQueryRequest, ActionCancelQueryResult,
ActionClosePreparedStatementRequest, ActionCreatePreparedStatementRequest,
- ActionCreatePreparedStatementResult, CommandGetCatalogs, CommandGetCrossReference,
- CommandGetDbSchemas, CommandGetExportedKeys, CommandGetImportedKeys,
- CommandGetPrimaryKeys, CommandGetSqlInfo, CommandGetTableTypes, CommandGetTables,
- CommandGetXdbcTypeInfo, CommandPreparedStatementQuery,
- CommandPreparedStatementUpdate, CommandStatementQuery, CommandStatementUpdate,
- DoPutUpdateResult, ProstMessageExt, SqlInfo, TicketStatementQuery,
+ ActionCreatePreparedStatementResult, ActionCreatePreparedSubstraitPlanRequest,
+ ActionEndSavepointRequest, ActionEndTransactionRequest, CommandGetCatalogs,
+ CommandGetCrossReference, CommandGetDbSchemas, CommandGetExportedKeys,
+ CommandGetImportedKeys, CommandGetPrimaryKeys, CommandGetSqlInfo,
+ CommandGetTableTypes, CommandGetTables, CommandGetXdbcTypeInfo,
+ CommandPreparedStatementQuery, CommandPreparedStatementUpdate, CommandStatementQuery,
+ CommandStatementSubstraitPlan, CommandStatementUpdate, DoPutUpdateResult,
+ ProstMessageExt, SqlInfo, TicketStatementQuery,
};
pub(crate) static CREATE_PREPARED_STATEMENT: &str = "CreatePreparedStatement";
pub(crate) static CLOSE_PREPARED_STATEMENT: &str = "ClosePreparedStatement";
+pub(crate) static CREATE_PREPARED_SUBSTRAIT_PLAN: &str = "CreatePreparedSubstraitPlan";
+pub(crate) static BEGIN_TRANSACTION: &str = "BeginTransaction";
+pub(crate) static END_TRANSACTION: &str = "EndTransaction";
+pub(crate) static BEGIN_SAVEPOINT: &str = "BeginSavepoint";
+pub(crate) static END_SAVEPOINT: &str = "EndSavepoint";
+pub(crate) static CANCEL_QUERY: &str = "CancelQuery";
/// Implements FlightSqlService to handle the flight sql protocol
#[tonic::async_trait]
@@ -81,6 +92,13 @@ pub trait FlightSqlService: Sync + Send + Sized + 'static {
request: Request<FlightDescriptor>,
) -> Result<Response<FlightInfo>, Status>;
+ /// Get a FlightInfo for executing a substrait plan.
+ async fn get_flight_info_substrait_plan(
+ &self,
+ query: CommandStatementSubstraitPlan,
+ request: Request<FlightDescriptor>,
+ ) -> Result<Response<FlightInfo>, Status>;
+
/// Get a FlightInfo for executing an already created prepared statement.
async fn get_flight_info_prepared_statement(
&self,
@@ -267,6 +285,13 @@ pub trait FlightSqlService: Sync + Send + Sized + 'static {
request: Request<Streaming<FlightData>>,
) -> Result<i64, Status>;
+ /// Execute a substrait plan
+ async fn do_put_substrait_plan(
+ &self,
+ query: CommandStatementSubstraitPlan,
+ request: Request<Streaming<FlightData>>,
+ ) -> Result<i64, Status>;
+
// do_action
/// Create a prepared statement from given SQL statement.
@@ -281,7 +306,49 @@ pub trait FlightSqlService: Sync + Send + Sized + 'static {
&self,
query: ActionClosePreparedStatementRequest,
request: Request<Action>,
- );
+ ) -> Result<(), Status>;
+
+ /// Create a prepared substrait plan.
+ async fn do_action_create_prepared_substrait_plan(
+ &self,
+ query: ActionCreatePreparedSubstraitPlanRequest,
+ request: Request<Action>,
+ ) -> Result<ActionCreatePreparedStatementResult, Status>;
+
+ /// Begin a transaction
+ async fn do_action_begin_transaction(
+ &self,
+ query: ActionBeginTransactionRequest,
+ request: Request<Action>,
+ ) -> Result<ActionBeginTransactionResult, Status>;
+
+ /// End a transaction
+ async fn do_action_end_transaction(
+ &self,
+ query: ActionEndTransactionRequest,
+ request: Request<Action>,
+ ) -> Result<(), Status>;
+
+ /// Begin a savepoint
+ async fn do_action_begin_savepoint(
+ &self,
+ query: ActionBeginSavepointRequest,
+ request: Request<Action>,
+ ) -> Result<ActionBeginSavepointResult, Status>;
+
+ /// End a savepoint
+ async fn do_action_end_savepoint(
+ &self,
+ query: ActionEndSavepointRequest,
+ request: Request<Action>,
+ ) -> Result<(), Status>;
+
+ /// Cancel a query
+ async fn do_action_cancel_query(
+ &self,
+ query: ActionCancelQueryRequest,
+ request: Request<Action>,
+ ) -> Result<ActionCancelQueryResult, Status>;
/// Register a new SqlInfo result, making it available when calling GetSqlInfo.
async fn register_sql_info(&self, id: i32, result: &SqlInfo);
@@ -339,6 +406,9 @@ where
self.get_flight_info_prepared_statement(handle, request)
.await
}
+ Command::CommandStatementSubstraitPlan(handle) => {
+ self.get_flight_info_substrait_plan(handle, request).await
+ }
Command::CommandGetCatalogs(token) => {
self.get_flight_info_catalogs(token, request).await
}
@@ -450,6 +520,14 @@ where
Command::CommandPreparedStatementQuery(command) => {
self.do_put_prepared_statement_query(command, request).await
}
+ Command::CommandStatementSubstraitPlan(command) => {
+ let record_count = self.do_put_substrait_plan(command, request).await?;
+ let result = DoPutUpdateResult { record_count };
+ let output = futures::stream::iter(vec![Ok(PutResult {
+ app_metadata: result.as_any().encode_to_vec().into(),
+ })]);
+ Ok(Response::new(Box::pin(output)))
+ }
Command::CommandPreparedStatementUpdate(command) => {
let record_count = self
.do_put_prepared_statement_update(command, request)
@@ -485,9 +563,58 @@ where
Response Message: N/A"
.into(),
};
+ let create_prepared_substrait_plan_action_type = ActionType {
+ r#type: CREATE_PREPARED_SUBSTRAIT_PLAN.to_string(),
+ description:
+ "Creates a reusable prepared substrait plan resource on the server.\n
+ Request Message: ActionCreatePreparedSubstraitPlanRequest\n
+ Response Message: ActionCreatePreparedStatementResult"
+ .into(),
+ };
+ let begin_transaction_action_type = ActionType {
+ r#type: BEGIN_TRANSACTION.to_string(),
+ description: "Begins a transaction.\n
+ Request Message: ActionBeginTransactionRequest\n
+ Response Message: ActionBeginTransactionResult"
+ .into(),
+ };
+ let end_transaction_action_type = ActionType {
+ r#type: END_TRANSACTION.to_string(),
+ description: "Ends a transaction\n
+ Request Message: ActionEndTransactionRequest\n
+ Response Message: N/A"
+ .into(),
+ };
+ let begin_savepoint_action_type = ActionType {
+ r#type: BEGIN_SAVEPOINT.to_string(),
+ description: "Begins a savepoint.\n
+ Request Message: ActionBeginSavepointRequest\n
+ Response Message: ActionBeginSavepointResult"
+ .into(),
+ };
+ let end_savepoint_action_type = ActionType {
+ r#type: END_SAVEPOINT.to_string(),
+ description: "Ends a savepoint\n
+ Request Message: ActionEndSavepointRequest\n
+ Response Message: N/A"
+ .into(),
+ };
+ let cancel_query_action_type = ActionType {
+ r#type: CANCEL_QUERY.to_string(),
+ description: "Cancels a query\n
+ Request Message: ActionCancelQueryRequest\n
+ Response Message: ActionCancelQueryResult"
+ .into(),
+ };
let actions: Vec<Result<ActionType, Status>> = vec![
Ok(create_prepared_statement_action_type),
Ok(close_prepared_statement_action_type),
+ Ok(create_prepared_substrait_plan_action_type),
+ Ok(begin_transaction_action_type),
+ Ok(end_transaction_action_type),
+ Ok(begin_savepoint_action_type),
+ Ok(end_savepoint_action_type),
+ Ok(cancel_query_action_type),
];
let output = futures::stream::iter(actions);
Ok(Response::new(Box::pin(output) as Self::ListActionsStream))
@@ -516,8 +643,7 @@ where
body: stmt.as_any().encode_to_vec().into(),
})]);
return Ok(Response::new(Box::pin(output)));
- }
- if request.get_ref().r#type == CLOSE_PREPARED_STATEMENT {
+ } else if request.get_ref().r#type == CLOSE_PREPARED_STATEMENT {
let any =
Any::decode(&*request.get_ref().body).map_err(decode_error_to_status)?;
@@ -529,8 +655,101 @@ where
"Unable to unpack ActionClosePreparedStatementRequest.",
)
})?;
- self.do_action_close_prepared_statement(cmd, request).await;
+ self.do_action_close_prepared_statement(cmd, request)
+ .await?;
+ return Ok(Response::new(Box::pin(futures::stream::empty())));
+ } else if request.get_ref().r#type == CREATE_PREPARED_SUBSTRAIT_PLAN {
+ let any =
+ Any::decode(&*request.get_ref().body).map_err(decode_error_to_status)?;
+
+ let cmd: ActionCreatePreparedSubstraitPlanRequest = any
+ .unpack()
+ .map_err(arrow_error_to_status)?
+ .ok_or_else(|| {
+ Status::invalid_argument(
+ "Unable to unpack ActionCreatePreparedSubstraitPlanRequest.",
+ )
+ })?;
+ self.do_action_create_prepared_substrait_plan(cmd, request)
+ .await?;
+ return Ok(Response::new(Box::pin(futures::stream::empty())));
+ } else if request.get_ref().r#type == BEGIN_TRANSACTION {
+ let any =
+ Any::decode(&*request.get_ref().body).map_err(decode_error_to_status)?;
+
+ let cmd: ActionBeginTransactionRequest = any
+ .unpack()
+ .map_err(arrow_error_to_status)?
+ .ok_or_else(|| {
+ Status::invalid_argument(
+ "Unable to unpack ActionBeginTransactionRequest.",
+ )
+ })?;
+ let stmt = self.do_action_begin_transaction(cmd, request).await?;
+ let output = futures::stream::iter(vec![Ok(super::super::gen::Result {
+ body: stmt.as_any().encode_to_vec().into(),
+ })]);
+ return Ok(Response::new(Box::pin(output)));
+ } else if request.get_ref().r#type == END_TRANSACTION {
+ let any =
+ Any::decode(&*request.get_ref().body).map_err(decode_error_to_status)?;
+
+ let cmd: ActionEndTransactionRequest = any
+ .unpack()
+ .map_err(arrow_error_to_status)?
+ .ok_or_else(|| {
+ Status::invalid_argument(
+ "Unable to unpack ActionEndTransactionRequest.",
+ )
+ })?;
+ self.do_action_end_transaction(cmd, request).await?;
return Ok(Response::new(Box::pin(futures::stream::empty())));
+ } else if request.get_ref().r#type == BEGIN_SAVEPOINT {
+ let any =
+ Any::decode(&*request.get_ref().body).map_err(decode_error_to_status)?;
+
+ let cmd: ActionBeginSavepointRequest = any
+ .unpack()
+ .map_err(arrow_error_to_status)?
+ .ok_or_else(|| {
+ Status::invalid_argument(
+ "Unable to unpack ActionBeginSavepointRequest.",
+ )
+ })?;
+ let stmt = self.do_action_begin_savepoint(cmd, request).await?;
+ let output = futures::stream::iter(vec![Ok(super::super::gen::Result {
+ body: stmt.as_any().encode_to_vec().into(),
+ })]);
+ return Ok(Response::new(Box::pin(output)));
+ } else if request.get_ref().r#type == END_SAVEPOINT {
+ let any =
+ Any::decode(&*request.get_ref().body).map_err(decode_error_to_status)?;
+
+ let cmd: ActionEndSavepointRequest = any
+ .unpack()
+ .map_err(arrow_error_to_status)?
+ .ok_or_else(|| {
+ Status::invalid_argument(
+ "Unable to unpack ActionEndSavepointRequest.",
+ )
+ })?;
+ self.do_action_end_savepoint(cmd, request).await?;
+ return Ok(Response::new(Box::pin(futures::stream::empty())));
+ } else if request.get_ref().r#type == CANCEL_QUERY {
+ let any =
+ Any::decode(&*request.get_ref().body).map_err(decode_error_to_status)?;
+
+ let cmd: ActionCancelQueryRequest = any
+ .unpack()
+ .map_err(arrow_error_to_status)?
+ .ok_or_else(|| {
+ Status::invalid_argument("Unable to unpack ActionCancelQueryRequest.")
+ })?;
+ let stmt = self.do_action_cancel_query(cmd, request).await?;
+ let output = futures::stream::iter(vec![Ok(super::super::gen::Result {
+ body: stmt.as_any().encode_to_vec().into(),
+ })]);
+ return Ok(Response::new(Box::pin(output)));
}
Err(Status::invalid_argument(format!(
diff --git a/format/Flight.proto b/format/Flight.proto
index 635b1793d2ba..9b44331a5765 100644
--- a/format/Flight.proto
+++ b/format/Flight.proto
@@ -16,347 +16,365 @@
* limitations under the License.
*/
-syntax = "proto3";
-
-option java_package = "org.apache.arrow.flight.impl";
-option go_package = "github.com/apache/arrow/go/arrow/flight/internal/flight";
-option csharp_namespace = "Apache.Arrow.Flight.Protocol";
-
-package arrow.flight.protocol;
-
-/*
- * A flight service is an endpoint for retrieving or storing Arrow data. A
- * flight service can expose one or more predefined endpoints that can be
- * accessed using the Arrow Flight Protocol. Additionally, a flight service
- * can expose a set of actions that are available.
- */
-service FlightService {
-
- /*
- * Handshake between client and server. Depending on the server, the
- * handshake may be required to determine the token that should be used for
- * future operations. Both request and response are streams to allow multiple
- * round-trips depending on auth mechanism.
- */
- rpc Handshake(stream HandshakeRequest) returns (stream HandshakeResponse) {}
-
- /*
- * Get a list of available streams given a particular criteria. Most flight
- * services will expose one or more streams that are readily available for
- * retrieval. This api allows listing the streams available for
- * consumption. A user can also provide a criteria. The criteria can limit
- * the subset of streams that can be listed via this interface. Each flight
- * service allows its own definition of how to consume criteria.
- */
- rpc ListFlights(Criteria) returns (stream FlightInfo) {}
-
- /*
- * For a given FlightDescriptor, get information about how the flight can be
- * consumed. This is a useful interface if the consumer of the interface
- * already can identify the specific flight to consume. This interface can
- * also allow a consumer to generate a flight stream through a specified
- * descriptor. For example, a flight descriptor might be something that
- * includes a SQL statement or a Pickled Python operation that will be
- * executed. In those cases, the descriptor will not be previously available
- * within the list of available streams provided by ListFlights but will be
- * available for consumption for the duration defined by the specific flight
- * service.
- */
- rpc GetFlightInfo(FlightDescriptor) returns (FlightInfo) {}
-
- /*
- * For a given FlightDescriptor, get the Schema as described in Schema.fbs::Schema
- * This is used when a consumer needs the Schema of flight stream. Similar to
- * GetFlightInfo this interface may generate a new flight that was not previously
- * available in ListFlights.
- */
- rpc GetSchema(FlightDescriptor) returns (SchemaResult) {}
-
- /*
- * Retrieve a single stream associated with a particular descriptor
- * associated with the referenced ticket. A Flight can be composed of one or
- * more streams where each stream can be retrieved using a separate opaque
- * ticket that the flight service uses for managing a collection of streams.
- */
- rpc DoGet(Ticket) returns (stream FlightData) {}
-
- /*
- * Push a stream to the flight service associated with a particular
- * flight stream. This allows a client of a flight service to upload a stream
- * of data. Depending on the particular flight service, a client consumer
- * could be allowed to upload a single stream per descriptor or an unlimited
- * number. In the latter, the service might implement a 'seal' action that
- * can be applied to a descriptor once all streams are uploaded.
- */
- rpc DoPut(stream FlightData) returns (stream PutResult) {}
-
- /*
- * Open a bidirectional data channel for a given descriptor. This
- * allows clients to send and receive arbitrary Arrow data and
- * application-specific metadata in a single logical stream. In
- * contrast to DoGet/DoPut, this is more suited for clients
- * offloading computation (rather than storage) to a Flight service.
- */
- rpc DoExchange(stream FlightData) returns (stream FlightData) {}
-
- /*
- * Flight services can support an arbitrary number of simple actions in
- * addition to the possible ListFlights, GetFlightInfo, DoGet, DoPut
- * operations that are potentially available. DoAction allows a flight client
- * to do a specific action against a flight service. An action includes
- * opaque request and response objects that are specific to the type action
- * being undertaken.
- */
- rpc DoAction(Action) returns (stream Result) {}
-
- /*
- * A flight service exposes all of the available action types that it has
- * along with descriptions. This allows different flight consumers to
- * understand the capabilities of the flight service.
- */
- rpc ListActions(Empty) returns (stream ActionType) {}
-
-}
-
-/*
- * The request that a client provides to a server on handshake.
- */
-message HandshakeRequest {
-
- /*
- * A defined protocol version
- */
- uint64 protocol_version = 1;
-
- /*
- * Arbitrary auth/handshake info.
- */
- bytes payload = 2;
-}
-
-message HandshakeResponse {
-
- /*
- * A defined protocol version
- */
- uint64 protocol_version = 1;
-
- /*
- * Arbitrary auth/handshake info.
- */
- bytes payload = 2;
-}
-
-/*
- * A message for doing simple auth.
- */
-message BasicAuth {
- string username = 2;
- string password = 3;
-}
-
-message Empty {}
-
-/*
- * Describes an available action, including both the name used for execution
- * along with a short description of the purpose of the action.
- */
-message ActionType {
- string type = 1;
- string description = 2;
-}
-
-/*
- * A service specific expression that can be used to return a limited set
- * of available Arrow Flight streams.
- */
-message Criteria {
- bytes expression = 1;
-}
-
-/*
- * An opaque action specific for the service.
- */
-message Action {
- string type = 1;
- bytes body = 2;
-}
-
-/*
- * An opaque result returned after executing an action.
- */
-message Result {
- bytes body = 1;
-}
-
-/*
- * Wrap the result of a getSchema call
- */
-message SchemaResult {
- // The schema of the dataset in its IPC form:
- // 4 bytes - an optional IPC_CONTINUATION_TOKEN prefix
- // 4 bytes - the byte length of the payload
- // a flatbuffer Message whose header is the Schema
- bytes schema = 1;
-}
-
-/*
- * The name or tag for a Flight. May be used as a way to retrieve or generate
- * a flight or be used to expose a set of previously defined flights.
- */
-message FlightDescriptor {
-
- /*
- * Describes what type of descriptor is defined.
- */
- enum DescriptorType {
-
- // Protobuf pattern, not used.
- UNKNOWN = 0;
-
- /*
- * A named path that identifies a dataset. A path is composed of a string
- * or list of strings describing a particular dataset. This is conceptually
- * similar to a path inside a filesystem.
- */
- PATH = 1;
-
- /*
- * An opaque command to generate a dataset.
- */
- CMD = 2;
- }
-
- DescriptorType type = 1;
-
- /*
- * Opaque value used to express a command. Should only be defined when
- * type = CMD.
- */
- bytes cmd = 2;
-
- /*
- * List of strings identifying a particular dataset. Should only be defined
- * when type = PATH.
- */
- repeated string path = 3;
-}
-
-/*
- * The access coordinates for retrieval of a dataset. With a FlightInfo, a
- * consumer is able to determine how to retrieve a dataset.
- */
-message FlightInfo {
- // The schema of the dataset in its IPC form:
- // 4 bytes - an optional IPC_CONTINUATION_TOKEN prefix
- // 4 bytes - the byte length of the payload
- // a flatbuffer Message whose header is the Schema
- bytes schema = 1;
-
- /*
- * The descriptor associated with this info.
- */
- FlightDescriptor flight_descriptor = 2;
-
- /*
- * A list of endpoints associated with the flight. To consume the
- * whole flight, all endpoints (and hence all Tickets) must be
- * consumed. Endpoints can be consumed in any order.
- *
- * In other words, an application can use multiple endpoints to
- * represent partitioned data.
- *
- * There is no ordering defined on endpoints. Hence, if the returned
- * data has an ordering, it should be returned in a single endpoint.
- */
- repeated FlightEndpoint endpoint = 3;
-
- // Set these to -1 if unknown.
- int64 total_records = 4;
- int64 total_bytes = 5;
-}
-
-/*
- * A particular stream or split associated with a flight.
- */
-message FlightEndpoint {
-
- /*
- * Token used to retrieve this stream.
- */
- Ticket ticket = 1;
-
- /*
- * A list of URIs where this ticket can be redeemed via DoGet().
- *
- * If the list is empty, the expectation is that the ticket can only
- * be redeemed on the current service where the ticket was
- * generated.
- *
- * If the list is not empty, the expectation is that the ticket can
- * be redeemed at any of the locations, and that the data returned
- * will be equivalent. In this case, the ticket may only be redeemed
- * at one of the given locations, and not (necessarily) on the
- * current service.
- *
- * In other words, an application can use multiple locations to
- * represent redundant and/or load balanced services.
- */
- repeated Location location = 2;
-}
-
-/*
- * A location where a Flight service will accept retrieval of a particular
- * stream given a ticket.
- */
-message Location {
- string uri = 1;
-}
-
-/*
- * An opaque identifier that the service can use to retrieve a particular
- * portion of a stream.
- *
- * Tickets are meant to be single use. It is an error/application-defined
- * behavior to reuse a ticket.
- */
-message Ticket {
- bytes ticket = 1;
-}
-
-/*
- * A batch of Arrow data as part of a stream of batches.
- */
-message FlightData {
-
- /*
- * The descriptor of the data. This is only relevant when a client is
- * starting a new DoPut stream.
- */
- FlightDescriptor flight_descriptor = 1;
-
- /*
- * Header for message data as described in Message.fbs::Message.
- */
- bytes data_header = 2;
-
- /*
- * Application-defined metadata.
- */
- bytes app_metadata = 3;
-
- /*
- * The actual batch of Arrow data. Preferably handled with minimal-copies
- * coming last in the definition to help with sidecar patterns (it is
- * expected that some implementations will fetch this field off the wire
- * with specialized code to avoid extra memory copies).
- */
- bytes data_body = 1000;
-}
-
-/**
- * The response message associated with the submission of a DoPut.
- */
-message PutResult {
- bytes app_metadata = 1;
-}
+ syntax = "proto3";
+
+ option java_package = "org.apache.arrow.flight.impl";
+ option go_package = "github.com/apache/arrow/go/arrow/flight/internal/flight";
+ option csharp_namespace = "Apache.Arrow.Flight.Protocol";
+
+ package arrow.flight.protocol;
+
+ /*
+ * A flight service is an endpoint for retrieving or storing Arrow data. A
+ * flight service can expose one or more predefined endpoints that can be
+ * accessed using the Arrow Flight Protocol. Additionally, a flight service
+ * can expose a set of actions that are available.
+ */
+ service FlightService {
+
+ /*
+ * Handshake between client and server. Depending on the server, the
+ * handshake may be required to determine the token that should be used for
+ * future operations. Both request and response are streams to allow multiple
+ * round-trips depending on auth mechanism.
+ */
+ rpc Handshake(stream HandshakeRequest) returns (stream HandshakeResponse) {}
+
+ /*
+ * Get a list of available streams given a particular criteria. Most flight
+ * services will expose one or more streams that are readily available for
+ * retrieval. This api allows listing the streams available for
+ * consumption. A user can also provide a criteria. The criteria can limit
+ * the subset of streams that can be listed via this interface. Each flight
+ * service allows its own definition of how to consume criteria.
+ */
+ rpc ListFlights(Criteria) returns (stream FlightInfo) {}
+
+ /*
+ * For a given FlightDescriptor, get information about how the flight can be
+ * consumed. This is a useful interface if the consumer of the interface
+ * already can identify the specific flight to consume. This interface can
+ * also allow a consumer to generate a flight stream through a specified
+ * descriptor. For example, a flight descriptor might be something that
+ * includes a SQL statement or a Pickled Python operation that will be
+ * executed. In those cases, the descriptor will not be previously available
+ * within the list of available streams provided by ListFlights but will be
+ * available for consumption for the duration defined by the specific flight
+ * service.
+ */
+ rpc GetFlightInfo(FlightDescriptor) returns (FlightInfo) {}
+
+ /*
+ * For a given FlightDescriptor, get the Schema as described in Schema.fbs::Schema
+ * This is used when a consumer needs the Schema of flight stream. Similar to
+ * GetFlightInfo this interface may generate a new flight that was not previously
+ * available in ListFlights.
+ */
+ rpc GetSchema(FlightDescriptor) returns (SchemaResult) {}
+
+ /*
+ * Retrieve a single stream associated with a particular descriptor
+ * associated with the referenced ticket. A Flight can be composed of one or
+ * more streams where each stream can be retrieved using a separate opaque
+ * ticket that the flight service uses for managing a collection of streams.
+ */
+ rpc DoGet(Ticket) returns (stream FlightData) {}
+
+ /*
+ * Push a stream to the flight service associated with a particular
+ * flight stream. This allows a client of a flight service to upload a stream
+ * of data. Depending on the particular flight service, a client consumer
+ * could be allowed to upload a single stream per descriptor or an unlimited
+ * number. In the latter, the service might implement a 'seal' action that
+ * can be applied to a descriptor once all streams are uploaded.
+ */
+ rpc DoPut(stream FlightData) returns (stream PutResult) {}
+
+ /*
+ * Open a bidirectional data channel for a given descriptor. This
+ * allows clients to send and receive arbitrary Arrow data and
+ * application-specific metadata in a single logical stream. In
+ * contrast to DoGet/DoPut, this is more suited for clients
+ * offloading computation (rather than storage) to a Flight service.
+ */
+ rpc DoExchange(stream FlightData) returns (stream FlightData) {}
+
+ /*
+ * Flight services can support an arbitrary number of simple actions in
+ * addition to the possible ListFlights, GetFlightInfo, DoGet, DoPut
+ * operations that are potentially available. DoAction allows a flight client
+ * to do a specific action against a flight service. An action includes
+ * opaque request and response objects that are specific to the type action
+ * being undertaken.
+ */
+ rpc DoAction(Action) returns (stream Result) {}
+
+ /*
+ * A flight service exposes all of the available action types that it has
+ * along with descriptions. This allows different flight consumers to
+ * understand the capabilities of the flight service.
+ */
+ rpc ListActions(Empty) returns (stream ActionType) {}
+
+ }
+
+ /*
+ * The request that a client provides to a server on handshake.
+ */
+ message HandshakeRequest {
+
+ /*
+ * A defined protocol version
+ */
+ uint64 protocol_version = 1;
+
+ /*
+ * Arbitrary auth/handshake info.
+ */
+ bytes payload = 2;
+ }
+
+ message HandshakeResponse {
+
+ /*
+ * A defined protocol version
+ */
+ uint64 protocol_version = 1;
+
+ /*
+ * Arbitrary auth/handshake info.
+ */
+ bytes payload = 2;
+ }
+
+ /*
+ * A message for doing simple auth.
+ */
+ message BasicAuth {
+ string username = 2;
+ string password = 3;
+ }
+
+ message Empty {}
+
+ /*
+ * Describes an available action, including both the name used for execution
+ * along with a short description of the purpose of the action.
+ */
+ message ActionType {
+ string type = 1;
+ string description = 2;
+ }
+
+ /*
+ * A service specific expression that can be used to return a limited set
+ * of available Arrow Flight streams.
+ */
+ message Criteria {
+ bytes expression = 1;
+ }
+
+ /*
+ * An opaque action specific for the service.
+ */
+ message Action {
+ string type = 1;
+ bytes body = 2;
+ }
+
+ /*
+ * An opaque result returned after executing an action.
+ */
+ message Result {
+ bytes body = 1;
+ }
+
+ /*
+ * Wrap the result of a getSchema call
+ */
+ message SchemaResult {
+ // The schema of the dataset in its IPC form:
+ // 4 bytes - an optional IPC_CONTINUATION_TOKEN prefix
+ // 4 bytes - the byte length of the payload
+ // a flatbuffer Message whose header is the Schema
+ bytes schema = 1;
+ }
+
+ /*
+ * The name or tag for a Flight. May be used as a way to retrieve or generate
+ * a flight or be used to expose a set of previously defined flights.
+ */
+ message FlightDescriptor {
+
+ /*
+ * Describes what type of descriptor is defined.
+ */
+ enum DescriptorType {
+
+ // Protobuf pattern, not used.
+ UNKNOWN = 0;
+
+ /*
+ * A named path that identifies a dataset. A path is composed of a string
+ * or list of strings describing a particular dataset. This is conceptually
+ * similar to a path inside a filesystem.
+ */
+ PATH = 1;
+
+ /*
+ * An opaque command to generate a dataset.
+ */
+ CMD = 2;
+ }
+
+ DescriptorType type = 1;
+
+ /*
+ * Opaque value used to express a command. Should only be defined when
+ * type = CMD.
+ */
+ bytes cmd = 2;
+
+ /*
+ * List of strings identifying a particular dataset. Should only be defined
+ * when type = PATH.
+ */
+ repeated string path = 3;
+ }
+
+ /*
+ * The access coordinates for retrieval of a dataset. With a FlightInfo, a
+ * consumer is able to determine how to retrieve a dataset.
+ */
+ message FlightInfo {
+ // The schema of the dataset in its IPC form:
+ // 4 bytes - an optional IPC_CONTINUATION_TOKEN prefix
+ // 4 bytes - the byte length of the payload
+ // a flatbuffer Message whose header is the Schema
+ bytes schema = 1;
+
+ /*
+ * The descriptor associated with this info.
+ */
+ FlightDescriptor flight_descriptor = 2;
+
+ /*
+ * A list of endpoints associated with the flight. To consume the
+ * whole flight, all endpoints (and hence all Tickets) must be
+ * consumed. Endpoints can be consumed in any order.
+ *
+ * In other words, an application can use multiple endpoints to
+ * represent partitioned data.
+ *
+ * If the returned data has an ordering, an application can use
+ * "FlightInfo.ordered = true" or should return the all data in a
+ * single endpoint. Otherwise, there is no ordering defined on
+ * endpoints or the data within.
+ *
+ * A client can read ordered data by reading data from returned
+ * endpoints, in order, from front to back.
+ *
+ * Note that a client may ignore "FlightInfo.ordered = true". If an
+ * ordering is important for an application, an application must
+ * choose one of them:
+ *
+ * * An application requires that all clients must read data in
+ * returned endpoints order.
+ * * An application must return the all data in a single endpoint.
+ */
+ repeated FlightEndpoint endpoint = 3;
+
+ // Set these to -1 if unknown.
+ int64 total_records = 4;
+ int64 total_bytes = 5;
+
+ /*
+ * FlightEndpoints are in the same order as the data.
+ */
+ bool ordered = 6;
+ }
+
+ /*
+ * A particular stream or split associated with a flight.
+ */
+ message FlightEndpoint {
+
+ /*
+ * Token used to retrieve this stream.
+ */
+ Ticket ticket = 1;
+
+ /*
+ * A list of URIs where this ticket can be redeemed via DoGet().
+ *
+ * If the list is empty, the expectation is that the ticket can only
+ * be redeemed on the current service where the ticket was
+ * generated.
+ *
+ * If the list is not empty, the expectation is that the ticket can
+ * be redeemed at any of the locations, and that the data returned
+ * will be equivalent. In this case, the ticket may only be redeemed
+ * at one of the given locations, and not (necessarily) on the
+ * current service.
+ *
+ * In other words, an application can use multiple locations to
+ * represent redundant and/or load balanced services.
+ */
+ repeated Location location = 2;
+ }
+
+ /*
+ * A location where a Flight service will accept retrieval of a particular
+ * stream given a ticket.
+ */
+ message Location {
+ string uri = 1;
+ }
+
+ /*
+ * An opaque identifier that the service can use to retrieve a particular
+ * portion of a stream.
+ *
+ * Tickets are meant to be single use. It is an error/application-defined
+ * behavior to reuse a ticket.
+ */
+ message Ticket {
+ bytes ticket = 1;
+ }
+
+ /*
+ * A batch of Arrow data as part of a stream of batches.
+ */
+ message FlightData {
+
+ /*
+ * The descriptor of the data. This is only relevant when a client is
+ * starting a new DoPut stream.
+ */
+ FlightDescriptor flight_descriptor = 1;
+
+ /*
+ * Header for message data as described in Message.fbs::Message.
+ */
+ bytes data_header = 2;
+
+ /*
+ * Application-defined metadata.
+ */
+ bytes app_metadata = 3;
+
+ /*
+ * The actual batch of Arrow data. Preferably handled with minimal-copies
+ * coming last in the definition to help with sidecar patterns (it is
+ * expected that some implementations will fetch this field off the wire
+ * with specialized code to avoid extra memory copies).
+ */
+ bytes data_body = 1000;
+ }
+
+ /**
+ * The response message associated with the submission of a DoPut.
+ */
+ message PutResult {
+ bytes app_metadata = 1;
+ }
\ No newline at end of file
diff --git a/format/FlightSql.proto b/format/FlightSql.proto
index 859427b68804..0acf647e1045 100644
--- a/format/FlightSql.proto
+++ b/format/FlightSql.proto
@@ -16,1540 +16,1832 @@
* limitations under the License.
*/
-syntax = "proto3";
-import "google/protobuf/descriptor.proto";
-
-option java_package = "org.apache.arrow.flight.sql.impl";
-option go_package = "github.com/apache/arrow/go/arrow/flight/internal/flight";
-package arrow.flight.protocol.sql;
-
-/*
- * Represents a metadata request. Used in the command member of FlightDescriptor
- * for the following RPC calls:
- * - GetSchema: return the Arrow schema of the query.
- * - GetFlightInfo: execute the metadata request.
- *
- * The returned Arrow schema will be:
- * <
- * info_name: uint32 not null,
- * value: dense_union<
- * string_value: utf8,
- * bool_value: bool,
- * bigint_value: int64,
- * int32_bitmask: int32,
- * string_list: list<string_data: utf8>
- * int32_to_int32_list_map: map<key: int32, value: list<$data$: int32>>
- * >
- * where there is one row per requested piece of metadata information.
- */
-message CommandGetSqlInfo {
- option (experimental) = true;
-
- /*
- * Values are modelled after ODBC's SQLGetInfo() function. This information is intended to provide
- * Flight SQL clients with basic, SQL syntax and SQL functions related information.
- * More information types can be added in future releases.
- * E.g. more SQL syntax support types, scalar functions support, type conversion support etc.
- *
- * Note that the set of metadata may expand.
- *
- * Initially, Flight SQL will support the following information types:
- * - Server Information - Range [0-500)
- * - Syntax Information - Range [500-1000)
- * Range [0-10,000) is reserved for defaults (see SqlInfo enum for default options).
- * Custom options should start at 10,000.
- *
- * If omitted, then all metadata will be retrieved.
- * Flight SQL Servers may choose to include additional metadata above and beyond the specified set, however they must
- * at least return the specified set. IDs ranging from 0 to 10,000 (exclusive) are reserved for future use.
- * If additional metadata is included, the metadata IDs should start from 10,000.
- */
- repeated uint32 info = 1;
-}
-
-// Options for CommandGetSqlInfo.
-enum SqlInfo {
-
- // Server Information [0-500): Provides basic information about the Flight SQL Server.
-
- // Retrieves a UTF-8 string with the name of the Flight SQL Server.
- FLIGHT_SQL_SERVER_NAME = 0;
-
- // Retrieves a UTF-8 string with the native version of the Flight SQL Server.
- FLIGHT_SQL_SERVER_VERSION = 1;
-
- // Retrieves a UTF-8 string with the Arrow format version of the Flight SQL Server.
- FLIGHT_SQL_SERVER_ARROW_VERSION = 2;
-
- /*
- * Retrieves a boolean value indicating whether the Flight SQL Server is read only.
- *
- * Returns:
- * - false: if read-write
- * - true: if read only
- */
- FLIGHT_SQL_SERVER_READ_ONLY = 3;
-
-
- // SQL Syntax Information [500-1000): provides information about SQL syntax supported by the Flight SQL Server.
-
- /*
- * Retrieves a boolean value indicating whether the Flight SQL Server supports CREATE and DROP of catalogs.
- *
- * Returns:
- * - false: if it doesn't support CREATE and DROP of catalogs.
- * - true: if it supports CREATE and DROP of catalogs.
- */
- SQL_DDL_CATALOG = 500;
-
- /*
- * Retrieves a boolean value indicating whether the Flight SQL Server supports CREATE and DROP of schemas.
- *
- * Returns:
- * - false: if it doesn't support CREATE and DROP of schemas.
- * - true: if it supports CREATE and DROP of schemas.
- */
- SQL_DDL_SCHEMA = 501;
-
- /*
- * Indicates whether the Flight SQL Server supports CREATE and DROP of tables.
- *
- * Returns:
- * - false: if it doesn't support CREATE and DROP of tables.
- * - true: if it supports CREATE and DROP of tables.
- */
- SQL_DDL_TABLE = 502;
-
- /*
- * Retrieves a int32 ordinal representing the case sensitivity of catalog, table, schema and table names.
- *
- * The possible values are listed in `arrow.flight.protocol.sql.SqlSupportedCaseSensitivity`.
- */
- SQL_IDENTIFIER_CASE = 503;
-
- // Retrieves a UTF-8 string with the supported character(s) used to surround a delimited identifier.
- SQL_IDENTIFIER_QUOTE_CHAR = 504;
-
- /*
- * Retrieves a int32 describing the case sensitivity of quoted identifiers.
- *
- * The possible values are listed in `arrow.flight.protocol.sql.SqlSupportedCaseSensitivity`.
- */
- SQL_QUOTED_IDENTIFIER_CASE = 505;
-
- /*
- * Retrieves a boolean value indicating whether all tables are selectable.
- *
- * Returns:
- * - false: if not all tables are selectable or if none are;
- * - true: if all tables are selectable.
- */
- SQL_ALL_TABLES_ARE_SELECTABLE = 506;
-
- /*
- * Retrieves the null ordering.
- *
- * Returns a int32 ordinal for the null ordering being used, as described in
- * `arrow.flight.protocol.sql.SqlNullOrdering`.
- */
- SQL_NULL_ORDERING = 507;
-
- // Retrieves a UTF-8 string list with values of the supported keywords.
- SQL_KEYWORDS = 508;
-
- // Retrieves a UTF-8 string list with values of the supported numeric functions.
- SQL_NUMERIC_FUNCTIONS = 509;
-
- // Retrieves a UTF-8 string list with values of the supported string functions.
- SQL_STRING_FUNCTIONS = 510;
-
- // Retrieves a UTF-8 string list with values of the supported system functions.
- SQL_SYSTEM_FUNCTIONS = 511;
-
- // Retrieves a UTF-8 string list with values of the supported datetime functions.
- SQL_DATETIME_FUNCTIONS = 512;
-
- /*
- * Retrieves the UTF-8 string that can be used to escape wildcard characters.
- * This is the string that can be used to escape '_' or '%' in the catalog search parameters that are a pattern
- * (and therefore use one of the wildcard characters).
- * The '_' character represents any single character; the '%' character represents any sequence of zero or more
- * characters.
- */
- SQL_SEARCH_STRING_ESCAPE = 513;
-
- /*
- * Retrieves a UTF-8 string with all the "extra" characters that can be used in unquoted identifier names
- * (those beyond a-z, A-Z, 0-9 and _).
- */
- SQL_EXTRA_NAME_CHARACTERS = 514;
-
- /*
- * Retrieves a boolean value indicating whether column aliasing is supported.
- * If so, the SQL AS clause can be used to provide names for computed columns or to provide alias names for columns
- * as required.
- *
- * Returns:
- * - false: if column aliasing is unsupported;
- * - true: if column aliasing is supported.
- */
- SQL_SUPPORTS_COLUMN_ALIASING = 515;
-
- /*
- * Retrieves a boolean value indicating whether concatenations between null and non-null values being
- * null are supported.
- *
- * - Returns:
- * - false: if concatenations between null and non-null values being null are unsupported;
- * - true: if concatenations between null and non-null values being null are supported.
- */
- SQL_NULL_PLUS_NULL_IS_NULL = 516;
-
- /*
- * Retrieves a map where the key is the type to convert from and the value is a list with the types to convert to,
- * indicating the supported conversions. Each key and each item on the list value is a value to a predefined type on
- * SqlSupportsConvert enum.
- * The returned map will be: map<int32, list<int32>>
- */
- SQL_SUPPORTS_CONVERT = 517;
-
- /*
- * Retrieves a boolean value indicating whether, when table correlation names are supported,
- * they are restricted to being different from the names of the tables.
- *
- * Returns:
- * - false: if table correlation names are unsupported;
- * - true: if table correlation names are supported.
- */
- SQL_SUPPORTS_TABLE_CORRELATION_NAMES = 518;
-
- /*
- * Retrieves a boolean value indicating whether, when table correlation names are supported,
- * they are restricted to being different from the names of the tables.
- *
- * Returns:
- * - false: if different table correlation names are unsupported;
- * - true: if different table correlation names are supported
- */
- SQL_SUPPORTS_DIFFERENT_TABLE_CORRELATION_NAMES = 519;
-
- /*
- * Retrieves a boolean value indicating whether expressions in ORDER BY lists are supported.
- *
- * Returns:
- * - false: if expressions in ORDER BY are unsupported;
- * - true: if expressions in ORDER BY are supported;
- */
- SQL_SUPPORTS_EXPRESSIONS_IN_ORDER_BY = 520;
-
- /*
- * Retrieves a boolean value indicating whether using a column that is not in the SELECT statement in a GROUP BY
- * clause is supported.
- *
- * Returns:
- * - false: if using a column that is not in the SELECT statement in a GROUP BY clause is unsupported;
- * - true: if using a column that is not in the SELECT statement in a GROUP BY clause is supported.
- */
- SQL_SUPPORTS_ORDER_BY_UNRELATED = 521;
-
- /*
- * Retrieves the supported GROUP BY commands;
- *
- * Returns an int32 bitmask value representing the supported commands.
- * The returned bitmask should be parsed in order to retrieve the supported commands.
- *
- * For instance:
- * - return 0 (\b0) => [] (GROUP BY is unsupported);
- * - return 1 (\b1) => [SQL_GROUP_BY_UNRELATED];
- * - return 2 (\b10) => [SQL_GROUP_BY_BEYOND_SELECT];
- * - return 3 (\b11) => [SQL_GROUP_BY_UNRELATED, SQL_GROUP_BY_BEYOND_SELECT].
- * Valid GROUP BY types are described under `arrow.flight.protocol.sql.SqlSupportedGroupBy`.
- */
- SQL_SUPPORTED_GROUP_BY = 522;
-
- /*
- * Retrieves a boolean value indicating whether specifying a LIKE escape clause is supported.
- *
- * Returns:
- * - false: if specifying a LIKE escape clause is unsupported;
- * - true: if specifying a LIKE escape clause is supported.
- */
- SQL_SUPPORTS_LIKE_ESCAPE_CLAUSE = 523;
-
- /*
- * Retrieves a boolean value indicating whether columns may be defined as non-nullable.
- *
- * Returns:
- * - false: if columns cannot be defined as non-nullable;
- * - true: if columns may be defined as non-nullable.
- */
- SQL_SUPPORTS_NON_NULLABLE_COLUMNS = 524;
-
- /*
- * Retrieves the supported SQL grammar level as per the ODBC specification.
- *
- * Returns an int32 bitmask value representing the supported SQL grammar level.
- * The returned bitmask should be parsed in order to retrieve the supported grammar levels.
- *
- * For instance:
- * - return 0 (\b0) => [] (SQL grammar is unsupported);
- * - return 1 (\b1) => [SQL_MINIMUM_GRAMMAR];
- * - return 2 (\b10) => [SQL_CORE_GRAMMAR];
- * - return 3 (\b11) => [SQL_MINIMUM_GRAMMAR, SQL_CORE_GRAMMAR];
- * - return 4 (\b100) => [SQL_EXTENDED_GRAMMAR];
- * - return 5 (\b101) => [SQL_MINIMUM_GRAMMAR, SQL_EXTENDED_GRAMMAR];
- * - return 6 (\b110) => [SQL_CORE_GRAMMAR, SQL_EXTENDED_GRAMMAR];
- * - return 7 (\b111) => [SQL_MINIMUM_GRAMMAR, SQL_CORE_GRAMMAR, SQL_EXTENDED_GRAMMAR].
- * Valid SQL grammar levels are described under `arrow.flight.protocol.sql.SupportedSqlGrammar`.
- */
- SQL_SUPPORTED_GRAMMAR = 525;
-
- /*
- * Retrieves the supported ANSI92 SQL grammar level.
- *
- * Returns an int32 bitmask value representing the supported ANSI92 SQL grammar level.
- * The returned bitmask should be parsed in order to retrieve the supported commands.
- *
- * For instance:
- * - return 0 (\b0) => [] (ANSI92 SQL grammar is unsupported);
- * - return 1 (\b1) => [ANSI92_ENTRY_SQL];
- * - return 2 (\b10) => [ANSI92_INTERMEDIATE_SQL];
- * - return 3 (\b11) => [ANSI92_ENTRY_SQL, ANSI92_INTERMEDIATE_SQL];
- * - return 4 (\b100) => [ANSI92_FULL_SQL];
- * - return 5 (\b101) => [ANSI92_ENTRY_SQL, ANSI92_FULL_SQL];
- * - return 6 (\b110) => [ANSI92_INTERMEDIATE_SQL, ANSI92_FULL_SQL];
- * - return 7 (\b111) => [ANSI92_ENTRY_SQL, ANSI92_INTERMEDIATE_SQL, ANSI92_FULL_SQL].
- * Valid ANSI92 SQL grammar levels are described under `arrow.flight.protocol.sql.SupportedAnsi92SqlGrammarLevel`.
- */
- SQL_ANSI92_SUPPORTED_LEVEL = 526;
-
- /*
- * Retrieves a boolean value indicating whether the SQL Integrity Enhancement Facility is supported.
- *
- * Returns:
- * - false: if the SQL Integrity Enhancement Facility is supported;
- * - true: if the SQL Integrity Enhancement Facility is supported.
- */
- SQL_SUPPORTS_INTEGRITY_ENHANCEMENT_FACILITY = 527;
-
- /*
- * Retrieves the support level for SQL OUTER JOINs.
- *
- * Returns a int32 ordinal for the SQL ordering being used, as described in
- * `arrow.flight.protocol.sql.SqlOuterJoinsSupportLevel`.
- */
- SQL_OUTER_JOINS_SUPPORT_LEVEL = 528;
-
- // Retrieves a UTF-8 string with the preferred term for "schema".
- SQL_SCHEMA_TERM = 529;
-
- // Retrieves a UTF-8 string with the preferred term for "procedure".
- SQL_PROCEDURE_TERM = 530;
-
- /*
- * Retrieves a UTF-8 string with the preferred term for "catalog".
- * If a empty string is returned its assumed that the server does NOT supports catalogs.
- */
- SQL_CATALOG_TERM = 531;
-
- /*
- * Retrieves a boolean value indicating whether a catalog appears at the start of a fully qualified table name.
- *
- * - false: if a catalog does not appear at the start of a fully qualified table name;
- * - true: if a catalog appears at the start of a fully qualified table name.
- */
- SQL_CATALOG_AT_START = 532;
-
- /*
- * Retrieves the supported actions for a SQL schema.
- *
- * Returns an int32 bitmask value representing the supported actions for a SQL schema.
- * The returned bitmask should be parsed in order to retrieve the supported actions for a SQL schema.
- *
- * For instance:
- * - return 0 (\b0) => [] (no supported actions for SQL schema);
- * - return 1 (\b1) => [SQL_ELEMENT_IN_PROCEDURE_CALLS];
- * - return 2 (\b10) => [SQL_ELEMENT_IN_INDEX_DEFINITIONS];
- * - return 3 (\b11) => [SQL_ELEMENT_IN_PROCEDURE_CALLS, SQL_ELEMENT_IN_INDEX_DEFINITIONS];
- * - return 4 (\b100) => [SQL_ELEMENT_IN_PRIVILEGE_DEFINITIONS];
- * - return 5 (\b101) => [SQL_ELEMENT_IN_PROCEDURE_CALLS, SQL_ELEMENT_IN_PRIVILEGE_DEFINITIONS];
- * - return 6 (\b110) => [SQL_ELEMENT_IN_INDEX_DEFINITIONS, SQL_ELEMENT_IN_PRIVILEGE_DEFINITIONS];
- * - return 7 (\b111) => [SQL_ELEMENT_IN_PROCEDURE_CALLS, SQL_ELEMENT_IN_INDEX_DEFINITIONS, SQL_ELEMENT_IN_PRIVILEGE_DEFINITIONS].
- * Valid actions for a SQL schema described under `arrow.flight.protocol.sql.SqlSupportedElementActions`.
- */
- SQL_SCHEMAS_SUPPORTED_ACTIONS = 533;
-
- /*
- * Retrieves the supported actions for a SQL schema.
- *
- * Returns an int32 bitmask value representing the supported actions for a SQL catalog.
- * The returned bitmask should be parsed in order to retrieve the supported actions for a SQL catalog.
- *
- * For instance:
- * - return 0 (\b0) => [] (no supported actions for SQL catalog);
- * - return 1 (\b1) => [SQL_ELEMENT_IN_PROCEDURE_CALLS];
- * - return 2 (\b10) => [SQL_ELEMENT_IN_INDEX_DEFINITIONS];
- * - return 3 (\b11) => [SQL_ELEMENT_IN_PROCEDURE_CALLS, SQL_ELEMENT_IN_INDEX_DEFINITIONS];
- * - return 4 (\b100) => [SQL_ELEMENT_IN_PRIVILEGE_DEFINITIONS];
- * - return 5 (\b101) => [SQL_ELEMENT_IN_PROCEDURE_CALLS, SQL_ELEMENT_IN_PRIVILEGE_DEFINITIONS];
- * - return 6 (\b110) => [SQL_ELEMENT_IN_INDEX_DEFINITIONS, SQL_ELEMENT_IN_PRIVILEGE_DEFINITIONS];
- * - return 7 (\b111) => [SQL_ELEMENT_IN_PROCEDURE_CALLS, SQL_ELEMENT_IN_INDEX_DEFINITIONS, SQL_ELEMENT_IN_PRIVILEGE_DEFINITIONS].
- * Valid actions for a SQL catalog are described under `arrow.flight.protocol.sql.SqlSupportedElementActions`.
- */
- SQL_CATALOGS_SUPPORTED_ACTIONS = 534;
-
- /*
- * Retrieves the supported SQL positioned commands.
- *
- * Returns an int32 bitmask value representing the supported SQL positioned commands.
- * The returned bitmask should be parsed in order to retrieve the supported SQL positioned commands.
- *
- * For instance:
- * - return 0 (\b0) => [] (no supported SQL positioned commands);
- * - return 1 (\b1) => [SQL_POSITIONED_DELETE];
- * - return 2 (\b10) => [SQL_POSITIONED_UPDATE];
- * - return 3 (\b11) => [SQL_POSITIONED_DELETE, SQL_POSITIONED_UPDATE].
- * Valid SQL positioned commands are described under `arrow.flight.protocol.sql.SqlSupportedPositionedCommands`.
- */
- SQL_SUPPORTED_POSITIONED_COMMANDS = 535;
-
- /*
- * Retrieves a boolean value indicating whether SELECT FOR UPDATE statements are supported.
- *
- * Returns:
- * - false: if SELECT FOR UPDATE statements are unsupported;
- * - true: if SELECT FOR UPDATE statements are supported.
- */
- SQL_SELECT_FOR_UPDATE_SUPPORTED = 536;
-
- /*
- * Retrieves a boolean value indicating whether stored procedure calls that use the stored procedure escape syntax
- * are supported.
- *
- * Returns:
- * - false: if stored procedure calls that use the stored procedure escape syntax are unsupported;
- * - true: if stored procedure calls that use the stored procedure escape syntax are supported.
- */
- SQL_STORED_PROCEDURES_SUPPORTED = 537;
-
- /*
- * Retrieves the supported SQL subqueries.
- *
- * Returns an int32 bitmask value representing the supported SQL subqueries.
- * The returned bitmask should be parsed in order to retrieve the supported SQL subqueries.
- *
- * For instance:
- * - return 0 (\b0) => [] (no supported SQL subqueries);
- * - return 1 (\b1) => [SQL_SUBQUERIES_IN_COMPARISONS];
- * - return 2 (\b10) => [SQL_SUBQUERIES_IN_EXISTS];
- * - return 3 (\b11) => [SQL_SUBQUERIES_IN_COMPARISONS, SQL_SUBQUERIES_IN_EXISTS];
- * - return 4 (\b100) => [SQL_SUBQUERIES_IN_INS];
- * - return 5 (\b101) => [SQL_SUBQUERIES_IN_COMPARISONS, SQL_SUBQUERIES_IN_INS];
- * - return 6 (\b110) => [SQL_SUBQUERIES_IN_INS, SQL_SUBQUERIES_IN_EXISTS];
- * - return 7 (\b111) => [SQL_SUBQUERIES_IN_COMPARISONS, SQL_SUBQUERIES_IN_EXISTS, SQL_SUBQUERIES_IN_INS];
- * - return 8 (\b1000) => [SQL_SUBQUERIES_IN_QUANTIFIEDS];
- * - return 9 (\b1001) => [SQL_SUBQUERIES_IN_COMPARISONS, SQL_SUBQUERIES_IN_QUANTIFIEDS];
- * - return 10 (\b1010) => [SQL_SUBQUERIES_IN_EXISTS, SQL_SUBQUERIES_IN_QUANTIFIEDS];
- * - return 11 (\b1011) => [SQL_SUBQUERIES_IN_COMPARISONS, SQL_SUBQUERIES_IN_EXISTS, SQL_SUBQUERIES_IN_QUANTIFIEDS];
- * - return 12 (\b1100) => [SQL_SUBQUERIES_IN_INS, SQL_SUBQUERIES_IN_QUANTIFIEDS];
- * - return 13 (\b1101) => [SQL_SUBQUERIES_IN_COMPARISONS, SQL_SUBQUERIES_IN_INS, SQL_SUBQUERIES_IN_QUANTIFIEDS];
- * - return 14 (\b1110) => [SQL_SUBQUERIES_IN_EXISTS, SQL_SUBQUERIES_IN_INS, SQL_SUBQUERIES_IN_QUANTIFIEDS];
- * - return 15 (\b1111) => [SQL_SUBQUERIES_IN_COMPARISONS, SQL_SUBQUERIES_IN_EXISTS, SQL_SUBQUERIES_IN_INS, SQL_SUBQUERIES_IN_QUANTIFIEDS];
- * - ...
- * Valid SQL subqueries are described under `arrow.flight.protocol.sql.SqlSupportedSubqueries`.
- */
- SQL_SUPPORTED_SUBQUERIES = 538;
-
- /*
- * Retrieves a boolean value indicating whether correlated subqueries are supported.
- *
- * Returns:
- * - false: if correlated subqueries are unsupported;
- * - true: if correlated subqueries are supported.
- */
- SQL_CORRELATED_SUBQUERIES_SUPPORTED = 539;
-
- /*
- * Retrieves the supported SQL UNIONs.
- *
- * Returns an int32 bitmask value representing the supported SQL UNIONs.
- * The returned bitmask should be parsed in order to retrieve the supported SQL UNIONs.
- *
- * For instance:
- * - return 0 (\b0) => [] (no supported SQL positioned commands);
- * - return 1 (\b1) => [SQL_UNION];
- * - return 2 (\b10) => [SQL_UNION_ALL];
- * - return 3 (\b11) => [SQL_UNION, SQL_UNION_ALL].
- * Valid SQL positioned commands are described under `arrow.flight.protocol.sql.SqlSupportedUnions`.
- */
- SQL_SUPPORTED_UNIONS = 540;
-
- // Retrieves a int64 value representing the maximum number of hex characters allowed in an inline binary literal.
- SQL_MAX_BINARY_LITERAL_LENGTH = 541;
-
- // Retrieves a int64 value representing the maximum number of characters allowed for a character literal.
- SQL_MAX_CHAR_LITERAL_LENGTH = 542;
-
- // Retrieves a int64 value representing the maximum number of characters allowed for a column name.
- SQL_MAX_COLUMN_NAME_LENGTH = 543;
-
- // Retrieves a int64 value representing the the maximum number of columns allowed in a GROUP BY clause.
- SQL_MAX_COLUMNS_IN_GROUP_BY = 544;
-
- // Retrieves a int64 value representing the maximum number of columns allowed in an index.
- SQL_MAX_COLUMNS_IN_INDEX = 545;
-
- // Retrieves a int64 value representing the maximum number of columns allowed in an ORDER BY clause.
- SQL_MAX_COLUMNS_IN_ORDER_BY = 546;
-
- // Retrieves a int64 value representing the maximum number of columns allowed in a SELECT list.
- SQL_MAX_COLUMNS_IN_SELECT = 547;
-
- // Retrieves a int64 value representing the maximum number of columns allowed in a table.
- SQL_MAX_COLUMNS_IN_TABLE = 548;
-
- // Retrieves a int64 value representing the maximum number of concurrent connections possible.
- SQL_MAX_CONNECTIONS = 549;
-
- // Retrieves a int64 value the maximum number of characters allowed in a cursor name.
- SQL_MAX_CURSOR_NAME_LENGTH = 550;
-
- /*
- * Retrieves a int64 value representing the maximum number of bytes allowed for an index,
- * including all of the parts of the index.
- */
- SQL_MAX_INDEX_LENGTH = 551;
-
- // Retrieves a int64 value representing the maximum number of characters allowed in a schema name.
- SQL_DB_SCHEMA_NAME_LENGTH = 552;
-
- // Retrieves a int64 value representing the maximum number of characters allowed in a procedure name.
- SQL_MAX_PROCEDURE_NAME_LENGTH = 553;
-
- // Retrieves a int64 value representing the maximum number of characters allowed in a catalog name.
- SQL_MAX_CATALOG_NAME_LENGTH = 554;
-
- // Retrieves a int64 value representing the maximum number of bytes allowed in a single row.
- SQL_MAX_ROW_SIZE = 555;
-
- /*
- * Retrieves a boolean indicating whether the return value for the JDBC method getMaxRowSize includes the SQL
- * data types LONGVARCHAR and LONGVARBINARY.
- *
- * Returns:
- * - false: if return value for the JDBC method getMaxRowSize does
- * not include the SQL data types LONGVARCHAR and LONGVARBINARY;
- * - true: if return value for the JDBC method getMaxRowSize includes
- * the SQL data types LONGVARCHAR and LONGVARBINARY.
- */
- SQL_MAX_ROW_SIZE_INCLUDES_BLOBS = 556;
-
- /*
- * Retrieves a int64 value representing the maximum number of characters allowed for an SQL statement;
- * a result of 0 (zero) means that there is no limit or the limit is not known.
- */
- SQL_MAX_STATEMENT_LENGTH = 557;
-
- // Retrieves a int64 value representing the maximum number of active statements that can be open at the same time.
- SQL_MAX_STATEMENTS = 558;
-
- // Retrieves a int64 value representing the maximum number of characters allowed in a table name.
- SQL_MAX_TABLE_NAME_LENGTH = 559;
-
- // Retrieves a int64 value representing the maximum number of tables allowed in a SELECT statement.
- SQL_MAX_TABLES_IN_SELECT = 560;
-
- // Retrieves a int64 value representing the maximum number of characters allowed in a user name.
- SQL_MAX_USERNAME_LENGTH = 561;
-
- /*
- * Retrieves this database's default transaction isolation level as described in
- * `arrow.flight.protocol.sql.SqlTransactionIsolationLevel`.
- *
- * Returns a int32 ordinal for the SQL transaction isolation level.
- */
- SQL_DEFAULT_TRANSACTION_ISOLATION = 562;
-
- /*
- * Retrieves a boolean value indicating whether transactions are supported. If not, invoking the method commit is a
- * noop, and the isolation level is `arrow.flight.protocol.sql.SqlTransactionIsolationLevel.TRANSACTION_NONE`.
- *
- * Returns:
- * - false: if transactions are unsupported;
- * - true: if transactions are supported.
- */
- SQL_TRANSACTIONS_SUPPORTED = 563;
-
- /*
- * Retrieves the supported transactions isolation levels.
- *
- * Returns an int32 bitmask value representing the supported transactions isolation levels.
- * The returned bitmask should be parsed in order to retrieve the supported transactions isolation levels.
- *
- * For instance:
- * - return 0 (\b0) => [] (no supported SQL transactions isolation levels);
- * - return 1 (\b1) => [SQL_TRANSACTION_NONE];
- * - return 2 (\b10) => [SQL_TRANSACTION_READ_UNCOMMITTED];
- * - return 3 (\b11) => [SQL_TRANSACTION_NONE, SQL_TRANSACTION_READ_UNCOMMITTED];
- * - return 4 (\b100) => [SQL_TRANSACTION_REPEATABLE_READ];
- * - return 5 (\b101) => [SQL_TRANSACTION_NONE, SQL_TRANSACTION_REPEATABLE_READ];
- * - return 6 (\b110) => [SQL_TRANSACTION_READ_UNCOMMITTED, SQL_TRANSACTION_REPEATABLE_READ];
- * - return 7 (\b111) => [SQL_TRANSACTION_NONE, SQL_TRANSACTION_READ_UNCOMMITTED, SQL_TRANSACTION_REPEATABLE_READ];
- * - return 8 (\b1000) => [SQL_TRANSACTION_REPEATABLE_READ];
- * - return 9 (\b1001) => [SQL_TRANSACTION_NONE, SQL_TRANSACTION_REPEATABLE_READ];
- * - return 10 (\b1010) => [SQL_TRANSACTION_READ_UNCOMMITTED, SQL_TRANSACTION_REPEATABLE_READ];
- * - return 11 (\b1011) => [SQL_TRANSACTION_NONE, SQL_TRANSACTION_READ_UNCOMMITTED, SQL_TRANSACTION_REPEATABLE_READ];
- * - return 12 (\b1100) => [SQL_TRANSACTION_REPEATABLE_READ, SQL_TRANSACTION_REPEATABLE_READ];
- * - return 13 (\b1101) => [SQL_TRANSACTION_NONE, SQL_TRANSACTION_REPEATABLE_READ, SQL_TRANSACTION_REPEATABLE_READ];
- * - return 14 (\b1110) => [SQL_TRANSACTION_READ_UNCOMMITTED, SQL_TRANSACTION_REPEATABLE_READ, SQL_TRANSACTION_REPEATABLE_READ];
- * - return 15 (\b1111) => [SQL_TRANSACTION_NONE, SQL_TRANSACTION_READ_UNCOMMITTED, SQL_TRANSACTION_REPEATABLE_READ, SQL_TRANSACTION_REPEATABLE_READ];
- * - return 16 (\b10000) => [SQL_TRANSACTION_SERIALIZABLE];
- * - ...
- * Valid SQL positioned commands are described under `arrow.flight.protocol.sql.SqlTransactionIsolationLevel`.
- */
- SQL_SUPPORTED_TRANSACTIONS_ISOLATION_LEVELS = 564;
-
- /*
- * Retrieves a boolean value indicating whether a data definition statement within a transaction forces
- * the transaction to commit.
- *
- * Returns:
- * - false: if a data definition statement within a transaction does not force the transaction to commit;
- * - true: if a data definition statement within a transaction forces the transaction to commit.
- */
- SQL_DATA_DEFINITION_CAUSES_TRANSACTION_COMMIT = 565;
-
- /*
- * Retrieves a boolean value indicating whether a data definition statement within a transaction is ignored.
- *
- * Returns:
- * - false: if a data definition statement within a transaction is taken into account;
- * - true: a data definition statement within a transaction is ignored.
- */
- SQL_DATA_DEFINITIONS_IN_TRANSACTIONS_IGNORED = 566;
-
- /*
- * Retrieves an int32 bitmask value representing the supported result set types.
- * The returned bitmask should be parsed in order to retrieve the supported result set types.
- *
- * For instance:
- * - return 0 (\b0) => [] (no supported result set types);
- * - return 1 (\b1) => [SQL_RESULT_SET_TYPE_UNSPECIFIED];
- * - return 2 (\b10) => [SQL_RESULT_SET_TYPE_FORWARD_ONLY];
- * - return 3 (\b11) => [SQL_RESULT_SET_TYPE_UNSPECIFIED, SQL_RESULT_SET_TYPE_FORWARD_ONLY];
- * - return 4 (\b100) => [SQL_RESULT_SET_TYPE_SCROLL_INSENSITIVE];
- * - return 5 (\b101) => [SQL_RESULT_SET_TYPE_UNSPECIFIED, SQL_RESULT_SET_TYPE_SCROLL_INSENSITIVE];
- * - return 6 (\b110) => [SQL_RESULT_SET_TYPE_FORWARD_ONLY, SQL_RESULT_SET_TYPE_SCROLL_INSENSITIVE];
- * - return 7 (\b111) => [SQL_RESULT_SET_TYPE_UNSPECIFIED, SQL_RESULT_SET_TYPE_FORWARD_ONLY, SQL_RESULT_SET_TYPE_SCROLL_INSENSITIVE];
- * - return 8 (\b1000) => [SQL_RESULT_SET_TYPE_SCROLL_SENSITIVE];
- * - ...
- * Valid result set types are described under `arrow.flight.protocol.sql.SqlSupportedResultSetType`.
- */
- SQL_SUPPORTED_RESULT_SET_TYPES = 567;
-
- /*
- * Returns an int32 bitmask value concurrency types supported for
- * `arrow.flight.protocol.sql.SqlSupportedResultSetType.SQL_RESULT_SET_TYPE_UNSPECIFIED`.
- *
- * For instance:
- * - return 0 (\b0) => [] (no supported concurrency types for this result set type)
- * - return 1 (\b1) => [SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED]
- * - return 2 (\b10) => [SQL_RESULT_SET_CONCURRENCY_READ_ONLY]
- * - return 3 (\b11) => [SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED, SQL_RESULT_SET_CONCURRENCY_READ_ONLY]
- * - return 4 (\b100) => [SQL_RESULT_SET_CONCURRENCY_UPDATABLE]
- * - return 5 (\b101) => [SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED, SQL_RESULT_SET_CONCURRENCY_UPDATABLE]
- * - return 6 (\b110) => [SQL_RESULT_SET_CONCURRENCY_READ_ONLY, SQL_RESULT_SET_CONCURRENCY_UPDATABLE]
- * - return 7 (\b111) => [SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED, SQL_RESULT_SET_CONCURRENCY_READ_ONLY, SQL_RESULT_SET_CONCURRENCY_UPDATABLE]
- * Valid result set types are described under `arrow.flight.protocol.sql.SqlSupportedResultSetConcurrency`.
- */
- SQL_SUPPORTED_CONCURRENCIES_FOR_RESULT_SET_UNSPECIFIED = 568;
-
- /*
- * Returns an int32 bitmask value concurrency types supported for
- * `arrow.flight.protocol.sql.SqlSupportedResultSetType.SQL_RESULT_SET_TYPE_FORWARD_ONLY`.
- *
- * For instance:
- * - return 0 (\b0) => [] (no supported concurrency types for this result set type)
- * - return 1 (\b1) => [SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED]
- * - return 2 (\b10) => [SQL_RESULT_SET_CONCURRENCY_READ_ONLY]
- * - return 3 (\b11) => [SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED, SQL_RESULT_SET_CONCURRENCY_READ_ONLY]
- * - return 4 (\b100) => [SQL_RESULT_SET_CONCURRENCY_UPDATABLE]
- * - return 5 (\b101) => [SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED, SQL_RESULT_SET_CONCURRENCY_UPDATABLE]
- * - return 6 (\b110) => [SQL_RESULT_SET_CONCURRENCY_READ_ONLY, SQL_RESULT_SET_CONCURRENCY_UPDATABLE]
- * - return 7 (\b111) => [SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED, SQL_RESULT_SET_CONCURRENCY_READ_ONLY, SQL_RESULT_SET_CONCURRENCY_UPDATABLE]
- * Valid result set types are described under `arrow.flight.protocol.sql.SqlSupportedResultSetConcurrency`.
- */
- SQL_SUPPORTED_CONCURRENCIES_FOR_RESULT_SET_FORWARD_ONLY = 569;
-
- /*
- * Returns an int32 bitmask value concurrency types supported for
- * `arrow.flight.protocol.sql.SqlSupportedResultSetType.SQL_RESULT_SET_TYPE_SCROLL_SENSITIVE`.
- *
- * For instance:
- * - return 0 (\b0) => [] (no supported concurrency types for this result set type)
- * - return 1 (\b1) => [SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED]
- * - return 2 (\b10) => [SQL_RESULT_SET_CONCURRENCY_READ_ONLY]
- * - return 3 (\b11) => [SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED, SQL_RESULT_SET_CONCURRENCY_READ_ONLY]
- * - return 4 (\b100) => [SQL_RESULT_SET_CONCURRENCY_UPDATABLE]
- * - return 5 (\b101) => [SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED, SQL_RESULT_SET_CONCURRENCY_UPDATABLE]
- * - return 6 (\b110) => [SQL_RESULT_SET_CONCURRENCY_READ_ONLY, SQL_RESULT_SET_CONCURRENCY_UPDATABLE]
- * - return 7 (\b111) => [SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED, SQL_RESULT_SET_CONCURRENCY_READ_ONLY, SQL_RESULT_SET_CONCURRENCY_UPDATABLE]
- * Valid result set types are described under `arrow.flight.protocol.sql.SqlSupportedResultSetConcurrency`.
- */
- SQL_SUPPORTED_CONCURRENCIES_FOR_RESULT_SET_SCROLL_SENSITIVE = 570;
-
- /*
- * Returns an int32 bitmask value concurrency types supported for
- * `arrow.flight.protocol.sql.SqlSupportedResultSetType.SQL_RESULT_SET_TYPE_SCROLL_INSENSITIVE`.
- *
- * For instance:
- * - return 0 (\b0) => [] (no supported concurrency types for this result set type)
- * - return 1 (\b1) => [SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED]
- * - return 2 (\b10) => [SQL_RESULT_SET_CONCURRENCY_READ_ONLY]
- * - return 3 (\b11) => [SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED, SQL_RESULT_SET_CONCURRENCY_READ_ONLY]
- * - return 4 (\b100) => [SQL_RESULT_SET_CONCURRENCY_UPDATABLE]
- * - return 5 (\b101) => [SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED, SQL_RESULT_SET_CONCURRENCY_UPDATABLE]
- * - return 6 (\b110) => [SQL_RESULT_SET_CONCURRENCY_READ_ONLY, SQL_RESULT_SET_CONCURRENCY_UPDATABLE]
- * - return 7 (\b111) => [SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED, SQL_RESULT_SET_CONCURRENCY_READ_ONLY, SQL_RESULT_SET_CONCURRENCY_UPDATABLE]
- * Valid result set types are described under `arrow.flight.protocol.sql.SqlSupportedResultSetConcurrency`.
- */
- SQL_SUPPORTED_CONCURRENCIES_FOR_RESULT_SET_SCROLL_INSENSITIVE = 571;
-
- /*
- * Retrieves a boolean value indicating whether this database supports batch updates.
- *
- * - false: if this database does not support batch updates;
- * - true: if this database supports batch updates.
- */
- SQL_BATCH_UPDATES_SUPPORTED = 572;
-
- /*
- * Retrieves a boolean value indicating whether this database supports savepoints.
- *
- * Returns:
- * - false: if this database does not support savepoints;
- * - true: if this database supports savepoints.
- */
- SQL_SAVEPOINTS_SUPPORTED = 573;
-
- /*
- * Retrieves a boolean value indicating whether named parameters are supported in callable statements.
- *
- * Returns:
- * - false: if named parameters in callable statements are unsupported;
- * - true: if named parameters in callable statements are supported.
- */
- SQL_NAMED_PARAMETERS_SUPPORTED = 574;
-
- /*
- * Retrieves a boolean value indicating whether updates made to a LOB are made on a copy or directly to the LOB.
- *
- * Returns:
- * - false: if updates made to a LOB are made directly to the LOB;
- * - true: if updates made to a LOB are made on a copy.
- */
- SQL_LOCATORS_UPDATE_COPY = 575;
-
- /*
- * Retrieves a boolean value indicating whether invoking user-defined or vendor functions
- * using the stored procedure escape syntax is supported.
- *
- * Returns:
- * - false: if invoking user-defined or vendor functions using the stored procedure escape syntax is unsupported;
- * - true: if invoking user-defined or vendor functions using the stored procedure escape syntax is supported.
- */
- SQL_STORED_FUNCTIONS_USING_CALL_SYNTAX_SUPPORTED = 576;
-}
-
-enum SqlSupportedCaseSensitivity {
- SQL_CASE_SENSITIVITY_UNKNOWN = 0;
- SQL_CASE_SENSITIVITY_CASE_INSENSITIVE = 1;
- SQL_CASE_SENSITIVITY_UPPERCASE = 2;
- SQL_CASE_SENSITIVITY_LOWERCASE = 3;
-}
-
-enum SqlNullOrdering {
- SQL_NULLS_SORTED_HIGH = 0;
- SQL_NULLS_SORTED_LOW = 1;
- SQL_NULLS_SORTED_AT_START = 2;
- SQL_NULLS_SORTED_AT_END = 3;
-}
-
-enum SupportedSqlGrammar {
- SQL_MINIMUM_GRAMMAR = 0;
- SQL_CORE_GRAMMAR = 1;
- SQL_EXTENDED_GRAMMAR = 2;
-}
-
-enum SupportedAnsi92SqlGrammarLevel {
- ANSI92_ENTRY_SQL = 0;
- ANSI92_INTERMEDIATE_SQL = 1;
- ANSI92_FULL_SQL = 2;
-}
-
-enum SqlOuterJoinsSupportLevel {
- SQL_JOINS_UNSUPPORTED = 0;
- SQL_LIMITED_OUTER_JOINS = 1;
- SQL_FULL_OUTER_JOINS = 2;
-}
-
-enum SqlSupportedGroupBy {
- SQL_GROUP_BY_UNRELATED = 0;
- SQL_GROUP_BY_BEYOND_SELECT = 1;
-}
-
-enum SqlSupportedElementActions {
- SQL_ELEMENT_IN_PROCEDURE_CALLS = 0;
- SQL_ELEMENT_IN_INDEX_DEFINITIONS = 1;
- SQL_ELEMENT_IN_PRIVILEGE_DEFINITIONS = 2;
-}
-
-enum SqlSupportedPositionedCommands {
- SQL_POSITIONED_DELETE = 0;
- SQL_POSITIONED_UPDATE = 1;
-}
-
-enum SqlSupportedSubqueries {
- SQL_SUBQUERIES_IN_COMPARISONS = 0;
- SQL_SUBQUERIES_IN_EXISTS = 1;
- SQL_SUBQUERIES_IN_INS = 2;
- SQL_SUBQUERIES_IN_QUANTIFIEDS = 3;
-}
-
-enum SqlSupportedUnions {
- SQL_UNION = 0;
- SQL_UNION_ALL = 1;
-}
-
-enum SqlTransactionIsolationLevel {
- SQL_TRANSACTION_NONE = 0;
- SQL_TRANSACTION_READ_UNCOMMITTED = 1;
- SQL_TRANSACTION_READ_COMMITTED = 2;
- SQL_TRANSACTION_REPEATABLE_READ = 3;
- SQL_TRANSACTION_SERIALIZABLE = 4;
-}
-
-enum SqlSupportedTransactions {
- SQL_TRANSACTION_UNSPECIFIED = 0;
- SQL_DATA_DEFINITION_TRANSACTIONS = 1;
- SQL_DATA_MANIPULATION_TRANSACTIONS = 2;
-}
-
-enum SqlSupportedResultSetType {
- SQL_RESULT_SET_TYPE_UNSPECIFIED = 0;
- SQL_RESULT_SET_TYPE_FORWARD_ONLY = 1;
- SQL_RESULT_SET_TYPE_SCROLL_INSENSITIVE = 2;
- SQL_RESULT_SET_TYPE_SCROLL_SENSITIVE = 3;
-}
-
-enum SqlSupportedResultSetConcurrency {
- SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED = 0;
- SQL_RESULT_SET_CONCURRENCY_READ_ONLY = 1;
- SQL_RESULT_SET_CONCURRENCY_UPDATABLE = 2;
-}
-
-enum SqlSupportsConvert {
- SQL_CONVERT_BIGINT = 0;
- SQL_CONVERT_BINARY = 1;
- SQL_CONVERT_BIT = 2;
- SQL_CONVERT_CHAR = 3;
- SQL_CONVERT_DATE = 4;
- SQL_CONVERT_DECIMAL = 5;
- SQL_CONVERT_FLOAT = 6;
- SQL_CONVERT_INTEGER = 7;
- SQL_CONVERT_INTERVAL_DAY_TIME = 8;
- SQL_CONVERT_INTERVAL_YEAR_MONTH = 9;
- SQL_CONVERT_LONGVARBINARY = 10;
- SQL_CONVERT_LONGVARCHAR = 11;
- SQL_CONVERT_NUMERIC = 12;
- SQL_CONVERT_REAL = 13;
- SQL_CONVERT_SMALLINT = 14;
- SQL_CONVERT_TIME = 15;
- SQL_CONVERT_TIMESTAMP = 16;
- SQL_CONVERT_TINYINT = 17;
- SQL_CONVERT_VARBINARY = 18;
- SQL_CONVERT_VARCHAR = 19;
-}
-
-/**
- * The JDBC/ODBC-defined type of any object.
- * All the values here are the sames as in the JDBC and ODBC specs.
- */
-enum XdbcDataType {
- XDBC_UNKNOWN_TYPE = 0;
- XDBC_CHAR = 1;
- XDBC_NUMERIC = 2;
- XDBC_DECIMAL = 3;
- XDBC_INTEGER = 4;
- XDBC_SMALLINT = 5;
- XDBC_FLOAT = 6;
- XDBC_REAL = 7;
- XDBC_DOUBLE = 8;
- XDBC_DATETIME = 9;
- XDBC_INTERVAL = 10;
- XDBC_VARCHAR = 12;
- XDBC_DATE = 91;
- XDBC_TIME = 92;
- XDBC_TIMESTAMP = 93;
- XDBC_LONGVARCHAR = -1;
- XDBC_BINARY = -2;
- XDBC_VARBINARY = -3;
- XDBC_LONGVARBINARY = -4;
- XDBC_BIGINT = -5;
- XDBC_TINYINT = -6;
- XDBC_BIT = -7;
- XDBC_WCHAR = -8;
- XDBC_WVARCHAR = -9;
-}
-
-/**
- * Detailed subtype information for XDBC_TYPE_DATETIME and XDBC_TYPE_INTERVAL.
- */
-enum XdbcDatetimeSubcode {
- option allow_alias = true;
- XDBC_SUBCODE_UNKNOWN = 0;
- XDBC_SUBCODE_YEAR = 1;
- XDBC_SUBCODE_DATE = 1;
- XDBC_SUBCODE_TIME = 2;
- XDBC_SUBCODE_MONTH = 2;
- XDBC_SUBCODE_TIMESTAMP = 3;
- XDBC_SUBCODE_DAY = 3;
- XDBC_SUBCODE_TIME_WITH_TIMEZONE = 4;
- XDBC_SUBCODE_HOUR = 4;
- XDBC_SUBCODE_TIMESTAMP_WITH_TIMEZONE = 5;
- XDBC_SUBCODE_MINUTE = 5;
- XDBC_SUBCODE_SECOND = 6;
- XDBC_SUBCODE_YEAR_TO_MONTH = 7;
- XDBC_SUBCODE_DAY_TO_HOUR = 8;
- XDBC_SUBCODE_DAY_TO_MINUTE = 9;
- XDBC_SUBCODE_DAY_TO_SECOND = 10;
- XDBC_SUBCODE_HOUR_TO_MINUTE = 11;
- XDBC_SUBCODE_HOUR_TO_SECOND = 12;
- XDBC_SUBCODE_MINUTE_TO_SECOND = 13;
- XDBC_SUBCODE_INTERVAL_YEAR = 101;
- XDBC_SUBCODE_INTERVAL_MONTH = 102;
- XDBC_SUBCODE_INTERVAL_DAY = 103;
- XDBC_SUBCODE_INTERVAL_HOUR = 104;
- XDBC_SUBCODE_INTERVAL_MINUTE = 105;
- XDBC_SUBCODE_INTERVAL_SECOND = 106;
- XDBC_SUBCODE_INTERVAL_YEAR_TO_MONTH = 107;
- XDBC_SUBCODE_INTERVAL_DAY_TO_HOUR = 108;
- XDBC_SUBCODE_INTERVAL_DAY_TO_MINUTE = 109;
- XDBC_SUBCODE_INTERVAL_DAY_TO_SECOND = 110;
- XDBC_SUBCODE_INTERVAL_HOUR_TO_MINUTE = 111;
- XDBC_SUBCODE_INTERVAL_HOUR_TO_SECOND = 112;
- XDBC_SUBCODE_INTERVAL_MINUTE_TO_SECOND = 113;
-}
-
-enum Nullable {
- /**
- * Indicates that the fields does not allow the use of null values.
- */
- NULLABILITY_NO_NULLS = 0;
-
- /**
- * Indicates that the fields allow the use of null values.
- */
- NULLABILITY_NULLABLE = 1;
-
- /**
- * Indicates that nullability of the fields can not be determined.
- */
- NULLABILITY_UNKNOWN = 2;
-}
-
-enum Searchable {
- /**
- * Indicates that column can not be used in a WHERE clause.
- */
- SEARCHABLE_NONE = 0;
-
- /**
- * Indicates that the column can be used in a WHERE clause if it is using a
- * LIKE operator.
- */
- SEARCHABLE_CHAR = 1;
-
- /**
- * Indicates that the column can be used In a WHERE clause with any
- * operator other than LIKE.
- *
- * - Allowed operators: comparison, quantified comparison, BETWEEN,
- * DISTINCT, IN, MATCH, and UNIQUE.
- */
- SEARCHABLE_BASIC = 2;
-
- /**
- * Indicates that the column can be used in a WHERE clause using any operator.
- */
- SEARCHABLE_FULL = 3;
-}
-
-/*
- * Represents a request to retrieve information about data type supported on a Flight SQL enabled backend.
- * Used in the command member of FlightDescriptor for the following RPC calls:
- * - GetSchema: return the schema of the query.
- * - GetFlightInfo: execute the catalog metadata request.
- *
- * The returned schema will be:
- * <
- * type_name: utf8 not null (The name of the data type, for example: VARCHAR, INTEGER, etc),
- * data_type: int not null (The SQL data type),
- * column_size: int (The maximum size supported by that column.
- * In case of exact numeric types, this represents the maximum precision.
- * In case of string types, this represents the character length.
- * In case of datetime data types, this represents the length in characters of the string representation.
- * NULL is returned for data types where column size is not applicable.),
- * literal_prefix: utf8 (Character or characters used to prefix a literal, NULL is returned for
- * data types where a literal prefix is not applicable.),
- * literal_suffix: utf8 (Character or characters used to terminate a literal,
- * NULL is returned for data types where a literal suffix is not applicable.),
- * create_params: list<utf8 not null>
- * (A list of keywords corresponding to which parameters can be used when creating
- * a column for that specific type.
- * NULL is returned if there are no parameters for the data type definition.),
- * nullable: int not null (Shows if the data type accepts a NULL value. The possible values can be seen in the
- * Nullable enum.),
- * case_sensitive: bool not null (Shows if a character data type is case-sensitive in collations and comparisons),
- * searchable: int not null (Shows how the data type is used in a WHERE clause. The possible values can be seen in the
- * Searchable enum.),
- * unsigned_attribute: bool (Shows if the data type is unsigned. NULL is returned if the attribute is
- * not applicable to the data type or the data type is not numeric.),
- * fixed_prec_scale: bool not null (Shows if the data type has predefined fixed precision and scale.),
- * auto_increment: bool (Shows if the data type is auto incremental. NULL is returned if the attribute
- * is not applicable to the data type or the data type is not numeric.),
- * local_type_name: utf8 (Localized version of the data source-dependent name of the data type. NULL
- * is returned if a localized name is not supported by the data source),
- * minimum_scale: int (The minimum scale of the data type on the data source.
- * If a data type has a fixed scale, the MINIMUM_SCALE and MAXIMUM_SCALE
- * columns both contain this value. NULL is returned if scale is not applicable.),
- * maximum_scale: int (The maximum scale of the data type on the data source.
- * NULL is returned if scale is not applicable.),
- * sql_data_type: int not null (The value of the SQL DATA TYPE which has the same values
- * as data_type value. Except for interval and datetime, which
- * uses generic values. More info about those types can be
- * obtained through datetime_subcode. The possible values can be seen
- * in the XdbcDataType enum.),
- * datetime_subcode: int (Only used when the SQL DATA TYPE is interval or datetime. It contains
- * its sub types. For type different from interval and datetime, this value
- * is NULL. The possible values can be seen in the XdbcDatetimeSubcode enum.),
- * num_prec_radix: int (If the data type is an approximate numeric type, this column contains
- * the value 2 to indicate that COLUMN_SIZE specifies a number of bits. For
- * exact numeric types, this column contains the value 10 to indicate that
- * column size specifies a number of decimal digits. Otherwise, this column is NULL.),
- * interval_precision: int (If the data type is an interval data type, then this column contains the value
- * of the interval leading precision. Otherwise, this column is NULL. This fields
- * is only relevant to be used by ODBC).
- * >
- * The returned data should be ordered by data_type and then by type_name.
- */
-message CommandGetXdbcTypeInfo {
- option (experimental) = true;
-
- /*
- * Specifies the data type to search for the info.
- */
- optional int32 data_type = 1;
-}
-
-/*
- * Represents a request to retrieve the list of catalogs on a Flight SQL enabled backend.
- * The definition of a catalog depends on vendor/implementation. It is usually the database itself
- * Used in the command member of FlightDescriptor for the following RPC calls:
- * - GetSchema: return the Arrow schema of the query.
- * - GetFlightInfo: execute the catalog metadata request.
- *
- * The returned Arrow schema will be:
- * <
- * catalog_name: utf8 not null
- * >
- * The returned data should be ordered by catalog_name.
- */
-message CommandGetCatalogs {
- option (experimental) = true;
-}
-
-/*
- * Represents a request to retrieve the list of database schemas on a Flight SQL enabled backend.
- * The definition of a database schema depends on vendor/implementation. It is usually a collection of tables.
- * Used in the command member of FlightDescriptor for the following RPC calls:
- * - GetSchema: return the Arrow schema of the query.
- * - GetFlightInfo: execute the catalog metadata request.
- *
- * The returned Arrow schema will be:
- * <
- * catalog_name: utf8,
- * db_schema_name: utf8 not null
- * >
- * The returned data should be ordered by catalog_name, then db_schema_name.
- */
-message CommandGetDbSchemas {
- option (experimental) = true;
-
- /*
- * Specifies the Catalog to search for the tables.
- * An empty string retrieves those without a catalog.
- * If omitted the catalog name should not be used to narrow the search.
- */
- optional string catalog = 1;
-
- /*
- * Specifies a filter pattern for schemas to search for.
- * When no db_schema_filter_pattern is provided, the pattern will not be used to narrow the search.
- * In the pattern string, two special characters can be used to denote matching rules:
- * - "%" means to match any substring with 0 or more characters.
- * - "_" means to match any one character.
- */
- optional string db_schema_filter_pattern = 2;
-}
-
-/*
- * Represents a request to retrieve the list of tables, and optionally their schemas, on a Flight SQL enabled backend.
- * Used in the command member of FlightDescriptor for the following RPC calls:
- * - GetSchema: return the Arrow schema of the query.
- * - GetFlightInfo: execute the catalog metadata request.
- *
- * The returned Arrow schema will be:
- * <
- * catalog_name: utf8,
- * db_schema_name: utf8,
- * table_name: utf8 not null,
- * table_type: utf8 not null,
- * [optional] table_schema: bytes not null (schema of the table as described in Schema.fbs::Schema,
- * it is serialized as an IPC message.)
- * >
- * Fields on table_schema may contain the following metadata:
- * - ARROW:FLIGHT:SQL:CATALOG_NAME - Table's catalog name
- * - ARROW:FLIGHT:SQL:DB_SCHEMA_NAME - Database schema name
- * - ARROW:FLIGHT:SQL:TABLE_NAME - Table name
- * - ARROW:FLIGHT:SQL:TYPE_NAME - The data source-specific name for the data type of the column.
- * - ARROW:FLIGHT:SQL:PRECISION - Column precision/size
- * - ARROW:FLIGHT:SQL:SCALE - Column scale/decimal digits if applicable
- * - ARROW:FLIGHT:SQL:IS_AUTO_INCREMENT - "1" indicates if the column is auto incremented, "0" otherwise.
- * - ARROW:FLIGHT:SQL:IS_CASE_SENSITIVE - "1" indicates if the column is case sensitive, "0" otherwise.
- * - ARROW:FLIGHT:SQL:IS_READ_ONLY - "1" indicates if the column is read only, "0" otherwise.
- * - ARROW:FLIGHT:SQL:IS_SEARCHABLE - "1" indicates if the column is searchable via WHERE clause, "0" otherwise.
- * The returned data should be ordered by catalog_name, db_schema_name, table_name, then table_type, followed by table_schema if requested.
- */
-message CommandGetTables {
- option (experimental) = true;
-
- /*
- * Specifies the Catalog to search for the tables.
- * An empty string retrieves those without a catalog.
- * If omitted the catalog name should not be used to narrow the search.
- */
- optional string catalog = 1;
-
- /*
- * Specifies a filter pattern for schemas to search for.
- * When no db_schema_filter_pattern is provided, all schemas matching other filters are searched.
- * In the pattern string, two special characters can be used to denote matching rules:
- * - "%" means to match any substring with 0 or more characters.
- * - "_" means to match any one character.
- */
- optional string db_schema_filter_pattern = 2;
-
- /*
- * Specifies a filter pattern for tables to search for.
- * When no table_name_filter_pattern is provided, all tables matching other filters are searched.
- * In the pattern string, two special characters can be used to denote matching rules:
- * - "%" means to match any substring with 0 or more characters.
- * - "_" means to match any one character.
- */
- optional string table_name_filter_pattern = 3;
-
- /*
- * Specifies a filter of table types which must match.
- * The table types depend on vendor/implementation. It is usually used to separate tables from views or system tables.
- * TABLE, VIEW, and SYSTEM TABLE are commonly supported.
- */
- repeated string table_types = 4;
-
- // Specifies if the Arrow schema should be returned for found tables.
- bool include_schema = 5;
-}
-
-/*
- * Represents a request to retrieve the list of table types on a Flight SQL enabled backend.
- * The table types depend on vendor/implementation. It is usually used to separate tables from views or system tables.
- * TABLE, VIEW, and SYSTEM TABLE are commonly supported.
- * Used in the command member of FlightDescriptor for the following RPC calls:
- * - GetSchema: return the Arrow schema of the query.
- * - GetFlightInfo: execute the catalog metadata request.
- *
- * The returned Arrow schema will be:
- * <
- * table_type: utf8 not null
- * >
- * The returned data should be ordered by table_type.
- */
-message CommandGetTableTypes {
- option (experimental) = true;
-}
-
-/*
- * Represents a request to retrieve the primary keys of a table on a Flight SQL enabled backend.
- * Used in the command member of FlightDescriptor for the following RPC calls:
- * - GetSchema: return the Arrow schema of the query.
- * - GetFlightInfo: execute the catalog metadata request.
- *
- * The returned Arrow schema will be:
- * <
- * catalog_name: utf8,
- * db_schema_name: utf8,
- * table_name: utf8 not null,
- * column_name: utf8 not null,
- * key_name: utf8,
- * key_sequence: int not null
- * >
- * The returned data should be ordered by catalog_name, db_schema_name, table_name, key_name, then key_sequence.
- */
-message CommandGetPrimaryKeys {
- option (experimental) = true;
-
- /*
- * Specifies the catalog to search for the table.
- * An empty string retrieves those without a catalog.
- * If omitted the catalog name should not be used to narrow the search.
- */
- optional string catalog = 1;
-
- /*
- * Specifies the schema to search for the table.
- * An empty string retrieves those without a schema.
- * If omitted the schema name should not be used to narrow the search.
- */
- optional string db_schema = 2;
-
- // Specifies the table to get the primary keys for.
- string table = 3;
-}
-
-enum UpdateDeleteRules {
- CASCADE = 0;
- RESTRICT = 1;
- SET_NULL = 2;
- NO_ACTION = 3;
- SET_DEFAULT = 4;
-}
-
-/*
- * Represents a request to retrieve a description of the foreign key columns that reference the given table's
- * primary key columns (the foreign keys exported by a table) of a table on a Flight SQL enabled backend.
- * Used in the command member of FlightDescriptor for the following RPC calls:
- * - GetSchema: return the Arrow schema of the query.
- * - GetFlightInfo: execute the catalog metadata request.
- *
- * The returned Arrow schema will be:
- * <
- * pk_catalog_name: utf8,
- * pk_db_schema_name: utf8,
- * pk_table_name: utf8 not null,
- * pk_column_name: utf8 not null,
- * fk_catalog_name: utf8,
- * fk_db_schema_name: utf8,
- * fk_table_name: utf8 not null,
- * fk_column_name: utf8 not null,
- * key_sequence: int not null,
- * fk_key_name: utf8,
- * pk_key_name: utf8,
- * update_rule: uint1 not null,
- * delete_rule: uint1 not null
- * >
- * The returned data should be ordered by fk_catalog_name, fk_db_schema_name, fk_table_name, fk_key_name, then key_sequence.
- * update_rule and delete_rule returns a byte that is equivalent to actions declared on UpdateDeleteRules enum.
- */
-message CommandGetExportedKeys {
- option (experimental) = true;
-
- /*
- * Specifies the catalog to search for the foreign key table.
- * An empty string retrieves those without a catalog.
- * If omitted the catalog name should not be used to narrow the search.
- */
- optional string catalog = 1;
-
- /*
- * Specifies the schema to search for the foreign key table.
- * An empty string retrieves those without a schema.
- * If omitted the schema name should not be used to narrow the search.
- */
- optional string db_schema = 2;
-
- // Specifies the foreign key table to get the foreign keys for.
- string table = 3;
-}
-
-/*
- * Represents a request to retrieve the foreign keys of a table on a Flight SQL enabled backend.
- * Used in the command member of FlightDescriptor for the following RPC calls:
- * - GetSchema: return the Arrow schema of the query.
- * - GetFlightInfo: execute the catalog metadata request.
- *
- * The returned Arrow schema will be:
- * <
- * pk_catalog_name: utf8,
- * pk_db_schema_name: utf8,
- * pk_table_name: utf8 not null,
- * pk_column_name: utf8 not null,
- * fk_catalog_name: utf8,
- * fk_db_schema_name: utf8,
- * fk_table_name: utf8 not null,
- * fk_column_name: utf8 not null,
- * key_sequence: int not null,
- * fk_key_name: utf8,
- * pk_key_name: utf8,
- * update_rule: uint1 not null,
- * delete_rule: uint1 not null
- * >
- * The returned data should be ordered by pk_catalog_name, pk_db_schema_name, pk_table_name, pk_key_name, then key_sequence.
- * update_rule and delete_rule returns a byte that is equivalent to actions:
- * - 0 = CASCADE
- * - 1 = RESTRICT
- * - 2 = SET NULL
- * - 3 = NO ACTION
- * - 4 = SET DEFAULT
- */
-message CommandGetImportedKeys {
- option (experimental) = true;
-
- /*
- * Specifies the catalog to search for the primary key table.
- * An empty string retrieves those without a catalog.
- * If omitted the catalog name should not be used to narrow the search.
- */
- optional string catalog = 1;
-
- /*
- * Specifies the schema to search for the primary key table.
- * An empty string retrieves those without a schema.
- * If omitted the schema name should not be used to narrow the search.
- */
- optional string db_schema = 2;
-
- // Specifies the primary key table to get the foreign keys for.
- string table = 3;
-}
-
-/*
- * Represents a request to retrieve a description of the foreign key columns in the given foreign key table that
- * reference the primary key or the columns representing a unique constraint of the parent table (could be the same
- * or a different table) on a Flight SQL enabled backend.
- * Used in the command member of FlightDescriptor for the following RPC calls:
- * - GetSchema: return the Arrow schema of the query.
- * - GetFlightInfo: execute the catalog metadata request.
- *
- * The returned Arrow schema will be:
- * <
- * pk_catalog_name: utf8,
- * pk_db_schema_name: utf8,
- * pk_table_name: utf8 not null,
- * pk_column_name: utf8 not null,
- * fk_catalog_name: utf8,
- * fk_db_schema_name: utf8,
- * fk_table_name: utf8 not null,
- * fk_column_name: utf8 not null,
- * key_sequence: int not null,
- * fk_key_name: utf8,
- * pk_key_name: utf8,
- * update_rule: uint1 not null,
- * delete_rule: uint1 not null
- * >
- * The returned data should be ordered by pk_catalog_name, pk_db_schema_name, pk_table_name, pk_key_name, then key_sequence.
- * update_rule and delete_rule returns a byte that is equivalent to actions:
- * - 0 = CASCADE
- * - 1 = RESTRICT
- * - 2 = SET NULL
- * - 3 = NO ACTION
- * - 4 = SET DEFAULT
- */
-message CommandGetCrossReference {
- option (experimental) = true;
-
- /**
- * The catalog name where the parent table is.
- * An empty string retrieves those without a catalog.
- * If omitted the catalog name should not be used to narrow the search.
- */
- optional string pk_catalog = 1;
-
- /**
- * The Schema name where the parent table is.
- * An empty string retrieves those without a schema.
- * If omitted the schema name should not be used to narrow the search.
- */
- optional string pk_db_schema = 2;
-
- /**
- * The parent table name. It cannot be null.
- */
- string pk_table = 3;
-
- /**
- * The catalog name where the foreign table is.
- * An empty string retrieves those without a catalog.
- * If omitted the catalog name should not be used to narrow the search.
- */
- optional string fk_catalog = 4;
-
- /**
- * The schema name where the foreign table is.
- * An empty string retrieves those without a schema.
- * If omitted the schema name should not be used to narrow the search.
- */
- optional string fk_db_schema = 5;
-
- /**
- * The foreign table name. It cannot be null.
- */
- string fk_table = 6;
-}
-
-// SQL Execution Action Messages
-
-/*
- * Request message for the "CreatePreparedStatement" action on a Flight SQL enabled backend.
- */
-message ActionCreatePreparedStatementRequest {
- option (experimental) = true;
-
- // The valid SQL string to create a prepared statement for.
- string query = 1;
-}
-
-/*
- * Wrap the result of a "GetPreparedStatement" action.
- *
- * The resultant PreparedStatement can be closed either:
- * - Manually, through the "ClosePreparedStatement" action;
- * - Automatically, by a server timeout.
- */
-message ActionCreatePreparedStatementResult {
- option (experimental) = true;
-
- // Opaque handle for the prepared statement on the server.
- bytes prepared_statement_handle = 1;
-
- // If a result set generating query was provided, dataset_schema contains the
- // schema of the dataset as described in Schema.fbs::Schema, it is serialized as an IPC message.
- bytes dataset_schema = 2;
-
- // If the query provided contained parameters, parameter_schema contains the
- // schema of the expected parameters as described in Schema.fbs::Schema, it is serialized as an IPC message.
- bytes parameter_schema = 3;
-}
-
-/*
- * Request message for the "ClosePreparedStatement" action on a Flight SQL enabled backend.
- * Closes server resources associated with the prepared statement handle.
- */
-message ActionClosePreparedStatementRequest {
- option (experimental) = true;
-
- // Opaque handle for the prepared statement on the server.
- bytes prepared_statement_handle = 1;
-}
-
-
-// SQL Execution Messages.
-
-/*
- * Represents a SQL query. Used in the command member of FlightDescriptor
- * for the following RPC calls:
- * - GetSchema: return the Arrow schema of the query.
- * Fields on this schema may contain the following metadata:
- * - ARROW:FLIGHT:SQL:CATALOG_NAME - Table's catalog name
- * - ARROW:FLIGHT:SQL:DB_SCHEMA_NAME - Database schema name
- * - ARROW:FLIGHT:SQL:TABLE_NAME - Table name
- * - ARROW:FLIGHT:SQL:TYPE_NAME - The data source-specific name for the data type of the column.
- * - ARROW:FLIGHT:SQL:PRECISION - Column precision/size
- * - ARROW:FLIGHT:SQL:SCALE - Column scale/decimal digits if applicable
- * - ARROW:FLIGHT:SQL:IS_AUTO_INCREMENT - "1" indicates if the column is auto incremented, "0" otherwise.
- * - ARROW:FLIGHT:SQL:IS_CASE_SENSITIVE - "1" indicates if the column is case sensitive, "0" otherwise.
- * - ARROW:FLIGHT:SQL:IS_READ_ONLY - "1" indicates if the column is read only, "0" otherwise.
- * - ARROW:FLIGHT:SQL:IS_SEARCHABLE - "1" indicates if the column is searchable via WHERE clause, "0" otherwise.
- * - GetFlightInfo: execute the query.
- */
-message CommandStatementQuery {
- option (experimental) = true;
-
- // The SQL syntax.
- string query = 1;
-}
-
-/**
- * Represents a ticket resulting from GetFlightInfo with a CommandStatementQuery.
- * This should be used only once and treated as an opaque value, that is, clients should not attempt to parse this.
- */
-message TicketStatementQuery {
- option (experimental) = true;
-
- // Unique identifier for the instance of the statement to execute.
- bytes statement_handle = 1;
-}
-
-/*
- * Represents an instance of executing a prepared statement. Used in the command member of FlightDescriptor for
- * the following RPC calls:
- * - GetSchema: return the Arrow schema of the query.
- * Fields on this schema may contain the following metadata:
- * - ARROW:FLIGHT:SQL:CATALOG_NAME - Table's catalog name
- * - ARROW:FLIGHT:SQL:DB_SCHEMA_NAME - Database schema name
- * - ARROW:FLIGHT:SQL:TABLE_NAME - Table name
- * - ARROW:FLIGHT:SQL:TYPE_NAME - The data source-specific name for the data type of the column.
- * - ARROW:FLIGHT:SQL:PRECISION - Column precision/size
- * - ARROW:FLIGHT:SQL:SCALE - Column scale/decimal digits if applicable
- * - ARROW:FLIGHT:SQL:IS_AUTO_INCREMENT - "1" indicates if the column is auto incremented, "0" otherwise.
- * - ARROW:FLIGHT:SQL:IS_CASE_SENSITIVE - "1" indicates if the column is case sensitive, "0" otherwise.
- * - ARROW:FLIGHT:SQL:IS_READ_ONLY - "1" indicates if the column is read only, "0" otherwise.
- * - ARROW:FLIGHT:SQL:IS_SEARCHABLE - "1" indicates if the column is searchable via WHERE clause, "0" otherwise.
- * - DoPut: bind parameter values. All of the bound parameter sets will be executed as a single atomic execution.
- * - GetFlightInfo: execute the prepared statement instance.
- */
-message CommandPreparedStatementQuery {
- option (experimental) = true;
-
- // Opaque handle for the prepared statement on the server.
- bytes prepared_statement_handle = 1;
-}
-
-/*
- * Represents a SQL update query. Used in the command member of FlightDescriptor
- * for the the RPC call DoPut to cause the server to execute the included SQL update.
- */
-message CommandStatementUpdate {
- option (experimental) = true;
-
- // The SQL syntax.
- string query = 1;
-}
-
-/*
- * Represents a SQL update query. Used in the command member of FlightDescriptor
- * for the the RPC call DoPut to cause the server to execute the included
- * prepared statement handle as an update.
- */
-message CommandPreparedStatementUpdate {
- option (experimental) = true;
-
- // Opaque handle for the prepared statement on the server.
- bytes prepared_statement_handle = 1;
-}
-
-/*
- * Returned from the RPC call DoPut when a CommandStatementUpdate
- * CommandPreparedStatementUpdate was in the request, containing
- * results from the update.
- */
-message DoPutUpdateResult {
- option (experimental) = true;
-
- // The number of records updated. A return value of -1 represents
- // an unknown updated record count.
- int64 record_count = 1;
-}
-
-extend google.protobuf.MessageOptions {
- bool experimental = 1000;
-}
+ syntax = "proto3";
+ import "google/protobuf/descriptor.proto";
+
+ option java_package = "org.apache.arrow.flight.sql.impl";
+ option go_package = "github.com/apache/arrow/go/arrow/flight/internal/flight";
+ package arrow.flight.protocol.sql;
+
+ /*
+ * Represents a metadata request. Used in the command member of FlightDescriptor
+ * for the following RPC calls:
+ * - GetSchema: return the Arrow schema of the query.
+ * - GetFlightInfo: execute the metadata request.
+ *
+ * The returned Arrow schema will be:
+ * <
+ * info_name: uint32 not null,
+ * value: dense_union<
+ * string_value: utf8,
+ * bool_value: bool,
+ * bigint_value: int64,
+ * int32_bitmask: int32,
+ * string_list: list<string_data: utf8>
+ * int32_to_int32_list_map: map<key: int32, value: list<$data$: int32>>
+ * >
+ * where there is one row per requested piece of metadata information.
+ */
+ message CommandGetSqlInfo {
+ option (experimental) = true;
+
+ /*
+ * Values are modelled after ODBC's SQLGetInfo() function. This information is intended to provide
+ * Flight SQL clients with basic, SQL syntax and SQL functions related information.
+ * More information types can be added in future releases.
+ * E.g. more SQL syntax support types, scalar functions support, type conversion support etc.
+ *
+ * Note that the set of metadata may expand.
+ *
+ * Initially, Flight SQL will support the following information types:
+ * - Server Information - Range [0-500)
+ * - Syntax Information - Range [500-1000)
+ * Range [0-10,000) is reserved for defaults (see SqlInfo enum for default options).
+ * Custom options should start at 10,000.
+ *
+ * If omitted, then all metadata will be retrieved.
+ * Flight SQL Servers may choose to include additional metadata above and beyond the specified set, however they must
+ * at least return the specified set. IDs ranging from 0 to 10,000 (exclusive) are reserved for future use.
+ * If additional metadata is included, the metadata IDs should start from 10,000.
+ */
+ repeated uint32 info = 1;
+ }
+
+ // Options for CommandGetSqlInfo.
+ enum SqlInfo {
+
+ // Server Information [0-500): Provides basic information about the Flight SQL Server.
+
+ // Retrieves a UTF-8 string with the name of the Flight SQL Server.
+ FLIGHT_SQL_SERVER_NAME = 0;
+
+ // Retrieves a UTF-8 string with the native version of the Flight SQL Server.
+ FLIGHT_SQL_SERVER_VERSION = 1;
+
+ // Retrieves a UTF-8 string with the Arrow format version of the Flight SQL Server.
+ FLIGHT_SQL_SERVER_ARROW_VERSION = 2;
+
+ /*
+ * Retrieves a boolean value indicating whether the Flight SQL Server is read only.
+ *
+ * Returns:
+ * - false: if read-write
+ * - true: if read only
+ */
+ FLIGHT_SQL_SERVER_READ_ONLY = 3;
+
+ /*
+ * Retrieves a boolean value indicating whether the Flight SQL Server supports executing
+ * SQL queries.
+ *
+ * Note that the absence of this info (as opposed to a false value) does not necessarily
+ * mean that SQL is not supported, as this property was not originally defined.
+ */
+ FLIGHT_SQL_SERVER_SQL = 4;
+
+ /*
+ * Retrieves a boolean value indicating whether the Flight SQL Server supports executing
+ * Substrait plans.
+ */
+ FLIGHT_SQL_SERVER_SUBSTRAIT = 5;
+
+ /*
+ * Retrieves a string value indicating the minimum supported Substrait version, or null
+ * if Substrait is not supported.
+ */
+ FLIGHT_SQL_SERVER_SUBSTRAIT_MIN_VERSION = 6;
+
+ /*
+ * Retrieves a string value indicating the maximum supported Substrait version, or null
+ * if Substrait is not supported.
+ */
+ FLIGHT_SQL_SERVER_SUBSTRAIT_MAX_VERSION = 7;
+
+ /*
+ * Retrieves an int32 indicating whether the Flight SQL Server supports the
+ * BeginTransaction/EndTransaction/BeginSavepoint/EndSavepoint actions.
+ *
+ * Even if this is not supported, the database may still support explicit "BEGIN
+ * TRANSACTION"/"COMMIT" SQL statements (see SQL_TRANSACTIONS_SUPPORTED); this property
+ * is only about whether the server implements the Flight SQL API endpoints.
+ *
+ * The possible values are listed in `SqlSupportedTransaction`.
+ */
+ FLIGHT_SQL_SERVER_TRANSACTION = 8;
+
+ /*
+ * Retrieves a boolean value indicating whether the Flight SQL Server supports explicit
+ * query cancellation (the CancelQuery action).
+ */
+ FLIGHT_SQL_SERVER_CANCEL = 9;
+
+ /*
+ * Retrieves an int32 indicating the timeout (in milliseconds) for prepared statement handles.
+ *
+ * If 0, there is no timeout. Servers should reset the timeout when the handle is used in a command.
+ */
+ FLIGHT_SQL_SERVER_STATEMENT_TIMEOUT = 100;
+
+ /*
+ * Retrieves an int32 indicating the timeout (in milliseconds) for transactions, since transactions are not tied to a connection.
+ *
+ * If 0, there is no timeout. Servers should reset the timeout when the handle is used in a command.
+ */
+ FLIGHT_SQL_SERVER_TRANSACTION_TIMEOUT = 101;
+
+ // SQL Syntax Information [500-1000): provides information about SQL syntax supported by the Flight SQL Server.
+
+ /*
+ * Retrieves a boolean value indicating whether the Flight SQL Server supports CREATE and DROP of catalogs.
+ *
+ * Returns:
+ * - false: if it doesn't support CREATE and DROP of catalogs.
+ * - true: if it supports CREATE and DROP of catalogs.
+ */
+ SQL_DDL_CATALOG = 500;
+
+ /*
+ * Retrieves a boolean value indicating whether the Flight SQL Server supports CREATE and DROP of schemas.
+ *
+ * Returns:
+ * - false: if it doesn't support CREATE and DROP of schemas.
+ * - true: if it supports CREATE and DROP of schemas.
+ */
+ SQL_DDL_SCHEMA = 501;
+
+ /*
+ * Indicates whether the Flight SQL Server supports CREATE and DROP of tables.
+ *
+ * Returns:
+ * - false: if it doesn't support CREATE and DROP of tables.
+ * - true: if it supports CREATE and DROP of tables.
+ */
+ SQL_DDL_TABLE = 502;
+
+ /*
+ * Retrieves a int32 ordinal representing the case sensitivity of catalog, table, schema and table names.
+ *
+ * The possible values are listed in `arrow.flight.protocol.sql.SqlSupportedCaseSensitivity`.
+ */
+ SQL_IDENTIFIER_CASE = 503;
+
+ // Retrieves a UTF-8 string with the supported character(s) used to surround a delimited identifier.
+ SQL_IDENTIFIER_QUOTE_CHAR = 504;
+
+ /*
+ * Retrieves a int32 describing the case sensitivity of quoted identifiers.
+ *
+ * The possible values are listed in `arrow.flight.protocol.sql.SqlSupportedCaseSensitivity`.
+ */
+ SQL_QUOTED_IDENTIFIER_CASE = 505;
+
+ /*
+ * Retrieves a boolean value indicating whether all tables are selectable.
+ *
+ * Returns:
+ * - false: if not all tables are selectable or if none are;
+ * - true: if all tables are selectable.
+ */
+ SQL_ALL_TABLES_ARE_SELECTABLE = 506;
+
+ /*
+ * Retrieves the null ordering.
+ *
+ * Returns a int32 ordinal for the null ordering being used, as described in
+ * `arrow.flight.protocol.sql.SqlNullOrdering`.
+ */
+ SQL_NULL_ORDERING = 507;
+
+ // Retrieves a UTF-8 string list with values of the supported keywords.
+ SQL_KEYWORDS = 508;
+
+ // Retrieves a UTF-8 string list with values of the supported numeric functions.
+ SQL_NUMERIC_FUNCTIONS = 509;
+
+ // Retrieves a UTF-8 string list with values of the supported string functions.
+ SQL_STRING_FUNCTIONS = 510;
+
+ // Retrieves a UTF-8 string list with values of the supported system functions.
+ SQL_SYSTEM_FUNCTIONS = 511;
+
+ // Retrieves a UTF-8 string list with values of the supported datetime functions.
+ SQL_DATETIME_FUNCTIONS = 512;
+
+ /*
+ * Retrieves the UTF-8 string that can be used to escape wildcard characters.
+ * This is the string that can be used to escape '_' or '%' in the catalog search parameters that are a pattern
+ * (and therefore use one of the wildcard characters).
+ * The '_' character represents any single character; the '%' character represents any sequence of zero or more
+ * characters.
+ */
+ SQL_SEARCH_STRING_ESCAPE = 513;
+
+ /*
+ * Retrieves a UTF-8 string with all the "extra" characters that can be used in unquoted identifier names
+ * (those beyond a-z, A-Z, 0-9 and _).
+ */
+ SQL_EXTRA_NAME_CHARACTERS = 514;
+
+ /*
+ * Retrieves a boolean value indicating whether column aliasing is supported.
+ * If so, the SQL AS clause can be used to provide names for computed columns or to provide alias names for columns
+ * as required.
+ *
+ * Returns:
+ * - false: if column aliasing is unsupported;
+ * - true: if column aliasing is supported.
+ */
+ SQL_SUPPORTS_COLUMN_ALIASING = 515;
+
+ /*
+ * Retrieves a boolean value indicating whether concatenations between null and non-null values being
+ * null are supported.
+ *
+ * - Returns:
+ * - false: if concatenations between null and non-null values being null are unsupported;
+ * - true: if concatenations between null and non-null values being null are supported.
+ */
+ SQL_NULL_PLUS_NULL_IS_NULL = 516;
+
+ /*
+ * Retrieves a map where the key is the type to convert from and the value is a list with the types to convert to,
+ * indicating the supported conversions. Each key and each item on the list value is a value to a predefined type on
+ * SqlSupportsConvert enum.
+ * The returned map will be: map<int32, list<int32>>
+ */
+ SQL_SUPPORTS_CONVERT = 517;
+
+ /*
+ * Retrieves a boolean value indicating whether, when table correlation names are supported,
+ * they are restricted to being different from the names of the tables.
+ *
+ * Returns:
+ * - false: if table correlation names are unsupported;
+ * - true: if table correlation names are supported.
+ */
+ SQL_SUPPORTS_TABLE_CORRELATION_NAMES = 518;
+
+ /*
+ * Retrieves a boolean value indicating whether, when table correlation names are supported,
+ * they are restricted to being different from the names of the tables.
+ *
+ * Returns:
+ * - false: if different table correlation names are unsupported;
+ * - true: if different table correlation names are supported
+ */
+ SQL_SUPPORTS_DIFFERENT_TABLE_CORRELATION_NAMES = 519;
+
+ /*
+ * Retrieves a boolean value indicating whether expressions in ORDER BY lists are supported.
+ *
+ * Returns:
+ * - false: if expressions in ORDER BY are unsupported;
+ * - true: if expressions in ORDER BY are supported;
+ */
+ SQL_SUPPORTS_EXPRESSIONS_IN_ORDER_BY = 520;
+
+ /*
+ * Retrieves a boolean value indicating whether using a column that is not in the SELECT statement in a GROUP BY
+ * clause is supported.
+ *
+ * Returns:
+ * - false: if using a column that is not in the SELECT statement in a GROUP BY clause is unsupported;
+ * - true: if using a column that is not in the SELECT statement in a GROUP BY clause is supported.
+ */
+ SQL_SUPPORTS_ORDER_BY_UNRELATED = 521;
+
+ /*
+ * Retrieves the supported GROUP BY commands;
+ *
+ * Returns an int32 bitmask value representing the supported commands.
+ * The returned bitmask should be parsed in order to retrieve the supported commands.
+ *
+ * For instance:
+ * - return 0 (\b0) => [] (GROUP BY is unsupported);
+ * - return 1 (\b1) => [SQL_GROUP_BY_UNRELATED];
+ * - return 2 (\b10) => [SQL_GROUP_BY_BEYOND_SELECT];
+ * - return 3 (\b11) => [SQL_GROUP_BY_UNRELATED, SQL_GROUP_BY_BEYOND_SELECT].
+ * Valid GROUP BY types are described under `arrow.flight.protocol.sql.SqlSupportedGroupBy`.
+ */
+ SQL_SUPPORTED_GROUP_BY = 522;
+
+ /*
+ * Retrieves a boolean value indicating whether specifying a LIKE escape clause is supported.
+ *
+ * Returns:
+ * - false: if specifying a LIKE escape clause is unsupported;
+ * - true: if specifying a LIKE escape clause is supported.
+ */
+ SQL_SUPPORTS_LIKE_ESCAPE_CLAUSE = 523;
+
+ /*
+ * Retrieves a boolean value indicating whether columns may be defined as non-nullable.
+ *
+ * Returns:
+ * - false: if columns cannot be defined as non-nullable;
+ * - true: if columns may be defined as non-nullable.
+ */
+ SQL_SUPPORTS_NON_NULLABLE_COLUMNS = 524;
+
+ /*
+ * Retrieves the supported SQL grammar level as per the ODBC specification.
+ *
+ * Returns an int32 bitmask value representing the supported SQL grammar level.
+ * The returned bitmask should be parsed in order to retrieve the supported grammar levels.
+ *
+ * For instance:
+ * - return 0 (\b0) => [] (SQL grammar is unsupported);
+ * - return 1 (\b1) => [SQL_MINIMUM_GRAMMAR];
+ * - return 2 (\b10) => [SQL_CORE_GRAMMAR];
+ * - return 3 (\b11) => [SQL_MINIMUM_GRAMMAR, SQL_CORE_GRAMMAR];
+ * - return 4 (\b100) => [SQL_EXTENDED_GRAMMAR];
+ * - return 5 (\b101) => [SQL_MINIMUM_GRAMMAR, SQL_EXTENDED_GRAMMAR];
+ * - return 6 (\b110) => [SQL_CORE_GRAMMAR, SQL_EXTENDED_GRAMMAR];
+ * - return 7 (\b111) => [SQL_MINIMUM_GRAMMAR, SQL_CORE_GRAMMAR, SQL_EXTENDED_GRAMMAR].
+ * Valid SQL grammar levels are described under `arrow.flight.protocol.sql.SupportedSqlGrammar`.
+ */
+ SQL_SUPPORTED_GRAMMAR = 525;
+
+ /*
+ * Retrieves the supported ANSI92 SQL grammar level.
+ *
+ * Returns an int32 bitmask value representing the supported ANSI92 SQL grammar level.
+ * The returned bitmask should be parsed in order to retrieve the supported commands.
+ *
+ * For instance:
+ * - return 0 (\b0) => [] (ANSI92 SQL grammar is unsupported);
+ * - return 1 (\b1) => [ANSI92_ENTRY_SQL];
+ * - return 2 (\b10) => [ANSI92_INTERMEDIATE_SQL];
+ * - return 3 (\b11) => [ANSI92_ENTRY_SQL, ANSI92_INTERMEDIATE_SQL];
+ * - return 4 (\b100) => [ANSI92_FULL_SQL];
+ * - return 5 (\b101) => [ANSI92_ENTRY_SQL, ANSI92_FULL_SQL];
+ * - return 6 (\b110) => [ANSI92_INTERMEDIATE_SQL, ANSI92_FULL_SQL];
+ * - return 7 (\b111) => [ANSI92_ENTRY_SQL, ANSI92_INTERMEDIATE_SQL, ANSI92_FULL_SQL].
+ * Valid ANSI92 SQL grammar levels are described under `arrow.flight.protocol.sql.SupportedAnsi92SqlGrammarLevel`.
+ */
+ SQL_ANSI92_SUPPORTED_LEVEL = 526;
+
+ /*
+ * Retrieves a boolean value indicating whether the SQL Integrity Enhancement Facility is supported.
+ *
+ * Returns:
+ * - false: if the SQL Integrity Enhancement Facility is supported;
+ * - true: if the SQL Integrity Enhancement Facility is supported.
+ */
+ SQL_SUPPORTS_INTEGRITY_ENHANCEMENT_FACILITY = 527;
+
+ /*
+ * Retrieves the support level for SQL OUTER JOINs.
+ *
+ * Returns a int32 ordinal for the SQL ordering being used, as described in
+ * `arrow.flight.protocol.sql.SqlOuterJoinsSupportLevel`.
+ */
+ SQL_OUTER_JOINS_SUPPORT_LEVEL = 528;
+
+ // Retrieves a UTF-8 string with the preferred term for "schema".
+ SQL_SCHEMA_TERM = 529;
+
+ // Retrieves a UTF-8 string with the preferred term for "procedure".
+ SQL_PROCEDURE_TERM = 530;
+
+ /*
+ * Retrieves a UTF-8 string with the preferred term for "catalog".
+ * If a empty string is returned its assumed that the server does NOT supports catalogs.
+ */
+ SQL_CATALOG_TERM = 531;
+
+ /*
+ * Retrieves a boolean value indicating whether a catalog appears at the start of a fully qualified table name.
+ *
+ * - false: if a catalog does not appear at the start of a fully qualified table name;
+ * - true: if a catalog appears at the start of a fully qualified table name.
+ */
+ SQL_CATALOG_AT_START = 532;
+
+ /*
+ * Retrieves the supported actions for a SQL schema.
+ *
+ * Returns an int32 bitmask value representing the supported actions for a SQL schema.
+ * The returned bitmask should be parsed in order to retrieve the supported actions for a SQL schema.
+ *
+ * For instance:
+ * - return 0 (\b0) => [] (no supported actions for SQL schema);
+ * - return 1 (\b1) => [SQL_ELEMENT_IN_PROCEDURE_CALLS];
+ * - return 2 (\b10) => [SQL_ELEMENT_IN_INDEX_DEFINITIONS];
+ * - return 3 (\b11) => [SQL_ELEMENT_IN_PROCEDURE_CALLS, SQL_ELEMENT_IN_INDEX_DEFINITIONS];
+ * - return 4 (\b100) => [SQL_ELEMENT_IN_PRIVILEGE_DEFINITIONS];
+ * - return 5 (\b101) => [SQL_ELEMENT_IN_PROCEDURE_CALLS, SQL_ELEMENT_IN_PRIVILEGE_DEFINITIONS];
+ * - return 6 (\b110) => [SQL_ELEMENT_IN_INDEX_DEFINITIONS, SQL_ELEMENT_IN_PRIVILEGE_DEFINITIONS];
+ * - return 7 (\b111) => [SQL_ELEMENT_IN_PROCEDURE_CALLS, SQL_ELEMENT_IN_INDEX_DEFINITIONS, SQL_ELEMENT_IN_PRIVILEGE_DEFINITIONS].
+ * Valid actions for a SQL schema described under `arrow.flight.protocol.sql.SqlSupportedElementActions`.
+ */
+ SQL_SCHEMAS_SUPPORTED_ACTIONS = 533;
+
+ /*
+ * Retrieves the supported actions for a SQL schema.
+ *
+ * Returns an int32 bitmask value representing the supported actions for a SQL catalog.
+ * The returned bitmask should be parsed in order to retrieve the supported actions for a SQL catalog.
+ *
+ * For instance:
+ * - return 0 (\b0) => [] (no supported actions for SQL catalog);
+ * - return 1 (\b1) => [SQL_ELEMENT_IN_PROCEDURE_CALLS];
+ * - return 2 (\b10) => [SQL_ELEMENT_IN_INDEX_DEFINITIONS];
+ * - return 3 (\b11) => [SQL_ELEMENT_IN_PROCEDURE_CALLS, SQL_ELEMENT_IN_INDEX_DEFINITIONS];
+ * - return 4 (\b100) => [SQL_ELEMENT_IN_PRIVILEGE_DEFINITIONS];
+ * - return 5 (\b101) => [SQL_ELEMENT_IN_PROCEDURE_CALLS, SQL_ELEMENT_IN_PRIVILEGE_DEFINITIONS];
+ * - return 6 (\b110) => [SQL_ELEMENT_IN_INDEX_DEFINITIONS, SQL_ELEMENT_IN_PRIVILEGE_DEFINITIONS];
+ * - return 7 (\b111) => [SQL_ELEMENT_IN_PROCEDURE_CALLS, SQL_ELEMENT_IN_INDEX_DEFINITIONS, SQL_ELEMENT_IN_PRIVILEGE_DEFINITIONS].
+ * Valid actions for a SQL catalog are described under `arrow.flight.protocol.sql.SqlSupportedElementActions`.
+ */
+ SQL_CATALOGS_SUPPORTED_ACTIONS = 534;
+
+ /*
+ * Retrieves the supported SQL positioned commands.
+ *
+ * Returns an int32 bitmask value representing the supported SQL positioned commands.
+ * The returned bitmask should be parsed in order to retrieve the supported SQL positioned commands.
+ *
+ * For instance:
+ * - return 0 (\b0) => [] (no supported SQL positioned commands);
+ * - return 1 (\b1) => [SQL_POSITIONED_DELETE];
+ * - return 2 (\b10) => [SQL_POSITIONED_UPDATE];
+ * - return 3 (\b11) => [SQL_POSITIONED_DELETE, SQL_POSITIONED_UPDATE].
+ * Valid SQL positioned commands are described under `arrow.flight.protocol.sql.SqlSupportedPositionedCommands`.
+ */
+ SQL_SUPPORTED_POSITIONED_COMMANDS = 535;
+
+ /*
+ * Retrieves a boolean value indicating whether SELECT FOR UPDATE statements are supported.
+ *
+ * Returns:
+ * - false: if SELECT FOR UPDATE statements are unsupported;
+ * - true: if SELECT FOR UPDATE statements are supported.
+ */
+ SQL_SELECT_FOR_UPDATE_SUPPORTED = 536;
+
+ /*
+ * Retrieves a boolean value indicating whether stored procedure calls that use the stored procedure escape syntax
+ * are supported.
+ *
+ * Returns:
+ * - false: if stored procedure calls that use the stored procedure escape syntax are unsupported;
+ * - true: if stored procedure calls that use the stored procedure escape syntax are supported.
+ */
+ SQL_STORED_PROCEDURES_SUPPORTED = 537;
+
+ /*
+ * Retrieves the supported SQL subqueries.
+ *
+ * Returns an int32 bitmask value representing the supported SQL subqueries.
+ * The returned bitmask should be parsed in order to retrieve the supported SQL subqueries.
+ *
+ * For instance:
+ * - return 0 (\b0) => [] (no supported SQL subqueries);
+ * - return 1 (\b1) => [SQL_SUBQUERIES_IN_COMPARISONS];
+ * - return 2 (\b10) => [SQL_SUBQUERIES_IN_EXISTS];
+ * - return 3 (\b11) => [SQL_SUBQUERIES_IN_COMPARISONS, SQL_SUBQUERIES_IN_EXISTS];
+ * - return 4 (\b100) => [SQL_SUBQUERIES_IN_INS];
+ * - return 5 (\b101) => [SQL_SUBQUERIES_IN_COMPARISONS, SQL_SUBQUERIES_IN_INS];
+ * - return 6 (\b110) => [SQL_SUBQUERIES_IN_INS, SQL_SUBQUERIES_IN_EXISTS];
+ * - return 7 (\b111) => [SQL_SUBQUERIES_IN_COMPARISONS, SQL_SUBQUERIES_IN_EXISTS, SQL_SUBQUERIES_IN_INS];
+ * - return 8 (\b1000) => [SQL_SUBQUERIES_IN_QUANTIFIEDS];
+ * - return 9 (\b1001) => [SQL_SUBQUERIES_IN_COMPARISONS, SQL_SUBQUERIES_IN_QUANTIFIEDS];
+ * - return 10 (\b1010) => [SQL_SUBQUERIES_IN_EXISTS, SQL_SUBQUERIES_IN_QUANTIFIEDS];
+ * - return 11 (\b1011) => [SQL_SUBQUERIES_IN_COMPARISONS, SQL_SUBQUERIES_IN_EXISTS, SQL_SUBQUERIES_IN_QUANTIFIEDS];
+ * - return 12 (\b1100) => [SQL_SUBQUERIES_IN_INS, SQL_SUBQUERIES_IN_QUANTIFIEDS];
+ * - return 13 (\b1101) => [SQL_SUBQUERIES_IN_COMPARISONS, SQL_SUBQUERIES_IN_INS, SQL_SUBQUERIES_IN_QUANTIFIEDS];
+ * - return 14 (\b1110) => [SQL_SUBQUERIES_IN_EXISTS, SQL_SUBQUERIES_IN_INS, SQL_SUBQUERIES_IN_QUANTIFIEDS];
+ * - return 15 (\b1111) => [SQL_SUBQUERIES_IN_COMPARISONS, SQL_SUBQUERIES_IN_EXISTS, SQL_SUBQUERIES_IN_INS, SQL_SUBQUERIES_IN_QUANTIFIEDS];
+ * - ...
+ * Valid SQL subqueries are described under `arrow.flight.protocol.sql.SqlSupportedSubqueries`.
+ */
+ SQL_SUPPORTED_SUBQUERIES = 538;
+
+ /*
+ * Retrieves a boolean value indicating whether correlated subqueries are supported.
+ *
+ * Returns:
+ * - false: if correlated subqueries are unsupported;
+ * - true: if correlated subqueries are supported.
+ */
+ SQL_CORRELATED_SUBQUERIES_SUPPORTED = 539;
+
+ /*
+ * Retrieves the supported SQL UNIONs.
+ *
+ * Returns an int32 bitmask value representing the supported SQL UNIONs.
+ * The returned bitmask should be parsed in order to retrieve the supported SQL UNIONs.
+ *
+ * For instance:
+ * - return 0 (\b0) => [] (no supported SQL positioned commands);
+ * - return 1 (\b1) => [SQL_UNION];
+ * - return 2 (\b10) => [SQL_UNION_ALL];
+ * - return 3 (\b11) => [SQL_UNION, SQL_UNION_ALL].
+ * Valid SQL positioned commands are described under `arrow.flight.protocol.sql.SqlSupportedUnions`.
+ */
+ SQL_SUPPORTED_UNIONS = 540;
+
+ // Retrieves a int64 value representing the maximum number of hex characters allowed in an inline binary literal.
+ SQL_MAX_BINARY_LITERAL_LENGTH = 541;
+
+ // Retrieves a int64 value representing the maximum number of characters allowed for a character literal.
+ SQL_MAX_CHAR_LITERAL_LENGTH = 542;
+
+ // Retrieves a int64 value representing the maximum number of characters allowed for a column name.
+ SQL_MAX_COLUMN_NAME_LENGTH = 543;
+
+ // Retrieves a int64 value representing the the maximum number of columns allowed in a GROUP BY clause.
+ SQL_MAX_COLUMNS_IN_GROUP_BY = 544;
+
+ // Retrieves a int64 value representing the maximum number of columns allowed in an index.
+ SQL_MAX_COLUMNS_IN_INDEX = 545;
+
+ // Retrieves a int64 value representing the maximum number of columns allowed in an ORDER BY clause.
+ SQL_MAX_COLUMNS_IN_ORDER_BY = 546;
+
+ // Retrieves a int64 value representing the maximum number of columns allowed in a SELECT list.
+ SQL_MAX_COLUMNS_IN_SELECT = 547;
+
+ // Retrieves a int64 value representing the maximum number of columns allowed in a table.
+ SQL_MAX_COLUMNS_IN_TABLE = 548;
+
+ // Retrieves a int64 value representing the maximum number of concurrent connections possible.
+ SQL_MAX_CONNECTIONS = 549;
+
+ // Retrieves a int64 value the maximum number of characters allowed in a cursor name.
+ SQL_MAX_CURSOR_NAME_LENGTH = 550;
+
+ /*
+ * Retrieves a int64 value representing the maximum number of bytes allowed for an index,
+ * including all of the parts of the index.
+ */
+ SQL_MAX_INDEX_LENGTH = 551;
+
+ // Retrieves a int64 value representing the maximum number of characters allowed in a schema name.
+ SQL_DB_SCHEMA_NAME_LENGTH = 552;
+
+ // Retrieves a int64 value representing the maximum number of characters allowed in a procedure name.
+ SQL_MAX_PROCEDURE_NAME_LENGTH = 553;
+
+ // Retrieves a int64 value representing the maximum number of characters allowed in a catalog name.
+ SQL_MAX_CATALOG_NAME_LENGTH = 554;
+
+ // Retrieves a int64 value representing the maximum number of bytes allowed in a single row.
+ SQL_MAX_ROW_SIZE = 555;
+
+ /*
+ * Retrieves a boolean indicating whether the return value for the JDBC method getMaxRowSize includes the SQL
+ * data types LONGVARCHAR and LONGVARBINARY.
+ *
+ * Returns:
+ * - false: if return value for the JDBC method getMaxRowSize does
+ * not include the SQL data types LONGVARCHAR and LONGVARBINARY;
+ * - true: if return value for the JDBC method getMaxRowSize includes
+ * the SQL data types LONGVARCHAR and LONGVARBINARY.
+ */
+ SQL_MAX_ROW_SIZE_INCLUDES_BLOBS = 556;
+
+ /*
+ * Retrieves a int64 value representing the maximum number of characters allowed for an SQL statement;
+ * a result of 0 (zero) means that there is no limit or the limit is not known.
+ */
+ SQL_MAX_STATEMENT_LENGTH = 557;
+
+ // Retrieves a int64 value representing the maximum number of active statements that can be open at the same time.
+ SQL_MAX_STATEMENTS = 558;
+
+ // Retrieves a int64 value representing the maximum number of characters allowed in a table name.
+ SQL_MAX_TABLE_NAME_LENGTH = 559;
+
+ // Retrieves a int64 value representing the maximum number of tables allowed in a SELECT statement.
+ SQL_MAX_TABLES_IN_SELECT = 560;
+
+ // Retrieves a int64 value representing the maximum number of characters allowed in a user name.
+ SQL_MAX_USERNAME_LENGTH = 561;
+
+ /*
+ * Retrieves this database's default transaction isolation level as described in
+ * `arrow.flight.protocol.sql.SqlTransactionIsolationLevel`.
+ *
+ * Returns a int32 ordinal for the SQL transaction isolation level.
+ */
+ SQL_DEFAULT_TRANSACTION_ISOLATION = 562;
+
+ /*
+ * Retrieves a boolean value indicating whether transactions are supported. If not, invoking the method commit is a
+ * noop, and the isolation level is `arrow.flight.protocol.sql.SqlTransactionIsolationLevel.TRANSACTION_NONE`.
+ *
+ * Returns:
+ * - false: if transactions are unsupported;
+ * - true: if transactions are supported.
+ */
+ SQL_TRANSACTIONS_SUPPORTED = 563;
+
+ /*
+ * Retrieves the supported transactions isolation levels.
+ *
+ * Returns an int32 bitmask value representing the supported transactions isolation levels.
+ * The returned bitmask should be parsed in order to retrieve the supported transactions isolation levels.
+ *
+ * For instance:
+ * - return 0 (\b0) => [] (no supported SQL transactions isolation levels);
+ * - return 1 (\b1) => [SQL_TRANSACTION_NONE];
+ * - return 2 (\b10) => [SQL_TRANSACTION_READ_UNCOMMITTED];
+ * - return 3 (\b11) => [SQL_TRANSACTION_NONE, SQL_TRANSACTION_READ_UNCOMMITTED];
+ * - return 4 (\b100) => [SQL_TRANSACTION_REPEATABLE_READ];
+ * - return 5 (\b101) => [SQL_TRANSACTION_NONE, SQL_TRANSACTION_REPEATABLE_READ];
+ * - return 6 (\b110) => [SQL_TRANSACTION_READ_UNCOMMITTED, SQL_TRANSACTION_REPEATABLE_READ];
+ * - return 7 (\b111) => [SQL_TRANSACTION_NONE, SQL_TRANSACTION_READ_UNCOMMITTED, SQL_TRANSACTION_REPEATABLE_READ];
+ * - return 8 (\b1000) => [SQL_TRANSACTION_REPEATABLE_READ];
+ * - return 9 (\b1001) => [SQL_TRANSACTION_NONE, SQL_TRANSACTION_REPEATABLE_READ];
+ * - return 10 (\b1010) => [SQL_TRANSACTION_READ_UNCOMMITTED, SQL_TRANSACTION_REPEATABLE_READ];
+ * - return 11 (\b1011) => [SQL_TRANSACTION_NONE, SQL_TRANSACTION_READ_UNCOMMITTED, SQL_TRANSACTION_REPEATABLE_READ];
+ * - return 12 (\b1100) => [SQL_TRANSACTION_REPEATABLE_READ, SQL_TRANSACTION_REPEATABLE_READ];
+ * - return 13 (\b1101) => [SQL_TRANSACTION_NONE, SQL_TRANSACTION_REPEATABLE_READ, SQL_TRANSACTION_REPEATABLE_READ];
+ * - return 14 (\b1110) => [SQL_TRANSACTION_READ_UNCOMMITTED, SQL_TRANSACTION_REPEATABLE_READ, SQL_TRANSACTION_REPEATABLE_READ];
+ * - return 15 (\b1111) => [SQL_TRANSACTION_NONE, SQL_TRANSACTION_READ_UNCOMMITTED, SQL_TRANSACTION_REPEATABLE_READ, SQL_TRANSACTION_REPEATABLE_READ];
+ * - return 16 (\b10000) => [SQL_TRANSACTION_SERIALIZABLE];
+ * - ...
+ * Valid SQL positioned commands are described under `arrow.flight.protocol.sql.SqlTransactionIsolationLevel`.
+ */
+ SQL_SUPPORTED_TRANSACTIONS_ISOLATION_LEVELS = 564;
+
+ /*
+ * Retrieves a boolean value indicating whether a data definition statement within a transaction forces
+ * the transaction to commit.
+ *
+ * Returns:
+ * - false: if a data definition statement within a transaction does not force the transaction to commit;
+ * - true: if a data definition statement within a transaction forces the transaction to commit.
+ */
+ SQL_DATA_DEFINITION_CAUSES_TRANSACTION_COMMIT = 565;
+
+ /*
+ * Retrieves a boolean value indicating whether a data definition statement within a transaction is ignored.
+ *
+ * Returns:
+ * - false: if a data definition statement within a transaction is taken into account;
+ * - true: a data definition statement within a transaction is ignored.
+ */
+ SQL_DATA_DEFINITIONS_IN_TRANSACTIONS_IGNORED = 566;
+
+ /*
+ * Retrieves an int32 bitmask value representing the supported result set types.
+ * The returned bitmask should be parsed in order to retrieve the supported result set types.
+ *
+ * For instance:
+ * - return 0 (\b0) => [] (no supported result set types);
+ * - return 1 (\b1) => [SQL_RESULT_SET_TYPE_UNSPECIFIED];
+ * - return 2 (\b10) => [SQL_RESULT_SET_TYPE_FORWARD_ONLY];
+ * - return 3 (\b11) => [SQL_RESULT_SET_TYPE_UNSPECIFIED, SQL_RESULT_SET_TYPE_FORWARD_ONLY];
+ * - return 4 (\b100) => [SQL_RESULT_SET_TYPE_SCROLL_INSENSITIVE];
+ * - return 5 (\b101) => [SQL_RESULT_SET_TYPE_UNSPECIFIED, SQL_RESULT_SET_TYPE_SCROLL_INSENSITIVE];
+ * - return 6 (\b110) => [SQL_RESULT_SET_TYPE_FORWARD_ONLY, SQL_RESULT_SET_TYPE_SCROLL_INSENSITIVE];
+ * - return 7 (\b111) => [SQL_RESULT_SET_TYPE_UNSPECIFIED, SQL_RESULT_SET_TYPE_FORWARD_ONLY, SQL_RESULT_SET_TYPE_SCROLL_INSENSITIVE];
+ * - return 8 (\b1000) => [SQL_RESULT_SET_TYPE_SCROLL_SENSITIVE];
+ * - ...
+ * Valid result set types are described under `arrow.flight.protocol.sql.SqlSupportedResultSetType`.
+ */
+ SQL_SUPPORTED_RESULT_SET_TYPES = 567;
+
+ /*
+ * Returns an int32 bitmask value concurrency types supported for
+ * `arrow.flight.protocol.sql.SqlSupportedResultSetType.SQL_RESULT_SET_TYPE_UNSPECIFIED`.
+ *
+ * For instance:
+ * - return 0 (\b0) => [] (no supported concurrency types for this result set type)
+ * - return 1 (\b1) => [SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED]
+ * - return 2 (\b10) => [SQL_RESULT_SET_CONCURRENCY_READ_ONLY]
+ * - return 3 (\b11) => [SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED, SQL_RESULT_SET_CONCURRENCY_READ_ONLY]
+ * - return 4 (\b100) => [SQL_RESULT_SET_CONCURRENCY_UPDATABLE]
+ * - return 5 (\b101) => [SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED, SQL_RESULT_SET_CONCURRENCY_UPDATABLE]
+ * - return 6 (\b110) => [SQL_RESULT_SET_CONCURRENCY_READ_ONLY, SQL_RESULT_SET_CONCURRENCY_UPDATABLE]
+ * - return 7 (\b111) => [SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED, SQL_RESULT_SET_CONCURRENCY_READ_ONLY, SQL_RESULT_SET_CONCURRENCY_UPDATABLE]
+ * Valid result set types are described under `arrow.flight.protocol.sql.SqlSupportedResultSetConcurrency`.
+ */
+ SQL_SUPPORTED_CONCURRENCIES_FOR_RESULT_SET_UNSPECIFIED = 568;
+
+ /*
+ * Returns an int32 bitmask value concurrency types supported for
+ * `arrow.flight.protocol.sql.SqlSupportedResultSetType.SQL_RESULT_SET_TYPE_FORWARD_ONLY`.
+ *
+ * For instance:
+ * - return 0 (\b0) => [] (no supported concurrency types for this result set type)
+ * - return 1 (\b1) => [SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED]
+ * - return 2 (\b10) => [SQL_RESULT_SET_CONCURRENCY_READ_ONLY]
+ * - return 3 (\b11) => [SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED, SQL_RESULT_SET_CONCURRENCY_READ_ONLY]
+ * - return 4 (\b100) => [SQL_RESULT_SET_CONCURRENCY_UPDATABLE]
+ * - return 5 (\b101) => [SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED, SQL_RESULT_SET_CONCURRENCY_UPDATABLE]
+ * - return 6 (\b110) => [SQL_RESULT_SET_CONCURRENCY_READ_ONLY, SQL_RESULT_SET_CONCURRENCY_UPDATABLE]
+ * - return 7 (\b111) => [SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED, SQL_RESULT_SET_CONCURRENCY_READ_ONLY, SQL_RESULT_SET_CONCURRENCY_UPDATABLE]
+ * Valid result set types are described under `arrow.flight.protocol.sql.SqlSupportedResultSetConcurrency`.
+ */
+ SQL_SUPPORTED_CONCURRENCIES_FOR_RESULT_SET_FORWARD_ONLY = 569;
+
+ /*
+ * Returns an int32 bitmask value concurrency types supported for
+ * `arrow.flight.protocol.sql.SqlSupportedResultSetType.SQL_RESULT_SET_TYPE_SCROLL_SENSITIVE`.
+ *
+ * For instance:
+ * - return 0 (\b0) => [] (no supported concurrency types for this result set type)
+ * - return 1 (\b1) => [SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED]
+ * - return 2 (\b10) => [SQL_RESULT_SET_CONCURRENCY_READ_ONLY]
+ * - return 3 (\b11) => [SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED, SQL_RESULT_SET_CONCURRENCY_READ_ONLY]
+ * - return 4 (\b100) => [SQL_RESULT_SET_CONCURRENCY_UPDATABLE]
+ * - return 5 (\b101) => [SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED, SQL_RESULT_SET_CONCURRENCY_UPDATABLE]
+ * - return 6 (\b110) => [SQL_RESULT_SET_CONCURRENCY_READ_ONLY, SQL_RESULT_SET_CONCURRENCY_UPDATABLE]
+ * - return 7 (\b111) => [SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED, SQL_RESULT_SET_CONCURRENCY_READ_ONLY, SQL_RESULT_SET_CONCURRENCY_UPDATABLE]
+ * Valid result set types are described under `arrow.flight.protocol.sql.SqlSupportedResultSetConcurrency`.
+ */
+ SQL_SUPPORTED_CONCURRENCIES_FOR_RESULT_SET_SCROLL_SENSITIVE = 570;
+
+ /*
+ * Returns an int32 bitmask value concurrency types supported for
+ * `arrow.flight.protocol.sql.SqlSupportedResultSetType.SQL_RESULT_SET_TYPE_SCROLL_INSENSITIVE`.
+ *
+ * For instance:
+ * - return 0 (\b0) => [] (no supported concurrency types for this result set type)
+ * - return 1 (\b1) => [SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED]
+ * - return 2 (\b10) => [SQL_RESULT_SET_CONCURRENCY_READ_ONLY]
+ * - return 3 (\b11) => [SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED, SQL_RESULT_SET_CONCURRENCY_READ_ONLY]
+ * - return 4 (\b100) => [SQL_RESULT_SET_CONCURRENCY_UPDATABLE]
+ * - return 5 (\b101) => [SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED, SQL_RESULT_SET_CONCURRENCY_UPDATABLE]
+ * - return 6 (\b110) => [SQL_RESULT_SET_CONCURRENCY_READ_ONLY, SQL_RESULT_SET_CONCURRENCY_UPDATABLE]
+ * - return 7 (\b111) => [SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED, SQL_RESULT_SET_CONCURRENCY_READ_ONLY, SQL_RESULT_SET_CONCURRENCY_UPDATABLE]
+ * Valid result set types are described under `arrow.flight.protocol.sql.SqlSupportedResultSetConcurrency`.
+ */
+ SQL_SUPPORTED_CONCURRENCIES_FOR_RESULT_SET_SCROLL_INSENSITIVE = 571;
+
+ /*
+ * Retrieves a boolean value indicating whether this database supports batch updates.
+ *
+ * - false: if this database does not support batch updates;
+ * - true: if this database supports batch updates.
+ */
+ SQL_BATCH_UPDATES_SUPPORTED = 572;
+
+ /*
+ * Retrieves a boolean value indicating whether this database supports savepoints.
+ *
+ * Returns:
+ * - false: if this database does not support savepoints;
+ * - true: if this database supports savepoints.
+ */
+ SQL_SAVEPOINTS_SUPPORTED = 573;
+
+ /*
+ * Retrieves a boolean value indicating whether named parameters are supported in callable statements.
+ *
+ * Returns:
+ * - false: if named parameters in callable statements are unsupported;
+ * - true: if named parameters in callable statements are supported.
+ */
+ SQL_NAMED_PARAMETERS_SUPPORTED = 574;
+
+ /*
+ * Retrieves a boolean value indicating whether updates made to a LOB are made on a copy or directly to the LOB.
+ *
+ * Returns:
+ * - false: if updates made to a LOB are made directly to the LOB;
+ * - true: if updates made to a LOB are made on a copy.
+ */
+ SQL_LOCATORS_UPDATE_COPY = 575;
+
+ /*
+ * Retrieves a boolean value indicating whether invoking user-defined or vendor functions
+ * using the stored procedure escape syntax is supported.
+ *
+ * Returns:
+ * - false: if invoking user-defined or vendor functions using the stored procedure escape syntax is unsupported;
+ * - true: if invoking user-defined or vendor functions using the stored procedure escape syntax is supported.
+ */
+ SQL_STORED_FUNCTIONS_USING_CALL_SYNTAX_SUPPORTED = 576;
+ }
+
+ // The level of support for Flight SQL transaction RPCs.
+ enum SqlSupportedTransaction {
+ // Unknown/not indicated/no support
+ SQL_SUPPORTED_TRANSACTION_NONE = 0;
+ // Transactions, but not savepoints.
+ // A savepoint is a mark within a transaction that can be individually
+ // rolled back to. Not all databases support savepoints.
+ SQL_SUPPORTED_TRANSACTION_TRANSACTION = 1;
+ // Transactions and savepoints
+ SQL_SUPPORTED_TRANSACTION_SAVEPOINT = 2;
+ }
+
+ enum SqlSupportedCaseSensitivity {
+ SQL_CASE_SENSITIVITY_UNKNOWN = 0;
+ SQL_CASE_SENSITIVITY_CASE_INSENSITIVE = 1;
+ SQL_CASE_SENSITIVITY_UPPERCASE = 2;
+ SQL_CASE_SENSITIVITY_LOWERCASE = 3;
+ }
+
+ enum SqlNullOrdering {
+ SQL_NULLS_SORTED_HIGH = 0;
+ SQL_NULLS_SORTED_LOW = 1;
+ SQL_NULLS_SORTED_AT_START = 2;
+ SQL_NULLS_SORTED_AT_END = 3;
+ }
+
+ enum SupportedSqlGrammar {
+ SQL_MINIMUM_GRAMMAR = 0;
+ SQL_CORE_GRAMMAR = 1;
+ SQL_EXTENDED_GRAMMAR = 2;
+ }
+
+ enum SupportedAnsi92SqlGrammarLevel {
+ ANSI92_ENTRY_SQL = 0;
+ ANSI92_INTERMEDIATE_SQL = 1;
+ ANSI92_FULL_SQL = 2;
+ }
+
+ enum SqlOuterJoinsSupportLevel {
+ SQL_JOINS_UNSUPPORTED = 0;
+ SQL_LIMITED_OUTER_JOINS = 1;
+ SQL_FULL_OUTER_JOINS = 2;
+ }
+
+ enum SqlSupportedGroupBy {
+ SQL_GROUP_BY_UNRELATED = 0;
+ SQL_GROUP_BY_BEYOND_SELECT = 1;
+ }
+
+ enum SqlSupportedElementActions {
+ SQL_ELEMENT_IN_PROCEDURE_CALLS = 0;
+ SQL_ELEMENT_IN_INDEX_DEFINITIONS = 1;
+ SQL_ELEMENT_IN_PRIVILEGE_DEFINITIONS = 2;
+ }
+
+ enum SqlSupportedPositionedCommands {
+ SQL_POSITIONED_DELETE = 0;
+ SQL_POSITIONED_UPDATE = 1;
+ }
+
+ enum SqlSupportedSubqueries {
+ SQL_SUBQUERIES_IN_COMPARISONS = 0;
+ SQL_SUBQUERIES_IN_EXISTS = 1;
+ SQL_SUBQUERIES_IN_INS = 2;
+ SQL_SUBQUERIES_IN_QUANTIFIEDS = 3;
+ }
+
+ enum SqlSupportedUnions {
+ SQL_UNION = 0;
+ SQL_UNION_ALL = 1;
+ }
+
+ enum SqlTransactionIsolationLevel {
+ SQL_TRANSACTION_NONE = 0;
+ SQL_TRANSACTION_READ_UNCOMMITTED = 1;
+ SQL_TRANSACTION_READ_COMMITTED = 2;
+ SQL_TRANSACTION_REPEATABLE_READ = 3;
+ SQL_TRANSACTION_SERIALIZABLE = 4;
+ }
+
+ enum SqlSupportedTransactions {
+ SQL_TRANSACTION_UNSPECIFIED = 0;
+ SQL_DATA_DEFINITION_TRANSACTIONS = 1;
+ SQL_DATA_MANIPULATION_TRANSACTIONS = 2;
+ }
+
+ enum SqlSupportedResultSetType {
+ SQL_RESULT_SET_TYPE_UNSPECIFIED = 0;
+ SQL_RESULT_SET_TYPE_FORWARD_ONLY = 1;
+ SQL_RESULT_SET_TYPE_SCROLL_INSENSITIVE = 2;
+ SQL_RESULT_SET_TYPE_SCROLL_SENSITIVE = 3;
+ }
+
+ enum SqlSupportedResultSetConcurrency {
+ SQL_RESULT_SET_CONCURRENCY_UNSPECIFIED = 0;
+ SQL_RESULT_SET_CONCURRENCY_READ_ONLY = 1;
+ SQL_RESULT_SET_CONCURRENCY_UPDATABLE = 2;
+ }
+
+ enum SqlSupportsConvert {
+ SQL_CONVERT_BIGINT = 0;
+ SQL_CONVERT_BINARY = 1;
+ SQL_CONVERT_BIT = 2;
+ SQL_CONVERT_CHAR = 3;
+ SQL_CONVERT_DATE = 4;
+ SQL_CONVERT_DECIMAL = 5;
+ SQL_CONVERT_FLOAT = 6;
+ SQL_CONVERT_INTEGER = 7;
+ SQL_CONVERT_INTERVAL_DAY_TIME = 8;
+ SQL_CONVERT_INTERVAL_YEAR_MONTH = 9;
+ SQL_CONVERT_LONGVARBINARY = 10;
+ SQL_CONVERT_LONGVARCHAR = 11;
+ SQL_CONVERT_NUMERIC = 12;
+ SQL_CONVERT_REAL = 13;
+ SQL_CONVERT_SMALLINT = 14;
+ SQL_CONVERT_TIME = 15;
+ SQL_CONVERT_TIMESTAMP = 16;
+ SQL_CONVERT_TINYINT = 17;
+ SQL_CONVERT_VARBINARY = 18;
+ SQL_CONVERT_VARCHAR = 19;
+ }
+
+ /**
+ * The JDBC/ODBC-defined type of any object.
+ * All the values here are the sames as in the JDBC and ODBC specs.
+ */
+ enum XdbcDataType {
+ XDBC_UNKNOWN_TYPE = 0;
+ XDBC_CHAR = 1;
+ XDBC_NUMERIC = 2;
+ XDBC_DECIMAL = 3;
+ XDBC_INTEGER = 4;
+ XDBC_SMALLINT = 5;
+ XDBC_FLOAT = 6;
+ XDBC_REAL = 7;
+ XDBC_DOUBLE = 8;
+ XDBC_DATETIME = 9;
+ XDBC_INTERVAL = 10;
+ XDBC_VARCHAR = 12;
+ XDBC_DATE = 91;
+ XDBC_TIME = 92;
+ XDBC_TIMESTAMP = 93;
+ XDBC_LONGVARCHAR = -1;
+ XDBC_BINARY = -2;
+ XDBC_VARBINARY = -3;
+ XDBC_LONGVARBINARY = -4;
+ XDBC_BIGINT = -5;
+ XDBC_TINYINT = -6;
+ XDBC_BIT = -7;
+ XDBC_WCHAR = -8;
+ XDBC_WVARCHAR = -9;
+ }
+
+ /**
+ * Detailed subtype information for XDBC_TYPE_DATETIME and XDBC_TYPE_INTERVAL.
+ */
+ enum XdbcDatetimeSubcode {
+ option allow_alias = true;
+ XDBC_SUBCODE_UNKNOWN = 0;
+ XDBC_SUBCODE_YEAR = 1;
+ XDBC_SUBCODE_DATE = 1;
+ XDBC_SUBCODE_TIME = 2;
+ XDBC_SUBCODE_MONTH = 2;
+ XDBC_SUBCODE_TIMESTAMP = 3;
+ XDBC_SUBCODE_DAY = 3;
+ XDBC_SUBCODE_TIME_WITH_TIMEZONE = 4;
+ XDBC_SUBCODE_HOUR = 4;
+ XDBC_SUBCODE_TIMESTAMP_WITH_TIMEZONE = 5;
+ XDBC_SUBCODE_MINUTE = 5;
+ XDBC_SUBCODE_SECOND = 6;
+ XDBC_SUBCODE_YEAR_TO_MONTH = 7;
+ XDBC_SUBCODE_DAY_TO_HOUR = 8;
+ XDBC_SUBCODE_DAY_TO_MINUTE = 9;
+ XDBC_SUBCODE_DAY_TO_SECOND = 10;
+ XDBC_SUBCODE_HOUR_TO_MINUTE = 11;
+ XDBC_SUBCODE_HOUR_TO_SECOND = 12;
+ XDBC_SUBCODE_MINUTE_TO_SECOND = 13;
+ XDBC_SUBCODE_INTERVAL_YEAR = 101;
+ XDBC_SUBCODE_INTERVAL_MONTH = 102;
+ XDBC_SUBCODE_INTERVAL_DAY = 103;
+ XDBC_SUBCODE_INTERVAL_HOUR = 104;
+ XDBC_SUBCODE_INTERVAL_MINUTE = 105;
+ XDBC_SUBCODE_INTERVAL_SECOND = 106;
+ XDBC_SUBCODE_INTERVAL_YEAR_TO_MONTH = 107;
+ XDBC_SUBCODE_INTERVAL_DAY_TO_HOUR = 108;
+ XDBC_SUBCODE_INTERVAL_DAY_TO_MINUTE = 109;
+ XDBC_SUBCODE_INTERVAL_DAY_TO_SECOND = 110;
+ XDBC_SUBCODE_INTERVAL_HOUR_TO_MINUTE = 111;
+ XDBC_SUBCODE_INTERVAL_HOUR_TO_SECOND = 112;
+ XDBC_SUBCODE_INTERVAL_MINUTE_TO_SECOND = 113;
+ }
+
+ enum Nullable {
+ /**
+ * Indicates that the fields does not allow the use of null values.
+ */
+ NULLABILITY_NO_NULLS = 0;
+
+ /**
+ * Indicates that the fields allow the use of null values.
+ */
+ NULLABILITY_NULLABLE = 1;
+
+ /**
+ * Indicates that nullability of the fields can not be determined.
+ */
+ NULLABILITY_UNKNOWN = 2;
+ }
+
+ enum Searchable {
+ /**
+ * Indicates that column can not be used in a WHERE clause.
+ */
+ SEARCHABLE_NONE = 0;
+
+ /**
+ * Indicates that the column can be used in a WHERE clause if it is using a
+ * LIKE operator.
+ */
+ SEARCHABLE_CHAR = 1;
+
+ /**
+ * Indicates that the column can be used In a WHERE clause with any
+ * operator other than LIKE.
+ *
+ * - Allowed operators: comparison, quantified comparison, BETWEEN,
+ * DISTINCT, IN, MATCH, and UNIQUE.
+ */
+ SEARCHABLE_BASIC = 2;
+
+ /**
+ * Indicates that the column can be used in a WHERE clause using any operator.
+ */
+ SEARCHABLE_FULL = 3;
+ }
+
+ /*
+ * Represents a request to retrieve information about data type supported on a Flight SQL enabled backend.
+ * Used in the command member of FlightDescriptor for the following RPC calls:
+ * - GetSchema: return the schema of the query.
+ * - GetFlightInfo: execute the catalog metadata request.
+ *
+ * The returned schema will be:
+ * <
+ * type_name: utf8 not null (The name of the data type, for example: VARCHAR, INTEGER, etc),
+ * data_type: int32 not null (The SQL data type),
+ * column_size: int32 (The maximum size supported by that column.
+ * In case of exact numeric types, this represents the maximum precision.
+ * In case of string types, this represents the character length.
+ * In case of datetime data types, this represents the length in characters of the string representation.
+ * NULL is returned for data types where column size is not applicable.),
+ * literal_prefix: utf8 (Character or characters used to prefix a literal, NULL is returned for
+ * data types where a literal prefix is not applicable.),
+ * literal_suffix: utf8 (Character or characters used to terminate a literal,
+ * NULL is returned for data types where a literal suffix is not applicable.),
+ * create_params: list<utf8 not null>
+ * (A list of keywords corresponding to which parameters can be used when creating
+ * a column for that specific type.
+ * NULL is returned if there are no parameters for the data type definition.),
+ * nullable: int32 not null (Shows if the data type accepts a NULL value. The possible values can be seen in the
+ * Nullable enum.),
+ * case_sensitive: bool not null (Shows if a character data type is case-sensitive in collations and comparisons),
+ * searchable: int32 not null (Shows how the data type is used in a WHERE clause. The possible values can be seen in the
+ * Searchable enum.),
+ * unsigned_attribute: bool (Shows if the data type is unsigned. NULL is returned if the attribute is
+ * not applicable to the data type or the data type is not numeric.),
+ * fixed_prec_scale: bool not null (Shows if the data type has predefined fixed precision and scale.),
+ * auto_increment: bool (Shows if the data type is auto incremental. NULL is returned if the attribute
+ * is not applicable to the data type or the data type is not numeric.),
+ * local_type_name: utf8 (Localized version of the data source-dependent name of the data type. NULL
+ * is returned if a localized name is not supported by the data source),
+ * minimum_scale: int32 (The minimum scale of the data type on the data source.
+ * If a data type has a fixed scale, the MINIMUM_SCALE and MAXIMUM_SCALE
+ * columns both contain this value. NULL is returned if scale is not applicable.),
+ * maximum_scale: int32 (The maximum scale of the data type on the data source.
+ * NULL is returned if scale is not applicable.),
+ * sql_data_type: int32 not null (The value of the SQL DATA TYPE which has the same values
+ * as data_type value. Except for interval and datetime, which
+ * uses generic values. More info about those types can be
+ * obtained through datetime_subcode. The possible values can be seen
+ * in the XdbcDataType enum.),
+ * datetime_subcode: int32 (Only used when the SQL DATA TYPE is interval or datetime. It contains
+ * its sub types. For type different from interval and datetime, this value
+ * is NULL. The possible values can be seen in the XdbcDatetimeSubcode enum.),
+ * num_prec_radix: int32 (If the data type is an approximate numeric type, this column contains
+ * the value 2 to indicate that COLUMN_SIZE specifies a number of bits. For
+ * exact numeric types, this column contains the value 10 to indicate that
+ * column size specifies a number of decimal digits. Otherwise, this column is NULL.),
+ * interval_precision: int32 (If the data type is an interval data type, then this column contains the value
+ * of the interval leading precision. Otherwise, this column is NULL. This fields
+ * is only relevant to be used by ODBC).
+ * >
+ * The returned data should be ordered by data_type and then by type_name.
+ */
+ message CommandGetXdbcTypeInfo {
+ option (experimental) = true;
+
+ /*
+ * Specifies the data type to search for the info.
+ */
+ optional int32 data_type = 1;
+ }
+
+ /*
+ * Represents a request to retrieve the list of catalogs on a Flight SQL enabled backend.
+ * The definition of a catalog depends on vendor/implementation. It is usually the database itself
+ * Used in the command member of FlightDescriptor for the following RPC calls:
+ * - GetSchema: return the Arrow schema of the query.
+ * - GetFlightInfo: execute the catalog metadata request.
+ *
+ * The returned Arrow schema will be:
+ * <
+ * catalog_name: utf8 not null
+ * >
+ * The returned data should be ordered by catalog_name.
+ */
+ message CommandGetCatalogs {
+ option (experimental) = true;
+ }
+
+ /*
+ * Represents a request to retrieve the list of database schemas on a Flight SQL enabled backend.
+ * The definition of a database schema depends on vendor/implementation. It is usually a collection of tables.
+ * Used in the command member of FlightDescriptor for the following RPC calls:
+ * - GetSchema: return the Arrow schema of the query.
+ * - GetFlightInfo: execute the catalog metadata request.
+ *
+ * The returned Arrow schema will be:
+ * <
+ * catalog_name: utf8,
+ * db_schema_name: utf8 not null
+ * >
+ * The returned data should be ordered by catalog_name, then db_schema_name.
+ */
+ message CommandGetDbSchemas {
+ option (experimental) = true;
+
+ /*
+ * Specifies the Catalog to search for the tables.
+ * An empty string retrieves those without a catalog.
+ * If omitted the catalog name should not be used to narrow the search.
+ */
+ optional string catalog = 1;
+
+ /*
+ * Specifies a filter pattern for schemas to search for.
+ * When no db_schema_filter_pattern is provided, the pattern will not be used to narrow the search.
+ * In the pattern string, two special characters can be used to denote matching rules:
+ * - "%" means to match any substring with 0 or more characters.
+ * - "_" means to match any one character.
+ */
+ optional string db_schema_filter_pattern = 2;
+ }
+
+ /*
+ * Represents a request to retrieve the list of tables, and optionally their schemas, on a Flight SQL enabled backend.
+ * Used in the command member of FlightDescriptor for the following RPC calls:
+ * - GetSchema: return the Arrow schema of the query.
+ * - GetFlightInfo: execute the catalog metadata request.
+ *
+ * The returned Arrow schema will be:
+ * <
+ * catalog_name: utf8,
+ * db_schema_name: utf8,
+ * table_name: utf8 not null,
+ * table_type: utf8 not null,
+ * [optional] table_schema: bytes not null (schema of the table as described in Schema.fbs::Schema,
+ * it is serialized as an IPC message.)
+ * >
+ * Fields on table_schema may contain the following metadata:
+ * - ARROW:FLIGHT:SQL:CATALOG_NAME - Table's catalog name
+ * - ARROW:FLIGHT:SQL:DB_SCHEMA_NAME - Database schema name
+ * - ARROW:FLIGHT:SQL:TABLE_NAME - Table name
+ * - ARROW:FLIGHT:SQL:TYPE_NAME - The data source-specific name for the data type of the column.
+ * - ARROW:FLIGHT:SQL:PRECISION - Column precision/size
+ * - ARROW:FLIGHT:SQL:SCALE - Column scale/decimal digits if applicable
+ * - ARROW:FLIGHT:SQL:IS_AUTO_INCREMENT - "1" indicates if the column is auto incremented, "0" otherwise.
+ * - ARROW:FLIGHT:SQL:IS_CASE_SENSITIVE - "1" indicates if the column is case sensitive, "0" otherwise.
+ * - ARROW:FLIGHT:SQL:IS_READ_ONLY - "1" indicates if the column is read only, "0" otherwise.
+ * - ARROW:FLIGHT:SQL:IS_SEARCHABLE - "1" indicates if the column is searchable via WHERE clause, "0" otherwise.
+ * The returned data should be ordered by catalog_name, db_schema_name, table_name, then table_type, followed by table_schema if requested.
+ */
+ message CommandGetTables {
+ option (experimental) = true;
+
+ /*
+ * Specifies the Catalog to search for the tables.
+ * An empty string retrieves those without a catalog.
+ * If omitted the catalog name should not be used to narrow the search.
+ */
+ optional string catalog = 1;
+
+ /*
+ * Specifies a filter pattern for schemas to search for.
+ * When no db_schema_filter_pattern is provided, all schemas matching other filters are searched.
+ * In the pattern string, two special characters can be used to denote matching rules:
+ * - "%" means to match any substring with 0 or more characters.
+ * - "_" means to match any one character.
+ */
+ optional string db_schema_filter_pattern = 2;
+
+ /*
+ * Specifies a filter pattern for tables to search for.
+ * When no table_name_filter_pattern is provided, all tables matching other filters are searched.
+ * In the pattern string, two special characters can be used to denote matching rules:
+ * - "%" means to match any substring with 0 or more characters.
+ * - "_" means to match any one character.
+ */
+ optional string table_name_filter_pattern = 3;
+
+ /*
+ * Specifies a filter of table types which must match.
+ * The table types depend on vendor/implementation. It is usually used to separate tables from views or system tables.
+ * TABLE, VIEW, and SYSTEM TABLE are commonly supported.
+ */
+ repeated string table_types = 4;
+
+ // Specifies if the Arrow schema should be returned for found tables.
+ bool include_schema = 5;
+ }
+
+ /*
+ * Represents a request to retrieve the list of table types on a Flight SQL enabled backend.
+ * The table types depend on vendor/implementation. It is usually used to separate tables from views or system tables.
+ * TABLE, VIEW, and SYSTEM TABLE are commonly supported.
+ * Used in the command member of FlightDescriptor for the following RPC calls:
+ * - GetSchema: return the Arrow schema of the query.
+ * - GetFlightInfo: execute the catalog metadata request.
+ *
+ * The returned Arrow schema will be:
+ * <
+ * table_type: utf8 not null
+ * >
+ * The returned data should be ordered by table_type.
+ */
+ message CommandGetTableTypes {
+ option (experimental) = true;
+ }
+
+ /*
+ * Represents a request to retrieve the primary keys of a table on a Flight SQL enabled backend.
+ * Used in the command member of FlightDescriptor for the following RPC calls:
+ * - GetSchema: return the Arrow schema of the query.
+ * - GetFlightInfo: execute the catalog metadata request.
+ *
+ * The returned Arrow schema will be:
+ * <
+ * catalog_name: utf8,
+ * db_schema_name: utf8,
+ * table_name: utf8 not null,
+ * column_name: utf8 not null,
+ * key_name: utf8,
+ * key_sequence: int32 not null
+ * >
+ * The returned data should be ordered by catalog_name, db_schema_name, table_name, key_name, then key_sequence.
+ */
+ message CommandGetPrimaryKeys {
+ option (experimental) = true;
+
+ /*
+ * Specifies the catalog to search for the table.
+ * An empty string retrieves those without a catalog.
+ * If omitted the catalog name should not be used to narrow the search.
+ */
+ optional string catalog = 1;
+
+ /*
+ * Specifies the schema to search for the table.
+ * An empty string retrieves those without a schema.
+ * If omitted the schema name should not be used to narrow the search.
+ */
+ optional string db_schema = 2;
+
+ // Specifies the table to get the primary keys for.
+ string table = 3;
+ }
+
+ enum UpdateDeleteRules {
+ CASCADE = 0;
+ RESTRICT = 1;
+ SET_NULL = 2;
+ NO_ACTION = 3;
+ SET_DEFAULT = 4;
+ }
+
+ /*
+ * Represents a request to retrieve a description of the foreign key columns that reference the given table's
+ * primary key columns (the foreign keys exported by a table) of a table on a Flight SQL enabled backend.
+ * Used in the command member of FlightDescriptor for the following RPC calls:
+ * - GetSchema: return the Arrow schema of the query.
+ * - GetFlightInfo: execute the catalog metadata request.
+ *
+ * The returned Arrow schema will be:
+ * <
+ * pk_catalog_name: utf8,
+ * pk_db_schema_name: utf8,
+ * pk_table_name: utf8 not null,
+ * pk_column_name: utf8 not null,
+ * fk_catalog_name: utf8,
+ * fk_db_schema_name: utf8,
+ * fk_table_name: utf8 not null,
+ * fk_column_name: utf8 not null,
+ * key_sequence: int32 not null,
+ * fk_key_name: utf8,
+ * pk_key_name: utf8,
+ * update_rule: uint8 not null,
+ * delete_rule: uint8 not null
+ * >
+ * The returned data should be ordered by fk_catalog_name, fk_db_schema_name, fk_table_name, fk_key_name, then key_sequence.
+ * update_rule and delete_rule returns a byte that is equivalent to actions declared on UpdateDeleteRules enum.
+ */
+ message CommandGetExportedKeys {
+ option (experimental) = true;
+
+ /*
+ * Specifies the catalog to search for the foreign key table.
+ * An empty string retrieves those without a catalog.
+ * If omitted the catalog name should not be used to narrow the search.
+ */
+ optional string catalog = 1;
+
+ /*
+ * Specifies the schema to search for the foreign key table.
+ * An empty string retrieves those without a schema.
+ * If omitted the schema name should not be used to narrow the search.
+ */
+ optional string db_schema = 2;
+
+ // Specifies the foreign key table to get the foreign keys for.
+ string table = 3;
+ }
+
+ /*
+ * Represents a request to retrieve the foreign keys of a table on a Flight SQL enabled backend.
+ * Used in the command member of FlightDescriptor for the following RPC calls:
+ * - GetSchema: return the Arrow schema of the query.
+ * - GetFlightInfo: execute the catalog metadata request.
+ *
+ * The returned Arrow schema will be:
+ * <
+ * pk_catalog_name: utf8,
+ * pk_db_schema_name: utf8,
+ * pk_table_name: utf8 not null,
+ * pk_column_name: utf8 not null,
+ * fk_catalog_name: utf8,
+ * fk_db_schema_name: utf8,
+ * fk_table_name: utf8 not null,
+ * fk_column_name: utf8 not null,
+ * key_sequence: int32 not null,
+ * fk_key_name: utf8,
+ * pk_key_name: utf8,
+ * update_rule: uint8 not null,
+ * delete_rule: uint8 not null
+ * >
+ * The returned data should be ordered by pk_catalog_name, pk_db_schema_name, pk_table_name, pk_key_name, then key_sequence.
+ * update_rule and delete_rule returns a byte that is equivalent to actions:
+ * - 0 = CASCADE
+ * - 1 = RESTRICT
+ * - 2 = SET NULL
+ * - 3 = NO ACTION
+ * - 4 = SET DEFAULT
+ */
+ message CommandGetImportedKeys {
+ option (experimental) = true;
+
+ /*
+ * Specifies the catalog to search for the primary key table.
+ * An empty string retrieves those without a catalog.
+ * If omitted the catalog name should not be used to narrow the search.
+ */
+ optional string catalog = 1;
+
+ /*
+ * Specifies the schema to search for the primary key table.
+ * An empty string retrieves those without a schema.
+ * If omitted the schema name should not be used to narrow the search.
+ */
+ optional string db_schema = 2;
+
+ // Specifies the primary key table to get the foreign keys for.
+ string table = 3;
+ }
+
+ /*
+ * Represents a request to retrieve a description of the foreign key columns in the given foreign key table that
+ * reference the primary key or the columns representing a unique constraint of the parent table (could be the same
+ * or a different table) on a Flight SQL enabled backend.
+ * Used in the command member of FlightDescriptor for the following RPC calls:
+ * - GetSchema: return the Arrow schema of the query.
+ * - GetFlightInfo: execute the catalog metadata request.
+ *
+ * The returned Arrow schema will be:
+ * <
+ * pk_catalog_name: utf8,
+ * pk_db_schema_name: utf8,
+ * pk_table_name: utf8 not null,
+ * pk_column_name: utf8 not null,
+ * fk_catalog_name: utf8,
+ * fk_db_schema_name: utf8,
+ * fk_table_name: utf8 not null,
+ * fk_column_name: utf8 not null,
+ * key_sequence: int32 not null,
+ * fk_key_name: utf8,
+ * pk_key_name: utf8,
+ * update_rule: uint8 not null,
+ * delete_rule: uint8 not null
+ * >
+ * The returned data should be ordered by pk_catalog_name, pk_db_schema_name, pk_table_name, pk_key_name, then key_sequence.
+ * update_rule and delete_rule returns a byte that is equivalent to actions:
+ * - 0 = CASCADE
+ * - 1 = RESTRICT
+ * - 2 = SET NULL
+ * - 3 = NO ACTION
+ * - 4 = SET DEFAULT
+ */
+ message CommandGetCrossReference {
+ option (experimental) = true;
+
+ /**
+ * The catalog name where the parent table is.
+ * An empty string retrieves those without a catalog.
+ * If omitted the catalog name should not be used to narrow the search.
+ */
+ optional string pk_catalog = 1;
+
+ /**
+ * The Schema name where the parent table is.
+ * An empty string retrieves those without a schema.
+ * If omitted the schema name should not be used to narrow the search.
+ */
+ optional string pk_db_schema = 2;
+
+ /**
+ * The parent table name. It cannot be null.
+ */
+ string pk_table = 3;
+
+ /**
+ * The catalog name where the foreign table is.
+ * An empty string retrieves those without a catalog.
+ * If omitted the catalog name should not be used to narrow the search.
+ */
+ optional string fk_catalog = 4;
+
+ /**
+ * The schema name where the foreign table is.
+ * An empty string retrieves those without a schema.
+ * If omitted the schema name should not be used to narrow the search.
+ */
+ optional string fk_db_schema = 5;
+
+ /**
+ * The foreign table name. It cannot be null.
+ */
+ string fk_table = 6;
+ }
+
+ // Query Execution Action Messages
+
+ /*
+ * Request message for the "CreatePreparedStatement" action on a Flight SQL enabled backend.
+ */
+ message ActionCreatePreparedStatementRequest {
+ option (experimental) = true;
+
+ // The valid SQL string to create a prepared statement for.
+ string query = 1;
+ // Create/execute the prepared statement as part of this transaction (if
+ // unset, executions of the prepared statement will be auto-committed).
+ optional bytes transaction_id = 2;
+ }
+
+ /*
+ * An embedded message describing a Substrait plan to execute.
+ */
+ message SubstraitPlan {
+ option (experimental) = true;
+
+ // The serialized substrait.Plan to create a prepared statement for.
+ // XXX(ARROW-16902): this is bytes instead of an embedded message
+ // because Protobuf does not really support one DLL using Protobuf
+ // definitions from another DLL.
+ bytes plan = 1;
+ // The Substrait release, e.g. "0.12.0". This information is not
+ // tracked in the plan itself, so this is the only way for consumers
+ // to potentially know if they can handle the plan.
+ string version = 2;
+ }
+
+ /*
+ * Request message for the "CreatePreparedSubstraitPlan" action on a Flight SQL enabled backend.
+ */
+ message ActionCreatePreparedSubstraitPlanRequest {
+ option (experimental) = true;
+
+ // The serialized substrait.Plan to create a prepared statement for.
+ SubstraitPlan plan = 1;
+ // Create/execute the prepared statement as part of this transaction (if
+ // unset, executions of the prepared statement will be auto-committed).
+ optional bytes transaction_id = 2;
+ }
+
+ /*
+ * Wrap the result of a "CreatePreparedStatement" or "CreatePreparedSubstraitPlan" action.
+ *
+ * The resultant PreparedStatement can be closed either:
+ * - Manually, through the "ClosePreparedStatement" action;
+ * - Automatically, by a server timeout.
+ *
+ * The result should be wrapped in a google.protobuf.Any message.
+ */
+ message ActionCreatePreparedStatementResult {
+ option (experimental) = true;
+
+ // Opaque handle for the prepared statement on the server.
+ bytes prepared_statement_handle = 1;
+
+ // If a result set generating query was provided, dataset_schema contains the
+ // schema of the dataset as described in Schema.fbs::Schema, it is serialized as an IPC message.
+ bytes dataset_schema = 2;
+
+ // If the query provided contained parameters, parameter_schema contains the
+ // schema of the expected parameters as described in Schema.fbs::Schema, it is serialized as an IPC message.
+ bytes parameter_schema = 3;
+ }
+
+ /*
+ * Request message for the "ClosePreparedStatement" action on a Flight SQL enabled backend.
+ * Closes server resources associated with the prepared statement handle.
+ */
+ message ActionClosePreparedStatementRequest {
+ option (experimental) = true;
+
+ // Opaque handle for the prepared statement on the server.
+ bytes prepared_statement_handle = 1;
+ }
+
+ /*
+ * Request message for the "BeginTransaction" action.
+ * Begins a transaction.
+ */
+ message ActionBeginTransactionRequest {
+ option (experimental) = true;
+ }
+
+ /*
+ * Request message for the "BeginSavepoint" action.
+ * Creates a savepoint within a transaction.
+ *
+ * Only supported if FLIGHT_SQL_TRANSACTION is
+ * FLIGHT_SQL_TRANSACTION_SUPPORT_SAVEPOINT.
+ */
+ message ActionBeginSavepointRequest {
+ option (experimental) = true;
+
+ // The transaction to which a savepoint belongs.
+ bytes transaction_id = 1;
+ // Name for the savepoint.
+ string name = 2;
+ }
+
+ /*
+ * The result of a "BeginTransaction" action.
+ *
+ * The transaction can be manipulated with the "EndTransaction" action, or
+ * automatically via server timeout. If the transaction times out, then it is
+ * automatically rolled back.
+ *
+ * The result should be wrapped in a google.protobuf.Any message.
+ */
+ message ActionBeginTransactionResult {
+ option (experimental) = true;
+
+ // Opaque handle for the transaction on the server.
+ bytes transaction_id = 1;
+ }
+
+ /*
+ * The result of a "BeginSavepoint" action.
+ *
+ * The transaction can be manipulated with the "EndSavepoint" action.
+ * If the associated transaction is committed, rolled back, or times
+ * out, then the savepoint is also invalidated.
+ *
+ * The result should be wrapped in a google.protobuf.Any message.
+ */
+ message ActionBeginSavepointResult {
+ option (experimental) = true;
+
+ // Opaque handle for the savepoint on the server.
+ bytes savepoint_id = 1;
+ }
+
+ /*
+ * Request message for the "EndTransaction" action.
+ *
+ * Commit (COMMIT) or rollback (ROLLBACK) the transaction.
+ *
+ * If the action completes successfully, the transaction handle is
+ * invalidated, as are all associated savepoints.
+ */
+ message ActionEndTransactionRequest {
+ option (experimental) = true;
+
+ enum EndTransaction {
+ END_TRANSACTION_UNSPECIFIED = 0;
+ // Commit the transaction.
+ END_TRANSACTION_COMMIT = 1;
+ // Roll back the transaction.
+ END_TRANSACTION_ROLLBACK = 2;
+ }
+ // Opaque handle for the transaction on the server.
+ bytes transaction_id = 1;
+ // Whether to commit/rollback the given transaction.
+ EndTransaction action = 2;
+ }
+
+ /*
+ * Request message for the "EndSavepoint" action.
+ *
+ * Release (RELEASE) the savepoint or rollback (ROLLBACK) to the
+ * savepoint.
+ *
+ * Releasing a savepoint invalidates that savepoint. Rolling back to
+ * a savepoint does not invalidate the savepoint, but invalidates all
+ * savepoints created after the current savepoint.
+ */
+ message ActionEndSavepointRequest {
+ option (experimental) = true;
+
+ enum EndSavepoint {
+ END_SAVEPOINT_UNSPECIFIED = 0;
+ // Release the savepoint.
+ END_SAVEPOINT_RELEASE = 1;
+ // Roll back to a savepoint.
+ END_SAVEPOINT_ROLLBACK = 2;
+ }
+ // Opaque handle for the savepoint on the server.
+ bytes savepoint_id = 1;
+ // Whether to rollback/release the given savepoint.
+ EndSavepoint action = 2;
+ }
+
+ // Query Execution Messages.
+
+ /*
+ * Represents a SQL query. Used in the command member of FlightDescriptor
+ * for the following RPC calls:
+ * - GetSchema: return the Arrow schema of the query.
+ * Fields on this schema may contain the following metadata:
+ * - ARROW:FLIGHT:SQL:CATALOG_NAME - Table's catalog name
+ * - ARROW:FLIGHT:SQL:DB_SCHEMA_NAME - Database schema name
+ * - ARROW:FLIGHT:SQL:TABLE_NAME - Table name
+ * - ARROW:FLIGHT:SQL:TYPE_NAME - The data source-specific name for the data type of the column.
+ * - ARROW:FLIGHT:SQL:PRECISION - Column precision/size
+ * - ARROW:FLIGHT:SQL:SCALE - Column scale/decimal digits if applicable
+ * - ARROW:FLIGHT:SQL:IS_AUTO_INCREMENT - "1" indicates if the column is auto incremented, "0" otherwise.
+ * - ARROW:FLIGHT:SQL:IS_CASE_SENSITIVE - "1" indicates if the column is case sensitive, "0" otherwise.
+ * - ARROW:FLIGHT:SQL:IS_READ_ONLY - "1" indicates if the column is read only, "0" otherwise.
+ * - ARROW:FLIGHT:SQL:IS_SEARCHABLE - "1" indicates if the column is searchable via WHERE clause, "0" otherwise.
+ * - GetFlightInfo: execute the query.
+ */
+ message CommandStatementQuery {
+ option (experimental) = true;
+
+ // The SQL syntax.
+ string query = 1;
+ // Include the query as part of this transaction (if unset, the query is auto-committed).
+ optional bytes transaction_id = 2;
+ }
+
+ /*
+ * Represents a Substrait plan. Used in the command member of FlightDescriptor
+ * for the following RPC calls:
+ * - GetSchema: return the Arrow schema of the query.
+ * Fields on this schema may contain the following metadata:
+ * - ARROW:FLIGHT:SQL:CATALOG_NAME - Table's catalog name
+ * - ARROW:FLIGHT:SQL:DB_SCHEMA_NAME - Database schema name
+ * - ARROW:FLIGHT:SQL:TABLE_NAME - Table name
+ * - ARROW:FLIGHT:SQL:TYPE_NAME - The data source-specific name for the data type of the column.
+ * - ARROW:FLIGHT:SQL:PRECISION - Column precision/size
+ * - ARROW:FLIGHT:SQL:SCALE - Column scale/decimal digits if applicable
+ * - ARROW:FLIGHT:SQL:IS_AUTO_INCREMENT - "1" indicates if the column is auto incremented, "0" otherwise.
+ * - ARROW:FLIGHT:SQL:IS_CASE_SENSITIVE - "1" indicates if the column is case sensitive, "0" otherwise.
+ * - ARROW:FLIGHT:SQL:IS_READ_ONLY - "1" indicates if the column is read only, "0" otherwise.
+ * - ARROW:FLIGHT:SQL:IS_SEARCHABLE - "1" indicates if the column is searchable via WHERE clause, "0" otherwise.
+ * - GetFlightInfo: execute the query.
+ * - DoPut: execute the query.
+ */
+ message CommandStatementSubstraitPlan {
+ option (experimental) = true;
+
+ // A serialized substrait.Plan
+ SubstraitPlan plan = 1;
+ // Include the query as part of this transaction (if unset, the query is auto-committed).
+ optional bytes transaction_id = 2;
+ }
+
+ /**
+ * Represents a ticket resulting from GetFlightInfo with a CommandStatementQuery.
+ * This should be used only once and treated as an opaque value, that is, clients should not attempt to parse this.
+ */
+ message TicketStatementQuery {
+ option (experimental) = true;
+
+ // Unique identifier for the instance of the statement to execute.
+ bytes statement_handle = 1;
+ }
+
+ /*
+ * Represents an instance of executing a prepared statement. Used in the command member of FlightDescriptor for
+ * the following RPC calls:
+ * - GetSchema: return the Arrow schema of the query.
+ * Fields on this schema may contain the following metadata:
+ * - ARROW:FLIGHT:SQL:CATALOG_NAME - Table's catalog name
+ * - ARROW:FLIGHT:SQL:DB_SCHEMA_NAME - Database schema name
+ * - ARROW:FLIGHT:SQL:TABLE_NAME - Table name
+ * - ARROW:FLIGHT:SQL:TYPE_NAME - The data source-specific name for the data type of the column.
+ * - ARROW:FLIGHT:SQL:PRECISION - Column precision/size
+ * - ARROW:FLIGHT:SQL:SCALE - Column scale/decimal digits if applicable
+ * - ARROW:FLIGHT:SQL:IS_AUTO_INCREMENT - "1" indicates if the column is auto incremented, "0" otherwise.
+ * - ARROW:FLIGHT:SQL:IS_CASE_SENSITIVE - "1" indicates if the column is case sensitive, "0" otherwise.
+ * - ARROW:FLIGHT:SQL:IS_READ_ONLY - "1" indicates if the column is read only, "0" otherwise.
+ * - ARROW:FLIGHT:SQL:IS_SEARCHABLE - "1" indicates if the column is searchable via WHERE clause, "0" otherwise.
+ * - DoPut: bind parameter values. All of the bound parameter sets will be executed as a single atomic execution.
+ * - GetFlightInfo: execute the prepared statement instance.
+ */
+ message CommandPreparedStatementQuery {
+ option (experimental) = true;
+
+ // Opaque handle for the prepared statement on the server.
+ bytes prepared_statement_handle = 1;
+ }
+
+ /*
+ * Represents a SQL update query. Used in the command member of FlightDescriptor
+ * for the the RPC call DoPut to cause the server to execute the included SQL update.
+ */
+ message CommandStatementUpdate {
+ option (experimental) = true;
+
+ // The SQL syntax.
+ string query = 1;
+ // Include the query as part of this transaction (if unset, the query is auto-committed).
+ optional bytes transaction_id = 2;
+ }
+
+ /*
+ * Represents a SQL update query. Used in the command member of FlightDescriptor
+ * for the the RPC call DoPut to cause the server to execute the included
+ * prepared statement handle as an update.
+ */
+ message CommandPreparedStatementUpdate {
+ option (experimental) = true;
+
+ // Opaque handle for the prepared statement on the server.
+ bytes prepared_statement_handle = 1;
+ }
+
+ /*
+ * Returned from the RPC call DoPut when a CommandStatementUpdate
+ * CommandPreparedStatementUpdate was in the request, containing
+ * results from the update.
+ */
+ message DoPutUpdateResult {
+ option (experimental) = true;
+
+ // The number of records updated. A return value of -1 represents
+ // an unknown updated record count.
+ int64 record_count = 1;
+ }
+
+ /*
+ * Request message for the "CancelQuery" action.
+ *
+ * Explicitly cancel a running query.
+ *
+ * This lets a single client explicitly cancel work, no matter how many clients
+ * are involved/whether the query is distributed or not, given server support.
+ * The transaction/statement is not rolled back; it is the application's job to
+ * commit or rollback as appropriate. This only indicates the client no longer
+ * wishes to read the remainder of the query results or continue submitting
+ * data.
+ *
+ * This command is idempotent.
+ */
+ message ActionCancelQueryRequest {
+ option (experimental) = true;
+
+ // The result of the GetFlightInfo RPC that initiated the query.
+ // XXX(ARROW-16902): this must be a serialized FlightInfo, but is
+ // rendered as bytes because Protobuf does not really support one
+ // DLL using Protobuf definitions from another DLL.
+ bytes info = 1;
+ }
+
+ /*
+ * The result of cancelling a query.
+ *
+ * The result should be wrapped in a google.protobuf.Any message.
+ */
+ message ActionCancelQueryResult {
+ option (experimental) = true;
+
+ enum CancelResult {
+ // The cancellation status is unknown. Servers should avoid using
+ // this value (send a NOT_FOUND error if the requested query is
+ // not known). Clients can retry the request.
+ CANCEL_RESULT_UNSPECIFIED = 0;
+ // The cancellation request is complete. Subsequent requests with
+ // the same payload may return CANCELLED or a NOT_FOUND error.
+ CANCEL_RESULT_CANCELLED = 1;
+ // The cancellation request is in progress. The client may retry
+ // the cancellation request.
+ CANCEL_RESULT_CANCELLING = 2;
+ // The query is not cancellable. The client should not retry the
+ // cancellation request.
+ CANCEL_RESULT_NOT_CANCELLABLE = 3;
+ }
+
+ CancelResult result = 1;
+ }
+
+ extend google.protobuf.MessageOptions {
+ bool experimental = 1000;
+ }
\ No newline at end of file
|
diff --git a/arrow-flight/tests/client.rs b/arrow-flight/tests/client.rs
index ed928a52c99a..8ea542879a27 100644
--- a/arrow-flight/tests/client.rs
+++ b/arrow-flight/tests/client.rs
@@ -104,6 +104,7 @@ fn test_flight_info(request: &FlightDescriptor) -> FlightInfo {
flight_descriptor: Some(request.clone()),
total_bytes: 123,
total_records: 456,
+ ordered: false,
}
}
diff --git a/arrow-flight/tests/flight_sql_client_cli.rs b/arrow-flight/tests/flight_sql_client_cli.rs
index 248b3732ff97..9b3baca9ba6c 100644
--- a/arrow-flight/tests/flight_sql_client_cli.rs
+++ b/arrow-flight/tests/flight_sql_client_cli.rs
@@ -21,13 +21,17 @@ use arrow_array::{ArrayRef, Int64Array, RecordBatch, StringArray};
use arrow_flight::{
flight_service_server::{FlightService, FlightServiceServer},
sql::{
- server::FlightSqlService, ActionClosePreparedStatementRequest,
- ActionCreatePreparedStatementRequest, ActionCreatePreparedStatementResult, Any,
- CommandGetCatalogs, CommandGetCrossReference, CommandGetDbSchemas,
- CommandGetExportedKeys, CommandGetImportedKeys, CommandGetPrimaryKeys,
- CommandGetSqlInfo, CommandGetTableTypes, CommandGetTables,
- CommandGetXdbcTypeInfo, CommandPreparedStatementQuery,
- CommandPreparedStatementUpdate, CommandStatementQuery, CommandStatementUpdate,
+ server::FlightSqlService, ActionBeginSavepointRequest,
+ ActionBeginSavepointResult, ActionBeginTransactionRequest,
+ ActionBeginTransactionResult, ActionCancelQueryRequest, ActionCancelQueryResult,
+ ActionClosePreparedStatementRequest, ActionCreatePreparedStatementRequest,
+ ActionCreatePreparedStatementResult, ActionCreatePreparedSubstraitPlanRequest,
+ ActionEndSavepointRequest, ActionEndTransactionRequest, Any, CommandGetCatalogs,
+ CommandGetCrossReference, CommandGetDbSchemas, CommandGetExportedKeys,
+ CommandGetImportedKeys, CommandGetPrimaryKeys, CommandGetSqlInfo,
+ CommandGetTableTypes, CommandGetTables, CommandGetXdbcTypeInfo,
+ CommandPreparedStatementQuery, CommandPreparedStatementUpdate,
+ CommandStatementQuery, CommandStatementSubstraitPlan, CommandStatementUpdate,
ProstMessageExt, SqlInfo, TicketStatementQuery,
},
utils::batches_to_flight_data,
@@ -197,6 +201,7 @@ impl FlightSqlService for FlightSqlServiceImpl {
],
total_records: batch.num_rows() as i64,
total_bytes: batch.get_array_memory_size() as i64,
+ ordered: false,
};
let resp = Response::new(info);
Ok(resp)
@@ -212,6 +217,16 @@ impl FlightSqlService for FlightSqlServiceImpl {
))
}
+ async fn get_flight_info_substrait_plan(
+ &self,
+ _query: CommandStatementSubstraitPlan,
+ _request: Request<FlightDescriptor>,
+ ) -> Result<Response<FlightInfo>, Status> {
+ Err(Status::unimplemented(
+ "get_flight_info_substrait_plan not implemented",
+ ))
+ }
+
async fn get_flight_info_catalogs(
&self,
_query: CommandGetCatalogs,
@@ -430,6 +445,16 @@ impl FlightSqlService for FlightSqlServiceImpl {
))
}
+ async fn do_put_substrait_plan(
+ &self,
+ _ticket: CommandStatementSubstraitPlan,
+ _request: Request<Streaming<FlightData>>,
+ ) -> Result<i64, Status> {
+ Err(Status::unimplemented(
+ "do_put_substrait_plan not implemented",
+ ))
+ }
+
async fn do_put_prepared_statement_query(
&self,
_query: CommandPreparedStatementQuery,
@@ -464,7 +489,56 @@ impl FlightSqlService for FlightSqlServiceImpl {
&self,
_query: ActionClosePreparedStatementRequest,
_request: Request<Action>,
- ) {
+ ) -> Result<(), Status> {
+ unimplemented!("Implement do_action_close_prepared_statement")
+ }
+
+ async fn do_action_create_prepared_substrait_plan(
+ &self,
+ _query: ActionCreatePreparedSubstraitPlanRequest,
+ _request: Request<Action>,
+ ) -> Result<ActionCreatePreparedStatementResult, Status> {
+ unimplemented!("Implement do_action_create_prepared_substrait_plan")
+ }
+
+ async fn do_action_begin_transaction(
+ &self,
+ _query: ActionBeginTransactionRequest,
+ _request: Request<Action>,
+ ) -> Result<ActionBeginTransactionResult, Status> {
+ unimplemented!("Implement do_action_begin_transaction")
+ }
+
+ async fn do_action_end_transaction(
+ &self,
+ _query: ActionEndTransactionRequest,
+ _request: Request<Action>,
+ ) -> Result<(), Status> {
+ unimplemented!("Implement do_action_end_transaction")
+ }
+
+ async fn do_action_begin_savepoint(
+ &self,
+ _query: ActionBeginSavepointRequest,
+ _request: Request<Action>,
+ ) -> Result<ActionBeginSavepointResult, Status> {
+ unimplemented!("Implement do_action_begin_savepoint")
+ }
+
+ async fn do_action_end_savepoint(
+ &self,
+ _query: ActionEndSavepointRequest,
+ _request: Request<Action>,
+ ) -> Result<(), Status> {
+ unimplemented!("Implement do_action_end_savepoint")
+ }
+
+ async fn do_action_cancel_query(
+ &self,
+ _query: ActionCancelQueryRequest,
+ _request: Request<Action>,
+ ) -> Result<ActionCancelQueryResult, Status> {
+ unimplemented!("Implement do_action_cancel_query")
}
async fn register_sql_info(&self, _id: i32, _result: &SqlInfo) {}
diff --git a/arrow-integration-testing/src/flight_server_scenarios/integration_test.rs b/arrow-integration-testing/src/flight_server_scenarios/integration_test.rs
index 51d08d94313c..e2c4cb5d88f3 100644
--- a/arrow-integration-testing/src/flight_server_scenarios/integration_test.rs
+++ b/arrow-integration-testing/src/flight_server_scenarios/integration_test.rs
@@ -200,6 +200,7 @@ impl FlightService for FlightServiceImpl {
endpoint: vec![endpoint],
total_records: total_records as i64,
total_bytes: -1,
+ ordered: false,
};
Ok(Response::new(info))
|
Update flight-sql implementation to latest specs
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
The proto definitions for the flight sql spec have seen some updates not yet reflected in the `arrow-flight` crate.
**Describe the solution you'd like**
Update and build latest proto files and update current implementations to reflect changes.
**Describe alternatives you've considered**
Not keeping up to date :).
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
|
2023-05-21T13:00:01Z
|
40.0
|
008cf9c27424d581a67ba97f338a22b6eace9cc1
|
|
apache/arrow-rs
| 4,232
|
apache__arrow-rs-4232
|
[
"4222"
] |
25bfccca58ff219d9f59ba9f4d75550493238a4f
|
diff --git a/arrow/src/ffi_stream.rs b/arrow/src/ffi_stream.rs
index 0e358c36a0dc..cfda4c88b4b9 100644
--- a/arrow/src/ffi_stream.rs
+++ b/arrow/src/ffi_stream.rs
@@ -37,25 +37,19 @@
//! let reader = Box::new(FileReader::try_new(file).unwrap());
//!
//! // export it
-//! let stream = Box::new(FFI_ArrowArrayStream::empty());
-//! let stream_ptr = Box::into_raw(stream) as *mut FFI_ArrowArrayStream;
-//! unsafe { export_reader_into_raw(reader, stream_ptr) };
+//! let mut stream = FFI_ArrowArrayStream::empty();
+//! unsafe { export_reader_into_raw(reader, &mut stream) };
//!
//! // consumed and used by something else...
//!
//! // import it
-//! let stream_reader = unsafe { ArrowArrayStreamReader::from_raw(stream_ptr).unwrap() };
+//! let stream_reader = unsafe { ArrowArrayStreamReader::from_raw(&mut stream).unwrap() };
//! let imported_schema = stream_reader.schema();
//!
//! let mut produced_batches = vec![];
//! for batch in stream_reader {
//! produced_batches.push(batch.unwrap());
//! }
-//!
-//! // (drop/release)
-//! unsafe {
-//! Box::from_raw(stream_ptr);
-//! }
//! Ok(())
//! }
//! ```
@@ -105,6 +99,8 @@ pub struct FFI_ArrowArrayStream {
pub private_data: *mut c_void,
}
+unsafe impl Send for FFI_ArrowArrayStream {}
+
// callback used to drop [FFI_ArrowArrayStream] when it is exported.
unsafe extern "C" fn release_stream(stream: *mut FFI_ArrowArrayStream) {
if stream.is_null() {
@@ -231,8 +227,7 @@ impl ExportedArrayStream {
let struct_array = StructArray::from(batch);
let array = FFI_ArrowArray::new(&struct_array.to_data());
- unsafe { std::ptr::copy(addr_of!(array), out, 1) };
- std::mem::forget(array);
+ unsafe { std::ptr::write_unaligned(out, array) };
0
} else {
let err = &next_batch.unwrap_err();
@@ -261,24 +256,21 @@ fn get_error_code(err: &ArrowError) -> i32 {
/// Struct used to fetch `RecordBatch` from the C Stream Interface.
/// Its main responsibility is to expose `RecordBatchReader` functionality
/// that requires [FFI_ArrowArrayStream].
-#[derive(Debug, Clone)]
+#[derive(Debug)]
pub struct ArrowArrayStreamReader {
- stream: Arc<FFI_ArrowArrayStream>,
+ stream: FFI_ArrowArrayStream,
schema: SchemaRef,
}
/// Gets schema from a raw pointer of `FFI_ArrowArrayStream`. This is used when constructing
/// `ArrowArrayStreamReader` to cache schema.
fn get_stream_schema(stream_ptr: *mut FFI_ArrowArrayStream) -> Result<SchemaRef> {
- let empty_schema = Arc::new(FFI_ArrowSchema::empty());
- let schema_ptr = Arc::into_raw(empty_schema) as *mut FFI_ArrowSchema;
+ let mut schema = FFI_ArrowSchema::empty();
- let ret_code = unsafe { (*stream_ptr).get_schema.unwrap()(stream_ptr, schema_ptr) };
-
- let ffi_schema = unsafe { Arc::from_raw(schema_ptr) };
+ let ret_code = unsafe { (*stream_ptr).get_schema.unwrap()(stream_ptr, &mut schema) };
if ret_code == 0 {
- let schema = Schema::try_from(ffi_schema.as_ref()).unwrap();
+ let schema = Schema::try_from(&schema).unwrap();
Ok(Arc::new(schema))
} else {
Err(ArrowError::CDataInterface(format!(
@@ -291,21 +283,16 @@ impl ArrowArrayStreamReader {
/// Creates a new `ArrowArrayStreamReader` from a `FFI_ArrowArrayStream`.
/// This is used to import from the C Stream Interface.
#[allow(dead_code)]
- pub fn try_new(stream: FFI_ArrowArrayStream) -> Result<Self> {
+ pub fn try_new(mut stream: FFI_ArrowArrayStream) -> Result<Self> {
if stream.release.is_none() {
return Err(ArrowError::CDataInterface(
"input stream is already released".to_string(),
));
}
- let stream_ptr = Arc::into_raw(Arc::new(stream)) as *mut FFI_ArrowArrayStream;
-
- let schema = get_stream_schema(stream_ptr)?;
+ let schema = get_stream_schema(&mut stream)?;
- Ok(Self {
- stream: unsafe { Arc::from_raw(stream_ptr) },
- schema,
- })
+ Ok(Self { stream, schema })
}
/// Creates a new `ArrowArrayStreamReader` from a raw pointer of `FFI_ArrowArrayStream`.
@@ -324,13 +311,12 @@ impl ArrowArrayStreamReader {
}
/// Get the last error from `ArrowArrayStreamReader`
- fn get_stream_last_error(&self) -> Option<String> {
+ fn get_stream_last_error(&mut self) -> Option<String> {
self.stream.get_last_error?;
- let stream_ptr = Arc::as_ptr(&self.stream) as *mut FFI_ArrowArrayStream;
-
let error_str = unsafe {
- let c_str = self.stream.get_last_error.unwrap()(stream_ptr) as *mut c_char;
+ let c_str =
+ self.stream.get_last_error.unwrap()(&mut self.stream) as *mut c_char;
CString::from_raw(c_str).into_string()
};
@@ -346,18 +332,14 @@ impl Iterator for ArrowArrayStreamReader {
type Item = Result<RecordBatch>;
fn next(&mut self) -> Option<Self::Item> {
- let stream_ptr = Arc::as_ptr(&self.stream) as *mut FFI_ArrowArrayStream;
-
- let empty_array = Arc::new(FFI_ArrowArray::empty());
- let array_ptr = Arc::into_raw(empty_array) as *mut FFI_ArrowArray;
+ let mut array = FFI_ArrowArray::empty();
- let ret_code = unsafe { self.stream.get_next.unwrap()(stream_ptr, array_ptr) };
+ let ret_code =
+ unsafe { self.stream.get_next.unwrap()(&mut self.stream, &mut array) };
if ret_code == 0 {
- let ffi_array = unsafe { Arc::from_raw(array_ptr) };
-
// The end of stream has been reached
- if ffi_array.is_released() {
+ if array.is_released() {
return None;
}
@@ -365,7 +347,7 @@ impl Iterator for ArrowArrayStreamReader {
let schema = FFI_ArrowSchema::try_from(schema_ref.as_ref()).ok()?;
let data = ArrowArray {
- array: ffi_array,
+ array: Arc::new(array),
schema: Arc::new(schema),
}
.to_data()
@@ -375,8 +357,6 @@ impl Iterator for ArrowArrayStreamReader {
Some(Ok(record_batch))
} else {
- unsafe { Arc::from_raw(array_ptr) };
-
let last_error = self.get_stream_last_error();
let err = ArrowError::CDataInterface(last_error.unwrap());
Some(Err(err))
@@ -451,40 +431,33 @@ mod tests {
let reader = TestRecordBatchReader::new(schema.clone(), iter);
// Export a `RecordBatchReader` through `FFI_ArrowArrayStream`
- let stream = Arc::new(FFI_ArrowArrayStream::empty());
- let stream_ptr = Arc::into_raw(stream) as *mut FFI_ArrowArrayStream;
-
- unsafe { export_reader_into_raw(reader, stream_ptr) };
-
- let empty_schema = Arc::new(FFI_ArrowSchema::empty());
- let schema_ptr = Arc::into_raw(empty_schema) as *mut FFI_ArrowSchema;
+ let mut ffi_stream = FFI_ArrowArrayStream::empty();
+ unsafe { export_reader_into_raw(reader, &mut ffi_stream) };
// Get schema from `FFI_ArrowArrayStream`
- let ret_code = unsafe { get_schema(stream_ptr, schema_ptr) };
+ let mut ffi_schema = FFI_ArrowSchema::empty();
+ let ret_code = unsafe { get_schema(&mut ffi_stream, &mut ffi_schema) };
assert_eq!(ret_code, 0);
- let ffi_schema = unsafe { Arc::from_raw(schema_ptr) };
-
- let exported_schema = Schema::try_from(ffi_schema.as_ref()).unwrap();
+ let exported_schema = Schema::try_from(&ffi_schema).unwrap();
assert_eq!(&exported_schema, schema.as_ref());
+ let ffi_schema = Arc::new(ffi_schema);
+
// Get array from `FFI_ArrowArrayStream`
let mut produced_batches = vec![];
loop {
- let empty_array = Arc::new(FFI_ArrowArray::empty());
- let array_ptr = Arc::into_raw(empty_array.clone()) as *mut FFI_ArrowArray;
-
- let ret_code = unsafe { get_next(stream_ptr, array_ptr) };
+ let mut ffi_array = FFI_ArrowArray::empty();
+ let ret_code = unsafe { get_next(&mut ffi_stream, &mut ffi_array) };
assert_eq!(ret_code, 0);
// The end of stream has been reached
- let ffi_array = unsafe { Arc::from_raw(array_ptr) };
if ffi_array.is_released() {
break;
}
let array = ArrowArray {
- array: ffi_array,
+ array: Arc::new(ffi_array),
schema: ffi_schema.clone(),
}
.to_data()
@@ -496,7 +469,6 @@ mod tests {
assert_eq!(produced_batches, vec![batch.clone(), batch]);
- unsafe { Arc::from_raw(stream_ptr) };
Ok(())
}
@@ -512,10 +484,8 @@ mod tests {
let reader = TestRecordBatchReader::new(schema.clone(), iter);
// Import through `FFI_ArrowArrayStream` as `ArrowArrayStreamReader`
- let stream = Arc::new(FFI_ArrowArrayStream::new(reader));
- let stream_ptr = Arc::into_raw(stream) as *mut FFI_ArrowArrayStream;
- let stream_reader =
- unsafe { ArrowArrayStreamReader::from_raw(stream_ptr).unwrap() };
+ let stream = FFI_ArrowArrayStream::new(reader);
+ let stream_reader = ArrowArrayStreamReader::try_new(stream).unwrap();
let imported_schema = stream_reader.schema();
assert_eq!(imported_schema, schema);
@@ -527,7 +497,6 @@ mod tests {
assert_eq!(produced_batches, vec![batch.clone(), batch]);
- unsafe { Arc::from_raw(stream_ptr) };
Ok(())
}
diff --git a/arrow/src/pyarrow.rs b/arrow/src/pyarrow.rs
index 081cc8063366..ba8d606f2e1f 100644
--- a/arrow/src/pyarrow.rs
+++ b/arrow/src/pyarrow.rs
@@ -15,13 +15,16 @@
// specific language governing permissions and limitations
// under the License.
-//! This module demonstrates a minimal usage of Rust's C data interface to pass
-//! arrays from and to Python.
+//! Pass Arrow objects from and to Python, using Arrow's
+//! [C Data Interface](https://arrow.apache.org/docs/format/CDataInterface.html)
+//! and [pyo3](https://docs.rs/pyo3/latest/pyo3/).
+//! For underlying implementation, see the [ffi] module.
use std::convert::{From, TryFrom};
use std::ptr::{addr_of, addr_of_mut};
use std::sync::Arc;
+use pyo3::exceptions::PyValueError;
use pyo3::ffi::Py_uintptr_t;
use pyo3::import_exception;
use pyo3::prelude::*;
@@ -44,12 +47,27 @@ fn to_py_err(err: ArrowError) -> PyErr {
PyArrowException::new_err(err.to_string())
}
-pub trait PyArrowConvert: Sized {
+pub trait FromPyArrow: Sized {
fn from_pyarrow(value: &PyAny) -> PyResult<Self>;
+}
+
+/// Create a new PyArrow object from a arrow-rs type.
+pub trait ToPyArrow {
fn to_pyarrow(&self, py: Python) -> PyResult<PyObject>;
}
-impl PyArrowConvert for DataType {
+/// Convert an arrow-rs type into a PyArrow object.
+pub trait IntoPyArrow {
+ fn into_pyarrow(self, py: Python) -> PyResult<PyObject>;
+}
+
+impl<T: ToPyArrow> IntoPyArrow for T {
+ fn into_pyarrow(self, py: Python) -> PyResult<PyObject> {
+ self.to_pyarrow(py)
+ }
+}
+
+impl FromPyArrow for DataType {
fn from_pyarrow(value: &PyAny) -> PyResult<Self> {
let c_schema = FFI_ArrowSchema::empty();
let c_schema_ptr = &c_schema as *const FFI_ArrowSchema;
@@ -57,7 +75,9 @@ impl PyArrowConvert for DataType {
let dtype = DataType::try_from(&c_schema).map_err(to_py_err)?;
Ok(dtype)
}
+}
+impl ToPyArrow for DataType {
fn to_pyarrow(&self, py: Python) -> PyResult<PyObject> {
let c_schema = FFI_ArrowSchema::try_from(self).map_err(to_py_err)?;
let c_schema_ptr = &c_schema as *const FFI_ArrowSchema;
@@ -69,7 +89,7 @@ impl PyArrowConvert for DataType {
}
}
-impl PyArrowConvert for Field {
+impl FromPyArrow for Field {
fn from_pyarrow(value: &PyAny) -> PyResult<Self> {
let c_schema = FFI_ArrowSchema::empty();
let c_schema_ptr = &c_schema as *const FFI_ArrowSchema;
@@ -77,7 +97,9 @@ impl PyArrowConvert for Field {
let field = Field::try_from(&c_schema).map_err(to_py_err)?;
Ok(field)
}
+}
+impl ToPyArrow for Field {
fn to_pyarrow(&self, py: Python) -> PyResult<PyObject> {
let c_schema = FFI_ArrowSchema::try_from(self).map_err(to_py_err)?;
let c_schema_ptr = &c_schema as *const FFI_ArrowSchema;
@@ -89,7 +111,7 @@ impl PyArrowConvert for Field {
}
}
-impl PyArrowConvert for Schema {
+impl FromPyArrow for Schema {
fn from_pyarrow(value: &PyAny) -> PyResult<Self> {
let c_schema = FFI_ArrowSchema::empty();
let c_schema_ptr = &c_schema as *const FFI_ArrowSchema;
@@ -97,7 +119,9 @@ impl PyArrowConvert for Schema {
let schema = Schema::try_from(&c_schema).map_err(to_py_err)?;
Ok(schema)
}
+}
+impl ToPyArrow for Schema {
fn to_pyarrow(&self, py: Python) -> PyResult<PyObject> {
let c_schema = FFI_ArrowSchema::try_from(self).map_err(to_py_err)?;
let c_schema_ptr = &c_schema as *const FFI_ArrowSchema;
@@ -109,7 +133,7 @@ impl PyArrowConvert for Schema {
}
}
-impl PyArrowConvert for ArrayData {
+impl FromPyArrow for ArrayData {
fn from_pyarrow(value: &PyAny) -> PyResult<Self> {
// prepare a pointer to receive the Array struct
let mut array = FFI_ArrowArray::empty();
@@ -131,7 +155,9 @@ impl PyArrowConvert for ArrayData {
Ok(data)
}
+}
+impl ToPyArrow for ArrayData {
fn to_pyarrow(&self, py: Python) -> PyResult<PyObject> {
let array = FFI_ArrowArray::new(self);
let schema = FFI_ArrowSchema::try_from(self.data_type()).map_err(to_py_err)?;
@@ -149,12 +175,14 @@ impl PyArrowConvert for ArrayData {
}
}
-impl<T: PyArrowConvert> PyArrowConvert for Vec<T> {
+impl<T: FromPyArrow> FromPyArrow for Vec<T> {
fn from_pyarrow(value: &PyAny) -> PyResult<Self> {
let list = value.downcast::<PyList>()?;
- list.iter().map(|x| T::from_pyarrow(&x)).collect()
+ list.iter().map(|x| T::from_pyarrow(x)).collect()
}
+}
+impl<T: ToPyArrow> ToPyArrow for Vec<T> {
fn to_pyarrow(&self, py: Python) -> PyResult<PyObject> {
let values = self
.iter()
@@ -164,7 +192,7 @@ impl<T: PyArrowConvert> PyArrowConvert for Vec<T> {
}
}
-impl PyArrowConvert for RecordBatch {
+impl FromPyArrow for RecordBatch {
fn from_pyarrow(value: &PyAny) -> PyResult<Self> {
// TODO(kszucs): implement the FFI conversions in arrow-rs for RecordBatches
let schema = value.getattr("schema")?;
@@ -179,7 +207,9 @@ impl PyArrowConvert for RecordBatch {
let batch = RecordBatch::try_new(schema, arrays).map_err(to_py_err)?;
Ok(batch)
}
+}
+impl ToPyArrow for RecordBatch {
fn to_pyarrow(&self, py: Python) -> PyResult<PyObject> {
let mut py_arrays = vec![];
@@ -203,38 +233,36 @@ impl PyArrowConvert for RecordBatch {
}
}
-impl PyArrowConvert for ArrowArrayStreamReader {
+impl FromPyArrow for ArrowArrayStreamReader {
fn from_pyarrow(value: &PyAny) -> PyResult<Self> {
// prepare a pointer to receive the stream struct
- let stream = Box::new(FFI_ArrowArrayStream::empty());
- let stream_ptr = Box::into_raw(stream) as *mut FFI_ArrowArrayStream;
+ let mut stream = FFI_ArrowArrayStream::empty();
+ let stream_ptr = &mut stream as *mut FFI_ArrowArrayStream;
// make the conversion through PyArrow's private API
// this changes the pointer's memory and is thus unsafe.
// In particular, `_export_to_c` can go out of bounds
- let args = PyTuple::new(value.py(), &[stream_ptr as Py_uintptr_t]);
+ let args = PyTuple::new(value.py(), [stream_ptr as Py_uintptr_t]);
value.call_method1("_export_to_c", args)?;
- let stream_reader =
- unsafe { ArrowArrayStreamReader::from_raw(stream_ptr).unwrap() };
-
- unsafe {
- drop(Box::from_raw(stream_ptr));
- }
+ let stream_reader = ArrowArrayStreamReader::try_new(stream)
+ .map_err(|err| PyValueError::new_err(err.to_string()))?;
Ok(stream_reader)
}
+}
- fn to_pyarrow(&self, py: Python) -> PyResult<PyObject> {
- let stream = Box::new(FFI_ArrowArrayStream::empty());
- let stream_ptr = Box::into_raw(stream) as *mut FFI_ArrowArrayStream;
-
- unsafe { export_reader_into_raw(Box::new(self.clone()), stream_ptr) };
+impl IntoPyArrow for ArrowArrayStreamReader {
+ fn into_pyarrow(self, py: Python) -> PyResult<PyObject> {
+ let mut stream = FFI_ArrowArrayStream::empty();
+ unsafe { export_reader_into_raw(Box::new(self), &mut stream) };
+ let stream_ptr = (&mut stream) as *mut FFI_ArrowArrayStream;
let module = py.import("pyarrow")?;
let class = module.getattr("RecordBatchReader")?;
- let args = PyTuple::new(py, &[stream_ptr as Py_uintptr_t]);
+ let args = PyTuple::new(py, [stream_ptr as Py_uintptr_t]);
let reader = class.call_method1("_import_from_c", args)?;
+
Ok(PyObject::from(reader))
}
}
@@ -242,21 +270,24 @@ impl PyArrowConvert for ArrowArrayStreamReader {
/// A newtype wrapper around a `T: PyArrowConvert` that implements
/// [`FromPyObject`] and [`IntoPy`] allowing usage with pyo3 macros
#[derive(Debug)]
-pub struct PyArrowType<T: PyArrowConvert>(pub T);
+pub struct PyArrowType<T: FromPyArrow + IntoPyArrow>(pub T);
-impl<'source, T: PyArrowConvert> FromPyObject<'source> for PyArrowType<T> {
+impl<'source, T: FromPyArrow + IntoPyArrow> FromPyObject<'source> for PyArrowType<T> {
fn extract(value: &'source PyAny) -> PyResult<Self> {
Ok(Self(T::from_pyarrow(value)?))
}
}
-impl<'a, T: PyArrowConvert> IntoPy<PyObject> for PyArrowType<T> {
+impl<T: FromPyArrow + IntoPyArrow> IntoPy<PyObject> for PyArrowType<T> {
fn into_py(self, py: Python) -> PyObject {
- self.0.to_pyarrow(py).unwrap()
+ match self.0.into_pyarrow(py) {
+ Ok(obj) => obj,
+ Err(err) => err.to_object(py),
+ }
}
}
-impl<T: PyArrowConvert> From<T> for PyArrowType<T> {
+impl<T: FromPyArrow + IntoPyArrow> From<T> for PyArrowType<T> {
fn from(s: T) -> Self {
Self(s)
}
|
diff --git a/arrow-pyarrow-integration-testing/src/lib.rs b/arrow-pyarrow-integration-testing/src/lib.rs
index af400868ffa9..730409b3777e 100644
--- a/arrow-pyarrow-integration-testing/src/lib.rs
+++ b/arrow-pyarrow-integration-testing/src/lib.rs
@@ -24,12 +24,12 @@ use arrow::array::new_empty_array;
use pyo3::prelude::*;
use pyo3::wrap_pyfunction;
-use arrow::array::{Array, ArrayData, ArrayRef, Int64Array, make_array};
+use arrow::array::{make_array, Array, ArrayData, ArrayRef, Int64Array};
use arrow::compute::kernels;
use arrow::datatypes::{DataType, Field, Schema};
use arrow::error::ArrowError;
use arrow::ffi_stream::ArrowArrayStreamReader;
-use arrow::pyarrow::{PyArrowConvert, PyArrowException, PyArrowType};
+use arrow::pyarrow::{FromPyArrow, PyArrowException, PyArrowType, ToPyArrow};
use arrow::record_batch::RecordBatch;
fn to_py_err(err: ArrowError) -> PyErr {
@@ -88,7 +88,8 @@ fn substring(
let array = make_array(array.0);
// substring
- let array = kernels::substring::substring(array.as_ref(), start, None).map_err(to_py_err)?;
+ let array =
+ kernels::substring::substring(array.as_ref(), start, None).map_err(to_py_err)?;
Ok(array.to_data().into())
}
@@ -99,7 +100,8 @@ fn concatenate(array: PyArrowType<ArrayData>, py: Python) -> PyResult<PyObject>
let array = make_array(array.0);
// concat
- let array = kernels::concat::concat(&[array.as_ref(), array.as_ref()]).map_err(to_py_err)?;
+ let array =
+ kernels::concat::concat(&[array.as_ref(), array.as_ref()]).map_err(to_py_err)?;
array.to_data().to_pyarrow(py)
}
diff --git a/arrow/tests/pyarrow.rs b/arrow/tests/pyarrow.rs
index 4b1226c738f5..4b6991da0063 100644
--- a/arrow/tests/pyarrow.rs
+++ b/arrow/tests/pyarrow.rs
@@ -16,7 +16,7 @@
// under the License.
use arrow::array::{ArrayRef, Int32Array, StringArray};
-use arrow::pyarrow::PyArrowConvert;
+use arrow::pyarrow::{FromPyArrow, ToPyArrow};
use arrow::record_batch::RecordBatch;
use pyo3::Python;
use std::sync::Arc;
|
Make ArrowArrayStreamReader Send
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
ArrowArrayStreamReader is not Send, which makes is very difficult to work with in async contexts.
While [FFI_ArrowArrayStream](https://docs.rs/arrow/39.0.0/arrow/ffi_stream/struct.FFI_ArrowArrayStream.html) shouldn't be Sync, I do think it should be marked Send. From the [docs](https://arrow.apache.org/docs/format/CStreamInterface.html#thread-safety):
> The stream source is not assumed to be thread-safe. Consumers wanting to call `get_next` from several threads should ensure those calls are serialized.
**Describe the solution you'd like**
If `FFI_ArrowArrayStream` were marked `Send` and `ArrowArrayStreamReader` were refactored to hold the inner type in a Box rather than an Arc, then it would be `Send`.
**Describe alternatives you've considered**
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
|
2023-05-17T03:12:15Z
|
40.0
|
008cf9c27424d581a67ba97f338a22b6eace9cc1
|
|
apache/arrow-rs
| 4,201
|
apache__arrow-rs-4201
|
[
"1936"
] |
378a9fcc9ee31fff4a9a13f5de5a326dc449541e
|
diff --git a/arrow-cast/src/cast.rs b/arrow-cast/src/cast.rs
index 37fede0a6fe0..2b286bfa9119 100644
--- a/arrow-cast/src/cast.rs
+++ b/arrow-cast/src/cast.rs
@@ -35,7 +35,7 @@
//! assert_eq!(7.0, c.value(2));
//! ```
-use chrono::{NaiveTime, TimeZone, Timelike, Utc};
+use chrono::{NaiveTime, Offset, TimeZone, Timelike, Utc};
use std::cmp::Ordering;
use std::sync::Arc;
@@ -1770,7 +1770,7 @@ pub fn cast_with_options(
tz.clone(),
)),
- (Timestamp(from_unit, _), Timestamp(to_unit, to_tz)) => {
+ (Timestamp(from_unit, from_tz), Timestamp(to_unit, to_tz)) => {
let array = cast_with_options(array, &Int64, cast_options)?;
let time_array = array.as_primitive::<Int64Type>();
let from_size = time_unit_multiple(from_unit);
@@ -1792,8 +1792,52 @@ pub fn cast_with_options(
}
}
};
+ // Normalize timezone
+ let adjusted = match (from_tz, to_tz) {
+ // Only this case needs to be adjusted because we're casting from
+ // unknown time offset to some time offset, we want the time to be
+ // unchanged.
+ //
+ // i.e. Timestamp('2001-01-01T00:00', None) -> Timestamp('2001-01-01T00:00', '+0700')
+ (None, Some(to_tz)) => {
+ let to_tz: Tz = to_tz.parse()?;
+ match to_unit {
+ TimeUnit::Second => {
+ adjust_timestamp_to_timezone::<TimestampSecondType>(
+ converted,
+ &to_tz,
+ cast_options,
+ )?
+ }
+ TimeUnit::Millisecond => {
+ adjust_timestamp_to_timezone::<TimestampMillisecondType>(
+ converted,
+ &to_tz,
+ cast_options,
+ )?
+ }
+ TimeUnit::Microsecond => {
+ adjust_timestamp_to_timezone::<TimestampMicrosecondType>(
+ converted,
+ &to_tz,
+ cast_options,
+ )?
+ }
+ TimeUnit::Nanosecond => {
+ adjust_timestamp_to_timezone::<TimestampNanosecondType>(
+ converted,
+ &to_tz,
+ cast_options,
+ )?
+ }
+ }
+ }
+ _ => {
+ converted
+ }
+ };
Ok(make_timestamp_array(
- &converted,
+ &adjusted,
to_unit.clone(),
to_tz.clone(),
))
@@ -3005,6 +3049,30 @@ fn cast_string_to_month_day_nano_interval<Offset: OffsetSizeTrait>(
Ok(Arc::new(interval_array) as ArrayRef)
}
+fn adjust_timestamp_to_timezone<T: ArrowTimestampType>(
+ array: PrimitiveArray<Int64Type>,
+ to_tz: &Tz,
+ cast_options: &CastOptions,
+) -> Result<PrimitiveArray<Int64Type>, ArrowError> {
+ let adjust = |o| {
+ let local = as_datetime::<T>(o)?;
+ let offset = to_tz.offset_from_local_datetime(&local).single()?;
+ T::make_value(local - offset.fix())
+ };
+ let adjusted = if cast_options.safe {
+ array.unary_opt::<_, Int64Type>(adjust)
+ } else {
+ array.try_unary::<_, Int64Type, _>(|o| {
+ adjust(o).ok_or_else(|| {
+ ArrowError::CastError(
+ "Cannot cast timezone to different timezone".to_string(),
+ )
+ })
+ })?
+ };
+ Ok(adjusted)
+}
+
/// Casts Utf8 to Boolean
fn cast_utf8_to_boolean<OffsetSize>(
from: &dyn Array,
@@ -5978,6 +6046,83 @@ mod tests {
assert!(b.is_err());
}
+ // Cast Timestamp(_, None) -> Timestamp(_, Some(timezone))
+ #[test]
+ fn test_cast_timestamp_with_timezone_1() {
+ let string_array: Arc<dyn Array> = Arc::new(StringArray::from(vec![
+ Some("2000-01-01T00:00:00.123456789"),
+ Some("2010-01-01T00:00:00.123456789"),
+ None,
+ ]));
+ let to_type = DataType::Timestamp(TimeUnit::Nanosecond, None);
+ let timestamp_array = cast(&string_array, &to_type).unwrap();
+
+ let to_type = DataType::Timestamp(TimeUnit::Microsecond, Some("+0700".into()));
+ let timestamp_array = cast(×tamp_array, &to_type).unwrap();
+
+ let string_array = cast(×tamp_array, &DataType::Utf8).unwrap();
+ let result = string_array.as_string::<i32>();
+ assert_eq!("2000-01-01T00:00:00.123456+07:00", result.value(0));
+ assert_eq!("2010-01-01T00:00:00.123456+07:00", result.value(1));
+ assert!(result.is_null(2));
+ }
+
+ // Cast Timestamp(_, Some(timezone)) -> Timestamp(_, None)
+ #[test]
+ fn test_cast_timestamp_with_timezone_2() {
+ let string_array: Arc<dyn Array> = Arc::new(StringArray::from(vec![
+ Some("2000-01-01T07:00:00.123456789"),
+ Some("2010-01-01T07:00:00.123456789"),
+ None,
+ ]));
+ let to_type = DataType::Timestamp(TimeUnit::Millisecond, Some("+0700".into()));
+ let timestamp_array = cast(&string_array, &to_type).unwrap();
+
+ // Check intermediate representation is correct
+ let string_array = cast(×tamp_array, &DataType::Utf8).unwrap();
+ let result = string_array.as_string::<i32>();
+ assert_eq!("2000-01-01T07:00:00.123+07:00", result.value(0));
+ assert_eq!("2010-01-01T07:00:00.123+07:00", result.value(1));
+ assert!(result.is_null(2));
+
+ let to_type = DataType::Timestamp(TimeUnit::Nanosecond, None);
+ let timestamp_array = cast(×tamp_array, &to_type).unwrap();
+
+ let string_array = cast(×tamp_array, &DataType::Utf8).unwrap();
+ let result = string_array.as_string::<i32>();
+ assert_eq!("2000-01-01T00:00:00.123", result.value(0));
+ assert_eq!("2010-01-01T00:00:00.123", result.value(1));
+ assert!(result.is_null(2));
+ }
+
+ // Cast Timestamp(_, Some(timezone)) -> Timestamp(_, Some(timezone))
+ #[test]
+ fn test_cast_timestamp_with_timezone_3() {
+ let string_array: Arc<dyn Array> = Arc::new(StringArray::from(vec![
+ Some("2000-01-01T07:00:00.123456789"),
+ Some("2010-01-01T07:00:00.123456789"),
+ None,
+ ]));
+ let to_type = DataType::Timestamp(TimeUnit::Microsecond, Some("+0700".into()));
+ let timestamp_array = cast(&string_array, &to_type).unwrap();
+
+ // Check intermediate representation is correct
+ let string_array = cast(×tamp_array, &DataType::Utf8).unwrap();
+ let result = string_array.as_string::<i32>();
+ assert_eq!("2000-01-01T07:00:00.123456+07:00", result.value(0));
+ assert_eq!("2010-01-01T07:00:00.123456+07:00", result.value(1));
+ assert!(result.is_null(2));
+
+ let to_type = DataType::Timestamp(TimeUnit::Second, Some("-08:00".into()));
+ let timestamp_array = cast(×tamp_array, &to_type).unwrap();
+
+ let string_array = cast(×tamp_array, &DataType::Utf8).unwrap();
+ let result = string_array.as_string::<i32>();
+ assert_eq!("1999-12-31T16:00:00-08:00", result.value(0));
+ assert_eq!("2009-12-31T16:00:00-08:00", result.value(1));
+ assert!(result.is_null(2));
+ }
+
#[test]
fn test_cast_date64_to_timestamp() {
let array =
|
diff --git a/arrow/tests/array_cast.rs b/arrow/tests/array_cast.rs
index bf7e7a326efc..43dc6dd0eb0a 100644
--- a/arrow/tests/array_cast.rs
+++ b/arrow/tests/array_cast.rs
@@ -18,6 +18,7 @@
use arrow_array::builder::{
PrimitiveDictionaryBuilder, StringDictionaryBuilder, UnionBuilder,
};
+use arrow_array::cast::AsArray;
use arrow_array::types::{
ArrowDictionaryKeyType, Decimal128Type, Decimal256Type, Int16Type, Int32Type,
Int64Type, Int8Type, TimestampMicrosecondType, UInt16Type, UInt32Type, UInt64Type,
@@ -64,6 +65,97 @@ fn test_cast_timestamp_to_string() {
assert!(c.is_null(2));
}
+// See: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones for list of valid
+// timezones
+
+// Cast Timestamp(_, None) -> Timestamp(_, Some(timezone))
+#[test]
+fn test_cast_timestamp_with_timezone_daylight_1() {
+ let string_array: Arc<dyn Array> = Arc::new(StringArray::from(vec![
+ // This is winter in New York so daylight saving is not in effect
+ // UTC offset is -05:00
+ Some("2000-01-01T00:00:00.123456789"),
+ // This is summer in New York so daylight saving is in effect
+ // UTC offset is -04:00
+ Some("2010-07-01T00:00:00.123456789"),
+ None,
+ ]));
+ let to_type = DataType::Timestamp(TimeUnit::Nanosecond, None);
+ let timestamp_array = cast(&string_array, &to_type).unwrap();
+
+ let to_type =
+ DataType::Timestamp(TimeUnit::Microsecond, Some("America/New_York".into()));
+ let timestamp_array = cast(×tamp_array, &to_type).unwrap();
+
+ let string_array = cast(×tamp_array, &DataType::Utf8).unwrap();
+ let result = string_array.as_string::<i32>();
+ assert_eq!("2000-01-01T00:00:00.123456-05:00", result.value(0));
+ assert_eq!("2010-07-01T00:00:00.123456-04:00", result.value(1));
+ assert!(result.is_null(2));
+}
+
+// Cast Timestamp(_, Some(timezone)) -> Timestamp(_, None)
+#[test]
+fn test_cast_timestamp_with_timezone_daylight_2() {
+ let string_array: Arc<dyn Array> = Arc::new(StringArray::from(vec![
+ Some("2000-01-01T07:00:00.123456789"),
+ Some("2010-07-01T07:00:00.123456789"),
+ None,
+ ]));
+ let to_type =
+ DataType::Timestamp(TimeUnit::Millisecond, Some("America/New_York".into()));
+ let timestamp_array = cast(&string_array, &to_type).unwrap();
+
+ // Check intermediate representation is correct
+ let string_array = cast(×tamp_array, &DataType::Utf8).unwrap();
+ let result = string_array.as_string::<i32>();
+ assert_eq!("2000-01-01T07:00:00.123-05:00", result.value(0));
+ assert_eq!("2010-07-01T07:00:00.123-04:00", result.value(1));
+ assert!(result.is_null(2));
+
+ let to_type = DataType::Timestamp(TimeUnit::Nanosecond, None);
+ let timestamp_array = cast(×tamp_array, &to_type).unwrap();
+
+ let string_array = cast(×tamp_array, &DataType::Utf8).unwrap();
+ let result = string_array.as_string::<i32>();
+ assert_eq!("2000-01-01T12:00:00.123", result.value(0));
+ assert_eq!("2010-07-01T11:00:00.123", result.value(1));
+ assert!(result.is_null(2));
+}
+
+// Cast Timestamp(_, Some(timezone)) -> Timestamp(_, Some(timezone))
+#[test]
+fn test_cast_timestamp_with_timezone_daylight_3() {
+ let string_array: Arc<dyn Array> = Arc::new(StringArray::from(vec![
+ // Winter in New York, summer in Sydney
+ // UTC offset is -05:00 (New York) and +11:00 (Sydney)
+ Some("2000-01-01T00:00:00.123456789"),
+ // Summer in New York, winter in Sydney
+ // UTC offset is -04:00 (New York) and +10:00 (Sydney)
+ Some("2010-07-01T00:00:00.123456789"),
+ None,
+ ]));
+ let to_type =
+ DataType::Timestamp(TimeUnit::Microsecond, Some("America/New_York".into()));
+ let timestamp_array = cast(&string_array, &to_type).unwrap();
+
+ // Check intermediate representation is correct
+ let string_array = cast(×tamp_array, &DataType::Utf8).unwrap();
+ let result = string_array.as_string::<i32>();
+ assert_eq!("2000-01-01T00:00:00.123456-05:00", result.value(0));
+ assert_eq!("2010-07-01T00:00:00.123456-04:00", result.value(1));
+ assert!(result.is_null(2));
+
+ let to_type = DataType::Timestamp(TimeUnit::Second, Some("Australia/Sydney".into()));
+ let timestamp_array = cast(×tamp_array, &to_type).unwrap();
+
+ let string_array = cast(×tamp_array, &DataType::Utf8).unwrap();
+ let result = string_array.as_string::<i32>();
+ assert_eq!("2000-01-01T16:00:00+11:00", result.value(0));
+ assert_eq!("2010-07-01T14:00:00+10:00", result.value(1));
+ assert!(result.is_null(2));
+}
+
#[test]
#[cfg_attr(miri, ignore)] // running forever
fn test_can_cast_types() {
|
Cast Kernel Ignores Timezone
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
The beginnings of timezone support were added in #824, however, this is currently ignored by the cast kernel
**Describe the solution you'd like**
Timezones should be correctly handled by the cast kernel
**Describe alternatives you've considered**
We could not support timezones
**Additional context**
Noticed whilst investigating #1932
|
I'd like to work on this. And I think `fmt` of timestamp array cannot ignore timezone too.
Could you assign it to me? @tustvold
I would recommend writing up the expected behaviour first, as timezone handling is notoriously messy, and once we have consensus we can move forward with implementing that.
FYI @avantgardnerio @waitingkuo
@tustvold thank you for pinging me, i'm working on these things now as well.
@doki23 it would be great if you could help ❤️
You could find some other related issues here apache/arrow-datafusion#3148 (search timezone)
some hints that might help
1
https://github.com/apache/arrow-rs/blob/3bf6eb98ceb3962e1d9419da6dc93e609f7893e6/arrow/src/compute/kernels/cast.rs#L1284
to make casting function consider timezone, we have to fix the second `_` identifier and check whether it's `None` or `Some`
2
https://github.com/apache/arrow-rs/blob/3bf6eb98ceb3962e1d9419da6dc93e609f7893e6/arrow/src/array/array_primitive.rs#L209
while using fmt to print, we first convert it to `NaiveDateTime` (from chrono-rs) which contains no timezone info so that you could only see timestamp without timezone
@doki23 are you planning to draft the proposal?
> @doki23 are you planning to draft the proposal?
sure, plz wait me hours
We consider tz only if from_type and to_type both needs it. For example, ignoring tz is ok when we cast ts to i64, because i64 array doesn't care about timezone.
So, there're 2 situations:
1. ts is from_type, and the to_type needs tz.
2. ts is to_type, and the from_type has tz.
I noticed that timestamp array is always treat as `PrimitiveArray`. We can't get tz from `ArrowPrimitiveType::DATA_TYPE`, because there're only utc ts definitions like:
```rust
make_type!(
TimestampSecondType,
i64,
DataType::Timestamp(TimeUnit::Second, None)
);
```
So, we may need a `TimestampBuilder` in place of `TimestampSecondArray::from_xxx` which can realize the timezone. And it has a valid `ArrayData::data_type`.
what's expected behavior for casting timestamp with timezone to timestamp without time zone?
e.g. if the timestamp with timezone is `1970-01-01T08:00:00+08:00` (note that the timestamp underline is 0), what's the casted result? `1970-01-01T08:00:00` (underline timestamp as 28800000000000) or `1970-01-01T00:00:00` (underline timestamp as 0)?
i recommend that listing these ambiguous cases and your proposed behavior so we could discuss
btw i tested it on pyarrow, it simply changes the datatype but not change the underline timestamp (`1970-01-01T08:00:00+08:00` becomes `1970-01-01T00:00:00`
> what's expected behavior for casting timestamp with timezone to timestamp without time zone?
The intuitive answer would be to convert it to UTC. I think postgres effectively casts it to server (local) time.
I believe this section of the arrow schema definition is relevant - https://github.com/apache/arrow-rs/blob/master/format/Schema.fbs#L280
In particular
> One possibility is to assume that the original timestamp values are relative to the epoch of the timezone being set; timestamp values should then adjusted to the Unix epoch
Given this is the only possibility enumerated in the schema, I feel this is probably the one we should follow unless people feel strongly otherwise. My 2 cents is that anything relying on the local timezone of the system is best avoided if at all possible, it just feels fragile and error-prone.
> local timezone of the system
Yes - these RecordBatches could be part of Flights, yes? In which case the whole point is to send them around to different computers that may be in different timezones, so it kind of forces our hand here.
And if we are doing it this way in arrow where we don't have the luxury of following postgres, maybe this is also where we break postgres compatibility in DataFusion. Just because postgres did it wrong doesn't mean we should follow...
> what's expected behavior for casting timestamp with timezone to timestamp without time zone?
Tz has no affect to the value of timestamp, it's just used for display.
> what's expected behavior for casting timestamp with timezone to timestamp without time zone?
The specification states
> /// However, if a Timestamp column has no timezone value, changing it to a
> /// non-empty value requires to think about the desired semantics.
> /// One possibility is to assume that the original timestamp values are
> /// relative to the epoch of the timezone being set; timestamp values should
> /// then adjusted to the Unix epoch (for example, changing the timezone from
> /// empty to "Europe/Paris" would require converting the timestamp values
> /// from "Europe/Paris" to "UTC", which seems counter-intuitive but is
> /// nevertheless correct).
As stated above, given this is the only possibility enumerated I think we should follow this. The inverse operation, i.e. removing a timezone, I would therefore expect to do the reverse i.e. `1970-01-01 01:00:01 +01:00` would become `1970-01-01 01:00:01`. This is consistent with both postgres and chrono.
thank you @tustvold , didn't aware this spec before
This looks good to me
btw, i think `with_timezone_opt` already covered another possibility - keep the underline i64 value and change the metadata
Yeah let's do the "hard" operation in the cast kernel, and if people don't like it, they can perform a metadata-only cast using`with_timezone_opt` :+1:
https://github.com/apache/arrow-rs/issues/3794 is related to this, and implements the necessary machinery for timezone aware parsing of strings
|
2023-05-11T11:37:13Z
|
39.0
|
378a9fcc9ee31fff4a9a13f5de5a326dc449541e
|
apache/arrow-rs
| 4,101
|
apache__arrow-rs-4101
|
[
"3855"
] |
6099864180b9a42472bd0a0a17d16a1b612902f4
|
diff --git a/arrow-flight/src/encode.rs b/arrow-flight/src/encode.rs
index f97311d6f9e3..9650031d8b5f 100644
--- a/arrow-flight/src/encode.rs
+++ b/arrow-flight/src/encode.rs
@@ -17,7 +17,7 @@
use std::{collections::VecDeque, fmt::Debug, pin::Pin, sync::Arc, task::Poll};
-use crate::{error::Result, FlightData, SchemaAsIpc};
+use crate::{error::Result, FlightData, FlightDescriptor, SchemaAsIpc};
use arrow_array::{ArrayRef, RecordBatch, RecordBatchOptions};
use arrow_ipc::writer::{DictionaryTracker, IpcDataGenerator, IpcWriteOptions};
use arrow_schema::{DataType, Field, Fields, Schema, SchemaRef};
@@ -72,6 +72,8 @@ pub struct FlightDataEncoderBuilder {
app_metadata: Bytes,
/// Optional schema, if known before data.
schema: Option<SchemaRef>,
+ /// Optional flight descriptor, if known before data.
+ descriptor: Option<FlightDescriptor>,
}
/// Default target size for encoded [`FlightData`].
@@ -87,6 +89,7 @@ impl Default for FlightDataEncoderBuilder {
options: IpcWriteOptions::default(),
app_metadata: Bytes::new(),
schema: None,
+ descriptor: None,
}
}
}
@@ -134,6 +137,15 @@ impl FlightDataEncoderBuilder {
self
}
+ /// Specify a flight descriptor in the first FlightData message.
+ pub fn with_flight_descriptor(
+ mut self,
+ descriptor: Option<FlightDescriptor>,
+ ) -> Self {
+ self.descriptor = descriptor;
+ self
+ }
+
/// Return a [`Stream`](futures::Stream) of [`FlightData`],
/// consuming self. More details on [`FlightDataEncoder`]
pub fn build<S>(self, input: S) -> FlightDataEncoder
@@ -145,6 +157,7 @@ impl FlightDataEncoderBuilder {
options,
app_metadata,
schema,
+ descriptor,
} = self;
FlightDataEncoder::new(
@@ -153,6 +166,7 @@ impl FlightDataEncoderBuilder {
max_flight_data_size,
options,
app_metadata,
+ descriptor,
)
}
}
@@ -176,6 +190,8 @@ pub struct FlightDataEncoder {
queue: VecDeque<FlightData>,
/// Is this stream done (inner is empty or errored)
done: bool,
+ /// cleared after the first FlightData message is sent
+ descriptor: Option<FlightDescriptor>,
}
impl FlightDataEncoder {
@@ -185,6 +201,7 @@ impl FlightDataEncoder {
max_flight_data_size: usize,
options: IpcWriteOptions,
app_metadata: Bytes,
+ descriptor: Option<FlightDescriptor>,
) -> Self {
let mut encoder = Self {
inner,
@@ -194,17 +211,22 @@ impl FlightDataEncoder {
app_metadata: Some(app_metadata),
queue: VecDeque::new(),
done: false,
+ descriptor,
};
// If schema is known up front, enqueue it immediately
if let Some(schema) = schema {
encoder.encode_schema(&schema);
}
+
encoder
}
/// Place the `FlightData` in the queue to send
- fn queue_message(&mut self, data: FlightData) {
+ fn queue_message(&mut self, mut data: FlightData) {
+ if let Some(descriptor) = self.descriptor.take() {
+ data.flight_descriptor = Some(descriptor);
+ }
self.queue.push_back(data);
}
|
diff --git a/arrow-flight/tests/encode_decode.rs b/arrow-flight/tests/encode_decode.rs
index 90fa2b7a6832..4f1a8e667ffc 100644
--- a/arrow-flight/tests/encode_decode.rs
+++ b/arrow-flight/tests/encode_decode.rs
@@ -22,6 +22,8 @@ use std::{collections::HashMap, sync::Arc};
use arrow_array::types::Int32Type;
use arrow_array::{ArrayRef, DictionaryArray, Float64Array, RecordBatch, UInt8Array};
use arrow_cast::pretty::pretty_format_batches;
+use arrow_flight::flight_descriptor::DescriptorType;
+use arrow_flight::FlightDescriptor;
use arrow_flight::{
decode::{DecodedPayload, FlightDataDecoder, FlightRecordBatchStream},
encode::FlightDataEncoderBuilder,
@@ -136,6 +138,29 @@ async fn test_zero_batches_schema_specified() {
assert_eq!(decoder.schema(), Some(&schema));
}
+#[tokio::test]
+async fn test_with_flight_descriptor() {
+ let stream = futures::stream::iter(vec![Ok(make_dictionary_batch(5))]);
+ let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Utf8, true)]));
+
+ let descriptor = Some(FlightDescriptor {
+ r#type: DescriptorType::Path.into(),
+ path: vec!["table_name".to_string()],
+ cmd: Bytes::default(),
+ });
+
+ let encoder = FlightDataEncoderBuilder::default()
+ .with_schema(schema.clone())
+ .with_flight_descriptor(descriptor.clone());
+
+ let mut encoder = encoder.build(stream);
+
+ // First batch should be the schema
+ let first_batch = encoder.next().await.unwrap().unwrap();
+
+ assert_eq!(first_batch.flight_descriptor, descriptor);
+}
+
#[tokio::test]
async fn test_zero_batches_dictionary_schema_specified() {
let schema = Arc::new(Schema::new(vec![
|
Enable setting FlightDescriptor on FlightDataEncoderBuilder
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
When using FlightDataEncoder to send arrow batches to a flight do_put endpoint, FlightDescriptor cannot easily be set on first message. https://arrow.apache.org/docs/format/Flight.html#uploading-data
**Describe the solution you'd like**
On FlightDataEncoderBuilder a `with_flight_descriptor` method would be nice. The FlightDescriptor would then be set on the first FlightData retrieved from the encoder.
**Describe alternatives you've considered**
Here is a workaround, I may be missing something simpler
```rust
let mut encoder = FlightDataEncoderBuilder::new()
.with_schema(schema.clone())
.build(stream);
let mut first_flight_data = encoder
.next()
.await
.expect("no flight data")
.expect("flight data was error");
first_flight_data.flight_descriptor = Some(FlightDescriptor {
r#type: DescriptorType::Path.into(),
path: vec!["table_name".to_string()],
cmd: Bytes::default(),
});
let put_stream = stream::once(async { Ok(first_flight_data) }).chain(encoder);
```
|
Thanks for the suggestion @alexwilcoxson-rel -- I agree this sounds like a nice addition to the API.
Given the request is well specified and the code is fairly easy to test, I think this would be a good first issue for someone to work on if they wanted, so marking it thusly
|
2023-04-19T22:31:46Z
|
38.0
|
6099864180b9a42472bd0a0a17d16a1b612902f4
|
apache/arrow-rs
| 4,061
|
apache__arrow-rs-4061
|
[
"3880"
] |
a35c6c5f4309787a9a2f523920af2efd9b1682b9
|
diff --git a/arrow-arith/src/aggregate.rs b/arrow-arith/src/aggregate.rs
index a9944db13ee1..9ed6dee516a4 100644
--- a/arrow-arith/src/aggregate.rs
+++ b/arrow-arith/src/aggregate.rs
@@ -1241,13 +1241,12 @@ mod tests {
.into_iter()
.collect();
let sliced_input = sliced_input.slice(4, 2);
- let sliced_input = sliced_input.as_boolean();
- assert_eq!(sliced_input, &input);
+ assert_eq!(sliced_input, input);
- let actual = min_boolean(sliced_input);
+ let actual = min_boolean(&sliced_input);
assert_eq!(actual, expected);
- let actual = max_boolean(sliced_input);
+ let actual = max_boolean(&sliced_input);
assert_eq!(actual, expected);
}
diff --git a/arrow-array/src/array/boolean_array.rs b/arrow-array/src/array/boolean_array.rs
index dea5c07da281..d03f0fd040f2 100644
--- a/arrow-array/src/array/boolean_array.rs
+++ b/arrow-array/src/array/boolean_array.rs
@@ -20,7 +20,7 @@ use crate::builder::BooleanBuilder;
use crate::iterator::BooleanIter;
use crate::{Array, ArrayAccessor, ArrayRef};
use arrow_buffer::{bit_util, BooleanBuffer, MutableBuffer, NullBuffer};
-use arrow_data::ArrayData;
+use arrow_data::{ArrayData, ArrayDataBuilder};
use arrow_schema::DataType;
use std::any::Any;
use std::sync::Arc;
@@ -66,8 +66,8 @@ use std::sync::Arc;
/// ```
#[derive(Clone)]
pub struct BooleanArray {
- data: ArrayData,
values: BooleanBuffer,
+ nulls: Option<NullBuffer>,
}
impl std::fmt::Debug for BooleanArray {
@@ -90,27 +90,25 @@ impl BooleanArray {
if let Some(n) = nulls.as_ref() {
assert_eq!(values.len(), n.len());
}
-
- // TODO: Don't store ArrayData inside arrays (#3880)
- let data = unsafe {
- ArrayData::builder(DataType::Boolean)
- .len(values.len())
- .offset(values.offset())
- .nulls(nulls)
- .buffers(vec![values.inner().clone()])
- .build_unchecked()
- };
- Self { data, values }
+ Self { values, nulls }
}
/// Returns the length of this array.
pub fn len(&self) -> usize {
- self.data.len()
+ self.values.len()
}
/// Returns whether this array is empty.
pub fn is_empty(&self) -> bool {
- self.data.is_empty()
+ self.values.is_empty()
+ }
+
+ /// Returns a zero-copy slice of this array with the indicated offset and length.
+ pub fn slice(&self, offset: usize, length: usize) -> Self {
+ Self {
+ values: self.values.slice(offset, length),
+ nulls: self.nulls.as_ref().map(|n| n.slice(offset, length)),
+ }
}
/// Returns a new boolean array builder
@@ -125,7 +123,7 @@ impl BooleanArray {
/// Returns the number of non null, true values within this array
pub fn true_count(&self) -> usize {
- match self.data.nulls() {
+ match self.nulls() {
Some(nulls) => {
let null_chunks = nulls.inner().bit_chunks().iter_padded();
let value_chunks = self.values().bit_chunks().iter_padded();
@@ -247,25 +245,48 @@ impl Array for BooleanArray {
self
}
- fn data(&self) -> &ArrayData {
- &self.data
- }
-
fn to_data(&self) -> ArrayData {
- self.data.clone()
+ self.clone().into()
}
fn into_data(self) -> ArrayData {
self.into()
}
+ fn data_type(&self) -> &DataType {
+ &DataType::Boolean
+ }
+
fn slice(&self, offset: usize, length: usize) -> ArrayRef {
- // TODO: Slice buffers directly (#3880)
- Arc::new(Self::from(self.data.slice(offset, length)))
+ Arc::new(self.slice(offset, length))
+ }
+
+ fn len(&self) -> usize {
+ self.values.len()
+ }
+
+ fn is_empty(&self) -> bool {
+ self.values.is_empty()
+ }
+
+ fn offset(&self) -> usize {
+ self.values.offset()
}
fn nulls(&self) -> Option<&NullBuffer> {
- self.data.nulls()
+ self.nulls.as_ref()
+ }
+
+ fn get_buffer_memory_size(&self) -> usize {
+ let mut sum = self.values.inner().capacity();
+ if let Some(x) = &self.nulls {
+ sum += x.buffer().capacity()
+ }
+ sum
+ }
+
+ fn get_array_memory_size(&self) -> usize {
+ std::mem::size_of::<Self>() + self.get_buffer_memory_size()
}
}
@@ -324,13 +345,22 @@ impl From<ArrayData> for BooleanArray {
let values =
BooleanBuffer::new(data.buffers()[0].clone(), data.offset(), data.len());
- Self { data, values }
+ Self {
+ values,
+ nulls: data.nulls().cloned(),
+ }
}
}
impl From<BooleanArray> for ArrayData {
fn from(array: BooleanArray) -> Self {
- array.data
+ let builder = ArrayDataBuilder::new(DataType::Boolean)
+ .len(array.values.len())
+ .offset(array.values.offset())
+ .nulls(array.nulls)
+ .buffers(vec![array.values.into_inner()]);
+
+ unsafe { builder.build_unchecked() }
}
}
diff --git a/arrow-array/src/array/byte_array.rs b/arrow-array/src/array/byte_array.rs
index f0e43e6949e9..e23079ef9be9 100644
--- a/arrow-array/src/array/byte_array.rs
+++ b/arrow-array/src/array/byte_array.rs
@@ -23,7 +23,7 @@ use crate::types::ByteArrayType;
use crate::{Array, ArrayAccessor, ArrayRef, OffsetSizeTrait};
use arrow_buffer::{ArrowNativeType, Buffer};
use arrow_buffer::{NullBuffer, OffsetBuffer};
-use arrow_data::ArrayData;
+use arrow_data::{ArrayData, ArrayDataBuilder};
use arrow_schema::DataType;
use std::any::Any;
use std::sync::Arc;
@@ -39,17 +39,19 @@ use std::sync::Arc;
/// [`BinaryArray`]: crate::BinaryArray
/// [`LargeBinaryArray`]: crate::LargeBinaryArray
pub struct GenericByteArray<T: ByteArrayType> {
- data: ArrayData,
+ data_type: DataType,
value_offsets: OffsetBuffer<T::Offset>,
value_data: Buffer,
+ nulls: Option<NullBuffer>,
}
impl<T: ByteArrayType> Clone for GenericByteArray<T> {
fn clone(&self) -> Self {
Self {
- data: self.data.clone(),
+ data_type: self.data_type.clone(),
value_offsets: self.value_offsets.clone(),
value_data: self.value_data.clone(),
+ nulls: self.nulls.clone(),
}
}
}
@@ -135,7 +137,7 @@ impl<T: ByteArrayType> GenericByteArray<T> {
/// Panics if index `i` is out of bounds.
pub fn value(&self, i: usize) -> &T::Native {
assert!(
- i < self.data.len(),
+ i < self.len(),
"Trying to access an element at index {} from a {}{}Array of length {}",
i,
T::Offset::PREFIX,
@@ -154,29 +156,33 @@ impl<T: ByteArrayType> GenericByteArray<T> {
/// Returns a zero-copy slice of this array with the indicated offset and length.
pub fn slice(&self, offset: usize, length: usize) -> Self {
- // TODO: Slice buffers directly (#3880)
- self.data.slice(offset, length).into()
+ Self {
+ data_type: self.data_type.clone(),
+ value_offsets: self.value_offsets.slice(offset, length),
+ value_data: self.value_data.clone(),
+ nulls: self.nulls.as_ref().map(|n| n.slice(offset, length)),
+ }
}
/// Returns `GenericByteBuilder` of this byte array for mutating its values if the underlying
/// offset and data buffers are not shared by others.
pub fn into_builder(self) -> Result<GenericByteBuilder<T>, Self> {
let len = self.len();
- let null_bit_buffer = self.data.nulls().map(|b| b.inner().sliced());
+ let value_len =
+ T::Offset::as_usize(self.value_offsets()[len] - self.value_offsets()[0]);
+
+ let data = self.into_data();
+ let null_bit_buffer = data.nulls().map(|b| b.inner().sliced());
let element_len = std::mem::size_of::<T::Offset>();
- let offset_buffer = self.data.buffers()[0]
- .slice_with_length(self.data.offset() * element_len, (len + 1) * element_len);
+ let offset_buffer = data.buffers()[0]
+ .slice_with_length(data.offset() * element_len, (len + 1) * element_len);
let element_len = std::mem::size_of::<u8>();
- let value_len =
- T::Offset::as_usize(self.value_offsets()[len] - self.value_offsets()[0]);
- let value_buffer = self.data.buffers()[1]
- .slice_with_length(self.data.offset() * element_len, value_len * element_len);
+ let value_buffer = data.buffers()[1]
+ .slice_with_length(data.offset() * element_len, value_len * element_len);
- drop(self.data);
- drop(self.value_data);
- drop(self.value_offsets);
+ drop(data);
let try_mutable_null_buffer = match null_bit_buffer {
None => Ok(None),
@@ -258,24 +264,49 @@ impl<T: ByteArrayType> Array for GenericByteArray<T> {
self
}
- fn data(&self) -> &ArrayData {
- &self.data
- }
-
fn to_data(&self) -> ArrayData {
- self.data.clone()
+ self.clone().into()
}
fn into_data(self) -> ArrayData {
self.into()
}
+ fn data_type(&self) -> &DataType {
+ &self.data_type
+ }
+
fn slice(&self, offset: usize, length: usize) -> ArrayRef {
Arc::new(self.slice(offset, length))
}
+ fn len(&self) -> usize {
+ self.value_offsets.len() - 1
+ }
+
+ fn is_empty(&self) -> bool {
+ self.value_offsets.len() <= 1
+ }
+
+ fn offset(&self) -> usize {
+ 0
+ }
+
fn nulls(&self) -> Option<&NullBuffer> {
- self.data.nulls()
+ self.nulls.as_ref()
+ }
+
+ fn get_buffer_memory_size(&self) -> usize {
+ let mut sum = self.value_offsets.inner().inner().capacity();
+ sum += self.value_data.capacity();
+ if let Some(x) = &self.nulls {
+ sum += x.buffer().capacity()
+ }
+ sum
+ }
+
+ fn get_array_memory_size(&self) -> usize {
+ std::mem::size_of::<Self>() + self.get_buffer_memory_size()
}
}
@@ -313,18 +344,25 @@ impl<T: ByteArrayType> From<ArrayData> for GenericByteArray<T> {
let value_offsets = unsafe { get_offsets(&data) };
let value_data = data.buffers()[1].clone();
Self {
- data,
- // SAFETY:
- // ArrayData must be valid, and validated data type above
value_offsets,
value_data,
+ data_type: data.data_type().clone(),
+ nulls: data.nulls().cloned(),
}
}
}
impl<T: ByteArrayType> From<GenericByteArray<T>> for ArrayData {
fn from(array: GenericByteArray<T>) -> Self {
- array.data
+ let len = array.len();
+
+ let offsets = array.value_offsets.into_inner().into_inner();
+ let builder = ArrayDataBuilder::new(array.data_type)
+ .len(len)
+ .buffers(vec![offsets, array.value_data])
+ .nulls(array.nulls);
+
+ unsafe { builder.build_unchecked() }
}
}
diff --git a/arrow-array/src/array/dictionary_array.rs b/arrow-array/src/array/dictionary_array.rs
index dd6213d543ea..f25a077a81ba 100644
--- a/arrow-array/src/array/dictionary_array.rs
+++ b/arrow-array/src/array/dictionary_array.rs
@@ -208,9 +208,7 @@ pub type UInt64DictionaryArray = DictionaryArray<UInt64Type>;
/// assert_eq!(&array, &expected);
/// ```
pub struct DictionaryArray<K: ArrowDictionaryKeyType> {
- /// Data of this dictionary. Note that this is _not_ compatible with the C Data interface,
- /// as, in the current implementation, `values` below are the first child of this struct.
- data: ArrayData,
+ data_type: DataType,
/// The keys of this dictionary. These are constructed from the
/// buffer and null bitmap of `data`. Also, note that these do
@@ -228,7 +226,7 @@ pub struct DictionaryArray<K: ArrowDictionaryKeyType> {
impl<K: ArrowDictionaryKeyType> Clone for DictionaryArray<K> {
fn clone(&self) -> Self {
Self {
- data: self.data.clone(),
+ data_type: self.data_type.clone(),
keys: self.keys.clone(),
values: self.values.clone(),
is_ordered: self.is_ordered,
@@ -325,8 +323,12 @@ impl<K: ArrowDictionaryKeyType> DictionaryArray<K> {
/// Returns a zero-copy slice of this array with the indicated offset and length.
pub fn slice(&self, offset: usize, length: usize) -> Self {
- // TODO: Slice buffers directly (#3880)
- self.data.slice(offset, length).into()
+ Self {
+ data_type: self.data_type.clone(),
+ keys: self.keys.slice(offset, length),
+ values: self.values.clone(),
+ is_ordered: self.is_ordered,
+ }
}
/// Downcast this dictionary to a [`TypedDictionaryArray`]
@@ -390,8 +392,7 @@ impl<K: ArrowDictionaryKeyType> DictionaryArray<K> {
assert!(values.len() >= self.values.len());
let builder = self
- .data
- .clone()
+ .to_data()
.into_builder()
.data_type(DataType::Dictionary(
Box::new(K::DATA_TYPE),
@@ -419,7 +420,6 @@ impl<K: ArrowDictionaryKeyType> DictionaryArray<K> {
let key_array = self.keys().clone();
let value_array = self.values().as_primitive::<V>().clone();
- drop(self.data);
drop(self.keys);
drop(self.values);
@@ -504,20 +504,22 @@ impl<T: ArrowDictionaryKeyType> From<ArrayData> for DictionaryArray<T> {
key_data_type
);
+ let values = make_array(data.child_data()[0].clone());
+ let data_type = data.data_type().clone();
+
// create a zero-copy of the keys' data
// SAFETY:
// ArrayData is valid and verified type above
let keys = PrimitiveArray::<T>::from(unsafe {
- data.clone()
- .into_builder()
+ data.into_builder()
.data_type(T::DATA_TYPE)
.child_data(vec![])
.build_unchecked()
});
- let values = make_array(data.child_data()[0].clone());
+
Self {
- data,
+ data_type,
keys,
values,
is_ordered: false,
@@ -530,7 +532,14 @@ impl<T: ArrowDictionaryKeyType> From<ArrayData> for DictionaryArray<T> {
impl<T: ArrowDictionaryKeyType> From<DictionaryArray<T>> for ArrayData {
fn from(array: DictionaryArray<T>) -> Self {
- array.data
+ let builder = array
+ .keys
+ .into_data()
+ .into_builder()
+ .data_type(array.data_type)
+ .child_data(vec![array.values.to_data()]);
+
+ unsafe { builder.build_unchecked() }
}
}
@@ -594,24 +603,46 @@ impl<T: ArrowDictionaryKeyType> Array for DictionaryArray<T> {
self
}
- fn data(&self) -> &ArrayData {
- &self.data
- }
-
fn to_data(&self) -> ArrayData {
- self.data.clone()
+ self.clone().into()
}
fn into_data(self) -> ArrayData {
self.into()
}
+ fn data_type(&self) -> &DataType {
+ &self.data_type
+ }
+
fn slice(&self, offset: usize, length: usize) -> ArrayRef {
Arc::new(self.slice(offset, length))
}
+ fn len(&self) -> usize {
+ self.keys.len()
+ }
+
+ fn is_empty(&self) -> bool {
+ self.keys.is_empty()
+ }
+
+ fn offset(&self) -> usize {
+ self.keys.offset()
+ }
+
fn nulls(&self) -> Option<&NullBuffer> {
- self.data.nulls()
+ self.keys.nulls()
+ }
+
+ fn get_buffer_memory_size(&self) -> usize {
+ self.keys.get_buffer_memory_size() + self.values.get_buffer_memory_size()
+ }
+
+ fn get_array_memory_size(&self) -> usize {
+ std::mem::size_of::<Self>()
+ + self.keys.get_buffer_memory_size()
+ + self.values.get_array_memory_size()
}
}
@@ -685,10 +716,6 @@ impl<'a, K: ArrowDictionaryKeyType, V: Sync> Array for TypedDictionaryArray<'a,
self.dictionary
}
- fn data(&self) -> &ArrayData {
- &self.dictionary.data
- }
-
fn to_data(&self) -> ArrayData {
self.dictionary.to_data()
}
@@ -697,13 +724,37 @@ impl<'a, K: ArrowDictionaryKeyType, V: Sync> Array for TypedDictionaryArray<'a,
self.dictionary.into_data()
}
+ fn data_type(&self) -> &DataType {
+ self.dictionary.data_type()
+ }
+
fn slice(&self, offset: usize, length: usize) -> ArrayRef {
Arc::new(self.dictionary.slice(offset, length))
}
+ fn len(&self) -> usize {
+ self.dictionary.len()
+ }
+
+ fn is_empty(&self) -> bool {
+ self.dictionary.is_empty()
+ }
+
+ fn offset(&self) -> usize {
+ self.dictionary.offset()
+ }
+
fn nulls(&self) -> Option<&NullBuffer> {
self.dictionary.nulls()
}
+
+ fn get_buffer_memory_size(&self) -> usize {
+ self.dictionary.get_buffer_memory_size()
+ }
+
+ fn get_array_memory_size(&self) -> usize {
+ self.dictionary.get_array_memory_size()
+ }
}
impl<'a, K, V> IntoIterator for TypedDictionaryArray<'a, K, V>
diff --git a/arrow-array/src/array/fixed_size_binary_array.rs b/arrow-array/src/array/fixed_size_binary_array.rs
index f8d2f04dee69..08ce76c066c3 100644
--- a/arrow-array/src/array/fixed_size_binary_array.rs
+++ b/arrow-array/src/array/fixed_size_binary_array.rs
@@ -20,7 +20,7 @@ use crate::iterator::FixedSizeBinaryIter;
use crate::{Array, ArrayAccessor, ArrayRef, FixedSizeListArray};
use arrow_buffer::buffer::NullBuffer;
use arrow_buffer::{bit_util, Buffer, MutableBuffer};
-use arrow_data::ArrayData;
+use arrow_data::{ArrayData, ArrayDataBuilder};
use arrow_schema::{ArrowError, DataType};
use std::any::Any;
use std::sync::Arc;
@@ -51,9 +51,11 @@ use std::sync::Arc;
///
#[derive(Clone)]
pub struct FixedSizeBinaryArray {
- data: ArrayData,
+ data_type: DataType, // Must be DataType::FixedSizeBinary(value_length)
value_data: Buffer,
- length: i32,
+ nulls: Option<NullBuffer>,
+ len: usize,
+ value_length: i32,
}
impl FixedSizeBinaryArray {
@@ -62,12 +64,12 @@ impl FixedSizeBinaryArray {
/// Panics if index `i` is out of bounds.
pub fn value(&self, i: usize) -> &[u8] {
assert!(
- i < self.data.len(),
+ i < self.len(),
"Trying to access an element at index {} from a FixedSizeBinaryArray of length {}",
i,
self.len()
);
- let offset = i + self.data.offset();
+ let offset = i + self.offset();
unsafe {
let pos = self.value_offset_at(offset);
std::slice::from_raw_parts(
@@ -81,7 +83,7 @@ impl FixedSizeBinaryArray {
/// # Safety
/// Caller is responsible for ensuring that the index is within the bounds of the array
pub unsafe fn value_unchecked(&self, i: usize) -> &[u8] {
- let offset = i + self.data.offset();
+ let offset = i + self.offset();
let pos = self.value_offset_at(offset);
std::slice::from_raw_parts(
self.value_data.as_ptr().offset(pos as isize),
@@ -94,7 +96,7 @@ impl FixedSizeBinaryArray {
/// Note this doesn't do any bound checking, for performance reason.
#[inline]
pub fn value_offset(&self, i: usize) -> i32 {
- self.value_offset_at(self.data.offset() + i)
+ self.value_offset_at(self.offset() + i)
}
/// Returns the length for an element.
@@ -102,18 +104,30 @@ impl FixedSizeBinaryArray {
/// All elements have the same length as the array is a fixed size.
#[inline]
pub fn value_length(&self) -> i32 {
- self.length
+ self.value_length
}
/// Returns a clone of the value data buffer
pub fn value_data(&self) -> Buffer {
- self.data.buffers()[0].clone()
+ self.value_data.clone()
}
/// Returns a zero-copy slice of this array with the indicated offset and length.
- pub fn slice(&self, offset: usize, length: usize) -> Self {
- // TODO: Slice buffers directly (#3880)
- self.data.slice(offset, length).into()
+ pub fn slice(&self, offset: usize, len: usize) -> Self {
+ assert!(
+ offset.saturating_add(len) <= self.len,
+ "the length + offset of the sliced FixedSizeBinaryArray cannot exceed the existing length"
+ );
+
+ let size = self.value_length as usize;
+
+ Self {
+ data_type: self.data_type.clone(),
+ nulls: self.nulls.as_ref().map(|n| n.slice(offset, len)),
+ value_length: self.value_length,
+ value_data: self.value_data.slice_with_length(offset * size, len * size),
+ len,
+ }
}
/// Create an array from an iterable argument of sparse byte slices.
@@ -364,7 +378,7 @@ impl FixedSizeBinaryArray {
#[inline]
fn value_offset_at(&self, i: usize) -> i32 {
- self.length * i as i32
+ self.value_length * i as i32
}
/// constructs a new iterator
@@ -380,22 +394,33 @@ impl From<ArrayData> for FixedSizeBinaryArray {
1,
"FixedSizeBinaryArray data should contain 1 buffer only (values)"
);
- let value_data = data.buffers()[0].clone();
- let length = match data.data_type() {
+ let value_length = match data.data_type() {
DataType::FixedSizeBinary(len) => *len,
_ => panic!("Expected data type to be FixedSizeBinary"),
};
+
+ let size = value_length as usize;
+ let value_data =
+ data.buffers()[0].slice_with_length(data.offset() * size, data.len() * size);
+
Self {
- data,
+ data_type: data.data_type().clone(),
+ nulls: data.nulls().cloned(),
+ len: data.len(),
value_data,
- length,
+ value_length,
}
}
}
impl From<FixedSizeBinaryArray> for ArrayData {
fn from(array: FixedSizeBinaryArray) -> Self {
- array.data
+ let builder = ArrayDataBuilder::new(array.data_type)
+ .len(array.len)
+ .buffers(vec![array.value_data])
+ .nulls(array.nulls);
+
+ unsafe { builder.build_unchecked() }
}
}
@@ -468,24 +493,48 @@ impl Array for FixedSizeBinaryArray {
self
}
- fn data(&self) -> &ArrayData {
- &self.data
- }
-
fn to_data(&self) -> ArrayData {
- self.data.clone()
+ self.clone().into()
}
fn into_data(self) -> ArrayData {
self.into()
}
+ fn data_type(&self) -> &DataType {
+ &self.data_type
+ }
+
fn slice(&self, offset: usize, length: usize) -> ArrayRef {
Arc::new(self.slice(offset, length))
}
+ fn len(&self) -> usize {
+ self.len
+ }
+
+ fn is_empty(&self) -> bool {
+ self.len == 0
+ }
+
+ fn offset(&self) -> usize {
+ 0
+ }
+
fn nulls(&self) -> Option<&NullBuffer> {
- self.data.nulls()
+ self.nulls.as_ref()
+ }
+
+ fn get_buffer_memory_size(&self) -> usize {
+ let mut sum = self.value_data.capacity();
+ if let Some(n) = &self.nulls {
+ sum += n.buffer().capacity();
+ }
+ sum
+ }
+
+ fn get_array_memory_size(&self) -> usize {
+ std::mem::size_of::<Self>() + self.get_buffer_memory_size()
}
}
@@ -566,9 +615,9 @@ mod tests {
fixed_size_binary_array.value(1)
);
assert_eq!(2, fixed_size_binary_array.len());
- assert_eq!(5, fixed_size_binary_array.value_offset(0));
+ assert_eq!(0, fixed_size_binary_array.value_offset(0));
assert_eq!(5, fixed_size_binary_array.value_length());
- assert_eq!(10, fixed_size_binary_array.value_offset(1));
+ assert_eq!(5, fixed_size_binary_array.value_offset(1));
}
#[test]
diff --git a/arrow-array/src/array/fixed_size_list_array.rs b/arrow-array/src/array/fixed_size_list_array.rs
index a56bb017f6b0..86adafa066f0 100644
--- a/arrow-array/src/array/fixed_size_list_array.rs
+++ b/arrow-array/src/array/fixed_size_list_array.rs
@@ -19,7 +19,7 @@ use crate::array::print_long_array;
use crate::builder::{FixedSizeListBuilder, PrimitiveBuilder};
use crate::{make_array, Array, ArrayAccessor, ArrayRef, ArrowPrimitiveType};
use arrow_buffer::buffer::NullBuffer;
-use arrow_data::ArrayData;
+use arrow_data::{ArrayData, ArrayDataBuilder};
use arrow_schema::DataType;
use std::any::Any;
use std::sync::Arc;
@@ -64,9 +64,11 @@ use std::sync::Arc;
/// [crate::array::FixedSizeBinaryArray]
#[derive(Clone)]
pub struct FixedSizeListArray {
- data: ArrayData,
+ data_type: DataType, // Must be DataType::FixedSizeList(value_length)
values: ArrayRef,
- length: i32,
+ nulls: Option<NullBuffer>,
+ value_length: i32,
+ len: usize,
}
impl FixedSizeListArray {
@@ -91,7 +93,7 @@ impl FixedSizeListArray {
/// Note this doesn't do any bound checking, for performance reason.
#[inline]
pub fn value_offset(&self, i: usize) -> i32 {
- self.value_offset_at(self.data.offset() + i)
+ self.value_offset_at(i)
}
/// Returns the length for an element.
@@ -99,18 +101,29 @@ impl FixedSizeListArray {
/// All elements have the same length as the array is a fixed size.
#[inline]
pub const fn value_length(&self) -> i32 {
- self.length
+ self.value_length
}
#[inline]
const fn value_offset_at(&self, i: usize) -> i32 {
- i as i32 * self.length
+ i as i32 * self.value_length
}
/// Returns a zero-copy slice of this array with the indicated offset and length.
- pub fn slice(&self, offset: usize, length: usize) -> Self {
- // TODO: Slice buffers directly (#3880)
- self.data.slice(offset, length).into()
+ pub fn slice(&self, offset: usize, len: usize) -> Self {
+ assert!(
+ offset.saturating_add(len) <= self.len,
+ "the length + offset of the sliced FixedSizeListArray cannot exceed the existing length"
+ );
+ let size = self.value_length as usize;
+
+ Self {
+ data_type: self.data_type.clone(),
+ values: self.values.slice(offset * size, len * size),
+ nulls: self.nulls.as_ref().map(|n| n.slice(offset, len)),
+ value_length: self.value_length,
+ len,
+ }
}
/// Creates a [`FixedSizeListArray`] from an iterator of primitive values
@@ -163,45 +176,35 @@ impl FixedSizeListArray {
impl From<ArrayData> for FixedSizeListArray {
fn from(data: ArrayData) -> Self {
- assert_eq!(
- data.buffers().len(),
- 0,
- "FixedSizeListArray data should not contain a buffer for value offsets"
- );
- assert_eq!(
- data.child_data().len(),
- 1,
- "FixedSizeListArray should contain a single child array (values array)"
- );
- let values = make_array(data.child_data()[0].clone());
- let length = match data.data_type() {
- DataType::FixedSizeList(_, len) => {
- if *len > 0 {
- // check that child data is multiple of length
- assert_eq!(
- values.len() % *len as usize,
- 0,
- "FixedSizeListArray child array length should be a multiple of {len}"
- );
- }
-
- *len
- }
+ let value_length = match data.data_type() {
+ DataType::FixedSizeList(_, len) => *len,
_ => {
panic!("FixedSizeListArray data should contain a FixedSizeList data type")
}
};
+
+ let size = value_length as usize;
+ let values = make_array(
+ data.child_data()[0].slice(data.offset() * size, data.len() * size),
+ );
Self {
- data,
+ data_type: data.data_type().clone(),
values,
- length,
+ nulls: data.nulls().cloned(),
+ value_length,
+ len: data.len(),
}
}
}
impl From<FixedSizeListArray> for ArrayData {
fn from(array: FixedSizeListArray) -> Self {
- array.data
+ let builder = ArrayDataBuilder::new(array.data_type)
+ .len(array.len)
+ .nulls(array.nulls)
+ .child_data(vec![array.values.to_data()]);
+
+ unsafe { builder.build_unchecked() }
}
}
@@ -210,24 +213,52 @@ impl Array for FixedSizeListArray {
self
}
- fn data(&self) -> &ArrayData {
- &self.data
- }
-
fn to_data(&self) -> ArrayData {
- self.data.clone()
+ self.clone().into()
}
fn into_data(self) -> ArrayData {
self.into()
}
+ fn data_type(&self) -> &DataType {
+ &self.data_type
+ }
+
fn slice(&self, offset: usize, length: usize) -> ArrayRef {
Arc::new(self.slice(offset, length))
}
+ fn len(&self) -> usize {
+ self.len
+ }
+
+ fn is_empty(&self) -> bool {
+ self.len == 0
+ }
+
+ fn offset(&self) -> usize {
+ 0
+ }
+
fn nulls(&self) -> Option<&NullBuffer> {
- self.data.nulls()
+ self.nulls.as_ref()
+ }
+
+ fn get_buffer_memory_size(&self) -> usize {
+ let mut size = self.values.get_buffer_memory_size();
+ if let Some(n) = self.nulls.as_ref() {
+ size += n.buffer().capacity();
+ }
+ size
+ }
+
+ fn get_array_memory_size(&self) -> usize {
+ let mut size = std::mem::size_of::<Self>() + self.values.get_array_memory_size();
+ if let Some(n) = self.nulls.as_ref() {
+ size += n.buffer().capacity();
+ }
+ size
}
}
@@ -258,7 +289,6 @@ mod tests {
use super::*;
use crate::cast::AsArray;
use crate::types::Int32Type;
- use crate::Int32Array;
use arrow_buffer::{bit_util, Buffer};
use arrow_schema::Field;
@@ -289,15 +319,7 @@ mod tests {
assert_eq!(0, list_array.null_count());
assert_eq!(6, list_array.value_offset(2));
assert_eq!(3, list_array.value_length());
- assert_eq!(
- 0,
- list_array
- .value(0)
- .as_any()
- .downcast_ref::<Int32Array>()
- .unwrap()
- .value(0)
- );
+ assert_eq!(0, list_array.value(0).as_primitive::<Int32Type>().value(0));
for i in 0..3 {
assert!(list_array.is_valid(i));
assert!(!list_array.is_null(i));
@@ -305,26 +327,24 @@ mod tests {
// Now test with a non-zero offset
let list_data = ArrayData::builder(list_data_type)
- .len(3)
+ .len(2)
.offset(1)
.add_child_data(value_data.clone())
.build()
.unwrap();
let list_array = FixedSizeListArray::from(list_data);
- assert_eq!(value_data, list_array.values().to_data());
+ assert_eq!(value_data.slice(3, 6), list_array.values().to_data());
assert_eq!(DataType::Int32, list_array.value_type());
- assert_eq!(3, list_array.len());
+ assert_eq!(2, list_array.len());
assert_eq!(0, list_array.null_count());
assert_eq!(3, list_array.value(0).as_primitive::<Int32Type>().value(0));
- assert_eq!(6, list_array.value_offset(1));
+ assert_eq!(3, list_array.value_offset(1));
assert_eq!(3, list_array.value_length());
}
#[test]
- #[should_panic(
- expected = "FixedSizeListArray child array length should be a multiple of 3"
- )]
+ #[should_panic(expected = "assertion failed: (offset + length) <= self.len()")]
// Different error messages, so skip for now
// https://github.com/apache/arrow-rs/issues/1545
#[cfg(not(feature = "force_validate"))]
@@ -389,11 +409,10 @@ mod tests {
let sliced_array = list_array.slice(1, 4);
assert_eq!(4, sliced_array.len());
- assert_eq!(1, sliced_array.offset());
assert_eq!(2, sliced_array.null_count());
for i in 0..sliced_array.len() {
- if bit_util::get_bit(&null_bits, sliced_array.offset() + i) {
+ if bit_util::get_bit(&null_bits, 1 + i) {
assert!(sliced_array.is_valid(i));
} else {
assert!(sliced_array.is_null(i));
@@ -406,12 +425,14 @@ mod tests {
.downcast_ref::<FixedSizeListArray>()
.unwrap();
assert_eq!(2, sliced_list_array.value_length());
- assert_eq!(6, sliced_list_array.value_offset(2));
- assert_eq!(8, sliced_list_array.value_offset(3));
+ assert_eq!(4, sliced_list_array.value_offset(2));
+ assert_eq!(6, sliced_list_array.value_offset(3));
}
#[test]
- #[should_panic(expected = "assertion failed: (offset + length) <= self.len()")]
+ #[should_panic(
+ expected = "the offset of the new Buffer cannot exceed the existing length"
+ )]
fn test_fixed_size_list_array_index_out_of_bound() {
// Construct a value array
let value_data = ArrayData::builder(DataType::Int32)
diff --git a/arrow-array/src/array/list_array.rs b/arrow-array/src/array/list_array.rs
index f47ea80696e7..8e6f84743f2a 100644
--- a/arrow-array/src/array/list_array.rs
+++ b/arrow-array/src/array/list_array.rs
@@ -21,7 +21,7 @@ use crate::{
iterator::GenericListArrayIter, Array, ArrayAccessor, ArrayRef, ArrowPrimitiveType,
};
use arrow_buffer::{ArrowNativeType, NullBuffer, OffsetBuffer};
-use arrow_data::ArrayData;
+use arrow_data::{ArrayData, ArrayDataBuilder};
use arrow_schema::{ArrowError, DataType, Field};
use num::Integer;
use std::any::Any;
@@ -52,7 +52,8 @@ impl OffsetSizeTrait for i64 {
///
/// For non generic lists, you may wish to consider using [`ListArray`] or [`LargeListArray`]`
pub struct GenericListArray<OffsetSize: OffsetSizeTrait> {
- data: ArrayData,
+ data_type: DataType,
+ nulls: Option<NullBuffer>,
values: ArrayRef,
value_offsets: OffsetBuffer<OffsetSize>,
}
@@ -60,7 +61,8 @@ pub struct GenericListArray<OffsetSize: OffsetSizeTrait> {
impl<OffsetSize: OffsetSizeTrait> Clone for GenericListArray<OffsetSize> {
fn clone(&self) -> Self {
Self {
- data: self.data.clone(),
+ data_type: self.data_type.clone(),
+ nulls: self.nulls.clone(),
values: self.values.clone(),
value_offsets: self.value_offsets.clone(),
}
@@ -144,8 +146,12 @@ impl<OffsetSize: OffsetSizeTrait> GenericListArray<OffsetSize> {
/// Returns a zero-copy slice of this array with the indicated offset and length.
pub fn slice(&self, offset: usize, length: usize) -> Self {
- // TODO: Slice buffers directly (#3880)
- self.data.slice(offset, length).into()
+ Self {
+ data_type: self.data_type.clone(),
+ nulls: self.nulls.as_ref().map(|n| n.slice(offset, length)),
+ values: self.values.clone(),
+ value_offsets: self.value_offsets.slice(offset, length),
+ }
}
/// Creates a [`GenericListArray`] from an iterator of primitive values
@@ -201,7 +207,14 @@ impl<OffsetSize: 'static + OffsetSizeTrait> From<GenericListArray<OffsetSize>>
for ArrayData
{
fn from(array: GenericListArray<OffsetSize>) -> Self {
- array.data
+ let len = array.len();
+ let builder = ArrayDataBuilder::new(array.data_type)
+ .len(len)
+ .nulls(array.nulls)
+ .buffers(vec![array.value_offsets.into_inner().into_inner()])
+ .child_data(vec![array.values.to_data()]);
+
+ unsafe { builder.build_unchecked() }
}
}
@@ -244,7 +257,8 @@ impl<OffsetSize: OffsetSizeTrait> GenericListArray<OffsetSize> {
let value_offsets = unsafe { get_offsets(&data) };
Ok(Self {
- data,
+ data_type: data.data_type().clone(),
+ nulls: data.nulls().cloned(),
values,
value_offsets,
})
@@ -256,24 +270,54 @@ impl<OffsetSize: OffsetSizeTrait> Array for GenericListArray<OffsetSize> {
self
}
- fn data(&self) -> &ArrayData {
- &self.data
- }
-
fn to_data(&self) -> ArrayData {
- self.data.clone()
+ self.clone().into()
}
fn into_data(self) -> ArrayData {
self.into()
}
+ fn data_type(&self) -> &DataType {
+ &self.data_type
+ }
+
fn slice(&self, offset: usize, length: usize) -> ArrayRef {
Arc::new(self.slice(offset, length))
}
+ fn len(&self) -> usize {
+ self.value_offsets.len() - 1
+ }
+
+ fn is_empty(&self) -> bool {
+ self.value_offsets.len() <= 1
+ }
+
+ fn offset(&self) -> usize {
+ 0
+ }
+
fn nulls(&self) -> Option<&NullBuffer> {
- self.data.nulls()
+ self.nulls.as_ref()
+ }
+
+ fn get_buffer_memory_size(&self) -> usize {
+ let mut size = self.values.get_buffer_memory_size();
+ size += self.value_offsets.inner().inner().capacity();
+ if let Some(n) = self.nulls.as_ref() {
+ size += n.buffer().capacity();
+ }
+ size
+ }
+
+ fn get_array_memory_size(&self) -> usize {
+ let mut size = std::mem::size_of::<Self>() + self.values.get_array_memory_size();
+ size += self.value_offsets.inner().inner().capacity();
+ if let Some(n) = self.nulls.as_ref() {
+ size += n.buffer().capacity();
+ }
+ size
}
}
@@ -649,11 +693,10 @@ mod tests {
let sliced_array = list_array.slice(1, 6);
assert_eq!(6, sliced_array.len());
- assert_eq!(1, sliced_array.offset());
assert_eq!(3, sliced_array.null_count());
for i in 0..sliced_array.len() {
- if bit_util::get_bit(&null_bits, sliced_array.offset() + i) {
+ if bit_util::get_bit(&null_bits, 1 + i) {
assert!(sliced_array.is_valid(i));
} else {
assert!(sliced_array.is_null(i));
@@ -713,11 +756,10 @@ mod tests {
let sliced_array = list_array.slice(1, 6);
assert_eq!(6, sliced_array.len());
- assert_eq!(1, sliced_array.offset());
assert_eq!(3, sliced_array.null_count());
for i in 0..sliced_array.len() {
- if bit_util::get_bit(&null_bits, sliced_array.offset() + i) {
+ if bit_util::get_bit(&null_bits, 1 + i) {
assert!(sliced_array.is_valid(i));
} else {
assert!(sliced_array.is_null(i));
diff --git a/arrow-array/src/array/map_array.rs b/arrow-array/src/array/map_array.rs
index 1629532b8452..18b3eb3cec32 100644
--- a/arrow-array/src/array/map_array.rs
+++ b/arrow-array/src/array/map_array.rs
@@ -18,7 +18,7 @@
use crate::array::{get_offsets, print_long_array};
use crate::{make_array, Array, ArrayRef, ListArray, StringArray, StructArray};
use arrow_buffer::{ArrowNativeType, Buffer, NullBuffer, OffsetBuffer, ToByteSlice};
-use arrow_data::ArrayData;
+use arrow_data::{ArrayData, ArrayDataBuilder};
use arrow_schema::{ArrowError, DataType, Field};
use std::any::Any;
use std::sync::Arc;
@@ -30,7 +30,8 @@ use std::sync::Arc;
/// [StructArray] with 2 child fields.
#[derive(Clone)]
pub struct MapArray {
- data: ArrayData,
+ data_type: DataType,
+ nulls: Option<NullBuffer>,
/// The [`StructArray`] that is the direct child of this array
entries: ArrayRef,
/// The first child of `entries`, the "keys" of this MapArray
@@ -112,8 +113,14 @@ impl MapArray {
/// Returns a zero-copy slice of this array with the indicated offset and length.
pub fn slice(&self, offset: usize, length: usize) -> Self {
- // TODO: Slice buffers directly (#3880)
- self.data.slice(offset, length).into()
+ Self {
+ data_type: self.data_type.clone(),
+ nulls: self.nulls.as_ref().map(|n| n.slice(offset, length)),
+ entries: self.entries.clone(),
+ keys: self.keys.clone(),
+ values: self.values.clone(),
+ value_offsets: self.value_offsets.slice(offset, length),
+ }
}
}
@@ -126,7 +133,14 @@ impl From<ArrayData> for MapArray {
impl From<MapArray> for ArrayData {
fn from(array: MapArray) -> Self {
- array.data
+ let len = array.len();
+ let builder = ArrayDataBuilder::new(array.data_type)
+ .len(len)
+ .nulls(array.nulls)
+ .buffers(vec![array.value_offsets.into_inner().into_inner()])
+ .child_data(vec![array.entries.to_data()]);
+
+ unsafe { builder.build_unchecked() }
}
}
@@ -177,7 +191,8 @@ impl MapArray {
let value_offsets = unsafe { get_offsets(&data) };
Ok(Self {
- data,
+ data_type: data.data_type().clone(),
+ nulls: data.nulls().cloned(),
entries,
keys,
values,
@@ -229,34 +244,54 @@ impl Array for MapArray {
self
}
- fn data(&self) -> &ArrayData {
- &self.data
- }
-
fn to_data(&self) -> ArrayData {
- self.data.clone()
+ self.clone().into_data()
}
fn into_data(self) -> ArrayData {
self.into()
}
+ fn data_type(&self) -> &DataType {
+ &self.data_type
+ }
+
fn slice(&self, offset: usize, length: usize) -> ArrayRef {
Arc::new(self.slice(offset, length))
}
+ fn len(&self) -> usize {
+ self.value_offsets.len() - 1
+ }
+
+ fn is_empty(&self) -> bool {
+ self.value_offsets.len() <= 1
+ }
+
+ fn offset(&self) -> usize {
+ 0
+ }
+
fn nulls(&self) -> Option<&NullBuffer> {
- self.data.nulls()
+ self.nulls.as_ref()
}
- /// Returns the total number of bytes of memory occupied by the buffers owned by this [MapArray].
fn get_buffer_memory_size(&self) -> usize {
- self.data.get_buffer_memory_size()
+ let mut size = self.entries.get_buffer_memory_size();
+ size += self.value_offsets.inner().inner().capacity();
+ if let Some(n) = self.nulls.as_ref() {
+ size += n.buffer().capacity();
+ }
+ size
}
- /// Returns the total number of bytes of memory occupied physically by this [MapArray].
fn get_array_memory_size(&self) -> usize {
- self.data.get_array_memory_size() + std::mem::size_of_val(self)
+ let mut size = std::mem::size_of::<Self>() + self.entries.get_array_memory_size();
+ size += self.value_offsets.inner().inner().capacity();
+ if let Some(n) = self.nulls.as_ref() {
+ size += n.buffer().capacity();
+ }
+ size
}
}
diff --git a/arrow-array/src/array/mod.rs b/arrow-array/src/array/mod.rs
index fa6e970b497a..e6fd6828bac7 100644
--- a/arrow-array/src/array/mod.rs
+++ b/arrow-array/src/array/mod.rs
@@ -94,10 +94,6 @@ pub trait Array: std::fmt::Debug + Send + Sync {
/// ```
fn as_any(&self) -> &dyn Any;
- /// Returns a reference to the underlying data of this array
- #[deprecated(note = "Use Array::to_data or Array::into_data")]
- fn data(&self) -> &ArrayData;
-
/// Returns the underlying data of this array
fn to_data(&self) -> ArrayData;
@@ -106,13 +102,6 @@ pub trait Array: std::fmt::Debug + Send + Sync {
/// Unlike [`Array::to_data`] this consumes self, allowing it avoid unnecessary clones
fn into_data(self) -> ArrayData;
- /// Returns a reference-counted pointer to the underlying data of this array.
- #[deprecated(note = "Use Array::to_data or Array::into_data")]
- #[allow(deprecated)]
- fn data_ref(&self) -> &ArrayData {
- self.data()
- }
-
/// Returns a reference to the [`DataType`](arrow_schema::DataType) of this array.
///
/// # Example:
@@ -125,10 +114,7 @@ pub trait Array: std::fmt::Debug + Send + Sync {
///
/// assert_eq!(*array.data_type(), DataType::Int32);
/// ```
- #[allow(deprecated)] // (#3880)
- fn data_type(&self) -> &DataType {
- self.data_ref().data_type()
- }
+ fn data_type(&self) -> &DataType;
/// Returns a zero-copy slice of this array with the indicated offset and length.
///
@@ -156,10 +142,7 @@ pub trait Array: std::fmt::Debug + Send + Sync {
///
/// assert_eq!(array.len(), 5);
/// ```
- #[allow(deprecated)] // (#3880)
- fn len(&self) -> usize {
- self.data_ref().len()
- }
+ fn len(&self) -> usize;
/// Returns whether this array is empty.
///
@@ -172,10 +155,7 @@ pub trait Array: std::fmt::Debug + Send + Sync {
///
/// assert_eq!(array.is_empty(), false);
/// ```
- #[allow(deprecated)] // (#3880)
- fn is_empty(&self) -> bool {
- self.data_ref().is_empty()
- }
+ fn is_empty(&self) -> bool;
/// Returns the offset into the underlying data used by this array(-slice).
/// Note that the underlying data can be shared by many arrays.
@@ -184,19 +164,15 @@ pub trait Array: std::fmt::Debug + Send + Sync {
/// # Example:
///
/// ```
- /// use arrow_array::{Array, Int32Array};
+ /// use arrow_array::{Array, BooleanArray};
///
- /// let array = Int32Array::from(vec![1, 2, 3, 4, 5]);
- /// // Make slice over the values [2, 3, 4]
+ /// let array = BooleanArray::from(vec![false, false, true, true]);
/// let array_slice = array.slice(1, 3);
///
/// assert_eq!(array.offset(), 0);
/// assert_eq!(array_slice.offset(), 1);
/// ```
- #[allow(deprecated)] // (#3880)
- fn offset(&self) -> usize {
- self.data_ref().offset()
- }
+ fn offset(&self) -> usize;
/// Returns the null buffers of this array if any
fn nulls(&self) -> Option<&NullBuffer>;
@@ -253,21 +229,12 @@ pub trait Array: std::fmt::Debug + Send + Sync {
/// Returns the total number of bytes of memory pointed to by this array.
/// The buffers store bytes in the Arrow memory format, and include the data as well as the validity map.
- #[allow(deprecated)] // (#3880)
- fn get_buffer_memory_size(&self) -> usize {
- self.data_ref().get_buffer_memory_size()
- }
+ fn get_buffer_memory_size(&self) -> usize;
/// Returns the total number of bytes of memory occupied physically by this array.
/// This value will always be greater than returned by `get_buffer_memory_size()` and
/// includes the overhead of the data structures that contain the pointers to the various buffers.
- #[allow(deprecated)] // (#3880)
- fn get_array_memory_size(&self) -> usize {
- // both data.get_array_memory_size and size_of_val(self) include ArrayData fields,
- // to only count additional fields of this array subtract size_of(ArrayData)
- self.data_ref().get_array_memory_size() + std::mem::size_of_val(self)
- - std::mem::size_of::<ArrayData>()
- }
+ fn get_array_memory_size(&self) -> usize;
}
/// A reference-counted reference to a generic `Array`.
@@ -279,11 +246,6 @@ impl Array for ArrayRef {
self.as_ref().as_any()
}
- #[allow(deprecated)]
- fn data(&self) -> &ArrayData {
- self.as_ref().data()
- }
-
fn to_data(&self) -> ArrayData {
self.as_ref().to_data()
}
@@ -292,11 +254,6 @@ impl Array for ArrayRef {
self.to_data()
}
- #[allow(deprecated)]
- fn data_ref(&self) -> &ArrayData {
- self.as_ref().data_ref()
- }
-
fn data_type(&self) -> &DataType {
self.as_ref().data_type()
}
@@ -347,11 +304,6 @@ impl<'a, T: Array> Array for &'a T {
T::as_any(self)
}
- #[allow(deprecated)]
- fn data(&self) -> &ArrayData {
- T::data(self)
- }
-
fn to_data(&self) -> ArrayData {
T::to_data(self)
}
@@ -360,11 +312,6 @@ impl<'a, T: Array> Array for &'a T {
self.to_data()
}
- #[allow(deprecated)]
- fn data_ref(&self) -> &ArrayData {
- T::data_ref(self)
- }
-
fn data_type(&self) -> &DataType {
T::data_type(self)
}
@@ -435,93 +382,80 @@ pub trait ArrayAccessor: Array {
}
impl PartialEq for dyn Array + '_ {
- #[allow(deprecated)]
fn eq(&self, other: &Self) -> bool {
- self.data().eq(other.data())
+ self.to_data().eq(&other.to_data())
}
}
impl<T: Array> PartialEq<T> for dyn Array + '_ {
- #[allow(deprecated)]
fn eq(&self, other: &T) -> bool {
- self.data().eq(other.data())
+ self.to_data().eq(&other.to_data())
}
}
impl PartialEq for NullArray {
- #[allow(deprecated)]
fn eq(&self, other: &NullArray) -> bool {
- self.data().eq(other.data())
+ self.to_data().eq(&other.to_data())
}
}
impl<T: ArrowPrimitiveType> PartialEq for PrimitiveArray<T> {
- #[allow(deprecated)]
fn eq(&self, other: &PrimitiveArray<T>) -> bool {
- self.data().eq(other.data())
+ self.to_data().eq(&other.to_data())
}
}
impl<K: ArrowDictionaryKeyType> PartialEq for DictionaryArray<K> {
- #[allow(deprecated)]
fn eq(&self, other: &Self) -> bool {
- self.data().eq(other.data())
+ self.to_data().eq(&other.to_data())
}
}
impl PartialEq for BooleanArray {
- #[allow(deprecated)]
fn eq(&self, other: &BooleanArray) -> bool {
- self.data().eq(other.data())
+ self.to_data().eq(&other.to_data())
}
}
impl<OffsetSize: OffsetSizeTrait> PartialEq for GenericStringArray<OffsetSize> {
- #[allow(deprecated)]
fn eq(&self, other: &Self) -> bool {
- self.data().eq(other.data())
+ self.to_data().eq(&other.to_data())
}
}
impl<OffsetSize: OffsetSizeTrait> PartialEq for GenericBinaryArray<OffsetSize> {
- #[allow(deprecated)]
fn eq(&self, other: &Self) -> bool {
- self.data().eq(other.data())
+ self.to_data().eq(&other.to_data())
}
}
impl PartialEq for FixedSizeBinaryArray {
- #[allow(deprecated)]
fn eq(&self, other: &Self) -> bool {
- self.data().eq(other.data())
+ self.to_data().eq(&other.to_data())
}
}
impl<OffsetSize: OffsetSizeTrait> PartialEq for GenericListArray<OffsetSize> {
- #[allow(deprecated)]
fn eq(&self, other: &Self) -> bool {
- self.data().eq(other.data())
+ self.to_data().eq(&other.to_data())
}
}
impl PartialEq for MapArray {
- #[allow(deprecated)]
fn eq(&self, other: &Self) -> bool {
- self.data().eq(other.data())
+ self.to_data().eq(&other.to_data())
}
}
impl PartialEq for FixedSizeListArray {
- #[allow(deprecated)]
fn eq(&self, other: &Self) -> bool {
- self.data().eq(other.data())
+ self.to_data().eq(&other.to_data())
}
}
impl PartialEq for StructArray {
- #[allow(deprecated)]
fn eq(&self, other: &Self) -> bool {
- self.data().eq(other.data())
+ self.to_data().eq(&other.to_data())
}
}
@@ -752,7 +686,7 @@ mod tests {
use super::*;
use crate::cast::{as_union_array, downcast_array};
use crate::downcast_run_array;
- use arrow_buffer::{Buffer, MutableBuffer};
+ use arrow_buffer::MutableBuffer;
use arrow_schema::{Field, Fields, UnionFields, UnionMode};
#[test]
@@ -962,13 +896,9 @@ mod tests {
assert_eq!(0, null_arr.get_buffer_memory_size());
assert_eq!(
- std::mem::size_of::<NullArray>(),
+ std::mem::size_of::<usize>(),
null_arr.get_array_memory_size()
);
- assert_eq!(
- std::mem::size_of::<NullArray>(),
- std::mem::size_of::<ArrayData>(),
- );
}
#[test]
@@ -1001,8 +931,7 @@ mod tests {
// which includes the optional validity buffer
// plus one buffer on the heap
assert_eq!(
- std::mem::size_of::<PrimitiveArray<Int64Type>>()
- + std::mem::size_of::<Buffer>(),
+ std::mem::size_of::<PrimitiveArray<Int64Type>>(),
empty_with_bitmap.get_array_memory_size()
);
diff --git a/arrow-array/src/array/null_array.rs b/arrow-array/src/array/null_array.rs
index b5d9247a6d7f..c7f61d91da70 100644
--- a/arrow-array/src/array/null_array.rs
+++ b/arrow-array/src/array/null_array.rs
@@ -19,7 +19,7 @@
use crate::{Array, ArrayRef};
use arrow_buffer::buffer::NullBuffer;
-use arrow_data::ArrayData;
+use arrow_data::{ArrayData, ArrayDataBuilder};
use arrow_schema::DataType;
use std::any::Any;
use std::sync::Arc;
@@ -40,7 +40,7 @@ use std::sync::Arc;
/// ```
#[derive(Clone)]
pub struct NullArray {
- data: ArrayData,
+ len: usize,
}
impl NullArray {
@@ -50,15 +50,17 @@ impl NullArray {
/// other [`DataType`].
///
pub fn new(length: usize) -> Self {
- let array_data = ArrayData::builder(DataType::Null).len(length);
- let array_data = unsafe { array_data.build_unchecked() };
- NullArray::from(array_data)
+ Self { len: length }
}
/// Returns a zero-copy slice of this array with the indicated offset and length.
- pub fn slice(&self, offset: usize, length: usize) -> Self {
- // TODO: Slice buffers directly (#3880)
- self.data.slice(offset, length).into()
+ pub fn slice(&self, offset: usize, len: usize) -> Self {
+ assert!(
+ offset.saturating_add(len) <= self.len,
+ "the length + offset of the sliced BooleanBuffer cannot exceed the existing length"
+ );
+
+ Self { len }
}
}
@@ -67,22 +69,34 @@ impl Array for NullArray {
self
}
- fn data(&self) -> &ArrayData {
- &self.data
- }
-
fn to_data(&self) -> ArrayData {
- self.data.clone()
+ self.clone().into()
}
fn into_data(self) -> ArrayData {
self.into()
}
+ fn data_type(&self) -> &DataType {
+ &DataType::Null
+ }
+
fn slice(&self, offset: usize, length: usize) -> ArrayRef {
Arc::new(self.slice(offset, length))
}
+ fn len(&self) -> usize {
+ self.len
+ }
+
+ fn is_empty(&self) -> bool {
+ self.len == 0
+ }
+
+ fn offset(&self) -> usize {
+ 0
+ }
+
fn nulls(&self) -> Option<&NullBuffer> {
None
}
@@ -104,6 +118,14 @@ impl Array for NullArray {
fn null_count(&self) -> usize {
self.len()
}
+
+ fn get_buffer_memory_size(&self) -> usize {
+ 0
+ }
+
+ fn get_array_memory_size(&self) -> usize {
+ std::mem::size_of::<Self>()
+ }
}
impl From<ArrayData> for NullArray {
@@ -122,13 +144,14 @@ impl From<ArrayData> for NullArray {
data.nulls().is_none(),
"NullArray data should not contain a null buffer, as no buffers are required"
);
- Self { data }
+ Self { len: data.len() }
}
}
impl From<NullArray> for ArrayData {
fn from(array: NullArray) -> Self {
- array.data
+ let builder = ArrayDataBuilder::new(DataType::Null).len(array.len);
+ unsafe { builder.build_unchecked() }
}
}
@@ -158,7 +181,6 @@ mod tests {
let array2 = array1.slice(8, 16);
assert_eq!(array2.len(), 16);
assert_eq!(array2.null_count(), 16);
- assert_eq!(array2.offset(), 8);
}
#[test]
diff --git a/arrow-array/src/array/primitive_array.rs b/arrow-array/src/array/primitive_array.rs
index 75bf85b3f2a0..3199104382a6 100644
--- a/arrow-array/src/array/primitive_array.rs
+++ b/arrow-array/src/array/primitive_array.rs
@@ -29,7 +29,7 @@ use arrow_buffer::{
i256, ArrowNativeType, BooleanBuffer, Buffer, NullBuffer, ScalarBuffer,
};
use arrow_data::bit_iterator::try_for_each_valid_idx;
-use arrow_data::ArrayData;
+use arrow_data::{ArrayData, ArrayDataBuilder};
use arrow_schema::{ArrowError, DataType};
use chrono::{DateTime, Duration, NaiveDate, NaiveDateTime, NaiveTime};
use half::f16;
@@ -248,17 +248,18 @@ pub use crate::types::ArrowPrimitiveType;
/// }
/// ```
pub struct PrimitiveArray<T: ArrowPrimitiveType> {
- /// Underlying ArrayData
- data: ArrayData,
+ data_type: DataType,
/// Values data
values: ScalarBuffer<T::Native>,
+ nulls: Option<NullBuffer>,
}
impl<T: ArrowPrimitiveType> Clone for PrimitiveArray<T> {
fn clone(&self) -> Self {
Self {
- data: self.data.clone(),
+ data_type: self.data_type.clone(),
values: self.values.clone(),
+ nulls: self.nulls.clone(),
}
}
}
@@ -281,16 +282,11 @@ impl<T: ArrowPrimitiveType> PrimitiveArray<T> {
assert_eq!(values.len(), n.len());
}
- // TODO: Don't store ArrayData inside arrays (#3880)
- let data = unsafe {
- ArrayData::builder(data_type)
- .len(values.len())
- .nulls(nulls)
- .buffers(vec![values.inner().clone()])
- .build_unchecked()
- };
-
- Self { data, values }
+ Self {
+ data_type,
+ values,
+ nulls,
+ }
}
/// Asserts that `data_type` is compatible with `Self`
@@ -306,12 +302,12 @@ impl<T: ArrowPrimitiveType> PrimitiveArray<T> {
/// Returns the length of this array.
#[inline]
pub fn len(&self) -> usize {
- self.data.len()
+ self.values.len()
}
/// Returns whether this array is empty.
pub fn is_empty(&self) -> bool {
- self.data.is_empty()
+ self.values.is_empty()
}
/// Returns the values of this array
@@ -367,18 +363,12 @@ impl<T: ArrowPrimitiveType> PrimitiveArray<T> {
/// Creates a PrimitiveArray based on an iterator of values without nulls
pub fn from_iter_values<I: IntoIterator<Item = T::Native>>(iter: I) -> Self {
let val_buf: Buffer = iter.into_iter().collect();
- let data = unsafe {
- ArrayData::new_unchecked(
- T::DATA_TYPE,
- val_buf.len() / std::mem::size_of::<<T as ArrowPrimitiveType>::Native>(),
- None,
- None,
- 0,
- vec![val_buf],
- vec![],
- )
- };
- PrimitiveArray::from(data)
+ let len = val_buf.len() / std::mem::size_of::<T::Native>();
+ Self {
+ data_type: T::DATA_TYPE,
+ values: ScalarBuffer::new(val_buf, 0, len),
+ nulls: None,
+ }
}
/// Creates a PrimitiveArray based on a constant value with `count` elements
@@ -410,8 +400,11 @@ impl<T: ArrowPrimitiveType> PrimitiveArray<T> {
/// Returns a zero-copy slice of this array with the indicated offset and length.
pub fn slice(&self, offset: usize, length: usize) -> Self {
- // TODO: Slice buffers directly (#3880)
- self.data.slice(offset, length).into()
+ Self {
+ data_type: self.data_type.clone(),
+ values: self.values.slice(offset, length),
+ nulls: self.nulls.as_ref().map(|n| n.slice(offset, length)),
+ }
}
/// Reinterprets this array's contents as a different data type without copying
@@ -436,7 +429,7 @@ impl<T: ArrowPrimitiveType> PrimitiveArray<T> {
where
K: ArrowPrimitiveType<Native = T::Native>,
{
- let d = self.data.clone().into_builder().data_type(K::DATA_TYPE);
+ let d = self.to_data().into_builder().data_type(K::DATA_TYPE);
// SAFETY:
// Native type is the same
@@ -629,14 +622,14 @@ impl<T: ArrowPrimitiveType> PrimitiveArray<T> {
/// data buffer is not shared by others.
pub fn into_builder(self) -> Result<PrimitiveBuilder<T>, Self> {
let len = self.len();
- let null_bit_buffer = self.data.nulls().map(|b| b.inner().sliced());
+ let data = self.into_data();
+ let null_bit_buffer = data.nulls().map(|b| b.inner().sliced());
let element_len = std::mem::size_of::<T::Native>();
- let buffer = self.data.buffers()[0]
- .slice_with_length(self.data.offset() * element_len, len * element_len);
+ let buffer = data.buffers()[0]
+ .slice_with_length(data.offset() * element_len, len * element_len);
- drop(self.data);
- drop(self.values);
+ drop(data);
let try_mutable_null_buffer = match null_bit_buffer {
None => Ok(None),
@@ -686,7 +679,12 @@ impl<T: ArrowPrimitiveType> PrimitiveArray<T> {
impl<T: ArrowPrimitiveType> From<PrimitiveArray<T>> for ArrayData {
fn from(array: PrimitiveArray<T>) -> Self {
- array.data
+ let builder = ArrayDataBuilder::new(array.data_type)
+ .len(array.values.len())
+ .nulls(array.nulls)
+ .buffers(vec![array.values.into_inner()]);
+
+ unsafe { builder.build_unchecked() }
}
}
@@ -695,24 +693,48 @@ impl<T: ArrowPrimitiveType> Array for PrimitiveArray<T> {
self
}
- fn data(&self) -> &ArrayData {
- &self.data
- }
-
fn to_data(&self) -> ArrayData {
- self.data.clone()
+ self.clone().into()
}
fn into_data(self) -> ArrayData {
self.into()
}
+ fn data_type(&self) -> &DataType {
+ &self.data_type
+ }
+
fn slice(&self, offset: usize, length: usize) -> ArrayRef {
Arc::new(self.slice(offset, length))
}
+ fn len(&self) -> usize {
+ self.values.len()
+ }
+
+ fn is_empty(&self) -> bool {
+ self.values.is_empty()
+ }
+
+ fn offset(&self) -> usize {
+ 0
+ }
+
fn nulls(&self) -> Option<&NullBuffer> {
- self.data.nulls()
+ self.nulls.as_ref()
+ }
+
+ fn get_buffer_memory_size(&self) -> usize {
+ let mut size = self.values.inner().capacity();
+ if let Some(n) = self.nulls.as_ref() {
+ size += n.buffer().capacity();
+ }
+ size
+ }
+
+ fn get_array_memory_size(&self) -> usize {
+ std::mem::size_of::<Self>() + self.get_buffer_memory_size()
}
}
@@ -1061,8 +1083,7 @@ impl<T: ArrowTimestampType> PrimitiveArray<T> {
/// Construct a timestamp array with an optional timezone
pub fn with_timezone_opt<S: Into<Arc<str>>>(&self, timezone: Option<S>) -> Self {
let array_data = unsafe {
- self.data
- .clone()
+ self.to_data()
.into_builder()
.data_type(DataType::Timestamp(T::UNIT, timezone.map(Into::into)))
.build_unchecked()
@@ -1083,7 +1104,11 @@ impl<T: ArrowPrimitiveType> From<ArrayData> for PrimitiveArray<T> {
let values =
ScalarBuffer::new(data.buffers()[0].clone(), data.offset(), data.len());
- Self { data, values }
+ Self {
+ data_type: data.data_type().clone(),
+ values,
+ nulls: data.nulls().cloned(),
+ }
}
}
@@ -1108,12 +1133,10 @@ impl<T: DecimalType + ArrowPrimitiveType> PrimitiveArray<T> {
self.validate_precision_scale(precision, scale)?;
// safety: self.data is valid DataType::Decimal as checked above
- let new_data_type = T::TYPE_CONSTRUCTOR(precision, scale);
- let data = self.data.into_builder().data_type(new_data_type);
-
- // SAFETY
- // Validated data above
- Ok(unsafe { data.build_unchecked().into() })
+ Ok(Self {
+ data_type: T::TYPE_CONSTRUCTOR(precision, scale),
+ ..self
+ })
}
// validate that the new precision and scale are valid or not
@@ -1244,7 +1267,7 @@ mod tests {
fn test_primitive_array_from_vec() {
let buf = Buffer::from_slice_ref([0, 1, 2, 3, 4]);
let arr = Int32Array::from(vec![0, 1, 2, 3, 4]);
- assert_eq!(buf, *arr.data.buffers()[0]);
+ assert_eq!(&buf, arr.values.inner());
assert_eq!(5, arr.len());
assert_eq!(0, arr.offset());
assert_eq!(0, arr.null_count());
@@ -1484,7 +1507,6 @@ mod tests {
let arr2 = arr.slice(2, 5);
assert_eq!(5, arr2.len());
- assert_eq!(2, arr2.offset());
assert_eq!(1, arr2.null_count());
for i in 0..arr2.len() {
@@ -1497,7 +1519,6 @@ mod tests {
let arr3 = arr2.slice(2, 3);
assert_eq!(3, arr3.len());
- assert_eq!(4, arr3.offset());
assert_eq!(0, arr3.null_count());
let int_arr3 = arr3.as_any().downcast_ref::<Int32Array>().unwrap();
@@ -1742,7 +1763,7 @@ mod tests {
fn test_primitive_array_builder() {
// Test building a primitive array with ArrayData builder and offset
let buf = Buffer::from_slice_ref([0i32, 1, 2, 3, 4, 5, 6]);
- let buf2 = buf.clone();
+ let buf2 = buf.slice_with_length(8, 20);
let data = ArrayData::builder(DataType::Int32)
.len(5)
.offset(2)
@@ -1750,7 +1771,7 @@ mod tests {
.build()
.unwrap();
let arr = Int32Array::from(data);
- assert_eq!(buf2, *arr.data.buffers()[0]);
+ assert_eq!(&buf2, arr.values.inner());
assert_eq!(5, arr.len());
assert_eq!(0, arr.null_count());
for i in 0..3 {
diff --git a/arrow-array/src/array/run_array.rs b/arrow-array/src/array/run_array.rs
index 0754913e9d3e..e7e71d3840bb 100644
--- a/arrow-array/src/array/run_array.rs
+++ b/arrow-array/src/array/run_array.rs
@@ -62,7 +62,7 @@ use crate::{
/// ```
pub struct RunArray<R: RunEndIndexType> {
- data: ArrayData,
+ data_type: DataType,
run_ends: RunEndBuffer<R::Native>,
values: ArrayRef,
}
@@ -70,7 +70,7 @@ pub struct RunArray<R: RunEndIndexType> {
impl<R: RunEndIndexType> Clone for RunArray<R> {
fn clone(&self) -> Self {
Self {
- data: self.data.clone(),
+ data_type: self.data_type.clone(),
run_ends: self.run_ends.clone(),
values: self.values.clone(),
}
@@ -256,8 +256,11 @@ impl<R: RunEndIndexType> RunArray<R> {
/// Returns a zero-copy slice of this array with the indicated offset and length.
pub fn slice(&self, offset: usize, length: usize) -> Self {
- // TODO: Slice buffers directly (#3880)
- self.data.slice(offset, length).into()
+ Self {
+ data_type: self.data_type.clone(),
+ run_ends: self.run_ends.slice(offset, length),
+ values: self.values.clone(),
+ }
}
}
@@ -282,7 +285,7 @@ impl<R: RunEndIndexType> From<ArrayData> for RunArray<R> {
let values = make_array(data.child_data()[1].clone());
Self {
- data,
+ data_type: data.data_type().clone(),
run_ends,
values,
}
@@ -291,7 +294,21 @@ impl<R: RunEndIndexType> From<ArrayData> for RunArray<R> {
impl<R: RunEndIndexType> From<RunArray<R>> for ArrayData {
fn from(array: RunArray<R>) -> Self {
- array.data
+ let len = array.run_ends.len();
+ let offset = array.run_ends.offset();
+
+ let run_ends = ArrayDataBuilder::new(R::DATA_TYPE)
+ .len(array.run_ends.values().len())
+ .buffers(vec![array.run_ends.into_inner().into_inner()]);
+
+ let run_ends = unsafe { run_ends.build_unchecked() };
+
+ let builder = ArrayDataBuilder::new(array.data_type)
+ .len(len)
+ .offset(offset)
+ .child_data(vec![run_ends, array.values.to_data()]);
+
+ unsafe { builder.build_unchecked() }
}
}
@@ -300,25 +317,47 @@ impl<T: RunEndIndexType> Array for RunArray<T> {
self
}
- fn data(&self) -> &ArrayData {
- &self.data
- }
-
fn to_data(&self) -> ArrayData {
- self.data.clone()
+ self.clone().into()
}
fn into_data(self) -> ArrayData {
self.into()
}
+ fn data_type(&self) -> &DataType {
+ &self.data_type
+ }
+
fn slice(&self, offset: usize, length: usize) -> ArrayRef {
Arc::new(self.slice(offset, length))
}
+ fn len(&self) -> usize {
+ self.run_ends.len()
+ }
+
+ fn is_empty(&self) -> bool {
+ self.run_ends.is_empty()
+ }
+
+ fn offset(&self) -> usize {
+ self.run_ends.offset()
+ }
+
fn nulls(&self) -> Option<&NullBuffer> {
None
}
+
+ fn get_buffer_memory_size(&self) -> usize {
+ self.run_ends.inner().inner().capacity() + self.values.get_buffer_memory_size()
+ }
+
+ fn get_array_memory_size(&self) -> usize {
+ std::mem::size_of::<Self>()
+ + self.run_ends.inner().inner().capacity()
+ + self.values.get_array_memory_size()
+ }
}
impl<R: RunEndIndexType> std::fmt::Debug for RunArray<R> {
@@ -497,10 +536,6 @@ impl<'a, R: RunEndIndexType, V: Sync> Array for TypedRunArray<'a, R, V> {
self.run_array
}
- fn data(&self) -> &ArrayData {
- &self.run_array.data
- }
-
fn to_data(&self) -> ArrayData {
self.run_array.to_data()
}
@@ -509,13 +544,37 @@ impl<'a, R: RunEndIndexType, V: Sync> Array for TypedRunArray<'a, R, V> {
self.run_array.into_data()
}
+ fn data_type(&self) -> &DataType {
+ self.run_array.data_type()
+ }
+
fn slice(&self, offset: usize, length: usize) -> ArrayRef {
Arc::new(self.run_array.slice(offset, length))
}
+ fn len(&self) -> usize {
+ self.run_array.len()
+ }
+
+ fn is_empty(&self) -> bool {
+ self.run_array.is_empty()
+ }
+
+ fn offset(&self) -> usize {
+ self.run_array.offset()
+ }
+
fn nulls(&self) -> Option<&NullBuffer> {
self.run_array.nulls()
}
+
+ fn get_buffer_memory_size(&self) -> usize {
+ self.run_array.get_buffer_memory_size()
+ }
+
+ fn get_array_memory_size(&self) -> usize {
+ self.run_array.get_array_memory_size()
+ }
}
// Array accessor converts the index of logical array to the index of the physical array
diff --git a/arrow-array/src/array/struct_array.rs b/arrow-array/src/array/struct_array.rs
index 1dccfc7d4ef3..fa43062b77bf 100644
--- a/arrow-array/src/array/struct_array.rs
+++ b/arrow-array/src/array/struct_array.rs
@@ -17,7 +17,7 @@
use crate::{make_array, Array, ArrayRef, RecordBatch};
use arrow_buffer::{buffer_bin_or, Buffer, NullBuffer};
-use arrow_data::ArrayData;
+use arrow_data::{ArrayData, ArrayDataBuilder};
use arrow_schema::{ArrowError, DataType, Field, Fields, SchemaBuilder};
use std::sync::Arc;
use std::{any::Any, ops::Index};
@@ -74,24 +74,26 @@ use std::{any::Any, ops::Index};
/// ```
#[derive(Clone)]
pub struct StructArray {
- data: ArrayData,
- pub(crate) boxed_fields: Vec<ArrayRef>,
+ len: usize,
+ data_type: DataType,
+ nulls: Option<NullBuffer>,
+ pub(crate) fields: Vec<ArrayRef>,
}
impl StructArray {
/// Returns the field at `pos`.
pub fn column(&self, pos: usize) -> &ArrayRef {
- &self.boxed_fields[pos]
+ &self.fields[pos]
}
/// Return the number of fields in this struct array
pub fn num_columns(&self) -> usize {
- self.boxed_fields.len()
+ self.fields.len()
}
/// Returns the fields of the struct array
pub fn columns(&self) -> &[ArrayRef] {
- &self.boxed_fields
+ &self.fields
}
/// Returns child array refs of the struct array
@@ -102,7 +104,7 @@ impl StructArray {
/// Return field names in this struct array
pub fn column_names(&self) -> Vec<&str> {
- match self.data.data_type() {
+ match self.data_type() {
DataType::Struct(fields) => fields
.iter()
.map(|f| f.name().as_str())
@@ -132,27 +134,48 @@ impl StructArray {
}
/// Returns a zero-copy slice of this array with the indicated offset and length.
- pub fn slice(&self, offset: usize, length: usize) -> Self {
- // TODO: Slice buffers directly (#3880)
- self.data.slice(offset, length).into()
+ pub fn slice(&self, offset: usize, len: usize) -> Self {
+ assert!(
+ offset.saturating_add(len) <= self.len,
+ "the length + offset of the sliced StructArray cannot exceed the existing length"
+ );
+
+ let fields = self.fields.iter().map(|a| a.slice(offset, len)).collect();
+
+ Self {
+ len,
+ data_type: self.data_type.clone(),
+ nulls: self.nulls.as_ref().map(|n| n.slice(offset, len)),
+ fields,
+ }
}
}
impl From<ArrayData> for StructArray {
fn from(data: ArrayData) -> Self {
- let boxed_fields = data
+ let fields = data
.child_data()
.iter()
.map(|cd| make_array(cd.clone()))
.collect();
- Self { data, boxed_fields }
+ Self {
+ len: data.len(),
+ data_type: data.data_type().clone(),
+ nulls: data.nulls().cloned(),
+ fields,
+ }
}
}
impl From<StructArray> for ArrayData {
fn from(array: StructArray) -> Self {
- array.data
+ let builder = ArrayDataBuilder::new(array.data_type)
+ .len(array.len)
+ .nulls(array.nulls)
+ .child_data(array.fields.iter().map(|x| x.to_data()).collect());
+
+ unsafe { builder.build_unchecked() }
}
}
@@ -228,24 +251,53 @@ impl Array for StructArray {
self
}
- fn data(&self) -> &ArrayData {
- &self.data
- }
-
fn to_data(&self) -> ArrayData {
- self.data.clone()
+ self.clone().into()
}
fn into_data(self) -> ArrayData {
self.into()
}
+ fn data_type(&self) -> &DataType {
+ &self.data_type
+ }
+
fn slice(&self, offset: usize, length: usize) -> ArrayRef {
Arc::new(self.slice(offset, length))
}
+ fn len(&self) -> usize {
+ self.len
+ }
+
+ fn is_empty(&self) -> bool {
+ self.len == 0
+ }
+
+ fn offset(&self) -> usize {
+ 0
+ }
+
fn nulls(&self) -> Option<&NullBuffer> {
- self.data.nulls()
+ self.nulls.as_ref()
+ }
+
+ fn get_buffer_memory_size(&self) -> usize {
+ let mut size = self.fields.iter().map(|a| a.get_buffer_memory_size()).sum();
+ if let Some(n) = self.nulls.as_ref() {
+ size += n.buffer().capacity();
+ }
+ size
+ }
+
+ fn get_array_memory_size(&self) -> usize {
+ let mut size = self.fields.iter().map(|a| a.get_array_memory_size()).sum();
+ size += std::mem::size_of::<Self>();
+ if let Some(n) = self.nulls.as_ref() {
+ size += n.buffer().capacity();
+ }
+ size
}
}
@@ -343,15 +395,11 @@ impl From<(Vec<(Field, ArrayRef)>, Buffer)> for StructArray {
impl From<RecordBatch> for StructArray {
fn from(value: RecordBatch) -> Self {
- // TODO: Don't store ArrayData inside arrays (#3880)
- let builder = ArrayData::builder(DataType::Struct(value.schema().fields.clone()))
- .child_data(value.columns().iter().map(|x| x.to_data()).collect())
- .len(value.num_rows());
-
- // Safety: RecordBatch must be valid
Self {
- data: unsafe { builder.build_unchecked() },
- boxed_fields: value.columns().to_vec(),
+ len: value.num_rows(),
+ data_type: DataType::Struct(value.schema().fields().clone()),
+ nulls: None,
+ fields: value.columns().to_vec(),
}
}
}
@@ -607,7 +655,6 @@ mod tests {
let sliced_array = struct_array.slice(2, 3);
let sliced_array = sliced_array.as_any().downcast_ref::<StructArray>().unwrap();
assert_eq!(3, sliced_array.len());
- assert_eq!(2, sliced_array.offset());
assert_eq!(1, sliced_array.null_count());
assert!(sliced_array.is_valid(0));
assert!(sliced_array.is_null(1));
@@ -616,7 +663,6 @@ mod tests {
let sliced_c0 = sliced_array.column(0);
let sliced_c0 = sliced_c0.as_any().downcast_ref::<BooleanArray>().unwrap();
assert_eq!(3, sliced_c0.len());
- assert_eq!(2, sliced_c0.offset());
assert!(sliced_c0.is_null(0));
assert!(sliced_c0.is_null(1));
assert!(sliced_c0.is_valid(2));
@@ -625,7 +671,6 @@ mod tests {
let sliced_c1 = sliced_array.column(1);
let sliced_c1 = sliced_c1.as_any().downcast_ref::<Int32Array>().unwrap();
assert_eq!(3, sliced_c1.len());
- assert_eq!(2, sliced_c1.offset());
assert!(sliced_c1.is_valid(0));
assert_eq!(42, sliced_c1.value(0));
assert!(sliced_c1.is_null(1));
diff --git a/arrow-array/src/array/union_array.rs b/arrow-array/src/array/union_array.rs
index 7b818f3130b7..172ae082197c 100644
--- a/arrow-array/src/array/union_array.rs
+++ b/arrow-array/src/array/union_array.rs
@@ -18,7 +18,7 @@
use crate::{make_array, Array, ArrayRef};
use arrow_buffer::buffer::NullBuffer;
use arrow_buffer::{Buffer, ScalarBuffer};
-use arrow_data::ArrayData;
+use arrow_data::{ArrayData, ArrayDataBuilder};
use arrow_schema::{ArrowError, DataType, Field, UnionFields, UnionMode};
/// Contains the `UnionArray` type.
///
@@ -108,10 +108,10 @@ use std::sync::Arc;
/// ```
#[derive(Clone)]
pub struct UnionArray {
- data: ArrayData,
+ data_type: DataType,
type_ids: ScalarBuffer<i8>,
offsets: Option<ScalarBuffer<i32>>,
- boxed_fields: Vec<Option<ArrayRef>>,
+ fields: Vec<Option<ArrayRef>>,
}
impl UnionArray {
@@ -231,7 +231,7 @@ impl UnionArray {
/// Panics if the `type_id` provided is less than zero or greater than the number of types
/// in the `Union`.
pub fn child(&self, type_id: i8) -> &ArrayRef {
- let boxed = &self.boxed_fields[type_id as usize];
+ let boxed = &self.fields[type_id as usize];
boxed.as_ref().expect("invalid type id")
}
@@ -279,7 +279,7 @@ impl UnionArray {
/// Returns the names of the types in the union.
pub fn type_names(&self) -> Vec<&str> {
- match self.data.data_type() {
+ match self.data_type() {
DataType::Union(fields, _) => fields
.iter()
.map(|(_, f)| f.name().as_str())
@@ -290,7 +290,7 @@ impl UnionArray {
/// Returns whether the `UnionArray` is dense (or sparse if `false`).
fn is_dense(&self) -> bool {
- match self.data.data_type() {
+ match self.data_type() {
DataType::Union(_, mode) => mode == &UnionMode::Dense,
_ => unreachable!("Union array's data type is not a union!"),
}
@@ -298,8 +298,26 @@ impl UnionArray {
/// Returns a zero-copy slice of this array with the indicated offset and length.
pub fn slice(&self, offset: usize, length: usize) -> Self {
- // TODO: Slice buffers directly (#3880)
- self.data.slice(offset, length).into()
+ let (offsets, fields) = match self.offsets.as_ref() {
+ // If dense union, slice offsets
+ Some(offsets) => (Some(offsets.slice(offset, length)), self.fields.clone()),
+ // Otherwise need to slice sparse children
+ None => {
+ let fields = self
+ .fields
+ .iter()
+ .map(|x| x.as_ref().map(|x| x.slice(offset, length)))
+ .collect();
+ (None, fields)
+ }
+ };
+
+ Self {
+ data_type: self.data_type.clone(),
+ type_ids: self.type_ids.slice(offset, length),
+ offsets,
+ fields,
+ }
}
}
@@ -330,17 +348,36 @@ impl From<ArrayData> for UnionArray {
boxed_fields[field_id as usize] = Some(make_array(cd.clone()));
}
Self {
- data,
+ data_type: data.data_type().clone(),
type_ids,
offsets,
- boxed_fields,
+ fields: boxed_fields,
}
}
}
impl From<UnionArray> for ArrayData {
fn from(array: UnionArray) -> Self {
- array.data
+ let len = array.len();
+ let f = match &array.data_type {
+ DataType::Union(f, _) => f,
+ _ => unreachable!(),
+ };
+ let buffers = match array.offsets {
+ Some(o) => vec![array.type_ids.into_inner(), o.into_inner()],
+ None => vec![array.type_ids.into_inner()],
+ };
+
+ let child = f
+ .iter()
+ .map(|(i, _)| array.fields[i as usize].as_ref().unwrap().to_data())
+ .collect();
+
+ let builder = ArrayDataBuilder::new(array.data_type)
+ .len(len)
+ .buffers(buffers)
+ .child_data(child);
+ unsafe { builder.build_unchecked() }
}
}
@@ -349,22 +386,34 @@ impl Array for UnionArray {
self
}
- fn data(&self) -> &ArrayData {
- &self.data
- }
-
fn to_data(&self) -> ArrayData {
- self.data.clone()
+ self.clone().into()
}
fn into_data(self) -> ArrayData {
self.into()
}
+ fn data_type(&self) -> &DataType {
+ &self.data_type
+ }
+
fn slice(&self, offset: usize, length: usize) -> ArrayRef {
Arc::new(self.slice(offset, length))
}
+ fn len(&self) -> usize {
+ self.type_ids.len()
+ }
+
+ fn is_empty(&self) -> bool {
+ self.type_ids.is_empty()
+ }
+
+ fn offset(&self) -> usize {
+ 0
+ }
+
fn nulls(&self) -> Option<&NullBuffer> {
None
}
@@ -386,6 +435,32 @@ impl Array for UnionArray {
fn null_count(&self) -> usize {
0
}
+
+ fn get_buffer_memory_size(&self) -> usize {
+ let mut sum = self.type_ids.inner().capacity();
+ if let Some(o) = self.offsets.as_ref() {
+ sum += o.inner().capacity()
+ }
+ self.fields
+ .iter()
+ .flat_map(|x| x.as_ref().map(|x| x.get_buffer_memory_size()))
+ .sum::<usize>()
+ + sum
+ }
+
+ fn get_array_memory_size(&self) -> usize {
+ let mut sum = self.type_ids.inner().capacity();
+ if let Some(o) = self.offsets.as_ref() {
+ sum += o.inner().capacity()
+ }
+ std::mem::size_of::<Self>()
+ + self
+ .fields
+ .iter()
+ .flat_map(|x| x.as_ref().map(|x| x.get_array_memory_size()))
+ .sum::<usize>()
+ + sum
+ }
}
impl std::fmt::Debug for UnionArray {
diff --git a/arrow-array/src/record_batch.rs b/arrow-array/src/record_batch.rs
index 1350285f8b26..ee61d2da6597 100644
--- a/arrow-array/src/record_batch.rs
+++ b/arrow-array/src/record_batch.rs
@@ -474,7 +474,7 @@ impl From<StructArray> for RecordBatch {
);
let row_count = value.len();
let schema = Arc::new(Schema::new(value.fields().clone()));
- let columns = value.boxed_fields;
+ let columns = value.fields;
RecordBatch {
schema,
@@ -614,7 +614,7 @@ mod tests {
let record_batch =
RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a), Arc::new(b)])
.unwrap();
- assert_eq!(record_batch.get_array_memory_size(), 564);
+ assert_eq!(record_batch.get_array_memory_size(), 364);
}
fn check_batch(record_batch: RecordBatch, num_rows: usize) {
diff --git a/arrow-cast/src/cast.rs b/arrow-cast/src/cast.rs
index 05b56a0e8d32..2c1dae5187fa 100644
--- a/arrow-cast/src/cast.rs
+++ b/arrow-cast/src/cast.rs
@@ -4667,10 +4667,8 @@ mod tests {
let array = Int32Array::from(vec![-5, 6, -7, 8, 100000000]);
assert_eq!(0, array.offset());
let array = array.slice(2, 3);
- assert_eq!(2, array.offset());
let b = cast(&array, &DataType::UInt8).unwrap();
assert_eq!(3, b.len());
- assert_eq!(0, b.offset());
let c = b.as_any().downcast_ref::<UInt8Array>().unwrap();
assert!(!c.is_valid(0));
assert_eq!(8, c.value(1));
diff --git a/arrow-ipc/src/writer.rs b/arrow-ipc/src/writer.rs
index 7d44d8f24030..08ddd1812bb7 100644
--- a/arrow-ipc/src/writer.rs
+++ b/arrow-ipc/src/writer.rs
@@ -24,11 +24,11 @@ use std::cmp::min;
use std::collections::HashMap;
use std::io::{BufWriter, Write};
-use arrow_array::types::{Int16Type, Int32Type, Int64Type, RunEndIndexType};
use flatbuffers::FlatBufferBuilder;
use arrow_array::builder::BufferBuilder;
use arrow_array::cast::*;
+use arrow_array::types::{Int16Type, Int32Type, Int64Type, RunEndIndexType};
use arrow_array::*;
use arrow_buffer::bit_util;
use arrow_buffer::{ArrowNativeType, Buffer, MutableBuffer};
@@ -1107,94 +1107,33 @@ fn get_buffer_element_width(spec: &BufferSpec) -> usize {
}
}
-/// Returns byte width for binary value_offset buffer spec.
-#[inline]
-fn get_value_offset_byte_width(data_type: &DataType) -> usize {
- match data_type {
- DataType::Binary | DataType::Utf8 => 4,
- DataType::LargeBinary | DataType::LargeUtf8 => 8,
- _ => unreachable!(),
+/// Returns the values and offsets [`Buffer`] for a ByteArray with offset type `O`
+///
+/// In particular, this handles re-encoding the offsets if they don't start at `0`,
+/// slicing the values buffer as appropriate. This helps reduce the encoded
+/// size of sliced arrays, as values that have been sliced away are not encoded
+fn get_byte_array_buffers<O: OffsetSizeTrait>(data: &ArrayData) -> (Buffer, Buffer) {
+ if data.is_empty() {
+ return (MutableBuffer::new(0).into(), MutableBuffer::new(0).into());
}
-}
-/// Returns the number of total bytes in base binary arrays.
-fn get_binary_buffer_len(array_data: &ArrayData) -> usize {
- if array_data.is_empty() {
- return 0;
- }
- match array_data.data_type() {
- DataType::Binary => {
- let array: BinaryArray = array_data.clone().into();
- let offsets = array.value_offsets();
- (offsets[array_data.len()] - offsets[0]) as usize
- }
- DataType::LargeBinary => {
- let array: LargeBinaryArray = array_data.clone().into();
- let offsets = array.value_offsets();
- (offsets[array_data.len()] - offsets[0]) as usize
- }
- DataType::Utf8 => {
- let array: StringArray = array_data.clone().into();
- let offsets = array.value_offsets();
- (offsets[array_data.len()] - offsets[0]) as usize
- }
- DataType::LargeUtf8 => {
- let array: LargeStringArray = array_data.clone().into();
- let offsets = array.value_offsets();
- (offsets[array_data.len()] - offsets[0]) as usize
- }
- _ => unreachable!(),
- }
-}
+ let buffers = data.buffers();
+ let offsets: &[O] = buffers[0].typed_data::<O>();
+ let offset_slice = &offsets[data.offset()..data.offset() + data.len() + 1];
-/// Rebase value offsets for given ArrayData to zero-based.
-fn get_zero_based_value_offsets<OffsetSize: OffsetSizeTrait>(
- array_data: &ArrayData,
-) -> Buffer {
- match array_data.data_type() {
- DataType::Binary | DataType::LargeBinary => {
- let array: GenericBinaryArray<OffsetSize> = array_data.clone().into();
- let offsets = array.value_offsets();
- let start_offset = offsets[0];
-
- let mut builder = BufferBuilder::<OffsetSize>::new(array_data.len() + 1);
- for x in offsets {
- builder.append(*x - start_offset);
- }
+ let start_offset = offset_slice.first().unwrap();
+ let end_offset = offset_slice.last().unwrap();
- builder.finish()
- }
- DataType::Utf8 | DataType::LargeUtf8 => {
- let array: GenericStringArray<OffsetSize> = array_data.clone().into();
- let offsets = array.value_offsets();
- let start_offset = offsets[0];
-
- let mut builder = BufferBuilder::<OffsetSize>::new(array_data.len() + 1);
- for x in offsets {
- builder.append(*x - start_offset);
- }
-
- builder.finish()
- }
- _ => unreachable!(),
- }
-}
+ let offsets = match start_offset.as_usize() {
+ 0 => buffers[0].clone(),
+ _ => offset_slice.iter().map(|x| *x - *start_offset).collect(),
+ };
-/// Returns the start offset of base binary array.
-fn get_buffer_offset<OffsetSize: OffsetSizeTrait>(array_data: &ArrayData) -> OffsetSize {
- match array_data.data_type() {
- DataType::Binary | DataType::LargeBinary => {
- let array: GenericBinaryArray<OffsetSize> = array_data.clone().into();
- let offsets = array.value_offsets();
- offsets[0]
- }
- DataType::Utf8 | DataType::LargeUtf8 => {
- let array: GenericStringArray<OffsetSize> = array_data.clone().into();
- let offsets = array.value_offsets();
- offsets[0]
- }
- _ => unreachable!(),
- }
+ let values = buffers[1].slice_with_length(
+ start_offset.as_usize(),
+ end_offset.as_usize() - start_offset.as_usize(),
+ );
+ (offsets, values)
}
/// Write array data to a vector of bytes
@@ -1241,65 +1180,27 @@ fn write_array_data(
}
let data_type = array_data.data_type();
- if matches!(
- data_type,
- DataType::Binary | DataType::LargeBinary | DataType::Utf8 | DataType::LargeUtf8
- ) {
- let offset_buffer = &array_data.buffers()[0];
- let value_offset_byte_width = get_value_offset_byte_width(data_type);
- let min_length = (array_data.len() + 1) * value_offset_byte_width;
- if buffer_need_truncate(
- array_data.offset(),
- offset_buffer,
- &BufferSpec::FixedWidth {
- byte_width: value_offset_byte_width,
- },
- min_length,
- ) {
- // Rebase offsets and truncate values
- let (new_offsets, byte_offset) =
- if matches!(data_type, DataType::Binary | DataType::Utf8) {
- (
- get_zero_based_value_offsets::<i32>(array_data),
- get_buffer_offset::<i32>(array_data) as usize,
- )
- } else {
- (
- get_zero_based_value_offsets::<i64>(array_data),
- get_buffer_offset::<i64>(array_data) as usize,
- )
- };
-
+ if matches!(data_type, DataType::Binary | DataType::Utf8) {
+ let (offsets, values) = get_byte_array_buffers::<i32>(array_data);
+ for buffer in [offsets, values] {
offset = write_buffer(
- new_offsets.as_slice(),
+ buffer.as_slice(),
buffers,
arrow_data,
offset,
compression_codec,
)?;
-
- let total_bytes = get_binary_buffer_len(array_data);
- let value_buffer = &array_data.buffers()[1];
- let buffer_length = min(total_bytes, value_buffer.len() - byte_offset);
- let buffer_slice =
- &value_buffer.as_slice()[byte_offset..(byte_offset + buffer_length)];
+ }
+ } else if matches!(data_type, DataType::LargeBinary | DataType::LargeUtf8) {
+ let (offsets, values) = get_byte_array_buffers::<i64>(array_data);
+ for buffer in [offsets, values] {
offset = write_buffer(
- buffer_slice,
+ buffer.as_slice(),
buffers,
arrow_data,
offset,
compression_codec,
)?;
- } else {
- for buffer in array_data.buffers() {
- offset = write_buffer(
- buffer.as_slice(),
- buffers,
- arrow_data,
- offset,
- compression_codec,
- )?;
- }
}
} else if DataType::is_numeric(data_type)
|| DataType::is_temporal(data_type)
@@ -1445,20 +1346,20 @@ fn pad_to_8(len: u32) -> usize {
#[cfg(test)]
mod tests {
- use super::*;
-
use std::io::Cursor;
use std::io::Seek;
use std::sync::Arc;
- use crate::MetadataVersion;
-
- use crate::reader::*;
use arrow_array::builder::PrimitiveRunBuilder;
use arrow_array::builder::UnionBuilder;
use arrow_array::types::*;
use arrow_schema::DataType;
+ use crate::reader::*;
+ use crate::MetadataVersion;
+
+ use super::*;
+
#[test]
#[cfg(feature = "lz4")]
fn test_write_empty_record_batch_lz4_compression() {
diff --git a/arrow-select/src/nullif.rs b/arrow-select/src/nullif.rs
index 6039d53eaedc..aaa3423d69e5 100644
--- a/arrow-select/src/nullif.rs
+++ b/arrow-select/src/nullif.rs
@@ -208,8 +208,7 @@ mod tests {
let s = s.slice(2, 3);
let select = select.slice(1, 3);
- let select = select.as_boolean();
- let a = nullif(&s, select).unwrap();
+ let a = nullif(&s, &select).unwrap();
let r: Vec<_> = a.as_string::<i32>().iter().collect();
assert_eq!(r, vec![None, Some("a"), None]);
}
@@ -509,9 +508,8 @@ mod tests {
.map(|_| rng.gen_bool(0.5).then(|| rng.gen_bool(0.5)))
.collect();
let b = b.slice(b_start_offset, a_length);
- let b = b.as_boolean();
- test_nullif(&a, b);
+ test_nullif(&a, &b);
}
}
}
diff --git a/arrow/src/lib.rs b/arrow/src/lib.rs
index 8bad29bf74b7..27c905ba0cd6 100644
--- a/arrow/src/lib.rs
+++ b/arrow/src/lib.rs
@@ -322,7 +322,7 @@
//! Advanced users may wish to interact with the underlying buffers of an [`Array`], for example,
//! for FFI or high-performance conversion from other formats. This interface is provided by
//! [`ArrayData`] which stores the [`Buffer`] comprising an [`Array`], and can be accessed
-//! with [`Array::data`](array::Array::data)
+//! with [`Array::to_data`](array::Array::to_data)
//!
//! The APIs for constructing [`ArrayData`] come in safe, and unsafe variants, with the former
//! performing extensive, but potentially expensive validation to ensure the buffers are well-formed.
|
diff --git a/arrow-pyarrow-integration-testing/src/lib.rs b/arrow-pyarrow-integration-testing/src/lib.rs
index cf94b0dd40af..af400868ffa9 100644
--- a/arrow-pyarrow-integration-testing/src/lib.rs
+++ b/arrow-pyarrow-integration-testing/src/lib.rs
@@ -52,7 +52,7 @@ fn double(array: &PyAny, py: Python) -> PyResult<PyObject> {
let array = kernels::arithmetic::add(array, array).map_err(to_py_err)?;
// export
- array.data().to_pyarrow(py)
+ array.to_data().to_pyarrow(py)
}
/// calls a lambda function that receives and returns an array
@@ -64,7 +64,7 @@ fn double_py(lambda: &PyAny, py: Python) -> PyResult<bool> {
let expected = Arc::new(Int64Array::from(vec![Some(2), None, Some(6)])) as ArrayRef;
// to py
- let pyarray = array.data().to_pyarrow(py)?;
+ let pyarray = array.to_data().to_pyarrow(py)?;
let pyarray = lambda.call1((pyarray,))?;
let array = make_array(ArrayData::from_pyarrow(pyarray)?);
@@ -75,7 +75,7 @@ fn double_py(lambda: &PyAny, py: Python) -> PyResult<bool> {
fn make_empty_array(datatype: PyArrowType<DataType>, py: Python) -> PyResult<PyObject> {
let array = new_empty_array(&datatype.0);
- array.data().to_pyarrow(py)
+ array.to_data().to_pyarrow(py)
}
/// Returns the substring
@@ -90,7 +90,7 @@ fn substring(
// substring
let array = kernels::substring::substring(array.as_ref(), start, None).map_err(to_py_err)?;
- Ok(array.data().to_owned().into())
+ Ok(array.to_data().into())
}
/// Returns the concatenate
@@ -101,7 +101,7 @@ fn concatenate(array: PyArrowType<ArrayData>, py: Python) -> PyResult<PyObject>
// concat
let array = kernels::concat::concat(&[array.as_ref(), array.as_ref()]).map_err(to_py_err)?;
- array.data().to_pyarrow(py)
+ array.to_data().to_pyarrow(py)
}
#[pyfunction]
|
First-Class Array Abstractions
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
<!--
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
(This section helps Arrow developers understand the context and *why* for this feature, in addition to the *what*)
-->
Currently `Array` are wrappers around an `ArrayData`, storing it as a member of the array. This is redundant, confusing and results in API friction.
**Describe the solution you'd like**
<!--
A clear and concise description of what you want to happen.
-->
I would like the Array implementations to just store their constituent parts, in the same vein as the typed ArrayData abstractions experimented with under https://github.com/apache/arrow-rs/issues/1799 did. This would involve the following
* Add `Array::nulls(&self) -> Option<&NullBuffer>`
* Add `Array::to_data(&self) -> ArrayData`
* Implement `Array::slice`, `Array::data_type`, `Array::len`, `Array::get_buffer_memory_size`, etc... for each `Array`
* Deprecate `Array::data`, `Array::data_ref` and `Array::offset`
**Describe alternatives you've considered**
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
https://github.com/apache/arrow-rs/issues/3879
|
2023-04-12T11:08:57Z
|
37.0
|
a35c6c5f4309787a9a2f523920af2efd9b1682b9
|
|
apache/arrow-rs
| 4,055
|
apache__arrow-rs-4055
|
[
"4054"
] |
ee4003328d6615e011303ba57c24264a3f454e12
|
diff --git a/arrow-flight/examples/flight_sql_server.rs b/arrow-flight/examples/flight_sql_server.rs
index 08744b65f7ac..675692aba6f9 100644
--- a/arrow-flight/examples/flight_sql_server.rs
+++ b/arrow-flight/examples/flight_sql_server.rs
@@ -44,9 +44,9 @@ use arrow_flight::{
ActionCreatePreparedStatementRequest, CommandGetCatalogs,
CommandGetCrossReference, CommandGetDbSchemas, CommandGetExportedKeys,
CommandGetImportedKeys, CommandGetPrimaryKeys, CommandGetSqlInfo,
- CommandGetTableTypes, CommandGetTables, CommandPreparedStatementQuery,
- CommandPreparedStatementUpdate, CommandStatementQuery, CommandStatementUpdate,
- TicketStatementQuery,
+ CommandGetTableTypes, CommandGetTables, CommandGetXdbcTypeInfo,
+ CommandPreparedStatementQuery, CommandPreparedStatementUpdate,
+ CommandStatementQuery, CommandStatementUpdate, TicketStatementQuery,
},
FlightDescriptor, FlightInfo,
};
@@ -315,6 +315,16 @@ impl FlightSqlService for FlightSqlServiceImpl {
))
}
+ async fn get_flight_info_xdbc_type_info(
+ &self,
+ _query: CommandGetXdbcTypeInfo,
+ _request: Request<FlightDescriptor>,
+ ) -> Result<Response<FlightInfo>, Status> {
+ Err(Status::unimplemented(
+ "get_flight_info_xdbc_type_info not implemented",
+ ))
+ }
+
// do_get
async fn do_get_statement(
&self,
@@ -412,6 +422,16 @@ impl FlightSqlService for FlightSqlServiceImpl {
))
}
+ async fn do_get_xdbc_type_info(
+ &self,
+ _query: CommandGetXdbcTypeInfo,
+ _request: Request<Ticket>,
+ ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
+ Err(Status::unimplemented(
+ "do_get_xdbc_type_info not implemented",
+ ))
+ }
+
// do_put
async fn do_put_statement_update(
&self,
diff --git a/arrow-flight/src/sql/client.rs b/arrow-flight/src/sql/client.rs
index d96c90afa806..15a896c109e1 100644
--- a/arrow-flight/src/sql/client.rs
+++ b/arrow-flight/src/sql/client.rs
@@ -31,9 +31,9 @@ use crate::sql::{
ActionCreatePreparedStatementResult, Any, CommandGetCatalogs,
CommandGetCrossReference, CommandGetDbSchemas, CommandGetExportedKeys,
CommandGetImportedKeys, CommandGetPrimaryKeys, CommandGetSqlInfo,
- CommandGetTableTypes, CommandGetTables, CommandPreparedStatementQuery,
- CommandStatementQuery, CommandStatementUpdate, DoPutUpdateResult, ProstMessageExt,
- SqlInfo,
+ CommandGetTableTypes, CommandGetTables, CommandGetXdbcTypeInfo,
+ CommandPreparedStatementQuery, CommandStatementQuery, CommandStatementUpdate,
+ DoPutUpdateResult, ProstMessageExt, SqlInfo,
};
use crate::{
Action, FlightData, FlightDescriptor, FlightInfo, HandshakeRequest,
@@ -313,6 +313,14 @@ impl FlightSqlServiceClient<Channel> {
self.get_flight_info_for_command(request).await
}
+ /// Request XDBC SQL information.
+ pub async fn get_xdbc_type_info(
+ &mut self,
+ request: CommandGetXdbcTypeInfo,
+ ) -> Result<FlightInfo, ArrowError> {
+ self.get_flight_info_for_command(request).await
+ }
+
/// Create a prepared statement object.
pub async fn prepare(
&mut self,
diff --git a/arrow-flight/src/sql/mod.rs b/arrow-flight/src/sql/mod.rs
index df828c9c08af..ed26b38751c5 100644
--- a/arrow-flight/src/sql/mod.rs
+++ b/arrow-flight/src/sql/mod.rs
@@ -58,6 +58,7 @@ pub use gen::CommandGetPrimaryKeys;
pub use gen::CommandGetSqlInfo;
pub use gen::CommandGetTableTypes;
pub use gen::CommandGetTables;
+pub use gen::CommandGetXdbcTypeInfo;
pub use gen::CommandPreparedStatementQuery;
pub use gen::CommandPreparedStatementUpdate;
pub use gen::CommandStatementQuery;
@@ -214,6 +215,7 @@ prost_message_ext!(
CommandGetSqlInfo,
CommandGetTableTypes,
CommandGetTables,
+ CommandGetXdbcTypeInfo,
CommandPreparedStatementQuery,
CommandPreparedStatementUpdate,
CommandStatementQuery,
diff --git a/arrow-flight/src/sql/server.rs b/arrow-flight/src/sql/server.rs
index f25ddb13db99..9a0183495434 100644
--- a/arrow-flight/src/sql/server.rs
+++ b/arrow-flight/src/sql/server.rs
@@ -34,9 +34,9 @@ use super::{
ActionCreatePreparedStatementResult, CommandGetCatalogs, CommandGetCrossReference,
CommandGetDbSchemas, CommandGetExportedKeys, CommandGetImportedKeys,
CommandGetPrimaryKeys, CommandGetSqlInfo, CommandGetTableTypes, CommandGetTables,
- CommandPreparedStatementQuery, CommandPreparedStatementUpdate, CommandStatementQuery,
- CommandStatementUpdate, DoPutUpdateResult, ProstMessageExt, SqlInfo,
- TicketStatementQuery,
+ CommandGetXdbcTypeInfo, CommandPreparedStatementQuery,
+ CommandPreparedStatementUpdate, CommandStatementQuery, CommandStatementUpdate,
+ DoPutUpdateResult, ProstMessageExt, SqlInfo, TicketStatementQuery,
};
pub(crate) static CREATE_PREPARED_STATEMENT: &str = "CreatePreparedStatement";
@@ -151,6 +151,13 @@ pub trait FlightSqlService: Sync + Send + Sized + 'static {
request: Request<FlightDescriptor>,
) -> Result<Response<FlightInfo>, Status>;
+ /// Get a FlightInfo to extract information about the supported XDBC types.
+ async fn get_flight_info_xdbc_type_info(
+ &self,
+ query: CommandGetXdbcTypeInfo,
+ request: Request<FlightDescriptor>,
+ ) -> Result<Response<FlightInfo>, Status>;
+
// do_get
/// Get a FlightDataStream containing the query results.
@@ -230,6 +237,13 @@ pub trait FlightSqlService: Sync + Send + Sized + 'static {
request: Request<Ticket>,
) -> Result<Response<<Self as FlightService>::DoGetStream>, Status>;
+ /// Get a FlightDataStream containing the data related to the supported XDBC types.
+ async fn do_get_xdbc_type_info(
+ &self,
+ query: CommandGetXdbcTypeInfo,
+ request: Request<Ticket>,
+ ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status>;
+
// do_put
/// Execute an update SQL statement.
@@ -352,6 +366,9 @@ where
Command::CommandGetCrossReference(token) => {
self.get_flight_info_cross_reference(token, request).await
}
+ Command::CommandGetXdbcTypeInfo(token) => {
+ self.get_flight_info_xdbc_type_info(token, request).await
+ }
cmd => Err(Status::unimplemented(format!(
"get_flight_info: The defined request is invalid: {}",
cmd.type_url()
@@ -407,6 +424,9 @@ where
Command::CommandGetCrossReference(command) => {
self.do_get_cross_reference(command, request).await
}
+ Command::CommandGetXdbcTypeInfo(command) => {
+ self.do_get_xdbc_type_info(command, request).await
+ }
cmd => self.do_get_fallback(request, cmd.into_any()).await,
}
}
|
diff --git a/arrow-flight/tests/flight_sql_client_cli.rs b/arrow-flight/tests/flight_sql_client_cli.rs
index 2c54bd263fdb..248b3732ff97 100644
--- a/arrow-flight/tests/flight_sql_client_cli.rs
+++ b/arrow-flight/tests/flight_sql_client_cli.rs
@@ -26,9 +26,9 @@ use arrow_flight::{
CommandGetCatalogs, CommandGetCrossReference, CommandGetDbSchemas,
CommandGetExportedKeys, CommandGetImportedKeys, CommandGetPrimaryKeys,
CommandGetSqlInfo, CommandGetTableTypes, CommandGetTables,
- CommandPreparedStatementQuery, CommandPreparedStatementUpdate,
- CommandStatementQuery, CommandStatementUpdate, ProstMessageExt, SqlInfo,
- TicketStatementQuery,
+ CommandGetXdbcTypeInfo, CommandPreparedStatementQuery,
+ CommandPreparedStatementUpdate, CommandStatementQuery, CommandStatementUpdate,
+ ProstMessageExt, SqlInfo, TicketStatementQuery,
},
utils::batches_to_flight_data,
Action, FlightData, FlightDescriptor, FlightEndpoint, FlightInfo, HandshakeRequest,
@@ -302,6 +302,16 @@ impl FlightSqlService for FlightSqlServiceImpl {
))
}
+ async fn get_flight_info_xdbc_type_info(
+ &self,
+ _query: CommandGetXdbcTypeInfo,
+ _request: Request<FlightDescriptor>,
+ ) -> Result<Response<FlightInfo>, Status> {
+ Err(Status::unimplemented(
+ "get_flight_info_xdbc_type_info not implemented",
+ ))
+ }
+
// do_get
async fn do_get_statement(
&self,
@@ -399,6 +409,16 @@ impl FlightSqlService for FlightSqlServiceImpl {
))
}
+ async fn do_get_xdbc_type_info(
+ &self,
+ _query: CommandGetXdbcTypeInfo,
+ _request: Request<Ticket>,
+ ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
+ Err(Status::unimplemented(
+ "do_get_xdbc_type_info not implemented",
+ ))
+ }
+
// do_put
async fn do_put_statement_update(
&self,
|
Flight SQL Server missing command type.googleapis.com/arrow.flight.protocol.sql.CommandGetXdbcTypeInfo
**Describe the bug**
In the flight SQL servers' get_flight_info method, there currently is no method for the
The command itself is defined here: https://github.com/apache/arrow-rs/blob/6b17775f37b939221d855514db4ffb3344deb1f4/arrow-flight/src/sql/arrow.flight.protocol.sql.rs#L104
It should be implemented in this match:
https://github.com/apache/arrow-rs/blob/ee4003328d6615e011303ba57c24264a3f454e12/arrow-flight/src/sql/server.rs#L320
as well as the Server Trait.
**Expected behavior**
I can implement all Flight SQL Commands without overwriting `get_flight_info` or using the Fallback.
**Further Motivation**
This command is actually quite common. When using PowerBI and the Dremio ODBC / Flight driver to connect to a flight server, it get's issued right before the preview of any dataset.
|
2023-04-11T16:40:59Z
|
37.0
|
a35c6c5f4309787a9a2f523920af2efd9b1682b9
|
|
apache/arrow-rs
| 4,045
|
apache__arrow-rs-4045
|
[
"4044"
] |
fec282fd43add7df97ca8f58eb5eaa42eb9c928d
|
diff --git a/arrow-data/src/equal/union.rs b/arrow-data/src/equal/union.rs
index 4f04bc287aa8..5869afc30dbe 100644
--- a/arrow-data/src/equal/union.rs
+++ b/arrow-data/src/equal/union.rs
@@ -70,7 +70,13 @@ fn equal_sparse(
.iter()
.zip(rhs.child_data())
.all(|(lhs_values, rhs_values)| {
- equal_range(lhs_values, rhs_values, lhs_start, rhs_start, len)
+ equal_range(
+ lhs_values,
+ rhs_values,
+ lhs_start + lhs.offset(),
+ rhs_start + rhs.offset(),
+ len,
+ )
})
}
|
diff --git a/arrow/tests/array_equal.rs b/arrow/tests/array_equal.rs
index 93296c3b0e43..83a280db67b8 100644
--- a/arrow/tests/array_equal.rs
+++ b/arrow/tests/array_equal.rs
@@ -1155,6 +1155,22 @@ fn test_union_equal_sparse() {
test_equal(&union1, &union4, false);
}
+#[test]
+fn test_union_equal_sparse_slice() {
+ let mut builder = UnionBuilder::new_sparse();
+ builder.append::<Int32Type>("a", 1).unwrap();
+ builder.append::<Int32Type>("a", 2).unwrap();
+ builder.append::<Int32Type>("b", 3).unwrap();
+ let a1 = builder.build().unwrap();
+
+ let mut builder = UnionBuilder::new_sparse();
+ builder.append::<Int32Type>("a", 2).unwrap();
+ builder.append::<Int32Type>("b", 3).unwrap();
+ let a2 = builder.build().unwrap();
+
+ test_equal(&a1.slice(1, 2), &a2, true)
+}
+
#[test]
fn test_boolean_slice() {
let array = BooleanArray::from(vec![true; 32]);
|
Sparse UnionArray Equality Incorrect Offset Handling
**Describe the bug**
<!--
A clear and concise description of what the bug is.
-->
**To Reproduce**
<!--
Steps to reproduce the behavior:
-->
```
#[test]
fn test_union_equal_sparse_slice() {
let mut builder = UnionBuilder::new_sparse();
builder.append::<Int32Type>("a", 1).unwrap();
builder.append::<Int32Type>("a", 2).unwrap();
builder.append::<Int32Type>("b", 3).unwrap();
let a1 = builder.build().unwrap();
let mut builder = UnionBuilder::new_sparse();
builder.append::<Int32Type>("a", 2).unwrap();
builder.append::<Int32Type>("b", 3).unwrap();
let a2 = builder.build().unwrap();
test_equal(&a1.slice(1, 2), &a2, true)
}
```
The above should pass, it currently does not
**Expected behavior**
<!--
A clear and concise description of what you expected to happen.
-->
**Additional context**
<!--
Add any other context about the problem here.
-->
|
2023-04-10T14:51:17Z
|
37.0
|
a35c6c5f4309787a9a2f523920af2efd9b1682b9
|
|
apache/arrow-rs
| 3,994
|
apache__arrow-rs-3994
|
[
"3991"
] |
4e7bb45050622d5b43505aa64dacf410cb329941
|
diff --git a/arrow-cast/src/cast.rs b/arrow-cast/src/cast.rs
index e4f4370fdde5..5d7bea0e9d0f 100644
--- a/arrow-cast/src/cast.rs
+++ b/arrow-cast/src/cast.rs
@@ -145,6 +145,9 @@ pub fn can_cast_types(from_type: &DataType, to_type: &DataType) -> bool {
// decimal to signed numeric
(Decimal128(_, _), Null | Int8 | Int16 | Int32 | Int64 | Float32 | Float64) |
(Decimal256(_, _), Null | Int8 | Int16 | Int32 | Int64 | Float32 | Float64) => true,
+ // decimal to Utf8
+ (Decimal128(_, _), Utf8 | LargeUtf8) => true,
+ (Decimal256(_, _), Utf8 | LargeUtf8) => true,
// Utf8 to decimal
(Utf8 | LargeUtf8, Decimal128(_, _)) => true,
(Utf8 | LargeUtf8, Decimal256(_, _)) => true,
@@ -826,6 +829,8 @@ pub fn cast_with_options(
x as f64 / 10_f64.powi(*scale as i32)
})
}
+ Utf8 => value_to_string::<i32>(array),
+ LargeUtf8 => value_to_string::<i64>(array),
Null => Ok(new_null_array(to_type, array.len())),
_ => Err(ArrowError::CastError(format!(
"Casting from {from_type:?} to {to_type:?} not supported"
@@ -893,6 +898,8 @@ pub fn cast_with_options(
x.to_f64().unwrap() / 10_f64.powi(*scale as i32)
})
}
+ Utf8 => value_to_string::<i32>(array),
+ LargeUtf8 => value_to_string::<i64>(array),
Null => Ok(new_null_array(to_type, array.len())),
_ => Err(ArrowError::CastError(format!(
"Casting from {from_type:?} to {to_type:?} not supported"
@@ -8146,6 +8153,60 @@ mod tests {
assert_eq!(1672531200000000000, c.value(0));
}
+ #[test]
+ fn test_cast_decimal_to_utf8() {
+ fn test_decimal_to_string<IN: ArrowPrimitiveType, OffsetSize: OffsetSizeTrait>(
+ output_type: DataType,
+ array: PrimitiveArray<IN>,
+ ) {
+ let b = cast(&array, &output_type).unwrap();
+
+ assert_eq!(b.data_type(), &output_type);
+ let c = b.as_string::<OffsetSize>();
+
+ assert_eq!("1123.454", c.value(0));
+ assert_eq!("2123.456", c.value(1));
+ assert_eq!("-3123.453", c.value(2));
+ assert_eq!("-3123.456", c.value(3));
+ assert_eq!("0.000", c.value(4));
+ assert_eq!("0.123", c.value(5));
+ assert_eq!("1234.567", c.value(6));
+ assert_eq!("-1234.567", c.value(7));
+ assert!(c.is_null(8));
+ }
+ let array128: Vec<Option<i128>> = vec![
+ Some(1123454),
+ Some(2123456),
+ Some(-3123453),
+ Some(-3123456),
+ Some(0),
+ Some(123),
+ Some(123456789),
+ Some(-123456789),
+ None,
+ ];
+
+ let array256: Vec<Option<i256>> =
+ array128.iter().map(|v| v.map(i256::from_i128)).collect();
+
+ test_decimal_to_string::<arrow_array::types::Decimal128Type, i32>(
+ DataType::Utf8,
+ create_decimal_array(array128.clone(), 7, 3).unwrap(),
+ );
+ test_decimal_to_string::<arrow_array::types::Decimal128Type, i64>(
+ DataType::LargeUtf8,
+ create_decimal_array(array128, 7, 3).unwrap(),
+ );
+ test_decimal_to_string::<arrow_array::types::Decimal256Type, i32>(
+ DataType::Utf8,
+ create_decimal256_array(array256.clone(), 7, 3).unwrap(),
+ );
+ test_decimal_to_string::<arrow_array::types::Decimal256Type, i64>(
+ DataType::LargeUtf8,
+ create_decimal256_array(array256, 7, 3).unwrap(),
+ );
+ }
+
#[test]
fn test_cast_numeric_to_decimal128_precision_overflow() {
let array = Int64Array::from(vec![1234567]);
|
diff --git a/arrow/tests/array_cast.rs b/arrow/tests/array_cast.rs
index 2807bbd79b83..96a4f2b41f3c 100644
--- a/arrow/tests/array_cast.rs
+++ b/arrow/tests/array_cast.rs
@@ -185,9 +185,7 @@ fn get_arrays_of_all_types() -> Vec<ArrayRef> {
Arc::new(DurationMillisecondArray::from(vec![1000, 2000])),
Arc::new(DurationMicrosecondArray::from(vec![1000, 2000])),
Arc::new(DurationNanosecondArray::from(vec![1000, 2000])),
- Arc::new(
- create_decimal_array(vec![Some(1), Some(2), Some(3), None], 38, 0).unwrap(),
- ),
+ Arc::new(create_decimal_array(vec![Some(1), Some(2), Some(3)], 38, 0).unwrap()),
make_dictionary_primitive::<Int8Type, Decimal128Type>(vec![1, 2]),
make_dictionary_primitive::<Int16Type, Decimal128Type>(vec![1, 2]),
make_dictionary_primitive::<Int32Type, Decimal128Type>(vec![1, 2]),
|
Support Decimals cast to Utf8/LargeUtf
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
<!--
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
(This section helps Arrow developers understand the context and *why* for this feature, in addition to the *what*)
-->
Currently the CAST is not supported from Decimal to UTF. This ticket to add the necessary cast
**Describe the solution you'd like**
<!--
A clear and concise description of what you want to happen.
-->
Support Decimals cast to Utf8/LargeUtf
**Describe alternatives you've considered**
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
None
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
None
|
I will create a PR today
|
2023-03-31T22:07:04Z
|
36.0
|
4e7bb45050622d5b43505aa64dacf410cb329941
|
apache/arrow-rs
| 3,983
|
apache__arrow-rs-3983
|
[
"3955"
] |
e5a1676950ab5c04b0a74953ec5418da67cedb45
|
diff --git a/arrow-array/src/array/binary_array.rs b/arrow-array/src/array/binary_array.rs
index 530f3835ce10..ccce3cda9989 100644
--- a/arrow-array/src/array/binary_array.rs
+++ b/arrow-array/src/array/binary_array.rs
@@ -303,6 +303,7 @@ mod tests {
use super::*;
use crate::{ListArray, StringArray};
use arrow_schema::Field;
+ use std::sync::Arc;
#[test]
fn test_binary_array() {
@@ -453,7 +454,7 @@ mod tests {
.unwrap();
let binary_array1 = GenericBinaryArray::<O>::from(array_data1);
- let data_type = GenericListArray::<O>::DATA_TYPE_CONSTRUCTOR(Box::new(
+ let data_type = GenericListArray::<O>::DATA_TYPE_CONSTRUCTOR(Arc::new(
Field::new("item", DataType::UInt8, false),
));
@@ -503,7 +504,7 @@ mod tests {
let offsets = [0, 5, 8, 15].map(|n| O::from_usize(n).unwrap());
let null_buffer = Buffer::from_slice_ref([0b101]);
- let data_type = GenericListArray::<O>::DATA_TYPE_CONSTRUCTOR(Box::new(
+ let data_type = GenericListArray::<O>::DATA_TYPE_CONSTRUCTOR(Arc::new(
Field::new("item", DataType::UInt8, false),
));
@@ -548,7 +549,7 @@ mod tests {
.unwrap();
let offsets = [0, 5, 10].map(|n| O::from_usize(n).unwrap());
- let data_type = GenericListArray::<O>::DATA_TYPE_CONSTRUCTOR(Box::new(
+ let data_type = GenericListArray::<O>::DATA_TYPE_CONSTRUCTOR(Arc::new(
Field::new("item", DataType::UInt8, true),
));
@@ -641,7 +642,7 @@ mod tests {
let offsets: [i32; 4] = [0, 5, 5, 12];
let data_type =
- DataType::List(Box::new(Field::new("item", DataType::UInt32, false)));
+ DataType::List(Arc::new(Field::new("item", DataType::UInt32, false)));
let array_data = ArrayData::builder(data_type)
.len(3)
.add_buffer(Buffer::from_slice_ref(offsets))
diff --git a/arrow-array/src/array/fixed_size_binary_array.rs b/arrow-array/src/array/fixed_size_binary_array.rs
index 75f6bf91442d..fa303b4a8dbc 100644
--- a/arrow-array/src/array/fixed_size_binary_array.rs
+++ b/arrow-array/src/array/fixed_size_binary_array.rs
@@ -583,7 +583,7 @@ mod tests {
// [null, [10, 11, 12, 13]]
let array_data = unsafe {
ArrayData::builder(DataType::FixedSizeList(
- Box::new(Field::new("item", DataType::UInt8, false)),
+ Arc::new(Field::new("item", DataType::UInt8, false)),
4,
))
.len(2)
@@ -619,7 +619,7 @@ mod tests {
let array_data = unsafe {
ArrayData::builder(DataType::FixedSizeList(
- Box::new(Field::new("item", DataType::Binary, false)),
+ Arc::new(Field::new("item", DataType::Binary, false)),
4,
))
.len(3)
@@ -643,7 +643,7 @@ mod tests {
let array_data = unsafe {
ArrayData::builder(DataType::FixedSizeList(
- Box::new(Field::new("item", DataType::UInt8, false)),
+ Arc::new(Field::new("item", DataType::UInt8, false)),
4,
))
.len(3)
diff --git a/arrow-array/src/array/fixed_size_list_array.rs b/arrow-array/src/array/fixed_size_list_array.rs
index 1a421fe53c25..4a592d869437 100644
--- a/arrow-array/src/array/fixed_size_list_array.rs
+++ b/arrow-array/src/array/fixed_size_list_array.rs
@@ -30,6 +30,7 @@ use std::sync::Arc;
/// # Example
///
/// ```
+/// # use std::sync::Arc;
/// # use arrow_array::{Array, FixedSizeListArray, Int32Array};
/// # use arrow_data::ArrayData;
/// # use arrow_schema::{DataType, Field};
@@ -41,7 +42,7 @@ use std::sync::Arc;
/// .build()
/// .unwrap();
/// let list_data_type = DataType::FixedSizeList(
-/// Box::new(Field::new("item", DataType::Int32, false)),
+/// Arc::new(Field::new("item", DataType::Int32, false)),
/// 3,
/// );
/// let list_data = ArrayData::builder(list_data_type.clone())
@@ -270,7 +271,7 @@ mod tests {
// Construct a list array from the above two
let list_data_type = DataType::FixedSizeList(
- Box::new(Field::new("item", DataType::Int32, false)),
+ Arc::new(Field::new("item", DataType::Int32, false)),
3,
);
let list_data = ArrayData::builder(list_data_type.clone())
@@ -343,7 +344,7 @@ mod tests {
// Construct a list array from the above two
let list_data_type = DataType::FixedSizeList(
- Box::new(Field::new("item", DataType::Int32, false)),
+ Arc::new(Field::new("item", DataType::Int32, false)),
3,
);
let list_data = unsafe {
@@ -374,7 +375,7 @@ mod tests {
// Construct a fixed size list array from the above two
let list_data_type = DataType::FixedSizeList(
- Box::new(Field::new("item", DataType::Int32, false)),
+ Arc::new(Field::new("item", DataType::Int32, false)),
2,
);
let list_data = ArrayData::builder(list_data_type)
@@ -435,7 +436,7 @@ mod tests {
// Construct a fixed size list array from the above two
let list_data_type = DataType::FixedSizeList(
- Box::new(Field::new("item", DataType::Int32, false)),
+ Arc::new(Field::new("item", DataType::Int32, false)),
2,
);
let list_data = ArrayData::builder(list_data_type)
diff --git a/arrow-array/src/array/list_array.rs b/arrow-array/src/array/list_array.rs
index af5ce59fe4d8..8961d606e4f7 100644
--- a/arrow-array/src/array/list_array.rs
+++ b/arrow-array/src/array/list_array.rs
@@ -71,7 +71,7 @@ impl<OffsetSize: OffsetSizeTrait> GenericListArray<OffsetSize> {
/// The data type constructor of list array.
/// The input is the schema of the child array and
/// the output is the [`DataType`], List or LargeList.
- pub const DATA_TYPE_CONSTRUCTOR: fn(Box<Field>) -> DataType = if OffsetSize::IS_LARGE
+ pub const DATA_TYPE_CONSTRUCTOR: fn(Arc<Field>) -> DataType = if OffsetSize::IS_LARGE
{
DataType::LargeList
} else {
@@ -368,7 +368,7 @@ mod tests {
// Construct a list array from the above two
let list_data_type =
- DataType::List(Box::new(Field::new("item", DataType::Int32, true)));
+ DataType::List(Arc::new(Field::new("item", DataType::Int32, true)));
let list_data = ArrayData::builder(list_data_type)
.len(3)
.add_buffer(value_offsets)
@@ -405,7 +405,7 @@ mod tests {
// Construct a list array from the above two
let list_data_type =
- DataType::List(Box::new(Field::new("item", DataType::Int32, false)));
+ DataType::List(Arc::new(Field::new("item", DataType::Int32, false)));
let list_data = ArrayData::builder(list_data_type)
.len(0)
.add_buffer(value_offsets)
@@ -432,7 +432,7 @@ mod tests {
// Construct a list array from the above two
let list_data_type =
- DataType::List(Box::new(Field::new("item", DataType::Int32, false)));
+ DataType::List(Arc::new(Field::new("item", DataType::Int32, false)));
let list_data = ArrayData::builder(list_data_type.clone())
.len(3)
.add_buffer(value_offsets.clone())
@@ -522,7 +522,7 @@ mod tests {
// Construct a list array from the above two
let list_data_type =
- DataType::LargeList(Box::new(Field::new("item", DataType::Int32, false)));
+ DataType::LargeList(Arc::new(Field::new("item", DataType::Int32, false)));
let list_data = ArrayData::builder(list_data_type.clone())
.len(3)
.add_buffer(value_offsets.clone())
@@ -619,7 +619,7 @@ mod tests {
// Construct a list array from the above two
let list_data_type =
- DataType::List(Box::new(Field::new("item", DataType::Int32, false)));
+ DataType::List(Arc::new(Field::new("item", DataType::Int32, false)));
let list_data = ArrayData::builder(list_data_type)
.len(9)
.add_buffer(value_offsets)
@@ -683,7 +683,7 @@ mod tests {
// Construct a list array from the above two
let list_data_type =
- DataType::LargeList(Box::new(Field::new("item", DataType::Int32, false)));
+ DataType::LargeList(Arc::new(Field::new("item", DataType::Int32, false)));
let list_data = ArrayData::builder(list_data_type)
.len(9)
.add_buffer(value_offsets)
@@ -750,7 +750,7 @@ mod tests {
// Construct a list array from the above two
let list_data_type =
- DataType::LargeList(Box::new(Field::new("item", DataType::Int32, false)));
+ DataType::LargeList(Arc::new(Field::new("item", DataType::Int32, false)));
let list_data = ArrayData::builder(list_data_type)
.len(9)
.add_buffer(value_offsets)
@@ -778,7 +778,7 @@ mod tests {
.build_unchecked()
};
let list_data_type =
- DataType::List(Box::new(Field::new("item", DataType::Int32, false)));
+ DataType::List(Arc::new(Field::new("item", DataType::Int32, false)));
let list_data = unsafe {
ArrayData::builder(list_data_type)
.len(3)
@@ -798,7 +798,7 @@ mod tests {
fn test_list_array_invalid_child_array_len() {
let value_offsets = Buffer::from_slice_ref([0, 2, 5, 7]);
let list_data_type =
- DataType::List(Box::new(Field::new("item", DataType::Int32, false)));
+ DataType::List(Arc::new(Field::new("item", DataType::Int32, false)));
let list_data = unsafe {
ArrayData::builder(list_data_type)
.len(3)
@@ -831,7 +831,7 @@ mod tests {
let value_offsets = Buffer::from_slice_ref([2, 2, 5, 7]);
let list_data_type =
- DataType::List(Box::new(Field::new("item", DataType::Int32, false)));
+ DataType::List(Arc::new(Field::new("item", DataType::Int32, false)));
let list_data = ArrayData::builder(list_data_type)
.len(3)
.add_buffer(value_offsets)
@@ -874,7 +874,7 @@ mod tests {
};
let list_data_type =
- DataType::List(Box::new(Field::new("item", DataType::Int32, false)));
+ DataType::List(Arc::new(Field::new("item", DataType::Int32, false)));
let list_data = unsafe {
ArrayData::builder(list_data_type)
.add_buffer(buf2)
@@ -958,7 +958,7 @@ mod tests {
#[test]
fn test_empty_offsets() {
- let f = Box::new(Field::new("element", DataType::Int32, true));
+ let f = Arc::new(Field::new("element", DataType::Int32, true));
let string = ListArray::from(
ArrayData::builder(DataType::List(f.clone()))
.buffers(vec![Buffer::from(&[])])
diff --git a/arrow-array/src/array/map_array.rs b/arrow-array/src/array/map_array.rs
index 112789fd51e8..fd4e2bd593e4 100644
--- a/arrow-array/src/array/map_array.rs
+++ b/arrow-array/src/array/map_array.rs
@@ -193,7 +193,7 @@ impl MapArray {
]);
let map_data_type = DataType::Map(
- Box::new(Field::new(
+ Arc::new(Field::new(
"entries",
entry_struct.data_type().clone(),
true,
@@ -308,7 +308,7 @@ mod tests {
// Construct a map array from the above two
let map_data_type = DataType::Map(
- Box::new(Field::new(
+ Arc::new(Field::new(
"entries",
entry_struct.data_type().clone(),
true,
@@ -354,7 +354,7 @@ mod tests {
// Construct a map array from the above two
let map_data_type = DataType::Map(
- Box::new(Field::new(
+ Arc::new(Field::new(
"entries",
entry_struct.data_type().clone(),
true,
@@ -483,7 +483,7 @@ mod tests {
// Construct a map array from the above two
let map_data_type = DataType::Map(
- Box::new(Field::new(
+ Arc::new(Field::new(
"entries",
entry_struct.data_type().clone(),
true,
diff --git a/arrow-array/src/array/mod.rs b/arrow-array/src/array/mod.rs
index 9a5172d0deec..ead8b3b99d46 100644
--- a/arrow-array/src/array/mod.rs
+++ b/arrow-array/src/array/mod.rs
@@ -762,7 +762,7 @@ mod tests {
#[test]
fn test_empty_list_primitive() {
let data_type =
- DataType::List(Box::new(Field::new("item", DataType::Int32, false)));
+ DataType::List(Arc::new(Field::new("item", DataType::Int32, false)));
let array = new_empty_array(&data_type);
let a = array.as_any().downcast_ref::<ListArray>().unwrap();
assert_eq!(a.len(), 0);
@@ -822,7 +822,7 @@ mod tests {
#[test]
fn test_null_list_primitive() {
let data_type =
- DataType::List(Box::new(Field::new("item", DataType::Int32, true)));
+ DataType::List(Arc::new(Field::new("item", DataType::Int32, true)));
let array = new_null_array(&data_type, 9);
let a = array.as_any().downcast_ref::<ListArray>().unwrap();
assert_eq!(a.len(), 9);
@@ -835,7 +835,7 @@ mod tests {
#[test]
fn test_null_map() {
let data_type = DataType::Map(
- Box::new(Field::new(
+ Arc::new(Field::new(
"entry",
DataType::Struct(Fields::from(vec![
Field::new("key", DataType::Utf8, false),
@@ -903,8 +903,8 @@ mod tests {
fn test_null_runs() {
for r in [DataType::Int16, DataType::Int32, DataType::Int64] {
let data_type = DataType::RunEndEncoded(
- Box::new(Field::new("run_ends", r, false)),
- Box::new(Field::new("values", DataType::Utf8, true)),
+ Arc::new(Field::new("run_ends", r, false)),
+ Arc::new(Field::new("values", DataType::Utf8, true)),
);
let array = new_null_array(&data_type, 4);
diff --git a/arrow-array/src/array/run_array.rs b/arrow-array/src/array/run_array.rs
index 3cd5848f1f49..c3c5269374f1 100644
--- a/arrow-array/src/array/run_array.rs
+++ b/arrow-array/src/array/run_array.rs
@@ -98,8 +98,8 @@ impl<R: RunEndIndexType> RunArray<R> {
let run_ends_type = run_ends.data_type().clone();
let values_type = values.data_type().clone();
let ree_array_type = DataType::RunEndEncoded(
- Box::new(Field::new("run_ends", run_ends_type, false)),
- Box::new(Field::new("values", values_type, true)),
+ Arc::new(Field::new("run_ends", run_ends_type, false)),
+ Arc::new(Field::new("values", values_type, true)),
);
let len = RunArray::logical_len(run_ends);
let builder = ArrayDataBuilder::new(ree_array_type)
diff --git a/arrow-array/src/array/string_array.rs b/arrow-array/src/array/string_array.rs
index 2ff1118bc798..f339a616f300 100644
--- a/arrow-array/src/array/string_array.rs
+++ b/arrow-array/src/array/string_array.rs
@@ -263,6 +263,7 @@ mod tests {
use crate::types::UInt8Type;
use arrow_buffer::Buffer;
use arrow_schema::Field;
+ use std::sync::Arc;
#[test]
fn test_string_array_from_u8_slice() {
@@ -548,7 +549,7 @@ mod tests {
let offsets = [0, 5, 8, 15].map(|n| O::from_usize(n).unwrap());
let null_buffer = Buffer::from_slice_ref([0b101]);
- let data_type = GenericListArray::<O>::DATA_TYPE_CONSTRUCTOR(Box::new(
+ let data_type = GenericListArray::<O>::DATA_TYPE_CONSTRUCTOR(Arc::new(
Field::new("item", DataType::UInt8, false),
));
@@ -596,7 +597,7 @@ mod tests {
// It is possible to create a null struct containing a non-nullable child
// see https://github.com/apache/arrow-rs/pull/3244 for details
- let data_type = GenericListArray::<O>::DATA_TYPE_CONSTRUCTOR(Box::new(
+ let data_type = GenericListArray::<O>::DATA_TYPE_CONSTRUCTOR(Arc::new(
Field::new("item", DataType::UInt8, true),
));
@@ -632,7 +633,7 @@ mod tests {
.unwrap();
let offsets = [0, 2, 3].map(|n| O::from_usize(n).unwrap());
- let data_type = GenericListArray::<O>::DATA_TYPE_CONSTRUCTOR(Box::new(
+ let data_type = GenericListArray::<O>::DATA_TYPE_CONSTRUCTOR(Arc::new(
Field::new("item", DataType::UInt16, false),
));
diff --git a/arrow-array/src/builder/fixed_size_list_builder.rs b/arrow-array/src/builder/fixed_size_list_builder.rs
index f8cd5d15f852..57af768447c8 100644
--- a/arrow-array/src/builder/fixed_size_list_builder.rs
+++ b/arrow-array/src/builder/fixed_size_list_builder.rs
@@ -169,7 +169,7 @@ where
let null_bit_buffer = self.null_buffer_builder.finish();
let array_data = ArrayData::builder(DataType::FixedSizeList(
- Box::new(Field::new("item", values_data.data_type().clone(), true)),
+ Arc::new(Field::new("item", values_data.data_type().clone(), true)),
self.list_len,
))
.len(len)
@@ -200,7 +200,7 @@ where
.as_slice()
.map(Buffer::from_slice_ref);
let array_data = ArrayData::builder(DataType::FixedSizeList(
- Box::new(Field::new("item", values_data.data_type().clone(), true)),
+ Arc::new(Field::new("item", values_data.data_type().clone(), true)),
self.list_len,
))
.len(len)
diff --git a/arrow-array/src/builder/generic_list_builder.rs b/arrow-array/src/builder/generic_list_builder.rs
index 719070356a6f..5f726a5b121c 100644
--- a/arrow-array/src/builder/generic_list_builder.rs
+++ b/arrow-array/src/builder/generic_list_builder.rs
@@ -233,7 +233,7 @@ where
let offset_buffer = self.offsets_builder.finish();
let null_bit_buffer = self.null_buffer_builder.finish();
self.offsets_builder.append(OffsetSize::zero());
- let field = Box::new(Field::new(
+ let field = Arc::new(Field::new(
"item",
values_data.data_type().clone(),
true, // TODO: find a consistent way of getting this
@@ -261,7 +261,7 @@ where
.null_buffer_builder
.as_slice()
.map(Buffer::from_slice_ref);
- let field = Box::new(Field::new(
+ let field = Arc::new(Field::new(
"item",
values_data.data_type().clone(),
true, // TODO: find a consistent way of getting this
diff --git a/arrow-array/src/builder/map_builder.rs b/arrow-array/src/builder/map_builder.rs
index cb6cd907c77a..72fa1bb919fb 100644
--- a/arrow-array/src/builder/map_builder.rs
+++ b/arrow-array/src/builder/map_builder.rs
@@ -195,7 +195,7 @@ impl<K: ArrayBuilder, V: ArrayBuilder> MapBuilder<K, V> {
let struct_array =
StructArray::from(vec![(keys_field, keys_arr), (values_field, values_arr)]);
- let map_field = Box::new(Field::new(
+ let map_field = Arc::new(Field::new(
self.field_names.entry.as_str(),
struct_array.data_type().clone(),
false, // always non-nullable
diff --git a/arrow-array/src/builder/mod.rs b/arrow-array/src/builder/mod.rs
index 41a4d92b0219..b0c0a49886d8 100644
--- a/arrow-array/src/builder/mod.rs
+++ b/arrow-array/src/builder/mod.rs
@@ -121,7 +121,7 @@
//! let string_field = Field::new("i32", DataType::Utf8, false);
//!
//! let i32_list = Arc::new(self.i32_list.finish()) as ArrayRef;
-//! let value_field = Box::new(Field::new("item", DataType::Int32, true));
+//! let value_field = Arc::new(Field::new("item", DataType::Int32, true));
//! let i32_list_field = Field::new("i32_list", DataType::List(value_field), true);
//!
//! StructArray::from(vec![
diff --git a/arrow-array/src/builder/struct_builder.rs b/arrow-array/src/builder/struct_builder.rs
index 7371df3b021c..499ae183f3e9 100644
--- a/arrow-array/src/builder/struct_builder.rs
+++ b/arrow-array/src/builder/struct_builder.rs
@@ -529,7 +529,7 @@ mod tests {
)]
fn test_struct_array_builder_from_schema_unsupported_type() {
let list_type =
- DataType::List(Box::new(Field::new("item", DataType::Int64, true)));
+ DataType::List(Arc::new(Field::new("item", DataType::Int64, true)));
let fields = vec![
Field::new("f1", DataType::Int16, false),
Field::new("f2", list_type, false),
diff --git a/arrow-array/src/cast.rs b/arrow-array/src/cast.rs
index a39ff88c6bcd..feb9167b2981 100644
--- a/arrow-array/src/cast.rs
+++ b/arrow-array/src/cast.rs
@@ -99,6 +99,7 @@ macro_rules! downcast_integer {
/// `m` with the corresponding integer [`RunEndIndexType`], followed by any additional arguments
///
/// ```
+/// # use std::sync::Arc;
/// # use arrow_array::{downcast_primitive, ArrowPrimitiveType, downcast_run_end_index};
/// # use arrow_schema::{DataType, Field};
///
@@ -118,9 +119,9 @@ macro_rules! downcast_integer {
/// }
/// }
///
-/// assert_eq!(run_end_index_size(&DataType::RunEndEncoded(Box::new(Field::new("a", DataType::Int32, false)), Box::new(Field::new("b", DataType::Utf8, true)))), 4);
-/// assert_eq!(run_end_index_size(&DataType::RunEndEncoded(Box::new(Field::new("a", DataType::Int64, false)), Box::new(Field::new("b", DataType::Utf8, true)))), 8);
-/// assert_eq!(run_end_index_size(&DataType::RunEndEncoded(Box::new(Field::new("a", DataType::Int16, false)), Box::new(Field::new("b", DataType::Utf8, true)))), 2);
+/// assert_eq!(run_end_index_size(&DataType::RunEndEncoded(Arc::new(Field::new("a", DataType::Int32, false)), Arc::new(Field::new("b", DataType::Utf8, true)))), 4);
+/// assert_eq!(run_end_index_size(&DataType::RunEndEncoded(Arc::new(Field::new("a", DataType::Int64, false)), Arc::new(Field::new("b", DataType::Utf8, true)))), 8);
+/// assert_eq!(run_end_index_size(&DataType::RunEndEncoded(Arc::new(Field::new("a", DataType::Int16, false)), Arc::new(Field::new("b", DataType::Utf8, true)))), 2);
/// ```
///
/// [`DataType`]: arrow_schema::DataType
diff --git a/arrow-array/src/record_batch.rs b/arrow-array/src/record_batch.rs
index 17b1f04e80af..8d4d04f0f525 100644
--- a/arrow-array/src/record_batch.rs
+++ b/arrow-array/src/record_batch.rs
@@ -712,7 +712,7 @@ mod tests {
Field::new("a1", DataType::Int32, false),
Field::new(
"a2",
- DataType::List(Box::new(Field::new("item", DataType::Int8, false))),
+ DataType::List(Arc::new(Field::new("item", DataType::Int8, false))),
false,
),
];
@@ -721,7 +721,7 @@ mod tests {
let a1: ArrayRef = Arc::new(Int32Array::from(vec![1, 2]));
let a2_child = Int8Array::from(vec![1, 2, 3, 4]);
- let a2 = ArrayDataBuilder::new(DataType::List(Box::new(Field::new(
+ let a2 = ArrayDataBuilder::new(DataType::List(Arc::new(Field::new(
"array",
DataType::Int8,
false,
diff --git a/arrow-cast/src/cast.rs b/arrow-cast/src/cast.rs
index d14c8d2fa4ba..02b87e73114c 100644
--- a/arrow-cast/src/cast.rs
+++ b/arrow-cast/src/cast.rs
@@ -4667,7 +4667,7 @@ mod tests {
let array = Int32Array::from(vec![5, 6, 7, 8, 9]);
let b = cast(
&array,
- &DataType::List(Box::new(Field::new("item", DataType::Int32, true))),
+ &DataType::List(Arc::new(Field::new("item", DataType::Int32, true))),
)
.unwrap();
assert_eq!(5, b.len());
@@ -4691,7 +4691,7 @@ mod tests {
let array = Int32Array::from(vec![Some(5), None, Some(7), Some(8), Some(9)]);
let b = cast(
&array,
- &DataType::List(Box::new(Field::new("item", DataType::Int32, true))),
+ &DataType::List(Arc::new(Field::new("item", DataType::Int32, true))),
)
.unwrap();
assert_eq!(5, b.len());
@@ -4720,7 +4720,7 @@ mod tests {
let array = array.slice(2, 4);
let b = cast(
&array,
- &DataType::List(Box::new(Field::new("item", DataType::Float64, true))),
+ &DataType::List(Arc::new(Field::new("item", DataType::Float64, true))),
)
.unwrap();
assert_eq!(4, b.len());
@@ -4833,7 +4833,7 @@ mod tests {
// Construct a list array from the above two
// [[0,0,0], [-1, -2, -1], [2, 100000000]]
let list_data_type =
- DataType::List(Box::new(Field::new("item", DataType::Int32, true)));
+ DataType::List(Arc::new(Field::new("item", DataType::Int32, true)));
let list_data = ArrayData::builder(list_data_type)
.len(3)
.add_buffer(value_offsets)
@@ -4844,7 +4844,7 @@ mod tests {
let cast_array = cast(
&list_array,
- &DataType::List(Box::new(Field::new("item", DataType::UInt16, true))),
+ &DataType::List(Arc::new(Field::new("item", DataType::UInt16, true))),
)
.unwrap();
@@ -4896,7 +4896,7 @@ mod tests {
// Construct a list array from the above two
let list_data_type =
- DataType::List(Box::new(Field::new("item", DataType::Int32, true)));
+ DataType::List(Arc::new(Field::new("item", DataType::Int32, true)));
let list_data = ArrayData::builder(list_data_type)
.len(3)
.add_buffer(value_offsets)
@@ -4907,7 +4907,7 @@ mod tests {
cast(
&list_array,
- &DataType::List(Box::new(Field::new(
+ &DataType::List(Arc::new(Field::new(
"item",
DataType::Timestamp(TimeUnit::Microsecond, None),
true,
@@ -7104,7 +7104,7 @@ mod tests {
fn test_cast_null_from_and_to_nested_type() {
// Cast null from and to map
let data_type = DataType::Map(
- Box::new(Field::new(
+ Arc::new(Field::new(
"entry",
DataType::Struct(Fields::from(vec![
Field::new("key", DataType::Utf8, false),
@@ -7118,13 +7118,13 @@ mod tests {
// Cast null from and to list
let data_type =
- DataType::List(Box::new(Field::new("item", DataType::Int32, true)));
+ DataType::List(Arc::new(Field::new("item", DataType::Int32, true)));
cast_from_null_to_other(&data_type);
let data_type =
- DataType::LargeList(Box::new(Field::new("item", DataType::Int32, true)));
+ DataType::LargeList(Arc::new(Field::new("item", DataType::Int32, true)));
cast_from_null_to_other(&data_type);
let data_type = DataType::FixedSizeList(
- Box::new(Field::new("item", DataType::Int32, true)),
+ Arc::new(Field::new("item", DataType::Int32, true)),
4,
);
cast_from_null_to_other(&data_type);
@@ -7229,7 +7229,7 @@ mod tests {
let array = Arc::new(make_large_list_array()) as ArrayRef;
let list_array = cast(
&array,
- &DataType::List(Box::new(Field::new("", DataType::Int32, false))),
+ &DataType::List(Arc::new(Field::new("", DataType::Int32, false))),
)
.unwrap();
let actual = list_array.as_any().downcast_ref::<ListArray>().unwrap();
@@ -7243,7 +7243,7 @@ mod tests {
let array = Arc::new(make_list_array()) as ArrayRef;
let large_list_array = cast(
&array,
- &DataType::LargeList(Box::new(Field::new("", DataType::Int32, false))),
+ &DataType::LargeList(Arc::new(Field::new("", DataType::Int32, false))),
)
.unwrap();
let actual = large_list_array
@@ -7271,7 +7271,7 @@ mod tests {
// Construct a list array from the above two
let list_data_type =
- DataType::List(Box::new(Field::new("item", DataType::Int32, true)));
+ DataType::List(Arc::new(Field::new("item", DataType::Int32, true)));
let list_data = ArrayData::builder(list_data_type)
.len(3)
.add_buffer(value_offsets)
@@ -7295,7 +7295,7 @@ mod tests {
// Construct a list array from the above two
let list_data_type =
- DataType::LargeList(Box::new(Field::new("item", DataType::Int32, true)));
+ DataType::LargeList(Arc::new(Field::new("item", DataType::Int32, true)));
let list_data = ArrayData::builder(list_data_type)
.len(3)
.add_buffer(value_offsets)
@@ -7324,7 +7324,7 @@ mod tests {
let array1 = make_list_array().slice(1, 2);
let array2 = Arc::new(make_list_array()) as ArrayRef;
- let dt = DataType::LargeList(Box::new(Field::new("item", DataType::Int32, true)));
+ let dt = DataType::LargeList(Arc::new(Field::new("item", DataType::Int32, true)));
let out1 = cast(&array1, &dt).unwrap();
let out2 = cast(&array2, &dt).unwrap();
@@ -7342,7 +7342,7 @@ mod tests {
.unwrap();
let list_data_type =
- DataType::List(Box::new(Field::new("item", DataType::Utf8, true)));
+ DataType::List(Arc::new(Field::new("item", DataType::Utf8, true)));
let list_data = ArrayData::builder(list_data_type)
.len(3)
.add_buffer(value_offsets)
diff --git a/arrow-cast/src/pretty.rs b/arrow-cast/src/pretty.rs
index 818e9d3c0770..7aa04a2dbcb3 100644
--- a/arrow-cast/src/pretty.rs
+++ b/arrow-cast/src/pretty.rs
@@ -291,7 +291,7 @@ mod tests {
fn test_pretty_format_fixed_size_list() {
// define a schema.
let field_type = DataType::FixedSizeList(
- Box::new(Field::new("item", DataType::Int32, true)),
+ Arc::new(Field::new("item", DataType::Int32, true)),
3,
);
let schema = Arc::new(Schema::new(vec![Field::new("d1", field_type, true)]));
diff --git a/arrow-data/src/transform/mod.rs b/arrow-data/src/transform/mod.rs
index ccdbaec3b5ea..52ce5ead725c 100644
--- a/arrow-data/src/transform/mod.rs
+++ b/arrow-data/src/transform/mod.rs
@@ -669,10 +669,11 @@ impl<'a> MutableArrayData<'a> {
mod test {
use super::*;
use arrow_schema::Field;
+ use std::sync::Arc;
#[test]
fn test_list_append_with_capacities() {
- let array = ArrayData::new_empty(&DataType::List(Box::new(Field::new(
+ let array = ArrayData::new_empty(&DataType::List(Arc::new(Field::new(
"element",
DataType::Int64,
false,
diff --git a/arrow-ipc/src/convert.rs b/arrow-ipc/src/convert.rs
index 8ca0d514f462..334b9f65627b 100644
--- a/arrow-ipc/src/convert.rs
+++ b/arrow-ipc/src/convert.rs
@@ -22,6 +22,7 @@ use flatbuffers::{
FlatBufferBuilder, ForwardsUOffset, UnionWIPOffset, Vector, WIPOffset,
};
use std::collections::HashMap;
+use std::sync::Arc;
use crate::{size_prefixed_root_as_message, CONTINUATION_MARKER};
use DataType::*;
@@ -337,14 +338,14 @@ pub(crate) fn get_data_type(field: crate::Field, may_be_dictionary: bool) -> Dat
if children.len() != 1 {
panic!("expect a list to have one child")
}
- DataType::List(Box::new(children.get(0).into()))
+ DataType::List(Arc::new(children.get(0).into()))
}
crate::Type::LargeList => {
let children = field.children().unwrap();
if children.len() != 1 {
panic!("expect a large list to have one child")
}
- DataType::LargeList(Box::new(children.get(0).into()))
+ DataType::LargeList(Arc::new(children.get(0).into()))
}
crate::Type::FixedSizeList => {
let children = field.children().unwrap();
@@ -352,7 +353,7 @@ pub(crate) fn get_data_type(field: crate::Field, may_be_dictionary: bool) -> Dat
panic!("expect a list to have one child")
}
let fsl = field.type_as_fixed_size_list().unwrap();
- DataType::FixedSizeList(Box::new(children.get(0).into()), fsl.listSize())
+ DataType::FixedSizeList(Arc::new(children.get(0).into()), fsl.listSize())
}
crate::Type::Struct_ => {
let fields = match field.children() {
@@ -371,7 +372,7 @@ pub(crate) fn get_data_type(field: crate::Field, may_be_dictionary: bool) -> Dat
}
let run_ends_field = children.get(0).into();
let values_field = children.get(1).into();
- DataType::RunEndEncoded(Box::new(run_ends_field), Box::new(values_field))
+ DataType::RunEndEncoded(Arc::new(run_ends_field), Arc::new(values_field))
}
crate::Type::Map => {
let map = field.type_as_map().unwrap();
@@ -379,7 +380,7 @@ pub(crate) fn get_data_type(field: crate::Field, may_be_dictionary: bool) -> Dat
if children.len() != 1 {
panic!("expect a map to have one child")
}
- DataType::Map(Box::new(children.get(0).into()), map.keysSorted())
+ DataType::Map(Arc::new(children.get(0).into()), map.keysSorted())
}
crate::Type::Decimal => {
let fsb = field.type_as_decimal().unwrap();
@@ -907,12 +908,12 @@ mod tests {
Field::new("binary", DataType::Binary, false),
Field::new(
"list[u8]",
- DataType::List(Box::new(Field::new("item", DataType::UInt8, false))),
+ DataType::List(Arc::new(Field::new("item", DataType::UInt8, false))),
true,
),
Field::new(
"list[struct<float32, int32, bool>]",
- List(Box::new(Field::new(
+ List(Arc::new(Field::new(
"struct",
Struct(Fields::from(vec![
Field::new("float32", DataType::UInt8, false),
@@ -938,13 +939,13 @@ mod tests {
Field::new("int64", DataType::Int64, true),
Field::new(
"list[struct<date32, list[struct<>]>]",
- DataType::List(Box::new(Field::new(
+ DataType::List(Arc::new(Field::new(
"struct",
DataType::Struct(Fields::from(vec![
Field::new("date32", DataType::Date32, true),
Field::new(
"list[struct<>]",
- DataType::List(Box::new(Field::new(
+ DataType::List(Arc::new(Field::new(
"struct",
DataType::Struct(Fields::empty()),
false,
@@ -968,7 +969,7 @@ mod tests {
Field::new("int64", DataType::Int64, true),
Field::new(
"list[union<date32, list[union<>]>]",
- DataType::List(Box::new(Field::new(
+ DataType::List(Arc::new(Field::new(
"union<date32, list[union<>]>",
DataType::Union(
UnionFields::new(
@@ -981,7 +982,7 @@ mod tests {
),
Field::new(
"list[union<>]",
- DataType::List(Box::new(
+ DataType::List(Arc::new(
Field::new(
"union",
DataType::Union(
diff --git a/arrow-ipc/src/reader.rs b/arrow-ipc/src/reader.rs
index 4f2e51336e34..c20f7bd012fb 100644
--- a/arrow-ipc/src/reader.rs
+++ b/arrow-ipc/src/reader.rs
@@ -1254,10 +1254,10 @@ mod tests {
fn create_test_projection_schema() -> Schema {
// define field types
let list_data_type =
- DataType::List(Box::new(Field::new("item", DataType::Int32, true)));
+ DataType::List(Arc::new(Field::new("item", DataType::Int32, true)));
let fixed_size_list_data_type = DataType::FixedSizeList(
- Box::new(Field::new("item", DataType::Int32, false)),
+ Arc::new(Field::new("item", DataType::Int32, false)),
3,
);
@@ -1280,15 +1280,15 @@ mod tests {
Field::new("id", DataType::Int32, false),
Field::new(
"list",
- DataType::List(Box::new(Field::new("item", DataType::Int8, true))),
+ DataType::List(Arc::new(Field::new("item", DataType::Int8, true))),
false,
),
]);
let struct_data_type = DataType::Struct(struct_fields);
let run_encoded_data_type = DataType::RunEndEncoded(
- Box::new(Field::new("run_ends", DataType::Int16, false)),
- Box::new(Field::new("values", DataType::Int32, true)),
+ Arc::new(Field::new("run_ends", DataType::Int16, false)),
+ Arc::new(Field::new("values", DataType::Int32, true)),
);
// define schema
@@ -1691,7 +1691,7 @@ mod tests {
(values_field, make_array(value_dict_array.into_data())),
]);
let map_data_type = DataType::Map(
- Box::new(Field::new(
+ Arc::new(Field::new(
"entries",
entry_struct.data_type().clone(),
true,
@@ -1763,7 +1763,7 @@ mod tests {
#[test]
fn test_roundtrip_stream_dict_of_list_of_dict() {
// list
- let list_data_type = DataType::List(Box::new(Field::new_dict(
+ let list_data_type = DataType::List(Arc::new(Field::new_dict(
"item",
DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Utf8)),
true,
@@ -1777,7 +1777,7 @@ mod tests {
);
// large list
- let list_data_type = DataType::LargeList(Box::new(Field::new_dict(
+ let list_data_type = DataType::LargeList(Arc::new(Field::new_dict(
"item",
DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Utf8)),
true,
@@ -1799,7 +1799,7 @@ mod tests {
let dict_data = dict_array.data();
let list_data_type = DataType::FixedSizeList(
- Box::new(Field::new_dict(
+ Arc::new(Field::new_dict(
"item",
DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Utf8)),
true,
diff --git a/arrow-json/src/raw/mod.rs b/arrow-json/src/raw/mod.rs
index a567b93c9d0f..c784bd347b4b 100644
--- a/arrow-json/src/raw/mod.rs
+++ b/arrow-json/src/raw/mod.rs
@@ -505,7 +505,7 @@ mod tests {
let schema = Arc::new(Schema::new(vec![
Field::new(
"list",
- DataType::List(Box::new(Field::new("element", DataType::Int32, false))),
+ DataType::List(Arc::new(Field::new("element", DataType::Int32, false))),
true,
),
Field::new(
@@ -520,7 +520,7 @@ mod tests {
"nested_list",
DataType::Struct(Fields::from(vec![Field::new(
"list2",
- DataType::List(Box::new(Field::new(
+ DataType::List(Arc::new(Field::new(
"element",
DataType::Struct(
vec![Field::new("c", DataType::Int32, false)].into(),
@@ -591,7 +591,7 @@ mod tests {
"nested_list",
DataType::Struct(Fields::from(vec![Field::new(
"list2",
- DataType::List(Box::new(Field::new(
+ DataType::List(Arc::new(Field::new(
"element",
DataType::Struct(
vec![Field::new("d", DataType::Int32, true)].into(),
@@ -639,13 +639,13 @@ mod tests {
{"map": {"a": [null], "b": []}}
{"map": {"c": null, "a": ["baz"]}}
"#;
- let list = DataType::List(Box::new(Field::new("element", DataType::Utf8, true)));
+ let list = DataType::List(Arc::new(Field::new("element", DataType::Utf8, true)));
let entries = DataType::Struct(Fields::from(vec![
Field::new("key", DataType::Utf8, false),
Field::new("value", list, true),
]));
- let map = DataType::Map(Box::new(Field::new("entries", entries, true)), false);
+ let map = DataType::Map(Arc::new(Field::new("entries", entries, true)), false);
let schema = Arc::new(Schema::new(vec![Field::new("map", map, true)]));
let batches = do_read(buf, 1024, false, schema);
@@ -1023,7 +1023,7 @@ mod tests {
DataType::Struct(Fields::from(vec![Field::new(
"partitionValues",
DataType::Map(
- Box::new(Field::new(
+ Arc::new(Field::new(
"key_value",
DataType::Struct(Fields::from(vec![
Field::new("key", DataType::Utf8, false),
diff --git a/arrow-json/src/reader.rs b/arrow-json/src/reader.rs
index c95f7c0be812..df6b998bee04 100644
--- a/arrow-json/src/reader.rs
+++ b/arrow-json/src/reader.rs
@@ -129,14 +129,14 @@ fn coerce_data_type(dt: Vec<&DataType>) -> DataType {
(DataType::Float64, DataType::Float64)
| (DataType::Float64, DataType::Int64)
| (DataType::Int64, DataType::Float64) => DataType::Float64,
- (DataType::List(l), DataType::List(r)) => DataType::List(Box::new(Field::new(
+ (DataType::List(l), DataType::List(r)) => DataType::List(Arc::new(Field::new(
"item",
coerce_data_type(vec![l.data_type(), r.data_type()]),
true,
))),
// coerce scalar and scalar array into scalar array
(DataType::List(e), not_list) | (not_list, DataType::List(e)) => {
- DataType::List(Box::new(Field::new(
+ DataType::List(Arc::new(Field::new(
"item",
coerce_data_type(vec![e.data_type(), ¬_list]),
true,
@@ -150,7 +150,7 @@ fn generate_datatype(t: &InferredType) -> Result<DataType, ArrowError> {
Ok(match t {
InferredType::Scalar(hs) => coerce_data_type(hs.iter().collect()),
InferredType::Object(spec) => DataType::Struct(generate_fields(spec)?),
- InferredType::Array(ele_type) => DataType::List(Box::new(Field::new(
+ InferredType::Array(ele_type) => DataType::List(Arc::new(Field::new(
"item",
generate_datatype(ele_type)?,
true,
@@ -1087,7 +1087,7 @@ impl Decoder {
fn build_nested_list_array<OffsetSize: OffsetSizeTrait>(
&self,
rows: &[Value],
- list_field: &Field,
+ list_field: &FieldRef,
) -> Result<ArrayRef, ArrowError> {
// build list offsets
let mut cur_offset = OffsetSize::zero();
@@ -1231,7 +1231,7 @@ impl Decoder {
}
};
// build list
- let list_data = ArrayData::builder(DataType::List(Box::new(list_field.clone())))
+ let list_data = ArrayData::builder(DataType::List(list_field.clone()))
.len(list_len)
.add_buffer(Buffer::from_slice_ref(&offsets))
.add_child_data(array_data)
@@ -2112,12 +2112,12 @@ mod tests {
assert_eq!(&DataType::Int64, a.1.data_type());
let b = schema.column_with_name("b").unwrap();
assert_eq!(
- &DataType::List(Box::new(Field::new("item", DataType::Float64, true))),
+ &DataType::List(Arc::new(Field::new("item", DataType::Float64, true))),
b.1.data_type()
);
let c = schema.column_with_name("c").unwrap();
assert_eq!(
- &DataType::List(Box::new(Field::new("item", DataType::Boolean, true))),
+ &DataType::List(Arc::new(Field::new("item", DataType::Boolean, true))),
c.1.data_type()
);
let d = schema.column_with_name("d").unwrap();
@@ -2176,32 +2176,32 @@ mod tests {
use arrow_schema::DataType::*;
assert_eq!(
- List(Box::new(Field::new("item", Float64, true))),
+ List(Arc::new(Field::new("item", Float64, true))),
coerce_data_type(vec![
&Float64,
- &List(Box::new(Field::new("item", Float64, true)))
+ &List(Arc::new(Field::new("item", Float64, true)))
])
);
assert_eq!(
- List(Box::new(Field::new("item", Float64, true))),
+ List(Arc::new(Field::new("item", Float64, true))),
coerce_data_type(vec![
&Float64,
- &List(Box::new(Field::new("item", Int64, true)))
+ &List(Arc::new(Field::new("item", Int64, true)))
])
);
assert_eq!(
- List(Box::new(Field::new("item", Int64, true))),
+ List(Arc::new(Field::new("item", Int64, true))),
coerce_data_type(vec![
&Int64,
- &List(Box::new(Field::new("item", Int64, true)))
+ &List(Arc::new(Field::new("item", Int64, true)))
])
);
// boolean and number are incompatible, return utf8
assert_eq!(
- List(Box::new(Field::new("item", Utf8, true))),
+ List(Arc::new(Field::new("item", Utf8, true))),
coerce_data_type(vec![
&Boolean,
- &List(Box::new(Field::new("item", Float64, true)))
+ &List(Arc::new(Field::new("item", Float64, true)))
])
);
}
@@ -2234,17 +2234,17 @@ mod tests {
assert_eq!(&DataType::Int64, a.1.data_type());
let b = schema.column_with_name("b").unwrap();
assert_eq!(
- &DataType::List(Box::new(Field::new("item", DataType::Float64, true))),
+ &DataType::List(Arc::new(Field::new("item", DataType::Float64, true))),
b.1.data_type()
);
let c = schema.column_with_name("c").unwrap();
assert_eq!(
- &DataType::List(Box::new(Field::new("item", DataType::Boolean, true))),
+ &DataType::List(Arc::new(Field::new("item", DataType::Boolean, true))),
c.1.data_type()
);
let d = schema.column_with_name("d").unwrap();
assert_eq!(
- &DataType::List(Box::new(Field::new("item", DataType::Utf8, true))),
+ &DataType::List(Arc::new(Field::new("item", DataType::Utf8, true))),
d.1.data_type()
);
@@ -2366,7 +2366,7 @@ mod tests {
true,
);
let a_field =
- Field::new("a", DataType::List(Box::new(a_struct_field.clone())), true);
+ Field::new("a", DataType::List(Arc::new(a_struct_field.clone())), true);
let schema = Arc::new(Schema::new(vec![a_field.clone()]));
let builder = ReaderBuilder::new().with_schema(schema).with_batch_size(64);
let json_content = r#"
@@ -2459,7 +2459,7 @@ mod tests {
fn test_map_json_arrays() {
let account_field = Field::new("account", DataType::UInt16, false);
let value_list_type =
- DataType::List(Box::new(Field::new("item", DataType::Utf8, false)));
+ DataType::List(Arc::new(Field::new("item", DataType::Utf8, false)));
let entries_struct_type = DataType::Struct(Fields::from(vec![
Field::new("key", DataType::Utf8, false),
Field::new("value", value_list_type.clone(), true),
@@ -2467,7 +2467,7 @@ mod tests {
let stocks_field = Field::new(
"stocks",
DataType::Map(
- Box::new(Field::new("entries", entries_struct_type.clone(), false)),
+ Arc::new(Field::new("entries", entries_struct_type.clone(), false)),
false,
),
true,
@@ -2712,7 +2712,7 @@ mod tests {
fn test_list_of_string_dictionary_from_json() {
let schema = Schema::new(vec![Field::new(
"events",
- List(Box::new(Field::new(
+ List(Arc::new(Field::new(
"item",
Dictionary(Box::new(DataType::UInt64), Box::new(DataType::Utf8)),
true,
@@ -2736,7 +2736,7 @@ mod tests {
let events = schema.column_with_name("events").unwrap();
assert_eq!(
- &List(Box::new(Field::new(
+ &List(Arc::new(Field::new(
"item",
Dictionary(Box::new(DataType::UInt64), Box::new(DataType::Utf8)),
true
@@ -2766,7 +2766,7 @@ mod tests {
fn test_list_of_string_dictionary_from_json_with_nulls() {
let schema = Schema::new(vec![Field::new(
"events",
- List(Box::new(Field::new(
+ List(Arc::new(Field::new(
"item",
Dictionary(Box::new(DataType::UInt64), Box::new(DataType::Utf8)),
true,
@@ -2792,7 +2792,7 @@ mod tests {
let events = schema.column_with_name("events").unwrap();
assert_eq!(
- &List(Box::new(Field::new(
+ &List(Arc::new(Field::new(
"item",
Dictionary(Box::new(DataType::UInt64), Box::new(DataType::Utf8)),
true
@@ -2930,17 +2930,17 @@ mod tests {
Field::new("a", DataType::Int64, true),
Field::new(
"b",
- DataType::List(Box::new(Field::new("item", DataType::Float64, true))),
+ DataType::List(Arc::new(Field::new("item", DataType::Float64, true))),
true,
),
Field::new(
"c",
- DataType::List(Box::new(Field::new("item", DataType::Boolean, true))),
+ DataType::List(Arc::new(Field::new("item", DataType::Boolean, true))),
true,
),
Field::new(
"d",
- DataType::List(Box::new(Field::new("item", DataType::Utf8, true))),
+ DataType::List(Arc::new(Field::new("item", DataType::Utf8, true))),
true,
),
]);
@@ -2997,7 +2997,7 @@ mod tests {
let schema = Schema::new(vec![
Field::new(
"c1",
- DataType::List(Box::new(Field::new(
+ DataType::List(Arc::new(Field::new(
"item",
DataType::Struct(Fields::from(vec![
Field::new("a", DataType::Utf8, true),
@@ -3012,7 +3012,7 @@ mod tests {
Field::new(
"c3",
// empty json array's inner types are inferred as null
- DataType::List(Box::new(Field::new("item", DataType::Null, true))),
+ DataType::List(Arc::new(Field::new("item", DataType::Null, true))),
true,
),
]);
@@ -3039,9 +3039,9 @@ mod tests {
let schema = Schema::new(vec![
Field::new(
"c1",
- DataType::List(Box::new(Field::new(
+ DataType::List(Arc::new(Field::new(
"item",
- DataType::List(Box::new(Field::new("item", DataType::Utf8, true))),
+ DataType::List(Arc::new(Field::new("item", DataType::Utf8, true))),
true,
))),
true,
@@ -3263,9 +3263,9 @@ mod tests {
fn test_json_read_nested_list() {
let schema = Schema::new(vec![Field::new(
"c1",
- DataType::List(Box::new(Field::new(
+ DataType::List(Arc::new(Field::new(
"item",
- DataType::List(Box::new(Field::new("item", DataType::Utf8, true))),
+ DataType::List(Arc::new(Field::new("item", DataType::Utf8, true))),
true,
))),
true,
@@ -3298,7 +3298,7 @@ mod tests {
fn test_json_read_list_of_structs() {
let schema = Schema::new(vec![Field::new(
"c1",
- DataType::List(Box::new(Field::new(
+ DataType::List(Arc::new(Field::new(
"item",
DataType::Struct(vec![Field::new("a", DataType::Int64, true)].into()),
true,
diff --git a/arrow-json/src/writer.rs b/arrow-json/src/writer.rs
index 534aea91af4e..d3ac46c937b8 100644
--- a/arrow-json/src/writer.rs
+++ b/arrow-json/src/writer.rs
@@ -1057,7 +1057,7 @@ mod tests {
fn write_struct_with_list_field() {
let field_c1 = Field::new(
"c1",
- DataType::List(Box::new(Field::new("c_list", DataType::Utf8, false))),
+ DataType::List(Arc::new(Field::new("c_list", DataType::Utf8, false))),
false,
);
let field_c2 = Field::new("c2", DataType::Int32, false);
@@ -1102,12 +1102,12 @@ mod tests {
fn write_nested_list() {
let list_inner_type = Field::new(
"a",
- DataType::List(Box::new(Field::new("b", DataType::Int32, false))),
+ DataType::List(Arc::new(Field::new("b", DataType::Int32, false))),
false,
);
let field_c1 = Field::new(
"c1",
- DataType::List(Box::new(list_inner_type.clone())),
+ DataType::List(Arc::new(list_inner_type.clone())),
false,
);
let field_c2 = Field::new("c2", DataType::Utf8, true);
@@ -1160,7 +1160,7 @@ mod tests {
fn write_list_of_struct() {
let field_c1 = Field::new(
"c1",
- DataType::List(Box::new(Field::new(
+ DataType::List(Arc::new(Field::new(
"s",
DataType::Struct(Fields::from(vec![
Field::new("c11", DataType::Int32, true),
@@ -1325,7 +1325,7 @@ mod tests {
"#;
let ints_struct =
DataType::Struct(vec![Field::new("ints", DataType::Int32, true)].into());
- let list_type = DataType::List(Box::new(Field::new("item", ints_struct, true)));
+ let list_type = DataType::List(Arc::new(Field::new("item", ints_struct, true)));
let list_field = Field::new("list", list_type, true);
let schema = Arc::new(Schema::new(vec![list_field]));
let builder = ReaderBuilder::new().with_schema(schema).with_batch_size(64);
@@ -1379,7 +1379,7 @@ mod tests {
]);
let map_data_type = DataType::Map(
- Box::new(Field::new(
+ Arc::new(Field::new(
"entries",
entry_struct.data_type().clone(),
true,
diff --git a/arrow-ord/src/comparison.rs b/arrow-ord/src/comparison.rs
index 683fd068af40..e68e064c775d 100644
--- a/arrow-ord/src/comparison.rs
+++ b/arrow-ord/src/comparison.rs
@@ -2785,6 +2785,7 @@ mod tests {
};
use arrow_buffer::i256;
use arrow_schema::Field;
+ use std::sync::Arc;
/// Evaluate `KERNEL` with two vectors as inputs and assert against the expected output.
/// `A_VEC` and `B_VEC` can be of type `Vec<T>` or `Vec<Option<T>>` where `T` is the native
@@ -3408,7 +3409,7 @@ mod tests {
.into_data();
let value_offsets = Buffer::from_slice_ref([0i64, 3, 6, 6, 9]);
let list_data_type =
- DataType::LargeList(Box::new(Field::new("item", DataType::Int32, true)));
+ DataType::LargeList(Arc::new(Field::new("item", DataType::Int32, true)));
let list_data = ArrayData::builder(list_data_type)
.len(4)
.add_buffer(value_offsets)
diff --git a/arrow-schema/src/datatype.rs b/arrow-schema/src/datatype.rs
index 57a5c68386fc..3ec5597b2854 100644
--- a/arrow-schema/src/datatype.rs
+++ b/arrow-schema/src/datatype.rs
@@ -18,8 +18,7 @@
use std::fmt;
use std::sync::Arc;
-use crate::field::Field;
-use crate::{Fields, UnionFields};
+use crate::{FieldRef, Fields, UnionFields};
/// The set of datatypes that are supported by this implementation of Apache Arrow.
///
@@ -183,13 +182,13 @@ pub enum DataType {
/// A list of some logical data type with variable length.
///
/// A single List array can store up to [`i32::MAX`] elements in total
- List(Box<Field>),
+ List(FieldRef),
/// A list of some logical data type with fixed length.
- FixedSizeList(Box<Field>, i32),
+ FixedSizeList(FieldRef, i32),
/// A list of some logical data type with variable length and 64-bit offsets.
///
/// A single LargeList array can store up to [`i64::MAX`] elements in total
- LargeList(Box<Field>),
+ LargeList(FieldRef),
/// A nested datatype that contains a number of sub-fields.
Struct(Fields),
/// A nested datatype that can represent slots of differing types. Components:
@@ -249,7 +248,7 @@ pub enum DataType {
/// has two children: key type and the second the value type. The names of the
/// child fields may be respectively "entries", "key", and "value", but this is
/// not enforced.
- Map(Box<Field>, bool),
+ Map(FieldRef, bool),
/// A run-end encoding (REE) is a variation of run-length encoding (RLE). These
/// encodings are well-suited for representing data containing sequences of the
/// same value, called runs. Each run is represented as a value and an integer giving
@@ -261,7 +260,7 @@ pub enum DataType {
///
/// These child arrays are prescribed the standard names of "run_ends" and "values"
/// respectively.
- RunEndEncoded(Box<Field>, Box<Field>),
+ RunEndEncoded(FieldRef, FieldRef),
}
/// An absolute length of time in seconds, milliseconds, microseconds or nanoseconds.
@@ -520,6 +519,7 @@ pub const DECIMAL_DEFAULT_SCALE: i8 = 10;
#[cfg(test)]
mod tests {
use super::*;
+ use crate::Field;
#[test]
#[cfg(feature = "serde")]
@@ -574,21 +574,21 @@ mod tests {
#[test]
fn test_list_datatype_equality() {
// tests that list type equality is checked while ignoring list names
- let list_a = DataType::List(Box::new(Field::new("item", DataType::Int32, true)));
- let list_b = DataType::List(Box::new(Field::new("array", DataType::Int32, true)));
- let list_c = DataType::List(Box::new(Field::new("item", DataType::Int32, false)));
- let list_d = DataType::List(Box::new(Field::new("item", DataType::UInt32, true)));
+ let list_a = DataType::List(Arc::new(Field::new("item", DataType::Int32, true)));
+ let list_b = DataType::List(Arc::new(Field::new("array", DataType::Int32, true)));
+ let list_c = DataType::List(Arc::new(Field::new("item", DataType::Int32, false)));
+ let list_d = DataType::List(Arc::new(Field::new("item", DataType::UInt32, true)));
assert!(list_a.equals_datatype(&list_b));
assert!(!list_a.equals_datatype(&list_c));
assert!(!list_b.equals_datatype(&list_c));
assert!(!list_a.equals_datatype(&list_d));
let list_e =
- DataType::FixedSizeList(Box::new(Field::new("item", list_a, false)), 3);
+ DataType::FixedSizeList(Arc::new(Field::new("item", list_a, false)), 3);
let list_f =
- DataType::FixedSizeList(Box::new(Field::new("array", list_b, false)), 3);
+ DataType::FixedSizeList(Arc::new(Field::new("array", list_b, false)), 3);
let list_g = DataType::FixedSizeList(
- Box::new(Field::new("item", DataType::FixedSizeBinary(3), true)),
+ Arc::new(Field::new("item", DataType::FixedSizeBinary(3), true)),
3,
);
assert!(list_e.equals_datatype(&list_f));
@@ -639,7 +639,7 @@ mod tests {
#[test]
fn test_nested() {
- let list = DataType::List(Box::new(Field::new("foo", DataType::Utf8, true)));
+ let list = DataType::List(Arc::new(Field::new("foo", DataType::Utf8, true)));
assert!(!DataType::is_nested(&DataType::Boolean));
assert!(!DataType::is_nested(&DataType::Int32));
diff --git a/arrow-schema/src/ffi.rs b/arrow-schema/src/ffi.rs
index 72afc5b0bbcb..9078e35b32e3 100644
--- a/arrow-schema/src/ffi.rs
+++ b/arrow-schema/src/ffi.rs
@@ -388,11 +388,11 @@ impl TryFrom<&FFI_ArrowSchema> for DataType {
"tDn" => DataType::Duration(TimeUnit::Nanosecond),
"+l" => {
let c_child = c_schema.child(0);
- DataType::List(Box::new(Field::try_from(c_child)?))
+ DataType::List(Arc::new(Field::try_from(c_child)?))
}
"+L" => {
let c_child = c_schema.child(0);
- DataType::LargeList(Box::new(Field::try_from(c_child)?))
+ DataType::LargeList(Arc::new(Field::try_from(c_child)?))
}
"+s" => {
let fields = c_schema.children().map(Field::try_from);
@@ -401,7 +401,7 @@ impl TryFrom<&FFI_ArrowSchema> for DataType {
"+m" => {
let c_child = c_schema.child(0);
let map_keys_sorted = c_schema.map_keys_sorted();
- DataType::Map(Box::new(Field::try_from(c_child)?), map_keys_sorted)
+ DataType::Map(Arc::new(Field::try_from(c_child)?), map_keys_sorted)
}
// Parametrized types, requiring string parse
other => {
@@ -421,7 +421,7 @@ impl TryFrom<&FFI_ArrowSchema> for DataType {
ArrowError::CDataInterface(
"The FixedSizeList type requires an integer parameter representing number of elements per list".to_string())
})?;
- DataType::FixedSizeList(Box::new(Field::try_from(c_child)?), parsed_num_elems)
+ DataType::FixedSizeList(Arc::new(Field::try_from(c_child)?), parsed_num_elems)
},
// Decimal types in format "d:precision,scale" or "d:precision,scale,bitWidth"
["d", extra] => {
@@ -772,11 +772,11 @@ mod tests {
round_trip_type(DataType::Time64(TimeUnit::Nanosecond));
round_trip_type(DataType::FixedSizeBinary(12));
round_trip_type(DataType::FixedSizeList(
- Box::new(Field::new("a", DataType::Int64, false)),
+ Arc::new(Field::new("a", DataType::Int64, false)),
5,
));
round_trip_type(DataType::Utf8);
- round_trip_type(DataType::List(Box::new(Field::new(
+ round_trip_type(DataType::List(Arc::new(Field::new(
"a",
DataType::Int16,
false,
@@ -828,7 +828,7 @@ mod tests {
// Construct a map array from the above two
let map_data_type =
- DataType::Map(Box::new(Field::new("entries", entry_struct, true)), true);
+ DataType::Map(Arc::new(Field::new("entries", entry_struct, true)), true);
let arrow_schema = FFI_ArrowSchema::try_from(map_data_type).unwrap();
assert!(arrow_schema.map_keys_sorted());
diff --git a/arrow-schema/src/field.rs b/arrow-schema/src/field.rs
index d68392f51f03..ac02eadd6640 100644
--- a/arrow-schema/src/field.rs
+++ b/arrow-schema/src/field.rs
@@ -454,6 +454,7 @@ mod test {
use crate::Fields;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
+ use std::sync::Arc;
#[test]
fn test_new_with_string() {
@@ -502,13 +503,13 @@ mod test {
dict1.clone(),
Field::new(
"list[struct<dict1, list[struct<dict2>]>]",
- DataType::List(Box::new(Field::new(
+ DataType::List(Arc::new(Field::new(
"struct<dict1, list[struct<dict2>]>",
DataType::Struct(Fields::from(vec![
dict1.clone(),
Field::new(
"list[struct<dict2>]",
- DataType::List(Box::new(Field::new(
+ DataType::List(Arc::new(Field::new(
"struct<dict2>",
DataType::Struct(vec![dict2.clone()].into()),
false,
diff --git a/arrow-select/src/filter.rs b/arrow-select/src/filter.rs
index f71a3cbc2ab0..1cab72b6d9f2 100644
--- a/arrow-select/src/filter.rs
+++ b/arrow-select/src/filter.rs
@@ -913,7 +913,7 @@ mod tests {
let value_offsets = Buffer::from_slice_ref([0i64, 3, 6, 8, 8]);
let list_data_type =
- DataType::LargeList(Box::new(Field::new("item", DataType::Int32, false)));
+ DataType::LargeList(Arc::new(Field::new("item", DataType::Int32, false)));
let list_data = ArrayData::builder(list_data_type)
.len(4)
.add_buffer(value_offsets)
@@ -937,7 +937,7 @@ mod tests {
let value_offsets = Buffer::from_slice_ref([0i64, 3, 3]);
let list_data_type =
- DataType::LargeList(Box::new(Field::new("item", DataType::Int32, false)));
+ DataType::LargeList(Arc::new(Field::new("item", DataType::Int32, false)));
let expected = ArrayData::builder(list_data_type)
.len(2)
.add_buffer(value_offsets)
@@ -1291,7 +1291,7 @@ mod tests {
.build()
.unwrap();
let list_data_type = DataType::FixedSizeList(
- Box::new(Field::new("item", DataType::Int32, false)),
+ Arc::new(Field::new("item", DataType::Int32, false)),
3,
);
let list_data = ArrayData::builder(list_data_type)
@@ -1350,7 +1350,7 @@ mod tests {
bit_util::set_bit(&mut null_bits, 4);
let list_data_type = DataType::FixedSizeList(
- Box::new(Field::new("item", DataType::Int32, false)),
+ Arc::new(Field::new("item", DataType::Int32, false)),
2,
);
let list_data = ArrayData::builder(list_data_type)
diff --git a/arrow-select/src/take.rs b/arrow-select/src/take.rs
index cf28c9682ae5..83fe1bb56f35 100644
--- a/arrow-select/src/take.rs
+++ b/arrow-select/src/take.rs
@@ -1574,7 +1574,7 @@ mod tests {
let value_offsets: [$offset_type; 5] = [0, 3, 6, 6, 8];
let value_offsets = Buffer::from_slice_ref(&value_offsets);
// Construct a list array from the above two
- let list_data_type = DataType::$list_data_type(Box::new(Field::new(
+ let list_data_type = DataType::$list_data_type(Arc::new(Field::new(
"item",
DataType::Int32,
false,
@@ -1646,7 +1646,7 @@ mod tests {
let value_offsets: [$offset_type; 5] = [0, 3, 6, 7, 9];
let value_offsets = Buffer::from_slice_ref(&value_offsets);
// Construct a list array from the above two
- let list_data_type = DataType::$list_data_type(Box::new(Field::new(
+ let list_data_type = DataType::$list_data_type(Arc::new(Field::new(
"item",
DataType::Int32,
true,
@@ -1719,7 +1719,7 @@ mod tests {
let value_offsets: [$offset_type; 5] = [0, 3, 6, 6, 8];
let value_offsets = Buffer::from_slice_ref(&value_offsets);
// Construct a list array from the above two
- let list_data_type = DataType::$list_data_type(Box::new(Field::new(
+ let list_data_type = DataType::$list_data_type(Arc::new(Field::new(
"item",
DataType::Int32,
true,
@@ -1895,7 +1895,7 @@ mod tests {
let value_offsets = Buffer::from_slice_ref([0, 3, 6, 8]);
// Construct a list array from the above two
let list_data_type =
- DataType::List(Box::new(Field::new("item", DataType::Int32, false)));
+ DataType::List(Arc::new(Field::new("item", DataType::Int32, false)));
let list_data = ArrayData::builder(list_data_type)
.len(3)
.add_buffer(value_offsets)
diff --git a/arrow/benches/json_reader.rs b/arrow/benches/json_reader.rs
index 5651813a6403..8ad6cfd3ab48 100644
--- a/arrow/benches/json_reader.rs
+++ b/arrow/benches/json_reader.rs
@@ -117,22 +117,22 @@ fn small_bench_list(c: &mut Criterion) {
let schema = Arc::new(Schema::new(vec![
Field::new(
"c1",
- DataType::List(Box::new(Field::new("item", DataType::Utf8, true))),
+ DataType::List(Arc::new(Field::new("item", DataType::Utf8, true))),
true,
),
Field::new(
"c2",
- DataType::List(Box::new(Field::new("item", DataType::Float64, true))),
+ DataType::List(Arc::new(Field::new("item", DataType::Float64, true))),
true,
),
Field::new(
"c3",
- DataType::List(Box::new(Field::new("item", DataType::UInt32, true))),
+ DataType::List(Arc::new(Field::new("item", DataType::UInt32, true))),
true,
),
Field::new(
"c4",
- DataType::List(Box::new(Field::new("item", DataType::Boolean, true))),
+ DataType::List(Arc::new(Field::new("item", DataType::Boolean, true))),
true,
),
]));
diff --git a/arrow/examples/builders.rs b/arrow/examples/builders.rs
index 312de11b303d..d0e6b31085e5 100644
--- a/arrow/examples/builders.rs
+++ b/arrow/examples/builders.rs
@@ -100,7 +100,7 @@ fn main() {
// Construct a list array from the above two
let list_data_type =
- DataType::List(Box::new(Field::new("item", DataType::Int32, false)));
+ DataType::List(Arc::new(Field::new("item", DataType::Int32, false)));
let list_data = ArrayData::builder(list_data_type)
.len(3)
.add_buffer(value_offsets)
diff --git a/arrow/src/array/ffi.rs b/arrow/src/array/ffi.rs
index 5f556dfff587..0249a70d168f 100644
--- a/arrow/src/array/ffi.rs
+++ b/arrow/src/array/ffi.rs
@@ -207,7 +207,7 @@ mod tests {
.add_buffer(Buffer::from_slice_ref(v))
.build()?;
let list_data_type =
- DataType::FixedSizeList(Box::new(Field::new("f", DataType::Int64, false)), 3);
+ DataType::FixedSizeList(Arc::new(Field::new("f", DataType::Int64, false)), 3);
let list_data = ArrayData::builder(list_data_type)
.len(3)
.add_child_data(value_data)
@@ -232,7 +232,7 @@ mod tests {
.add_buffer(Buffer::from_slice_ref(v))
.build()?;
let list_data_type =
- DataType::FixedSizeList(Box::new(Field::new("f", DataType::Int16, false)), 2);
+ DataType::FixedSizeList(Arc::new(Field::new("f", DataType::Int16, false)), 2);
let list_data = ArrayData::builder(list_data_type)
.len(8)
.null_bit_buffer(Some(Buffer::from(validity_bits)))
@@ -255,7 +255,7 @@ mod tests {
let offsets: Vec<i32> = vec![0, 2, 4, 6, 8, 10, 12, 14, 16];
let value_offsets = Buffer::from_slice_ref(offsets);
let inner_list_data_type =
- DataType::List(Box::new(Field::new("item", DataType::Int32, false)));
+ DataType::List(Arc::new(Field::new("item", DataType::Int32, false)));
let inner_list_data = ArrayData::builder(inner_list_data_type.clone())
.len(8)
.add_buffer(value_offsets)
@@ -267,7 +267,7 @@ mod tests {
bit_util::set_bit(&mut validity_bits, 2);
let list_data_type = DataType::FixedSizeList(
- Box::new(Field::new("f", inner_list_data_type, false)),
+ Arc::new(Field::new("f", inner_list_data_type, false)),
2,
);
let list_data = ArrayData::builder(list_data_type)
diff --git a/arrow/src/compute/kernels/limit.rs b/arrow/src/compute/kernels/limit.rs
index 357e9b13ae82..74cbd2096bfd 100644
--- a/arrow/src/compute/kernels/limit.rs
+++ b/arrow/src/compute/kernels/limit.rs
@@ -110,7 +110,7 @@ mod tests {
// Construct a list array from the above two
let list_data_type =
- DataType::List(Box::new(Field::new("item", DataType::Int32, false)));
+ DataType::List(Arc::new(Field::new("item", DataType::Int32, false)));
let list_data = ArrayData::builder(list_data_type)
.len(9)
.add_buffer(value_offsets)
diff --git a/arrow/src/ffi.rs b/arrow/src/ffi.rs
index fe2e186a72f9..7b26cf7f25a5 100644
--- a/arrow/src/ffi.rs
+++ b/arrow/src/ffi.rs
@@ -662,7 +662,7 @@ mod tests {
.collect::<Buffer>();
// Construct a list array from the above two
- let list_data_type = GenericListArray::<Offset>::DATA_TYPE_CONSTRUCTOR(Box::new(
+ let list_data_type = GenericListArray::<Offset>::DATA_TYPE_CONSTRUCTOR(Arc::new(
Field::new("item", DataType::Int32, false),
));
@@ -921,7 +921,7 @@ mod tests {
.build()?;
let list_data_type =
- DataType::FixedSizeList(Box::new(Field::new("f", DataType::Int32, false)), 3);
+ DataType::FixedSizeList(Arc::new(Field::new("f", DataType::Int32, false)), 3);
let list_data = ArrayData::builder(list_data_type.clone())
.len(3)
.null_bit_buffer(Some(Buffer::from(validity_bits)))
diff --git a/arrow/src/util/data_gen.rs b/arrow/src/util/data_gen.rs
index 1983ea72d2fb..29e7420f10be 100644
--- a/arrow/src/util/data_gen.rs
+++ b/arrow/src/util/data_gen.rs
@@ -273,7 +273,7 @@ mod tests {
Field::new("a", DataType::Int32, false),
Field::new(
"b",
- DataType::List(Box::new(Field::new("item", DataType::LargeUtf8, true))),
+ DataType::List(Arc::new(Field::new("item", DataType::LargeUtf8, true))),
false,
),
Field::new("a", DataType::Int32, false),
@@ -303,9 +303,9 @@ mod tests {
Field::new("b", DataType::Boolean, true),
Field::new(
"c",
- DataType::LargeList(Box::new(Field::new(
+ DataType::LargeList(Arc::new(Field::new(
"item",
- DataType::List(Box::new(Field::new(
+ DataType::List(Arc::new(Field::new(
"item",
DataType::FixedSizeBinary(6),
true,
diff --git a/parquet/benches/arrow_writer.rs b/parquet/benches/arrow_writer.rs
index 818fe0b3e49b..a494d9a97791 100644
--- a/parquet/benches/arrow_writer.rs
+++ b/parquet/benches/arrow_writer.rs
@@ -171,17 +171,17 @@ fn create_list_primitive_bench_batch(
let fields = vec![
Field::new(
"_1",
- DataType::List(Box::new(Field::new("item", DataType::Int32, true))),
+ DataType::List(Arc::new(Field::new("item", DataType::Int32, true))),
true,
),
Field::new(
"_2",
- DataType::List(Box::new(Field::new("item", DataType::Boolean, true))),
+ DataType::List(Arc::new(Field::new("item", DataType::Boolean, true))),
true,
),
Field::new(
"_3",
- DataType::LargeList(Box::new(Field::new("item", DataType::Utf8, true))),
+ DataType::LargeList(Arc::new(Field::new("item", DataType::Utf8, true))),
true,
),
];
@@ -202,17 +202,17 @@ fn create_list_primitive_bench_batch_non_null(
let fields = vec![
Field::new(
"_1",
- DataType::List(Box::new(Field::new("item", DataType::Int32, false))),
+ DataType::List(Arc::new(Field::new("item", DataType::Int32, false))),
false,
),
Field::new(
"_2",
- DataType::List(Box::new(Field::new("item", DataType::Boolean, false))),
+ DataType::List(Arc::new(Field::new("item", DataType::Boolean, false))),
false,
),
Field::new(
"_3",
- DataType::LargeList(Box::new(Field::new("item", DataType::Utf8, false))),
+ DataType::LargeList(Arc::new(Field::new("item", DataType::Utf8, false))),
false,
),
];
@@ -256,9 +256,9 @@ fn _create_nested_bench_batch(
),
Field::new(
"_2",
- DataType::LargeList(Box::new(Field::new(
+ DataType::LargeList(Arc::new(Field::new(
"item",
- DataType::List(Box::new(Field::new(
+ DataType::List(Arc::new(Field::new(
"item",
DataType::Struct(Fields::from(vec![
Field::new(
@@ -272,7 +272,7 @@ fn _create_nested_bench_batch(
),
Field::new(
"_2",
- DataType::List(Box::new(Field::new(
+ DataType::List(Arc::new(Field::new(
"",
DataType::FixedSizeBinary(2),
true,
diff --git a/parquet/src/arrow/array_reader/builder.rs b/parquet/src/arrow/array_reader/builder.rs
index 60cc84f9f8d4..241a5efe078a 100644
--- a/parquet/src/arrow/array_reader/builder.rs
+++ b/parquet/src/arrow/array_reader/builder.rs
@@ -90,13 +90,13 @@ fn build_map_reader(
DataType::Map(map_field, is_sorted) => match map_field.data_type() {
DataType::Struct(fields) => {
assert_eq!(fields.len(), 2);
- let struct_field = map_field.clone().with_data_type(
+ let struct_field = map_field.as_ref().clone().with_data_type(
DataType::Struct(Fields::from(vec![
fields[0].as_ref().clone().with_data_type(key_type),
fields[1].as_ref().clone().with_data_type(value_type),
])),
);
- DataType::Map(Box::new(struct_field), *is_sorted)
+ DataType::Map(Arc::new(struct_field), *is_sorted)
}
_ => unreachable!(),
},
@@ -135,11 +135,11 @@ fn build_list_reader(
let item_type = item_reader.get_data_type().clone();
let data_type = match &field.arrow_type {
DataType::List(f) => {
- DataType::List(Box::new(f.clone().with_data_type(item_type)))
- }
- DataType::LargeList(f) => {
- DataType::LargeList(Box::new(f.clone().with_data_type(item_type)))
+ DataType::List(Arc::new(f.as_ref().clone().with_data_type(item_type)))
}
+ DataType::LargeList(f) => DataType::LargeList(Arc::new(
+ f.as_ref().clone().with_data_type(item_type),
+ )),
_ => unreachable!(),
};
diff --git a/parquet/src/arrow/array_reader/fixed_len_byte_array.rs b/parquet/src/arrow/array_reader/fixed_len_byte_array.rs
index e8d426d3a850..fee032a4d763 100644
--- a/parquet/src/arrow/array_reader/fixed_len_byte_array.rs
+++ b/parquet/src/arrow/array_reader/fixed_len_byte_array.rs
@@ -440,7 +440,7 @@ mod tests {
let decimals = Decimal128Array::from_iter_values([1, 2, 3, 4, 5, 6, 7, 8]);
// [[], [1], [2, 3], null, [4], null, [6, 7, 8]]
- let data = ArrayDataBuilder::new(ArrowType::List(Box::new(Field::new(
+ let data = ArrayDataBuilder::new(ArrowType::List(Arc::new(Field::new(
"item",
decimals.data_type().clone(),
false,
diff --git a/parquet/src/arrow/array_reader/list_array.rs b/parquet/src/arrow/array_reader/list_array.rs
index 6218a5466da2..504591c0ca89 100644
--- a/parquet/src/arrow/array_reader/list_array.rs
+++ b/parquet/src/arrow/array_reader/list_array.rs
@@ -268,7 +268,7 @@ mod tests {
data_type: ArrowType,
item_nullable: bool,
) -> ArrowType {
- let field = Box::new(Field::new("item", data_type, item_nullable));
+ let field = Arc::new(Field::new("item", data_type, item_nullable));
GenericListArray::<OffsetSize>::DATA_TYPE_CONSTRUCTOR(field)
}
@@ -584,7 +584,7 @@ mod tests {
batch.data_type(),
&ArrowType::Struct(Fields::from(vec![Field::new(
"table_info",
- ArrowType::List(Box::new(Field::new(
+ ArrowType::List(Arc::new(Field::new(
"table_info",
ArrowType::Struct(
vec![Field::new("name", ArrowType::Binary, false)].into()
diff --git a/parquet/src/arrow/array_reader/map_array.rs b/parquet/src/arrow/array_reader/map_array.rs
index 621292ee7900..d7645a593505 100644
--- a/parquet/src/arrow/array_reader/map_array.rs
+++ b/parquet/src/arrow/array_reader/map_array.rs
@@ -149,7 +149,7 @@ mod tests {
let schema = Schema::new(vec![Field::new(
"map",
ArrowType::Map(
- Box::new(Field::new(
+ Arc::new(Field::new(
"entries",
ArrowType::Struct(Fields::from(vec![
Field::new("keys", ArrowType::Utf8, false),
diff --git a/parquet/src/arrow/arrow_reader/mod.rs b/parquet/src/arrow/arrow_reader/mod.rs
index 8464b959215d..9507967836f1 100644
--- a/parquet/src/arrow/arrow_reader/mod.rs
+++ b/parquet/src/arrow/arrow_reader/mod.rs
@@ -1181,7 +1181,7 @@ mod tests {
let decimals = Decimal128Array::from_iter_values([1, 2, 3, 4, 5, 6, 7, 8]);
// [[], [1], [2, 3], null, [4], null, [6, 7, 8]]
- let data = ArrayDataBuilder::new(ArrowDataType::List(Box::new(Field::new(
+ let data = ArrayDataBuilder::new(ArrowDataType::List(Arc::new(Field::new(
"item",
decimals.data_type().clone(),
false,
@@ -2122,7 +2122,7 @@ mod tests {
let arrow_field = Field::new(
"emptylist",
- ArrowDataType::List(Box::new(Field::new("item", ArrowDataType::Null, true))),
+ ArrowDataType::List(Arc::new(Field::new("item", ArrowDataType::Null, true))),
true,
);
@@ -2236,7 +2236,7 @@ mod tests {
fn test_row_group_batch(row_group_size: usize, batch_size: usize) {
let schema = Arc::new(Schema::new(vec![Field::new(
"list",
- ArrowDataType::List(Box::new(Field::new("item", ArrowDataType::Int32, true))),
+ ArrowDataType::List(Arc::new(Field::new("item", ArrowDataType::Int32, true))),
true,
)]));
diff --git a/parquet/src/arrow/arrow_writer/levels.rs b/parquet/src/arrow/arrow_writer/levels.rs
index 9a6a97df4467..4239f3fba59b 100644
--- a/parquet/src/arrow/arrow_writer/levels.rs
+++ b/parquet/src/arrow/arrow_writer/levels.rs
@@ -494,9 +494,9 @@ mod tests {
// [[a, b, c], [d, e, f, g]], [[h], [i,j]]
let leaf_type = Field::new("item", DataType::Int32, false);
- let inner_type = DataType::List(Box::new(leaf_type));
+ let inner_type = DataType::List(Arc::new(leaf_type));
let inner_field = Field::new("l2", inner_type.clone(), false);
- let outer_type = DataType::List(Box::new(inner_field));
+ let outer_type = DataType::List(Arc::new(inner_field));
let outer_field = Field::new("l1", outer_type.clone(), false);
let primitives = Int32Array::from_iter(0..10);
@@ -579,7 +579,7 @@ mod tests {
#[test]
fn test_calculate_array_levels_1() {
let leaf_field = Field::new("item", DataType::Int32, false);
- let list_type = DataType::List(Box::new(leaf_field));
+ let list_type = DataType::List(Arc::new(leaf_field));
// if all array values are defined (e.g. batch<list<_>>)
// [[0], [1], [2], [3], [4]]
@@ -659,7 +659,7 @@ mod tests {
let leaf = Int32Array::from_iter(0..11);
let leaf_field = Field::new("leaf", DataType::Int32, false);
- let list_type = DataType::List(Box::new(leaf_field));
+ let list_type = DataType::List(Arc::new(leaf_field));
let list = ArrayData::builder(list_type.clone())
.len(5)
.add_child_data(leaf.into_data())
@@ -700,7 +700,7 @@ mod tests {
let leaf = Int32Array::from_iter(100..122);
let leaf_field = Field::new("leaf", DataType::Int32, true);
- let l1_type = DataType::List(Box::new(leaf_field));
+ let l1_type = DataType::List(Arc::new(leaf_field));
let offsets = Buffer::from_iter([0_i32, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22]);
let l1 = ArrayData::builder(l1_type.clone())
.len(11)
@@ -710,7 +710,7 @@ mod tests {
.unwrap();
let l1_field = Field::new("l1", l1_type, true);
- let l2_type = DataType::List(Box::new(l1_field));
+ let l2_type = DataType::List(Arc::new(l1_field));
let l2 = ArrayData::builder(l2_type)
.len(5)
.add_child_data(l1)
@@ -742,7 +742,7 @@ mod tests {
#[test]
fn test_calculate_array_levels_nested_list() {
let leaf_field = Field::new("leaf", DataType::Int32, false);
- let list_type = DataType::List(Box::new(leaf_field));
+ let list_type = DataType::List(Arc::new(leaf_field));
// if all array values are defined (e.g. batch<list<_>>)
// The array at this level looks like:
@@ -813,7 +813,7 @@ mod tests {
let leaf = Int32Array::from_iter(201..216);
let leaf_field = Field::new("leaf", DataType::Int32, false);
- let list_1_type = DataType::List(Box::new(leaf_field));
+ let list_1_type = DataType::List(Arc::new(leaf_field));
let list_1 = ArrayData::builder(list_1_type.clone())
.len(7)
.add_buffer(Buffer::from_iter([0_i32, 1, 3, 3, 6, 10, 10, 15]))
@@ -822,7 +822,7 @@ mod tests {
.unwrap();
let list_1_field = Field::new("l1", list_1_type, true);
- let list_2_type = DataType::List(Box::new(list_1_field));
+ let list_2_type = DataType::List(Arc::new(list_1_field));
let list_2 = ArrayData::builder(list_2_type.clone())
.len(4)
.add_buffer(Buffer::from_iter([0_i32, 0, 3, 5, 7]))
@@ -899,7 +899,7 @@ mod tests {
let a_values = Int32Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
let a_value_offsets = arrow::buffer::Buffer::from_iter([0_i32, 1, 3, 3, 6, 10]);
let a_list_type =
- DataType::List(Box::new(Field::new("item", DataType::Int32, true)));
+ DataType::List(Arc::new(Field::new("item", DataType::Int32, true)));
let a_list_data = ArrayData::builder(a_list_type.clone())
.len(5)
.add_buffer(a_value_offsets)
@@ -942,7 +942,7 @@ mod tests {
let struct_field_f = Field::new("f", DataType::Float32, true);
let struct_field_g = Field::new(
"g",
- DataType::List(Box::new(Field::new("items", DataType::Int16, false))),
+ DataType::List(Arc::new(Field::new("items", DataType::Int16, false))),
false,
);
let struct_field_e = Field::new(
@@ -1131,7 +1131,7 @@ mod tests {
let stocks_field = Field::new(
"stocks",
DataType::Map(
- Box::new(Field::new("entries", entries_struct_type, false)),
+ Arc::new(Field::new("entries", entries_struct_type, false)),
false,
),
// not nullable, so the keys have max level = 1
@@ -1186,7 +1186,7 @@ mod tests {
let int_field = Field::new("a", DataType::Int32, true);
let fields = Fields::from([Arc::new(int_field)]);
let item_field = Field::new("item", DataType::Struct(fields.clone()), true);
- let list_field = Field::new("list", DataType::List(Box::new(item_field)), true);
+ let list_field = Field::new("list", DataType::List(Arc::new(item_field)), true);
let int_builder = Int32Builder::with_capacity(10);
let struct_builder = StructBuilder::new(fields, vec![Box::new(int_builder)]);
@@ -1336,7 +1336,7 @@ mod tests {
let offsets = Buffer::from_iter([0_i32, 0, 2, 2, 3, 5, 5]);
let nulls = Buffer::from([0b00111100]);
- let list_type = DataType::List(Box::new(Field::new(
+ let list_type = DataType::List(Arc::new(Field::new(
"struct",
struct_a.data_type().clone(),
true,
diff --git a/parquet/src/arrow/arrow_writer/mod.rs b/parquet/src/arrow/arrow_writer/mod.rs
index f594f2f79947..0515ed4e39e2 100644
--- a/parquet/src/arrow/arrow_writer/mod.rs
+++ b/parquet/src/arrow/arrow_writer/mod.rs
@@ -750,7 +750,7 @@ mod tests {
// define schema
let schema = Schema::new(vec![Field::new(
"a",
- DataType::List(Box::new(Field::new("item", DataType::Int32, false))),
+ DataType::List(Arc::new(Field::new("item", DataType::Int32, false))),
true,
)]);
@@ -763,7 +763,7 @@ mod tests {
arrow::buffer::Buffer::from(&[0, 1, 3, 3, 6, 10].to_byte_slice());
// Construct a list array from the above two
- let a_list_data = ArrayData::builder(DataType::List(Box::new(Field::new(
+ let a_list_data = ArrayData::builder(DataType::List(Arc::new(Field::new(
"item",
DataType::Int32,
false,
@@ -791,7 +791,7 @@ mod tests {
// define schema
let schema = Schema::new(vec![Field::new(
"a",
- DataType::List(Box::new(Field::new("item", DataType::Int32, false))),
+ DataType::List(Arc::new(Field::new("item", DataType::Int32, false))),
false,
)]);
@@ -804,7 +804,7 @@ mod tests {
arrow::buffer::Buffer::from(&[0, 1, 3, 3, 6, 10].to_byte_slice());
// Construct a list array from the above two
- let a_list_data = ArrayData::builder(DataType::List(Box::new(Field::new(
+ let a_list_data = ArrayData::builder(DataType::List(Arc::new(Field::new(
"item",
DataType::Int32,
false,
@@ -890,12 +890,12 @@ mod tests {
let struct_field_f = Field::new("f", DataType::Float32, true);
let struct_field_g = Field::new(
"g",
- DataType::List(Box::new(Field::new("item", DataType::Int16, true))),
+ DataType::List(Arc::new(Field::new("item", DataType::Int16, true))),
false,
);
let struct_field_h = Field::new(
"h",
- DataType::List(Box::new(Field::new("item", DataType::Int16, false))),
+ DataType::List(Arc::new(Field::new("item", DataType::Int16, false))),
true,
);
let struct_field_e = Field::new(
@@ -1025,7 +1025,7 @@ mod tests {
let stocks_field = Field::new(
"stocks",
DataType::Map(
- Box::new(Field::new("entries", entries_struct_type, false)),
+ Arc::new(Field::new("entries", entries_struct_type, false)),
false,
),
true,
@@ -1766,14 +1766,14 @@ mod tests {
fn null_list_single_column() {
let null_field = Field::new("item", DataType::Null, true);
let list_field =
- Field::new("emptylist", DataType::List(Box::new(null_field)), true);
+ Field::new("emptylist", DataType::List(Arc::new(null_field)), true);
let schema = Schema::new(vec![list_field]);
// Build [[], null, [null, null]]
let a_values = NullArray::new(2);
let a_value_offsets = arrow::buffer::Buffer::from(&[0, 0, 0, 2].to_byte_slice());
- let a_list_data = ArrayData::builder(DataType::List(Box::new(Field::new(
+ let a_list_data = ArrayData::builder(DataType::List(Arc::new(Field::new(
"item",
DataType::Null,
true,
@@ -1804,7 +1804,7 @@ mod tests {
let a_values = Int32Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
let a_value_offsets =
arrow::buffer::Buffer::from(&[0, 1, 3, 3, 6, 10].to_byte_slice());
- let a_list_data = ArrayData::builder(DataType::List(Box::new(Field::new(
+ let a_list_data = ArrayData::builder(DataType::List(Arc::new(Field::new(
"item",
DataType::Int32,
false,
@@ -1829,7 +1829,7 @@ mod tests {
let a_values = Int32Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
let a_value_offsets =
arrow::buffer::Buffer::from(&[0i64, 1, 3, 3, 6, 10].to_byte_slice());
- let a_list_data = ArrayData::builder(DataType::LargeList(Box::new(Field::new(
+ let a_list_data = ArrayData::builder(DataType::LargeList(Arc::new(Field::new(
"large_item",
DataType::Int32,
true,
@@ -2256,7 +2256,7 @@ mod tests {
true,
);
- let list_a = Field::new("list", DataType::List(Box::new(struct_a)), true);
+ let list_a = Field::new("list", DataType::List(Arc::new(struct_a)), true);
let struct_b = Field::new(
"struct_b",
DataType::Struct(vec![list_a.clone()].into()),
diff --git a/parquet/src/arrow/schema/complex.rs b/parquet/src/arrow/schema/complex.rs
index ad6ded1b842f..25227aeeebc8 100644
--- a/parquet/src/arrow/schema/complex.rs
+++ b/parquet/src/arrow/schema/complex.rs
@@ -62,7 +62,7 @@ impl ParquetField {
rep_level: self.rep_level,
def_level: self.def_level,
nullable: false,
- arrow_type: DataType::List(Box::new(Field::new(
+ arrow_type: DataType::List(Arc::new(Field::new(
name,
self.arrow_type.clone(),
false,
@@ -362,7 +362,7 @@ impl Visitor {
rep_level,
def_level,
nullable,
- arrow_type: DataType::Map(Box::new(map_field), sorted),
+ arrow_type: DataType::Map(Arc::new(map_field), sorted),
field_type: ParquetFieldType::Group {
children: vec![key, value],
},
@@ -479,7 +479,7 @@ impl Visitor {
match self.dispatch(item_type, new_context) {
Ok(Some(item)) => {
- let item_field = Box::new(convert_field(item_type, &item, arrow_field));
+ let item_field = Arc::new(convert_field(item_type, &item, arrow_field));
// Use arrow type as hint for index size
let arrow_type = match context.data_type {
diff --git a/parquet/src/arrow/schema/mod.rs b/parquet/src/arrow/schema/mod.rs
index b541a754ba41..81ed5e8177bb 100644
--- a/parquet/src/arrow/schema/mod.rs
+++ b/parquet/src/arrow/schema/mod.rs
@@ -711,7 +711,7 @@ mod tests {
{
arrow_fields.push(Field::new(
"my_list",
- DataType::List(Box::new(Field::new("element", DataType::Utf8, true))),
+ DataType::List(Arc::new(Field::new("element", DataType::Utf8, true))),
false,
));
}
@@ -725,7 +725,7 @@ mod tests {
{
arrow_fields.push(Field::new(
"my_list",
- DataType::List(Box::new(Field::new("element", DataType::Utf8, false))),
+ DataType::List(Arc::new(Field::new("element", DataType::Utf8, false))),
true,
));
}
@@ -744,10 +744,10 @@ mod tests {
// }
{
let arrow_inner_list =
- DataType::List(Box::new(Field::new("element", DataType::Int32, false)));
+ DataType::List(Arc::new(Field::new("element", DataType::Int32, false)));
arrow_fields.push(Field::new(
"array_of_arrays",
- DataType::List(Box::new(Field::new("element", arrow_inner_list, false))),
+ DataType::List(Arc::new(Field::new("element", arrow_inner_list, false))),
true,
));
}
@@ -761,7 +761,7 @@ mod tests {
{
arrow_fields.push(Field::new(
"my_list",
- DataType::List(Box::new(Field::new("str", DataType::Utf8, false))),
+ DataType::List(Arc::new(Field::new("str", DataType::Utf8, false))),
true,
));
}
@@ -773,7 +773,7 @@ mod tests {
{
arrow_fields.push(Field::new(
"my_list",
- DataType::List(Box::new(Field::new("element", DataType::Int32, false))),
+ DataType::List(Arc::new(Field::new("element", DataType::Int32, false))),
true,
));
}
@@ -792,7 +792,7 @@ mod tests {
]));
arrow_fields.push(Field::new(
"my_list",
- DataType::List(Box::new(Field::new("element", arrow_struct, false))),
+ DataType::List(Arc::new(Field::new("element", arrow_struct, false))),
true,
));
}
@@ -809,7 +809,7 @@ mod tests {
let arrow_struct = DataType::Struct(fields);
arrow_fields.push(Field::new(
"my_list",
- DataType::List(Box::new(Field::new("array", arrow_struct, false))),
+ DataType::List(Arc::new(Field::new("array", arrow_struct, false))),
true,
));
}
@@ -826,7 +826,7 @@ mod tests {
let arrow_struct = DataType::Struct(fields);
arrow_fields.push(Field::new(
"my_list",
- DataType::List(Box::new(Field::new(
+ DataType::List(Arc::new(Field::new(
"my_list_tuple",
arrow_struct,
false,
@@ -840,7 +840,7 @@ mod tests {
{
arrow_fields.push(Field::new(
"name",
- DataType::List(Box::new(Field::new("name", DataType::Int32, false))),
+ DataType::List(Arc::new(Field::new("name", DataType::Int32, false))),
false,
));
}
@@ -891,7 +891,7 @@ mod tests {
{
arrow_fields.push(Field::new(
"my_list1",
- DataType::List(Box::new(Field::new("element", DataType::Utf8, true))),
+ DataType::List(Arc::new(Field::new("element", DataType::Utf8, true))),
false,
));
}
@@ -905,7 +905,7 @@ mod tests {
{
arrow_fields.push(Field::new(
"my_list2",
- DataType::List(Box::new(Field::new("element", DataType::Utf8, false))),
+ DataType::List(Arc::new(Field::new("element", DataType::Utf8, false))),
true,
));
}
@@ -919,7 +919,7 @@ mod tests {
{
arrow_fields.push(Field::new(
"my_list3",
- DataType::List(Box::new(Field::new("element", DataType::Utf8, false))),
+ DataType::List(Arc::new(Field::new("element", DataType::Utf8, false))),
false,
));
}
@@ -976,7 +976,7 @@ mod tests {
arrow_fields.push(Field::new(
"my_map1",
DataType::Map(
- Box::new(Field::new(
+ Arc::new(Field::new(
"key_value",
DataType::Struct(Fields::from(vec![
Field::new("key", DataType::Utf8, false),
@@ -1001,7 +1001,7 @@ mod tests {
arrow_fields.push(Field::new(
"my_map2",
DataType::Map(
- Box::new(Field::new(
+ Arc::new(Field::new(
"map",
DataType::Struct(Fields::from(vec![
Field::new("str", DataType::Utf8, false),
@@ -1026,7 +1026,7 @@ mod tests {
arrow_fields.push(Field::new(
"my_map3",
DataType::Map(
- Box::new(Field::new(
+ Arc::new(Field::new(
"map",
DataType::Struct(Fields::from(vec![
Field::new("key", DataType::Utf8, false),
@@ -1201,7 +1201,7 @@ mod tests {
let inner_group_list = Field::new(
"innerGroup",
- DataType::List(Box::new(Field::new(
+ DataType::List(Arc::new(Field::new(
"innerGroup",
DataType::Struct(
vec![Field::new("leaf3", DataType::Int32, true)].into(),
@@ -1213,7 +1213,7 @@ mod tests {
let outer_group_list = Field::new(
"outerGroup",
- DataType::List(Box::new(Field::new(
+ DataType::List(Arc::new(Field::new(
"outerGroup",
DataType::Struct(Fields::from(vec![
Field::new("leaf2", DataType::Int32, true),
@@ -1302,7 +1302,7 @@ mod tests {
Field::new("string", DataType::Utf8, true),
Field::new(
"bools",
- DataType::List(Box::new(Field::new("bools", DataType::Boolean, false))),
+ DataType::List(Arc::new(Field::new("bools", DataType::Boolean, false))),
false,
),
Field::new("date", DataType::Date32, true),
@@ -1326,12 +1326,12 @@ mod tests {
),
Field::new(
"int_list",
- DataType::List(Box::new(Field::new("int_list", DataType::Int32, false))),
+ DataType::List(Arc::new(Field::new("int_list", DataType::Int32, false))),
false,
),
Field::new(
"byte_list",
- DataType::List(Box::new(Field::new(
+ DataType::List(Arc::new(Field::new(
"byte_list",
DataType::Binary,
false,
@@ -1340,7 +1340,7 @@ mod tests {
),
Field::new(
"string_list",
- DataType::List(Box::new(Field::new(
+ DataType::List(Arc::new(Field::new(
"string_list",
DataType::Utf8,
false,
@@ -1417,12 +1417,12 @@ mod tests {
Field::new("string", DataType::Utf8, true),
Field::new(
"bools",
- DataType::List(Box::new(Field::new("element", DataType::Boolean, true))),
+ DataType::List(Arc::new(Field::new("element", DataType::Boolean, true))),
true,
),
Field::new(
"bools_non_null",
- DataType::List(Box::new(Field::new("element", DataType::Boolean, false))),
+ DataType::List(Arc::new(Field::new("element", DataType::Boolean, false))),
false,
),
Field::new("date", DataType::Date32, true),
@@ -1470,7 +1470,7 @@ mod tests {
Field::new("uint32", DataType::UInt32, false),
Field::new(
"int32",
- DataType::List(Box::new(Field::new(
+ DataType::List(Arc::new(Field::new(
"element",
DataType::Int32,
true,
@@ -1602,7 +1602,7 @@ mod tests {
Field::new("c20", DataType::Interval(IntervalUnit::YearMonth), false),
Field::new(
"c21",
- DataType::List(Box::new(Field::new("list", DataType::Boolean, true))),
+ DataType::List(Arc::new(Field::new("list", DataType::Boolean, true))),
false,
),
// Field::new(
@@ -1663,13 +1663,13 @@ mod tests {
Field::new(
"c39",
DataType::Map(
- Box::new(Field::new(
+ Arc::new(Field::new(
"key_value",
DataType::Struct(Fields::from(vec![
Field::new("key", DataType::Utf8, false),
Field::new(
"value",
- DataType::List(Box::new(Field::new(
+ DataType::List(Arc::new(Field::new(
"element",
DataType::Utf8,
true,
@@ -1686,13 +1686,13 @@ mod tests {
Field::new(
"c40",
DataType::Map(
- Box::new(Field::new(
+ Arc::new(Field::new(
"my_entries",
DataType::Struct(Fields::from(vec![
Field::new("my_key", DataType::Utf8, false),
Field::new(
"my_value",
- DataType::List(Box::new(Field::new(
+ DataType::List(Arc::new(Field::new(
"item",
DataType::Utf8,
true,
@@ -1709,13 +1709,13 @@ mod tests {
Field::new(
"c41",
DataType::Map(
- Box::new(Field::new(
+ Arc::new(Field::new(
"my_entries",
DataType::Struct(Fields::from(vec![
Field::new("my_key", DataType::Utf8, false),
Field::new(
"my_value",
- DataType::List(Box::new(Field::new(
+ DataType::List(Arc::new(Field::new(
"item",
DataType::Utf8,
true,
@@ -1762,7 +1762,7 @@ mod tests {
vec![
Field::new(
"c21",
- DataType::List(Box::new(Field::new(
+ DataType::List(Arc::new(Field::new(
"array",
DataType::Boolean,
true,
@@ -1772,16 +1772,16 @@ mod tests {
Field::new(
"c22",
DataType::FixedSizeList(
- Box::new(Field::new("items", DataType::Boolean, false)),
+ Arc::new(Field::new("items", DataType::Boolean, false)),
5,
),
false,
),
Field::new(
"c23",
- DataType::List(Box::new(Field::new(
+ DataType::List(Arc::new(Field::new(
"items",
- DataType::LargeList(Box::new(Field::new(
+ DataType::LargeList(Arc::new(Field::new(
"items",
DataType::Struct(Fields::from(vec![
Field::new("a", DataType::Int16, true),
|
diff --git a/arrow-integration-test/src/datatype.rs b/arrow-integration-test/src/datatype.rs
index 5a5dd67fc7a1..47bacc7cc74b 100644
--- a/arrow-integration-test/src/datatype.rs
+++ b/arrow-integration-test/src/datatype.rs
@@ -22,7 +22,7 @@ use std::sync::Arc;
/// Parse a data type from a JSON representation.
pub fn data_type_from_json(json: &serde_json::Value) -> Result<DataType> {
use serde_json::Value;
- let default_field = Field::new("", DataType::Boolean, true);
+ let default_field = Arc::new(Field::new("", DataType::Boolean, true));
match *json {
Value::Object(ref map) => match map.get("name") {
Some(s) if s == "null" => Ok(DataType::Null),
@@ -186,17 +186,17 @@ pub fn data_type_from_json(json: &serde_json::Value) -> Result<DataType> {
},
Some(s) if s == "list" => {
// return a list with any type as its child isn't defined in the map
- Ok(DataType::List(Box::new(default_field)))
+ Ok(DataType::List(default_field))
}
Some(s) if s == "largelist" => {
// return a largelist with any type as its child isn't defined in the map
- Ok(DataType::LargeList(Box::new(default_field)))
+ Ok(DataType::LargeList(default_field))
}
Some(s) if s == "fixedsizelist" => {
// return a list with any type as its child isn't defined in the map
if let Some(Value::Number(size)) = map.get("listSize") {
Ok(DataType::FixedSizeList(
- Box::new(default_field),
+ default_field,
size.as_i64().unwrap() as i32,
))
} else {
@@ -212,7 +212,7 @@ pub fn data_type_from_json(json: &serde_json::Value) -> Result<DataType> {
Some(s) if s == "map" => {
if let Some(Value::Bool(keys_sorted)) = map.get("keysSorted") {
// Return a map with an empty type as its children aren't defined in the map
- Ok(DataType::Map(Box::new(default_field), *keys_sorted))
+ Ok(DataType::Map(default_field, *keys_sorted))
} else {
Err(ArrowError::ParseError(
"Expecting a keysSorted for map".to_string(),
@@ -231,11 +231,10 @@ pub fn data_type_from_json(json: &serde_json::Value) -> Result<DataType> {
)));
};
if let Some(values) = map.get("typeIds") {
- let field = Arc::new(default_field);
let values = values.as_array().unwrap();
let fields = values
.iter()
- .map(|t| (t.as_i64().unwrap() as i8, field.clone()))
+ .map(|t| (t.as_i64().unwrap() as i8, default_field.clone()))
.collect();
Ok(DataType::Union(fields, union_mode))
diff --git a/arrow-integration-test/src/field.rs b/arrow-integration-test/src/field.rs
index c714fe4671d6..a0cd4adc83f0 100644
--- a/arrow-integration-test/src/field.rs
+++ b/arrow-integration-test/src/field.rs
@@ -126,13 +126,13 @@ pub fn field_from_json(json: &serde_json::Value) -> Result<Field> {
}
match data_type {
DataType::List(_) => {
- DataType::List(Box::new(field_from_json(&values[0])?))
+ DataType::List(Arc::new(field_from_json(&values[0])?))
}
- DataType::LargeList(_) => DataType::LargeList(Box::new(
+ DataType::LargeList(_) => DataType::LargeList(Arc::new(
field_from_json(&values[0])?,
)),
DataType::FixedSizeList(_, int) => DataType::FixedSizeList(
- Box::new(field_from_json(&values[0])?),
+ Arc::new(field_from_json(&values[0])?),
int,
),
_ => unreachable!(
@@ -173,7 +173,7 @@ pub fn field_from_json(json: &serde_json::Value) -> Result<Field> {
// child must be a struct
match child.data_type() {
DataType::Struct(map_fields) if map_fields.len() == 2 => {
- DataType::Map(Box::new(child), keys_sorted)
+ DataType::Map(Arc::new(child), keys_sorted)
}
t => {
return Err(ArrowError::ParseError(
@@ -354,7 +354,7 @@ mod tests {
let f = Field::new(
"my_map",
DataType::Map(
- Box::new(Field::new(
+ Arc::new(Field::new(
"my_entries",
DataType::Struct(Fields::from(vec![
Field::new("my_keys", DataType::Utf8, false),
@@ -518,7 +518,7 @@ mod tests {
let expected = Field::new(
"my_map",
DataType::Map(
- Box::new(Field::new(
+ Arc::new(Field::new(
"my_entries",
DataType::Struct(Fields::from(vec![
Field::new("my_keys", DataType::Utf8, false),
diff --git a/arrow-integration-test/src/lib.rs b/arrow-integration-test/src/lib.rs
index 61bcbea5a707..8ee7bc60085e 100644
--- a/arrow-integration-test/src/lib.rs
+++ b/arrow-integration-test/src/lib.rs
@@ -1098,7 +1098,7 @@ mod tests {
Field::new("c3", DataType::Utf8, true),
Field::new(
"c4",
- DataType::List(Box::new(Field::new(
+ DataType::List(Arc::new(Field::new(
"custom_item",
DataType::Int32,
false,
@@ -1185,7 +1185,7 @@ mod tests {
Field::new("utf8s", DataType::Utf8, true),
Field::new(
"lists",
- DataType::List(Box::new(Field::new("item", DataType::Int32, true))),
+ DataType::List(Arc::new(Field::new("item", DataType::Int32, true))),
true,
),
Field::new(
@@ -1260,7 +1260,7 @@ mod tests {
let value_data = Int32Array::from(vec![None, Some(2), None, None]);
let value_offsets = Buffer::from_slice_ref([0, 3, 4, 4]);
let list_data_type =
- DataType::List(Box::new(Field::new("item", DataType::Int32, true)));
+ DataType::List(Arc::new(Field::new("item", DataType::Int32, true)));
let list_data = ArrayData::builder(list_data_type)
.len(3)
.add_buffer(value_offsets)
diff --git a/arrow-integration-test/src/schema.rs b/arrow-integration-test/src/schema.rs
index d640e298c6ad..6e143c2838d9 100644
--- a/arrow-integration-test/src/schema.rs
+++ b/arrow-integration-test/src/schema.rs
@@ -105,6 +105,7 @@ mod tests {
use super::*;
use arrow::datatypes::{DataType, Field, Fields, IntervalUnit, TimeUnit};
use serde_json::Value;
+ use std::sync::Arc;
#[test]
fn schema_json() {
@@ -155,22 +156,22 @@ mod tests {
Field::new("c21", DataType::Interval(IntervalUnit::MonthDayNano), false),
Field::new(
"c22",
- DataType::List(Box::new(Field::new("item", DataType::Boolean, true))),
+ DataType::List(Arc::new(Field::new("item", DataType::Boolean, true))),
false,
),
Field::new(
"c23",
DataType::FixedSizeList(
- Box::new(Field::new("bools", DataType::Boolean, false)),
+ Arc::new(Field::new("bools", DataType::Boolean, false)),
5,
),
false,
),
Field::new(
"c24",
- DataType::List(Box::new(Field::new(
+ DataType::List(Arc::new(Field::new(
"inner_list",
- DataType::List(Box::new(Field::new(
+ DataType::List(Arc::new(Field::new(
"struct",
DataType::Struct(Fields::empty()),
true,
@@ -208,9 +209,9 @@ mod tests {
Field::new("c35", DataType::LargeUtf8, true),
Field::new(
"c36",
- DataType::LargeList(Box::new(Field::new(
+ DataType::LargeList(Arc::new(Field::new(
"inner_large_list",
- DataType::LargeList(Box::new(Field::new(
+ DataType::LargeList(Arc::new(Field::new(
"struct",
DataType::Struct(Fields::empty()),
false,
@@ -222,7 +223,7 @@ mod tests {
Field::new(
"c37",
DataType::Map(
- Box::new(Field::new(
+ Arc::new(Field::new(
"my_entries",
DataType::Struct(Fields::from(vec![
Field::new("my_keys", DataType::Utf8, false),
diff --git a/arrow-integration-testing/src/bin/arrow-json-integration-test.rs b/arrow-integration-testing/src/bin/arrow-json-integration-test.rs
index 1d65be41c41c..90a2d171d347 100644
--- a/arrow-integration-testing/src/bin/arrow-json-integration-test.rs
+++ b/arrow-integration-testing/src/bin/arrow-json-integration-test.rs
@@ -140,7 +140,7 @@ fn canonicalize_schema(schema: &Schema) -> Schema {
Arc::new(Field::new(
field.name().as_str(),
- DataType::Map(Box::new(child_field), *sorted),
+ DataType::Map(Arc::new(child_field), *sorted),
field.is_nullable(),
))
}
diff --git a/arrow/tests/array_cast.rs b/arrow/tests/array_cast.rs
index 27fb1dcd232b..2807bbd79b83 100644
--- a/arrow/tests/array_cast.rs
+++ b/arrow/tests/array_cast.rs
@@ -241,7 +241,7 @@ fn make_fixed_size_list_array() -> FixedSizeListArray {
// Construct a fixed size list array from the above two
let list_data_type =
- DataType::FixedSizeList(Box::new(Field::new("item", DataType::Int32, true)), 2);
+ DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Int32, true)), 2);
let list_data = ArrayData::builder(list_data_type)
.len(5)
.add_child_data(value_data)
@@ -275,7 +275,7 @@ fn make_list_array() -> ListArray {
// Construct a list array from the above two
let list_data_type =
- DataType::List(Box::new(Field::new("item", DataType::Int32, true)));
+ DataType::List(Arc::new(Field::new("item", DataType::Int32, true)));
let list_data = ArrayData::builder(list_data_type)
.len(3)
.add_buffer(value_offsets)
@@ -299,7 +299,7 @@ fn make_large_list_array() -> LargeListArray {
// Construct a list array from the above two
let list_data_type =
- DataType::LargeList(Box::new(Field::new("item", DataType::Int32, true)));
+ DataType::LargeList(Arc::new(Field::new("item", DataType::Int32, true)));
let list_data = ArrayData::builder(list_data_type)
.len(3)
.add_buffer(value_offsets)
@@ -394,12 +394,12 @@ fn get_all_types() -> Vec<DataType> {
LargeBinary,
Utf8,
LargeUtf8,
- List(Box::new(Field::new("item", DataType::Int8, true))),
- List(Box::new(Field::new("item", DataType::Utf8, true))),
- FixedSizeList(Box::new(Field::new("item", DataType::Int8, true)), 10),
- FixedSizeList(Box::new(Field::new("item", DataType::Utf8, false)), 10),
- LargeList(Box::new(Field::new("item", DataType::Int8, true))),
- LargeList(Box::new(Field::new("item", DataType::Utf8, false))),
+ List(Arc::new(Field::new("item", DataType::Int8, true))),
+ List(Arc::new(Field::new("item", DataType::Utf8, true))),
+ FixedSizeList(Arc::new(Field::new("item", DataType::Int8, true)), 10),
+ FixedSizeList(Arc::new(Field::new("item", DataType::Utf8, false)), 10),
+ LargeList(Arc::new(Field::new("item", DataType::Int8, true))),
+ LargeList(Arc::new(Field::new("item", DataType::Utf8, false))),
Struct(Fields::from(vec![
Field::new("f1", DataType::Int32, true),
Field::new("f2", DataType::Utf8, true),
diff --git a/arrow/tests/array_equal.rs b/arrow/tests/array_equal.rs
index dbbeb934d37c..37968ec6a055 100644
--- a/arrow/tests/array_equal.rs
+++ b/arrow/tests/array_equal.rs
@@ -365,7 +365,7 @@ fn test_empty_offsets_list_equal() {
let values = Int32Array::from(empty);
let empty_offsets: [u8; 0] = [];
- let a: ListArray = ArrayDataBuilder::new(DataType::List(Box::new(Field::new(
+ let a: ListArray = ArrayDataBuilder::new(DataType::List(Arc::new(Field::new(
"item",
DataType::Int32,
true,
@@ -378,7 +378,7 @@ fn test_empty_offsets_list_equal() {
.unwrap()
.into();
- let b: ListArray = ArrayDataBuilder::new(DataType::List(Box::new(Field::new(
+ let b: ListArray = ArrayDataBuilder::new(DataType::List(Arc::new(Field::new(
"item",
DataType::Int32,
true,
@@ -393,7 +393,7 @@ fn test_empty_offsets_list_equal() {
test_equal(&a, &b, true);
- let c: ListArray = ArrayDataBuilder::new(DataType::List(Box::new(Field::new(
+ let c: ListArray = ArrayDataBuilder::new(DataType::List(Arc::new(Field::new(
"item",
DataType::Int32,
true,
@@ -435,7 +435,7 @@ fn test_list_null() {
// a list where the nullness of values is determined by the list's bitmap
let c_values = Int32Array::from(vec![1, 2, -1, -2, 3, 4, -3, -4]);
- let c: ListArray = ArrayDataBuilder::new(DataType::List(Box::new(Field::new(
+ let c: ListArray = ArrayDataBuilder::new(DataType::List(Arc::new(Field::new(
"item",
DataType::Int32,
true,
@@ -458,7 +458,7 @@ fn test_list_null() {
None,
None,
]);
- let d: ListArray = ArrayDataBuilder::new(DataType::List(Box::new(Field::new(
+ let d: ListArray = ArrayDataBuilder::new(DataType::List(Arc::new(Field::new(
"item",
DataType::Int32,
true,
diff --git a/arrow/tests/array_transform.rs b/arrow/tests/array_transform.rs
index 57816306ba4e..97869544ddd0 100644
--- a/arrow/tests/array_transform.rs
+++ b/arrow/tests/array_transform.rs
@@ -560,7 +560,7 @@ fn test_list_append() {
]);
let list_value_offsets = Buffer::from_slice_ref([0i32, 3, 5, 11, 13, 13, 15, 15, 17]);
let expected_list_data = ArrayData::try_new(
- DataType::List(Box::new(Field::new("item", DataType::Int64, true))),
+ DataType::List(Arc::new(Field::new("item", DataType::Int64, true))),
8,
None,
0,
@@ -639,7 +639,7 @@ fn test_list_nulls_append() {
let list_value_offsets =
Buffer::from_slice_ref([0, 3, 5, 5, 13, 15, 15, 15, 19, 19, 19, 19, 23]);
let expected_list_data = ArrayData::try_new(
- DataType::List(Box::new(Field::new("item", DataType::Int64, true))),
+ DataType::List(Arc::new(Field::new("item", DataType::Int64, true))),
12,
Some(Buffer::from(&[0b11011011, 0b1110])),
0,
@@ -776,7 +776,7 @@ fn test_map_nulls_append() {
let expected_list_data = ArrayData::try_new(
DataType::Map(
- Box::new(Field::new(
+ Arc::new(Field::new(
"entries",
DataType::Struct(Fields::from(vec![
Field::new("keys", DataType::Int64, false),
@@ -854,7 +854,7 @@ fn test_list_of_strings_append() {
]);
let list_value_offsets = Buffer::from_slice_ref([0, 3, 5, 6, 9, 10, 13]);
let expected_list_data = ArrayData::try_new(
- DataType::List(Box::new(Field::new("item", DataType::Utf8, true))),
+ DataType::List(Arc::new(Field::new("item", DataType::Utf8, true))),
6,
None,
0,
@@ -986,7 +986,7 @@ fn test_fixed_size_list_append() -> Result<()> {
]);
let expected_list_data = ArrayData::new(
DataType::FixedSizeList(
- Box::new(Field::new("item", DataType::UInt16, true)),
+ Arc::new(Field::new("item", DataType::UInt16, true)),
2,
),
12,
diff --git a/arrow/tests/array_validation.rs b/arrow/tests/array_validation.rs
index ef0d40d64e2d..082d020ca462 100644
--- a/arrow/tests/array_validation.rs
+++ b/arrow/tests/array_validation.rs
@@ -367,7 +367,7 @@ fn test_validate_fixed_size_list() {
// 10 is off the end of the buffer
let field = Field::new("field", DataType::Int32, true);
ArrayData::try_new(
- DataType::FixedSizeList(Box::new(field), 2),
+ DataType::FixedSizeList(Arc::new(field), 2),
3,
None,
0,
@@ -715,7 +715,7 @@ fn check_list_offsets<T: ArrowNativeType>(data_type: DataType) {
)]
fn test_validate_list_offsets() {
let field_type = Field::new("f", DataType::Int32, true);
- check_list_offsets::<i32>(DataType::List(Box::new(field_type)));
+ check_list_offsets::<i32>(DataType::List(Arc::new(field_type)));
}
#[test]
@@ -724,7 +724,7 @@ fn test_validate_list_offsets() {
)]
fn test_validate_large_list_offsets() {
let field_type = Field::new("f", DataType::Int32, true);
- check_list_offsets::<i64>(DataType::LargeList(Box::new(field_type)));
+ check_list_offsets::<i64>(DataType::LargeList(Arc::new(field_type)));
}
/// Test that the list of type `data_type` generates correct errors for negative offsets
@@ -735,7 +735,7 @@ fn test_validate_large_list_offsets() {
fn test_validate_list_negative_offsets() {
let values: Int32Array = [Some(1), Some(2), Some(3), Some(4)].into_iter().collect();
let field_type = Field::new("f", values.data_type().clone(), true);
- let data_type = DataType::List(Box::new(field_type));
+ let data_type = DataType::List(Arc::new(field_type));
// -1 is an invalid offset any way you look at it
let offsets: Vec<i32> = vec![0, 2, -1, 4];
@@ -1027,7 +1027,7 @@ fn test_sliced_array_child() {
let offsets = Buffer::from_iter([1_i32, 3_i32]);
let list_field = Field::new("element", DataType::Int32, false);
- let data_type = DataType::List(Box::new(list_field));
+ let data_type = DataType::List(Arc::new(list_field));
let data = unsafe {
ArrayData::new_unchecked(
|
Reduce Cloning of Field
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
<!--
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
(This section helps Arrow developers understand the context and *why* for this feature, in addition to the *what*)
-->
Currently `DataType` and `Schema` use `Box<Field>` and `Vec<Field>` for nested types such as `StructArray`, etc... This has a couple of drawbacks:
* `Field` is not cheap to clone, involving cloning `String`, `DataType`, and potentially `HashMap`
* `DataType` comparison cannot make use of cheap pointer comparison
* Converting between `DataType::Struct` and `Schema` is unnecessarily expensive
**Describe the solution you'd like**
<!--
A clear and concise description of what you want to happen.
-->
`DataType` should be updated to use `Arc<Field>` instead of `Box<Field>` and `Arc<[Field]>` instead of `Vec<Field>`.
Similarly `Schema::new` should be updated to accept `impl Into<Arc<[Field]>>`
**Describe alternatives you've considered**
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
We could instead move the `Arc` inside of `Field` i.e. `struct Field(Arc<FieldInner>)`. This would potentially help codepaths that project or otherwise rearrange fields within a `Vec<Field>` but at the cost of an additional indirection. It is also unclear how to support this with the builder APIs added in https://github.com/apache/arrow-rs/pull/2024
We could also introduce a FieldPtr type and use this where we currently use Field
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
|
This would be a potentially breaking change as https://github.com/apache/arrow-rs/pull/2239 made Schema's fields public...
I believe @tustvold is working on this, so assigning to him
|
2023-03-30T14:17:08Z
|
36.0
|
4e7bb45050622d5b43505aa64dacf410cb329941
|
apache/arrow-rs
| 3,961
|
apache__arrow-rs-3961
|
[
"3826"
] |
9bd2bae586ed5b0edfd699f89a0855d79f61b611
|
diff --git a/arrow-cast/src/cast.rs b/arrow-cast/src/cast.rs
index ba909649da3a..7ff7bcdd09f3 100644
--- a/arrow-cast/src/cast.rs
+++ b/arrow-cast/src/cast.rs
@@ -157,8 +157,9 @@ pub fn can_cast_types(from_type: &DataType, to_type: &DataType) -> bool {
(_, Boolean) => DataType::is_numeric(from_type) || from_type == &Utf8 || from_type == &LargeUtf8,
(Boolean, _) => DataType::is_numeric(to_type) || to_type == &Utf8 || to_type == &LargeUtf8,
- (Binary, LargeBinary | Utf8 | LargeUtf8) => true,
- (LargeBinary, Binary | Utf8 | LargeUtf8) => true,
+ (Binary, LargeBinary | Utf8 | LargeUtf8 | FixedSizeBinary(_)) => true,
+ (LargeBinary, Binary | Utf8 | LargeUtf8 | FixedSizeBinary(_)) => true,
+ (FixedSizeBinary(_), Binary | LargeBinary) => true,
(Utf8,
Binary
| LargeBinary
@@ -1242,6 +1243,9 @@ pub fn cast_with_options(
LargeBinary => {
cast_byte_container::<BinaryType, LargeBinaryType>(array)
}
+ FixedSizeBinary(size) => {
+ cast_binary_to_fixed_size_binary::<i32>(array,*size, cast_options)
+ }
_ => Err(ArrowError::CastError(format!(
"Casting from {from_type:?} to {to_type:?} not supported",
))),
@@ -1253,6 +1257,17 @@ pub fn cast_with_options(
}
LargeUtf8 => cast_binary_to_string::<i64>(array, cast_options),
Binary => cast_byte_container::<LargeBinaryType, BinaryType>(array),
+ FixedSizeBinary(size) => {
+ cast_binary_to_fixed_size_binary::<i64>(array, *size, cast_options)
+ }
+ _ => Err(ArrowError::CastError(format!(
+ "Casting from {from_type:?} to {to_type:?} not supported",
+ ))),
+ },
+ (FixedSizeBinary(size), _) => match to_type {
+ Binary => cast_fixed_size_binary_to_binary::<i32>(array, *size),
+ LargeBinary =>
+ cast_fixed_size_binary_to_binary::<i64>(array, *size),
_ => Err(ArrowError::CastError(format!(
"Casting from {from_type:?} to {to_type:?} not supported",
))),
@@ -3390,6 +3405,69 @@ fn cast_binary_to_string<O: OffsetSizeTrait>(
}
}
+/// Helper function to cast from one `BinaryArray` or 'LargeBinaryArray' to 'FixedSizeBinaryArray'.
+fn cast_binary_to_fixed_size_binary<O: OffsetSizeTrait>(
+ array: &dyn Array,
+ byte_width: i32,
+ cast_options: &CastOptions,
+) -> Result<ArrayRef, ArrowError> {
+ let array = array.as_binary::<O>();
+ let mut builder = FixedSizeBinaryBuilder::with_capacity(array.len(), byte_width);
+
+ for i in 0..array.len() {
+ if array.is_null(i) {
+ builder.append_null();
+ } else {
+ match builder.append_value(array.value(i)) {
+ Ok(_) => {}
+ Err(e) => match cast_options.safe {
+ true => builder.append_null(),
+ false => return Err(e),
+ },
+ }
+ }
+ }
+
+ Ok(Arc::new(builder.finish()))
+}
+
+/// Helper function to cast from 'FixedSizeBinaryArray' to one `BinaryArray` or 'LargeBinaryArray'.
+/// If the target one is too large for the source array it will return an Error.
+fn cast_fixed_size_binary_to_binary<O: OffsetSizeTrait>(
+ array: &dyn Array,
+ byte_width: i32,
+) -> Result<ArrayRef, ArrowError> {
+ let array = array
+ .as_any()
+ .downcast_ref::<FixedSizeBinaryArray>()
+ .unwrap();
+
+ let offsets: i128 = byte_width as i128 * array.len() as i128;
+
+ let is_binary = matches!(GenericBinaryType::<O>::DATA_TYPE, DataType::Binary);
+ if is_binary && offsets > i32::MAX as i128 {
+ return Err(ArrowError::ComputeError(
+ "FixedSizeBinary array too large to cast to Binary array".to_string(),
+ ));
+ } else if !is_binary && offsets > i64::MAX as i128 {
+ return Err(ArrowError::ComputeError(
+ "FixedSizeBinary array too large to cast to LargeBinary array".to_string(),
+ ));
+ }
+
+ let mut builder = GenericBinaryBuilder::<O>::with_capacity(array.len(), array.len());
+
+ for i in 0..array.len() {
+ if array.is_null(i) {
+ builder.append_null();
+ } else {
+ builder.append_value(array.value(i));
+ }
+ }
+
+ Ok(Arc::new(builder.finish()))
+}
+
/// Helper function to cast from one `ByteArrayType` to another and vice versa.
/// If the target one (e.g., `LargeUtf8`) is too large for the source array it will return an Error.
fn cast_byte_container<FROM, TO>(array: &dyn Array) -> Result<ArrayRef, ArrowError>
@@ -5296,31 +5374,74 @@ mod tests {
}
#[test]
- fn test_cast_string_to_binary() {
- let string_1 = "Hi";
- let string_2 = "Hello";
-
- let bytes_1 = string_1.as_bytes();
- let bytes_2 = string_2.as_bytes();
+ fn test_cast_binary_to_fixed_size_binary() {
+ let bytes_1 = "Hiiii".as_bytes();
+ let bytes_2 = "Hello".as_bytes();
- let string_data = vec![Some(string_1), Some(string_2), None];
- let a1 = Arc::new(StringArray::from(string_data.clone())) as ArrayRef;
- let a2 = Arc::new(LargeStringArray::from(string_data)) as ArrayRef;
+ let binary_data = vec![Some(bytes_1), Some(bytes_2), None];
+ let a1 = Arc::new(BinaryArray::from(binary_data.clone())) as ArrayRef;
+ let a2 = Arc::new(LargeBinaryArray::from(binary_data)) as ArrayRef;
- let mut array_ref = cast(&a1, &DataType::Binary).unwrap();
- let down_cast = array_ref.as_any().downcast_ref::<BinaryArray>().unwrap();
+ let array_ref = cast(&a1, &DataType::FixedSizeBinary(5)).unwrap();
+ let down_cast = array_ref
+ .as_any()
+ .downcast_ref::<FixedSizeBinaryArray>()
+ .unwrap();
assert_eq!(bytes_1, down_cast.value(0));
assert_eq!(bytes_2, down_cast.value(1));
assert!(down_cast.is_null(2));
- array_ref = cast(&a2, &DataType::LargeBinary).unwrap();
+ let array_ref = cast(&a2, &DataType::FixedSizeBinary(5)).unwrap();
let down_cast = array_ref
.as_any()
- .downcast_ref::<LargeBinaryArray>()
+ .downcast_ref::<FixedSizeBinaryArray>()
.unwrap();
assert_eq!(bytes_1, down_cast.value(0));
assert_eq!(bytes_2, down_cast.value(1));
assert!(down_cast.is_null(2));
+
+ // test error cases when the length of binary are not same
+ let bytes_1 = "Hi".as_bytes();
+ let bytes_2 = "Hello".as_bytes();
+
+ let binary_data = vec![Some(bytes_1), Some(bytes_2), None];
+ let a1 = Arc::new(BinaryArray::from(binary_data.clone())) as ArrayRef;
+ let a2 = Arc::new(LargeBinaryArray::from(binary_data)) as ArrayRef;
+
+ let array_ref = cast_with_options(
+ &a1,
+ &DataType::FixedSizeBinary(5),
+ &CastOptions { safe: false },
+ );
+ assert!(array_ref.is_err());
+
+ let array_ref = cast_with_options(
+ &a2,
+ &DataType::FixedSizeBinary(5),
+ &CastOptions { safe: false },
+ );
+ assert!(array_ref.is_err());
+ }
+
+ #[test]
+ fn test_fixed_size_binary_to_binary() {
+ let bytes_1 = "Hiiii".as_bytes();
+ let bytes_2 = "Hello".as_bytes();
+
+ let binary_data = vec![Some(bytes_1), Some(bytes_2), None];
+ let a1 = Arc::new(FixedSizeBinaryArray::from(binary_data.clone())) as ArrayRef;
+
+ let array_ref = cast(&a1, &DataType::Binary).unwrap();
+ let down_cast = array_ref.as_binary::<i32>();
+ assert_eq!(bytes_1, down_cast.value(0));
+ assert_eq!(bytes_2, down_cast.value(1));
+ assert!(down_cast.is_null(2));
+
+ let array_ref = cast(&a1, &DataType::LargeBinary).unwrap();
+ let down_cast = array_ref.as_binary::<i64>();
+ assert_eq!(bytes_1, down_cast.value(0));
+ assert_eq!(bytes_2, down_cast.value(1));
+ assert!(down_cast.is_null(2));
}
#[test]
|
diff --git a/arrow/tests/array_cast.rs b/arrow/tests/array_cast.rs
index 33695e2edeb6..4c1f5019597c 100644
--- a/arrow/tests/array_cast.rs
+++ b/arrow/tests/array_cast.rs
@@ -388,7 +388,7 @@ fn get_all_types() -> Vec<DataType> {
Interval(IntervalUnit::DayTime),
Interval(IntervalUnit::MonthDayNano),
Binary,
- FixedSizeBinary(10),
+ FixedSizeBinary(3),
LargeBinary,
Utf8,
LargeUtf8,
|
Support Casting Between Binary / LargeBinary and FixedSizeBinary
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
<!--
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
(This section helps Arrow developers understand the context and *why* for this feature, in addition to the *what*)
-->
Currently arrow_cast does not have any support for FixedSizeBinary outside of casting to a `NullArray`, this should be fixed
**Describe the solution you'd like**
<!--
A clear and concise description of what you want to happen.
-->
* A conversion to FixedSizeBinary that verifies that all the slices have the correct length
* An conversion to Binary / LargeBinary that creates a new set of offsets, first verifying this won't overflow the offset type
**Describe alternatives you've considered**
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
|
@tustvold what do you think about casting between UTF8 and FixedSizeBinary? If that is worth it I will file a separate ticket
> what do you think about casting between UTF8 and FixedSizeBinary
Given the cast from UTF8 -> Binary is purely a metadata operation, I see no reason we couldn't support this using the same logic.
That being said, I should highlight that the cast peformed by arrow-cast, casts the underlying bytes themselves, which may not be what people are after in the case of https://github.com/apache/arrow-datafusion/issues/5530
In particular `'002920a3044b3c9f56e797b8'` would be converted to `[48, 48, 50, 57, ...]` not `[0x00, 0x00, ...]`
I think it is better to encourage users to specify the correct types, e.g. `bytea` literals, instead of relying on casting UTF8 strings
Could I pick this up?
|
2023-03-27T17:05:51Z
|
36.0
|
4e7bb45050622d5b43505aa64dacf410cb329941
|
apache/arrow-rs
| 3,944
|
apache__arrow-rs-3944
|
[
"478"
] |
888c1cab7c76f0b28cecdd704c14e42256736def
|
diff --git a/arrow-schema/src/ffi.rs b/arrow-schema/src/ffi.rs
index 8e58e3158c8b..058febbdd35c 100644
--- a/arrow-schema/src/ffi.rs
+++ b/arrow-schema/src/ffi.rs
@@ -36,7 +36,10 @@
use crate::{ArrowError, DataType, Field, Schema, TimeUnit, UnionMode};
use bitflags::bitflags;
-use std::ffi::{c_char, c_void, CStr, CString};
+use std::{
+ collections::HashMap,
+ ffi::{c_char, c_void, CStr, CString},
+};
bitflags! {
pub struct Flags: i64 {
@@ -74,6 +77,7 @@ pub struct FFI_ArrowSchema {
struct SchemaPrivateData {
children: Box<[*mut FFI_ArrowSchema]>,
dictionary: *mut FFI_ArrowSchema,
+ metadata: Option<Vec<u8>>,
}
// callback used to drop [FFI_ArrowSchema] when it is exported.
@@ -130,6 +134,7 @@ impl FFI_ArrowSchema {
let mut private_data = Box::new(SchemaPrivateData {
children: children_ptr,
dictionary: dictionary_ptr,
+ metadata: None,
});
// intentionally set from private_data (see https://github.com/apache/arrow-rs/issues/580)
@@ -152,6 +157,63 @@ impl FFI_ArrowSchema {
Ok(self)
}
+ pub fn with_metadata<I, S>(mut self, metadata: I) -> Result<Self, ArrowError>
+ where
+ I: IntoIterator<Item = (S, S)>,
+ S: AsRef<str>,
+ {
+ let metadata: Vec<(S, S)> = metadata.into_iter().collect();
+ // https://arrow.apache.org/docs/format/CDataInterface.html#c.ArrowSchema.metadata
+ let new_metadata = if !metadata.is_empty() {
+ let mut metadata_serialized: Vec<u8> = Vec::new();
+ let num_entries: i32 = metadata.len().try_into().map_err(|_| {
+ ArrowError::CDataInterface(format!(
+ "metadata can only have {} entries, but {} were provided",
+ i32::MAX,
+ metadata.len()
+ ))
+ })?;
+ metadata_serialized.extend(num_entries.to_ne_bytes());
+
+ for (key, value) in metadata.into_iter() {
+ let key_len: i32 = key.as_ref().len().try_into().map_err(|_| {
+ ArrowError::CDataInterface(format!(
+ "metadata key can only have {} bytes, but {} were provided",
+ i32::MAX,
+ key.as_ref().len()
+ ))
+ })?;
+ let value_len: i32 = value.as_ref().len().try_into().map_err(|_| {
+ ArrowError::CDataInterface(format!(
+ "metadata value can only have {} bytes, but {} were provided",
+ i32::MAX,
+ value.as_ref().len()
+ ))
+ })?;
+
+ metadata_serialized.extend(key_len.to_ne_bytes());
+ metadata_serialized.extend_from_slice(key.as_ref().as_bytes());
+ metadata_serialized.extend(value_len.to_ne_bytes());
+ metadata_serialized.extend_from_slice(value.as_ref().as_bytes());
+ }
+
+ self.metadata = metadata_serialized.as_ptr() as *const c_char;
+ Some(metadata_serialized)
+ } else {
+ self.metadata = std::ptr::null_mut();
+ None
+ };
+
+ unsafe {
+ let mut private_data =
+ Box::from_raw(self.private_data as *mut SchemaPrivateData);
+ private_data.metadata = new_metadata;
+ self.private_data = Box::into_raw(private_data) as *mut c_void;
+ }
+
+ Ok(self)
+ }
+
pub fn empty() -> Self {
Self {
format: std::ptr::null_mut(),
@@ -212,6 +274,71 @@ impl FFI_ArrowSchema {
pub fn dictionary_ordered(&self) -> bool {
self.flags & 0b00000001 != 0
}
+
+ pub fn metadata(&self) -> Result<HashMap<String, String>, ArrowError> {
+ if self.metadata.is_null() {
+ Ok(HashMap::new())
+ } else {
+ let mut pos = 0;
+ let buffer: *const u8 = self.metadata as *const u8;
+
+ fn next_four_bytes(buffer: *const u8, pos: &mut isize) -> [u8; 4] {
+ let out = unsafe {
+ [
+ *buffer.offset(*pos),
+ *buffer.offset(*pos + 1),
+ *buffer.offset(*pos + 2),
+ *buffer.offset(*pos + 3),
+ ]
+ };
+ *pos += 4;
+ out
+ }
+
+ fn next_n_bytes(buffer: *const u8, pos: &mut isize, n: i32) -> &[u8] {
+ let out = unsafe {
+ std::slice::from_raw_parts(buffer.offset(*pos), n.try_into().unwrap())
+ };
+ *pos += isize::try_from(n).unwrap();
+ out
+ }
+
+ let num_entries = i32::from_ne_bytes(next_four_bytes(buffer, &mut pos));
+ if num_entries < 0 {
+ return Err(ArrowError::CDataInterface(
+ "Negative number of metadata entries".to_string(),
+ ));
+ }
+
+ let mut metadata = HashMap::with_capacity(
+ num_entries.try_into().expect("Too many metadata entries"),
+ );
+
+ for _ in 0..num_entries {
+ let key_length = i32::from_ne_bytes(next_four_bytes(buffer, &mut pos));
+ if key_length < 0 {
+ return Err(ArrowError::CDataInterface(
+ "Negative key length in metadata".to_string(),
+ ));
+ }
+ let key = String::from_utf8(
+ next_n_bytes(buffer, &mut pos, key_length).to_vec(),
+ )?;
+ let value_length = i32::from_ne_bytes(next_four_bytes(buffer, &mut pos));
+ if value_length < 0 {
+ return Err(ArrowError::CDataInterface(
+ "Negative value length in metadata".to_string(),
+ ));
+ }
+ let value = String::from_utf8(
+ next_n_bytes(buffer, &mut pos, value_length).to_vec(),
+ )?;
+ metadata.insert(key, value);
+ }
+
+ Ok(metadata)
+ }
+ }
}
impl Drop for FFI_ArrowSchema {
@@ -421,7 +548,8 @@ impl TryFrom<&FFI_ArrowSchema> for Field {
fn try_from(c_schema: &FFI_ArrowSchema) -> Result<Self, ArrowError> {
let dtype = DataType::try_from(c_schema)?;
- let field = Field::new(c_schema.name(), dtype, c_schema.nullable());
+ let mut field = Field::new(c_schema.name(), dtype, c_schema.nullable());
+ field.set_metadata(c_schema.metadata()?);
Ok(field)
}
}
@@ -433,7 +561,7 @@ impl TryFrom<&FFI_ArrowSchema> for Schema {
// interpret it as a struct type then extract its fields
let dtype = DataType::try_from(c_schema)?;
if let DataType::Struct(fields) = dtype {
- Ok(Schema::new(fields))
+ Ok(Schema::new(fields).with_metadata(c_schema.metadata()?))
} else {
Err(ArrowError::CDataInterface(
"Unable to interpret C data struct as a Schema".to_string(),
@@ -558,7 +686,8 @@ impl TryFrom<&Field> for FFI_ArrowSchema {
FFI_ArrowSchema::try_from(field.data_type())?
.with_name(field.name())?
- .with_flags(flags)
+ .with_flags(flags)?
+ .with_metadata(field.metadata())
}
}
@@ -567,7 +696,8 @@ impl TryFrom<&Schema> for FFI_ArrowSchema {
fn try_from(schema: &Schema) -> Result<Self, ArrowError> {
let dtype = DataType::Struct(schema.fields().clone());
- let c_schema = FFI_ArrowSchema::try_from(&dtype)?;
+ let c_schema =
+ FFI_ArrowSchema::try_from(&dtype)?.with_metadata(&schema.metadata)?;
Ok(c_schema)
}
}
@@ -655,7 +785,9 @@ mod tests {
Field::new("name", DataType::Utf8, false),
Field::new("address", DataType::Utf8, false),
Field::new("priority", DataType::UInt8, false),
- ]);
+ ])
+ .with_metadata([("hello".to_string(), "world".to_string())].into());
+
round_trip_schema(schema);
// test that we can interpret struct types as schema
@@ -700,4 +832,29 @@ mod tests {
let arrow_schema = FFI_ArrowSchema::try_from(schema).unwrap();
assert!(arrow_schema.child(0).dictionary_ordered());
}
+
+ #[test]
+ fn test_set_field_metadata() {
+ let metadata_cases: Vec<HashMap<String, String>> = vec![
+ [].into(),
+ [("key".to_string(), "value".to_string())].into(),
+ [
+ ("key".to_string(), "".to_string()),
+ ("ascii123".to_string(), "你好".to_string()),
+ ("".to_string(), "value".to_string()),
+ ]
+ .into(),
+ ];
+
+ let mut schema = FFI_ArrowSchema::try_new("b", vec![], None)
+ .unwrap()
+ .with_name("test")
+ .unwrap();
+
+ for metadata in metadata_cases {
+ schema = schema.with_metadata(&metadata).unwrap();
+ let field = Field::try_from(&schema).unwrap();
+ assert_eq!(field.metadata(), &metadata);
+ }
+ }
}
diff --git a/arrow/src/ffi.rs b/arrow/src/ffi.rs
index 9d0ed0b85fb6..9179b1279ff6 100644
--- a/arrow/src/ffi.rs
+++ b/arrow/src/ffi.rs
@@ -497,7 +497,8 @@ mod tests {
use crate::datatypes::{Field, Int8Type};
use arrow_array::builder::UnionBuilder;
use arrow_array::types::{Float64Type, Int32Type};
- use arrow_array::{Float64Array, UnionArray};
+ use arrow_array::{Float64Array, StructArray, UnionArray};
+ use std::collections::HashMap;
use std::convert::TryFrom;
use std::mem::ManuallyDrop;
use std::ptr::addr_of_mut;
@@ -1092,6 +1093,30 @@ mod tests {
Ok(())
}
+ #[test]
+ fn test_struct_array() -> Result<()> {
+ let metadata: HashMap<String, String> =
+ [("Hello".to_string(), "World! 😊".to_string())].into();
+ let struct_array = StructArray::from(vec![(
+ Field::new("a", DataType::Int32, false).with_metadata(metadata),
+ Arc::new(Int32Array::from(vec![2, 4, 6])) as Arc<dyn Array>,
+ )]);
+
+ // export it
+ let array = ArrowArray::try_from(struct_array.data().clone())?;
+
+ // (simulate consumer) import it
+ let data = ArrayData::try_from(array)?;
+ let array = make_array(data);
+
+ // perform some operation
+ let array = array.as_any().downcast_ref::<StructArray>().unwrap();
+ assert_eq!(array.data_type(), struct_array.data_type());
+ assert_eq!(array, &struct_array);
+
+ Ok(())
+ }
+
#[test]
fn test_union_sparse_array() -> Result<()> {
let mut builder = UnionBuilder::new_sparse();
|
diff --git a/arrow-pyarrow-integration-testing/tests/test_sql.py b/arrow-pyarrow-integration-testing/tests/test_sql.py
index 98564408d937..f631f67cbfea 100644
--- a/arrow-pyarrow-integration-testing/tests/test_sql.py
+++ b/arrow-pyarrow-integration-testing/tests/test_sql.py
@@ -138,6 +138,12 @@ def test_field_roundtrip(pyarrow_type):
field = rust.round_trip_field(pyarrow_field)
assert field == pyarrow_field
+def test_field_metadata_roundtrip():
+ metadata = {"hello": "World! 😊", "x": "2"}
+ pyarrow_field = pa.field("test", pa.int32(), metadata=metadata)
+ field = rust.round_trip_field(pyarrow_field)
+ assert field == pyarrow_field
+ assert field.metadata == pyarrow_field.metadata
def test_schema_roundtrip():
pyarrow_fields = zip(string.ascii_lowercase, _supported_pyarrow_types)
|
Exchange key-value metadata in the python FFI bridge
The `key_value_metadata` is currently ignored, we should add support for exchanging it for both the schema-like and array objects.
|
2023-03-25T23:27:26Z
|
36.0
|
4e7bb45050622d5b43505aa64dacf410cb329941
|
|
apache/arrow-rs
| 3,930
|
apache__arrow-rs-3930
|
[
"3929"
] |
5eeccab922c377a18e54cf39ad49a2e4d54ffaf2
|
diff --git a/arrow-arith/src/aggregate.rs b/arrow-arith/src/aggregate.rs
index 9e9d9333fdcb..a9944db13ee1 100644
--- a/arrow-arith/src/aggregate.rs
+++ b/arrow-arith/src/aggregate.rs
@@ -1219,13 +1219,12 @@ mod tests {
.into_iter()
.collect();
let sliced_input = sliced_input.slice(4, 2);
- let sliced_input = sliced_input.as_primitive::<Float64Type>();
- assert_eq!(sliced_input, &input);
+ assert_eq!(&sliced_input, &input);
- let actual = min(sliced_input);
+ let actual = min(&sliced_input);
assert_eq!(actual, expected);
- let actual = max(sliced_input);
+ let actual = max(&sliced_input);
assert_eq!(actual, expected);
}
@@ -1265,13 +1264,12 @@ mod tests {
.into_iter()
.collect();
let sliced_input = sliced_input.slice(4, 2);
- let sliced_input = sliced_input.as_string::<i32>();
- assert_eq!(sliced_input, &input);
+ assert_eq!(&sliced_input, &input);
- let actual = min_string(sliced_input);
+ let actual = min_string(&sliced_input);
assert_eq!(actual, expected);
- let actual = max_string(sliced_input);
+ let actual = max_string(&sliced_input);
assert_eq!(actual, expected);
}
@@ -1288,13 +1286,12 @@ mod tests {
.into_iter()
.collect();
let sliced_input = sliced_input.slice(4, 2);
- let sliced_input = sliced_input.as_binary::<i32>();
- assert_eq!(sliced_input, &input);
+ assert_eq!(&sliced_input, &input);
- let actual = min_binary(sliced_input);
+ let actual = min_binary(&sliced_input);
assert_eq!(actual, expected);
- let actual = max_binary(sliced_input);
+ let actual = max_binary(&sliced_input);
assert_eq!(actual, expected);
}
diff --git a/arrow-arith/src/arithmetic.rs b/arrow-arith/src/arithmetic.rs
index 7d60d131bf52..b7174711fd5a 100644
--- a/arrow-arith/src/arithmetic.rs
+++ b/arrow-arith/src/arithmetic.rs
@@ -2043,7 +2043,7 @@ mod tests {
fn test_primitive_array_add_scalar_sliced() {
let a = Int32Array::from(vec![Some(15), None, Some(9), Some(8), None]);
let a = a.slice(1, 4);
- let actual = add_scalar(a.as_primitive(), 3).unwrap();
+ let actual = add_scalar(&a, 3).unwrap();
let expected = Int32Array::from(vec![None, Some(12), Some(11), None]);
assert_eq!(actual, expected);
}
@@ -2073,7 +2073,7 @@ mod tests {
fn test_primitive_array_subtract_scalar_sliced() {
let a = Int32Array::from(vec![Some(15), None, Some(9), Some(8), None]);
let a = a.slice(1, 4);
- let actual = subtract_scalar(a.as_primitive(), 3).unwrap();
+ let actual = subtract_scalar(&a, 3).unwrap();
let expected = Int32Array::from(vec![None, Some(6), Some(5), None]);
assert_eq!(actual, expected);
}
@@ -2103,7 +2103,7 @@ mod tests {
fn test_primitive_array_multiply_scalar_sliced() {
let a = Int32Array::from(vec![Some(15), None, Some(9), Some(8), None]);
let a = a.slice(1, 4);
- let actual = multiply_scalar(a.as_primitive(), 3).unwrap();
+ let actual = multiply_scalar(&a, 3).unwrap();
let expected = Int32Array::from(vec![None, Some(27), Some(24), None]);
assert_eq!(actual, expected);
}
@@ -2223,7 +2223,7 @@ mod tests {
fn test_primitive_array_divide_scalar_sliced() {
let a = Int32Array::from(vec![Some(15), None, Some(9), Some(8), None]);
let a = a.slice(1, 4);
- let actual = divide_scalar(a.as_primitive(), 3).unwrap();
+ let actual = divide_scalar(&a, 3).unwrap();
let expected = Int32Array::from(vec![None, Some(3), Some(2), None]);
assert_eq!(actual, expected);
}
@@ -2246,12 +2246,11 @@ mod tests {
fn test_int_array_modulus_scalar_sliced() {
let a = Int32Array::from(vec![Some(15), None, Some(9), Some(8), None]);
let a = a.slice(1, 4);
- let a = a.as_primitive();
- let actual = modulus_scalar(a, 3).unwrap();
+ let actual = modulus_scalar(&a, 3).unwrap();
let expected = Int32Array::from(vec![None, Some(0), Some(2), None]);
assert_eq!(actual, expected);
- let actual = modulus_scalar_dyn::<Int32Type>(a, 3).unwrap();
+ let actual = modulus_scalar_dyn::<Int32Type>(&a, 3).unwrap();
let actual = actual.as_primitive::<Int32Type>();
let expected = Int32Array::from(vec![None, Some(0), Some(2), None]);
assert_eq!(actual, &expected);
diff --git a/arrow-arith/src/arity.rs b/arrow-arith/src/arity.rs
index 501a240f37d5..d69bbde8d056 100644
--- a/arrow-arith/src/arity.rs
+++ b/arrow-arith/src/arity.rs
@@ -499,7 +499,6 @@ where
mod tests {
use super::*;
use arrow_array::builder::*;
- use arrow_array::cast::*;
use arrow_array::types::*;
#[test]
@@ -507,14 +506,13 @@ mod tests {
let input =
Float64Array::from(vec![Some(5.1f64), None, Some(6.8), None, Some(7.2)]);
let input_slice = input.slice(1, 4);
- let input_slice: &Float64Array = input_slice.as_primitive();
- let result = unary(input_slice, |n| n.round());
+ let result = unary(&input_slice, |n| n.round());
assert_eq!(
result,
Float64Array::from(vec![None, Some(7.0), None, Some(7.0)])
);
- let result = unary_dyn::<_, Float64Type>(input_slice, |n| n + 1.0).unwrap();
+ let result = unary_dyn::<_, Float64Type>(&input_slice, |n| n + 1.0).unwrap();
assert_eq!(
result.as_any().downcast_ref::<Float64Array>().unwrap(),
diff --git a/arrow-arith/src/boolean.rs b/arrow-arith/src/boolean.rs
index eaef1378258b..258d683ad71a 100644
--- a/arrow-arith/src/boolean.rs
+++ b/arrow-arith/src/boolean.rs
@@ -775,7 +775,7 @@ mod tests {
let a = Int32Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1]);
let a = a.slice(8, 4);
- let res = is_null(a.as_ref()).unwrap();
+ let res = is_null(&a).unwrap();
let expected = BooleanArray::from(vec![false, false, false, false]);
@@ -800,7 +800,7 @@ mod tests {
let a = Int32Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1]);
let a = a.slice(8, 4);
- let res = is_not_null(a.as_ref()).unwrap();
+ let res = is_not_null(&a).unwrap();
let expected = BooleanArray::from(vec![true, true, true, true]);
@@ -843,7 +843,7 @@ mod tests {
]);
let a = a.slice(8, 4);
- let res = is_null(a.as_ref()).unwrap();
+ let res = is_null(&a).unwrap();
let expected = BooleanArray::from(vec![false, true, false, true]);
@@ -886,7 +886,7 @@ mod tests {
]);
let a = a.slice(8, 4);
- let res = is_not_null(a.as_ref()).unwrap();
+ let res = is_not_null(&a).unwrap();
let expected = BooleanArray::from(vec![true, false, true, false]);
diff --git a/arrow-array/src/array/byte_array.rs b/arrow-array/src/array/byte_array.rs
index 991e02501505..34e7d79ab3e0 100644
--- a/arrow-array/src/array/byte_array.rs
+++ b/arrow-array/src/array/byte_array.rs
@@ -134,6 +134,12 @@ impl<T: ByteArrayType> GenericByteArray<T> {
ArrayIter::new(self)
}
+ /// Returns a zero-copy slice of this array with the indicated offset and length.
+ pub fn slice(&self, offset: usize, length: usize) -> Self {
+ // TODO: Slice buffers directly (#3880)
+ self.data.slice(offset, length).into()
+ }
+
/// Returns `GenericByteBuilder` of this byte array for mutating its values if the underlying
/// offset and data buffers are not shared by others.
pub fn into_builder(self) -> Result<GenericByteBuilder<T>, Self> {
@@ -247,8 +253,7 @@ impl<T: ByteArrayType> Array for GenericByteArray<T> {
}
fn slice(&self, offset: usize, length: usize) -> ArrayRef {
- // TODO: Slice buffers directly (#3880)
- Arc::new(Self::from(self.data.slice(offset, length)))
+ Arc::new(self.slice(offset, length))
}
fn nulls(&self) -> Option<&NullBuffer> {
diff --git a/arrow-array/src/array/dictionary_array.rs b/arrow-array/src/array/dictionary_array.rs
index 49a184369801..343fed76846a 100644
--- a/arrow-array/src/array/dictionary_array.rs
+++ b/arrow-array/src/array/dictionary_array.rs
@@ -323,6 +323,12 @@ impl<K: ArrowDictionaryKeyType> DictionaryArray<K> {
self.keys.is_valid(i).then(|| self.keys.value(i).as_usize())
}
+ /// Returns a zero-copy slice of this array with the indicated offset and length.
+ pub fn slice(&self, offset: usize, length: usize) -> Self {
+ // TODO: Slice buffers directly (#3880)
+ self.data.slice(offset, length).into()
+ }
+
/// Downcast this dictionary to a [`TypedDictionaryArray`]
///
/// ```
@@ -601,8 +607,7 @@ impl<T: ArrowDictionaryKeyType> Array for DictionaryArray<T> {
}
fn slice(&self, offset: usize, length: usize) -> ArrayRef {
- // TODO: Slice buffers directly (#3880)
- Arc::new(Self::from(self.data.slice(offset, length)))
+ Arc::new(self.slice(offset, length))
}
fn nulls(&self) -> Option<&NullBuffer> {
@@ -693,7 +698,7 @@ impl<'a, K: ArrowDictionaryKeyType, V: Sync> Array for TypedDictionaryArray<'a,
}
fn slice(&self, offset: usize, length: usize) -> ArrayRef {
- self.dictionary.slice(offset, length)
+ Arc::new(self.dictionary.slice(offset, length))
}
fn nulls(&self) -> Option<&NullBuffer> {
diff --git a/arrow-array/src/array/fixed_size_binary_array.rs b/arrow-array/src/array/fixed_size_binary_array.rs
index af51ff787722..bb76fd63d649 100644
--- a/arrow-array/src/array/fixed_size_binary_array.rs
+++ b/arrow-array/src/array/fixed_size_binary_array.rs
@@ -110,6 +110,12 @@ impl FixedSizeBinaryArray {
self.data.buffers()[0].clone()
}
+ /// Returns a zero-copy slice of this array with the indicated offset and length.
+ pub fn slice(&self, offset: usize, length: usize) -> Self {
+ // TODO: Slice buffers directly (#3880)
+ self.data.slice(offset, length).into()
+ }
+
/// Create an array from an iterable argument of sparse byte slices.
/// Sparsity means that items returned by the iterator are optional, i.e input argument can
/// contain `None` items.
@@ -473,8 +479,7 @@ impl Array for FixedSizeBinaryArray {
}
fn slice(&self, offset: usize, length: usize) -> ArrayRef {
- // TODO: Slice buffers directly (#3880)
- Arc::new(Self::from(self.data.slice(offset, length)))
+ Arc::new(self.slice(offset, length))
}
fn nulls(&self) -> Option<&NullBuffer> {
diff --git a/arrow-array/src/array/fixed_size_list_array.rs b/arrow-array/src/array/fixed_size_list_array.rs
index 0910e2944f76..1a421fe53c25 100644
--- a/arrow-array/src/array/fixed_size_list_array.rs
+++ b/arrow-array/src/array/fixed_size_list_array.rs
@@ -106,6 +106,12 @@ impl FixedSizeListArray {
i as i32 * self.length
}
+ /// Returns a zero-copy slice of this array with the indicated offset and length.
+ pub fn slice(&self, offset: usize, length: usize) -> Self {
+ // TODO: Slice buffers directly (#3880)
+ self.data.slice(offset, length).into()
+ }
+
/// Creates a [`FixedSizeListArray`] from an iterator of primitive values
/// # Example
/// ```
@@ -216,8 +222,7 @@ impl Array for FixedSizeListArray {
}
fn slice(&self, offset: usize, length: usize) -> ArrayRef {
- // TODO: Slice buffers directly (#3880)
- Arc::new(Self::from(self.data.slice(offset, length)))
+ Arc::new(self.slice(offset, length))
}
fn nulls(&self) -> Option<&NullBuffer> {
diff --git a/arrow-array/src/array/list_array.rs b/arrow-array/src/array/list_array.rs
index c7e2a817ba33..ba4fa1043cfd 100644
--- a/arrow-array/src/array/list_array.rs
+++ b/arrow-array/src/array/list_array.rs
@@ -132,6 +132,12 @@ impl<OffsetSize: OffsetSizeTrait> GenericListArray<OffsetSize> {
}
}
+ /// Returns a zero-copy slice of this array with the indicated offset and length.
+ pub fn slice(&self, offset: usize, length: usize) -> Self {
+ // TODO: Slice buffers directly (#3880)
+ self.data.slice(offset, length).into()
+ }
+
/// Creates a [`GenericListArray`] from an iterator of primitive values
/// # Example
/// ```
@@ -253,8 +259,7 @@ impl<OffsetSize: OffsetSizeTrait> Array for GenericListArray<OffsetSize> {
}
fn slice(&self, offset: usize, length: usize) -> ArrayRef {
- // TODO: Slice buffers directly (#3880)
- Arc::new(Self::from(self.data.slice(offset, length)))
+ Arc::new(self.slice(offset, length))
}
fn nulls(&self) -> Option<&NullBuffer> {
diff --git a/arrow-array/src/array/map_array.rs b/arrow-array/src/array/map_array.rs
index c9651f0b2019..f3afcb638a43 100644
--- a/arrow-array/src/array/map_array.rs
+++ b/arrow-array/src/array/map_array.rs
@@ -95,6 +95,12 @@ impl MapArray {
let offsets = self.value_offsets();
offsets[i + 1] - offsets[i]
}
+
+ /// Returns a zero-copy slice of this array with the indicated offset and length.
+ pub fn slice(&self, offset: usize, length: usize) -> Self {
+ // TODO: Slice buffers directly (#3880)
+ self.data.slice(offset, length).into()
+ }
}
impl From<ArrayData> for MapArray {
@@ -222,8 +228,7 @@ impl Array for MapArray {
}
fn slice(&self, offset: usize, length: usize) -> ArrayRef {
- // TODO: Slice buffers directly (#3880)
- Arc::new(Self::from(self.data.slice(offset, length)))
+ Arc::new(self.slice(offset, length))
}
fn nulls(&self) -> Option<&NullBuffer> {
diff --git a/arrow-array/src/array/mod.rs b/arrow-array/src/array/mod.rs
index 9afefc07f8d4..9b3855eabafa 100644
--- a/arrow-array/src/array/mod.rs
+++ b/arrow-array/src/array/mod.rs
@@ -141,7 +141,7 @@ pub trait Array: std::fmt::Debug + Send + Sync {
/// // Make slice over the values [2, 3, 4]
/// let array_slice = array.slice(1, 3);
///
- /// assert_eq!(array_slice.as_ref(), &Int32Array::from(vec![2, 3, 4]));
+ /// assert_eq!(&array_slice, &Int32Array::from(vec![2, 3, 4]));
/// ```
fn slice(&self, offset: usize, length: usize) -> ArrayRef;
diff --git a/arrow-array/src/array/null_array.rs b/arrow-array/src/array/null_array.rs
index 3d65e9e9ebad..b5d9247a6d7f 100644
--- a/arrow-array/src/array/null_array.rs
+++ b/arrow-array/src/array/null_array.rs
@@ -54,6 +54,12 @@ impl NullArray {
let array_data = unsafe { array_data.build_unchecked() };
NullArray::from(array_data)
}
+
+ /// Returns a zero-copy slice of this array with the indicated offset and length.
+ pub fn slice(&self, offset: usize, length: usize) -> Self {
+ // TODO: Slice buffers directly (#3880)
+ self.data.slice(offset, length).into()
+ }
}
impl Array for NullArray {
@@ -74,8 +80,7 @@ impl Array for NullArray {
}
fn slice(&self, offset: usize, length: usize) -> ArrayRef {
- // TODO: Slice buffers directly (#3880)
- Arc::new(Self::from(self.data.slice(offset, length)))
+ Arc::new(self.slice(offset, length))
}
fn nulls(&self) -> Option<&NullBuffer> {
diff --git a/arrow-array/src/array/primitive_array.rs b/arrow-array/src/array/primitive_array.rs
index bc62677c738b..92fedfc1ca5d 100644
--- a/arrow-array/src/array/primitive_array.rs
+++ b/arrow-array/src/array/primitive_array.rs
@@ -408,6 +408,12 @@ impl<T: ArrowPrimitiveType> PrimitiveArray<T> {
indexes.map(|opt_index| opt_index.map(|index| self.value_unchecked(index)))
}
+ /// Returns a zero-copy slice of this array with the indicated offset and length.
+ pub fn slice(&self, offset: usize, length: usize) -> Self {
+ // TODO: Slice buffers directly (#3880)
+ self.data.slice(offset, length).into()
+ }
+
/// Reinterprets this array's contents as a different data type without copying
///
/// This can be used to efficiently convert between primitive arrays with the
@@ -706,8 +712,7 @@ impl<T: ArrowPrimitiveType> Array for PrimitiveArray<T> {
}
fn slice(&self, offset: usize, length: usize) -> ArrayRef {
- // TODO: Slice buffers directly (#3880)
- Arc::new(Self::from(self.data.slice(offset, length)))
+ Arc::new(self.slice(offset, length))
}
fn nulls(&self) -> Option<&NullBuffer> {
diff --git a/arrow-array/src/array/run_array.rs b/arrow-array/src/array/run_array.rs
index 652ec0be6e6f..3cd5848f1f49 100644
--- a/arrow-array/src/array/run_array.rs
+++ b/arrow-array/src/array/run_array.rs
@@ -253,6 +253,12 @@ impl<R: RunEndIndexType> RunArray<R> {
}
Ok(physical_indices)
}
+
+ /// Returns a zero-copy slice of this array with the indicated offset and length.
+ pub fn slice(&self, offset: usize, length: usize) -> Self {
+ // TODO: Slice buffers directly (#3880)
+ self.data.slice(offset, length).into()
+ }
}
impl<R: RunEndIndexType> From<ArrayData> for RunArray<R> {
@@ -307,8 +313,7 @@ impl<T: RunEndIndexType> Array for RunArray<T> {
}
fn slice(&self, offset: usize, length: usize) -> ArrayRef {
- // TODO: Slice buffers directly (#3880)
- Arc::new(Self::from(self.data.slice(offset, length)))
+ Arc::new(self.slice(offset, length))
}
fn nulls(&self) -> Option<&NullBuffer> {
@@ -505,7 +510,7 @@ impl<'a, R: RunEndIndexType, V: Sync> Array for TypedRunArray<'a, R, V> {
}
fn slice(&self, offset: usize, length: usize) -> ArrayRef {
- self.run_array.slice(offset, length)
+ Arc::new(self.run_array.slice(offset, length))
}
fn nulls(&self) -> Option<&NullBuffer> {
diff --git a/arrow-array/src/array/struct_array.rs b/arrow-array/src/array/struct_array.rs
index 4fe59c0c240f..4c9613afbf88 100644
--- a/arrow-array/src/array/struct_array.rs
+++ b/arrow-array/src/array/struct_array.rs
@@ -100,6 +100,12 @@ impl StructArray {
.position(|c| c == &column_name)
.map(|pos| self.column(pos))
}
+
+ /// Returns a zero-copy slice of this array with the indicated offset and length.
+ pub fn slice(&self, offset: usize, length: usize) -> Self {
+ // TODO: Slice buffers directly (#3880)
+ self.data.slice(offset, length).into()
+ }
}
impl From<ArrayData> for StructArray {
@@ -205,8 +211,7 @@ impl Array for StructArray {
}
fn slice(&self, offset: usize, length: usize) -> ArrayRef {
- // TODO: Slice buffers directly (#3880)
- Arc::new(Self::from(self.data.slice(offset, length)))
+ Arc::new(self.slice(offset, length))
}
fn nulls(&self) -> Option<&NullBuffer> {
diff --git a/arrow-array/src/array/union_array.rs b/arrow-array/src/array/union_array.rs
index fe227226f77d..6c372d8d05b9 100644
--- a/arrow-array/src/array/union_array.rs
+++ b/arrow-array/src/array/union_array.rs
@@ -287,6 +287,12 @@ impl UnionArray {
_ => unreachable!("Union array's data type is not a union!"),
}
}
+
+ /// Returns a zero-copy slice of this array with the indicated offset and length.
+ pub fn slice(&self, offset: usize, length: usize) -> Self {
+ // TODO: Slice buffers directly (#3880)
+ self.data.slice(offset, length).into()
+ }
}
impl From<ArrayData> for UnionArray {
@@ -328,7 +334,7 @@ impl Array for UnionArray {
}
fn slice(&self, offset: usize, length: usize) -> ArrayRef {
- Arc::new(Self::from(self.data.slice(offset, length)))
+ Arc::new(self.slice(offset, length))
}
fn nulls(&self) -> Option<&NullBuffer> {
diff --git a/arrow-ipc/src/writer.rs b/arrow-ipc/src/writer.rs
index 2d859f608387..07d4b0fe9f93 100644
--- a/arrow-ipc/src/writer.rs
+++ b/arrow-ipc/src/writer.rs
@@ -2024,15 +2024,11 @@ mod tests {
);
let sliced = array.slice(1, 2);
- let read_sliced: &UInt32Array = sliced.as_primitive();
- assert_eq!(
- vec![Some(2), Some(3)],
- read_sliced.iter().collect::<Vec<_>>()
- );
+ assert_eq!(vec![Some(2), Some(3)], sliced.iter().collect::<Vec<_>>());
let batch = RecordBatch::try_new(
Arc::new(Schema::new(vec![Field::new("a", DataType::UInt32, true)])),
- vec![sliced],
+ vec![Arc::new(sliced)],
)
.expect("new batch");
diff --git a/arrow-ord/src/comparison.rs b/arrow-ord/src/comparison.rs
index aa2f1416d83d..d984bee0fdb9 100644
--- a/arrow-ord/src/comparison.rs
+++ b/arrow-ord/src/comparison.rs
@@ -2858,7 +2858,7 @@ mod tests {
// slice and test if the dynamic array works
let a = a.slice(0, a.len());
let b = b.slice(0, b.len());
- let c = $DYN_KERNEL(a.as_ref(), b.as_ref()).unwrap();
+ let c = $DYN_KERNEL(&a, &b).unwrap();
assert_eq!(BooleanArray::from($EXPECTED), c);
// test with a larger version of the same data to ensure we cover the chunked part of the comparison
@@ -2995,8 +2995,7 @@ mod tests {
fn test_primitive_array_eq_scalar_with_slice() {
let a = Int32Array::from(vec![Some(1), None, Some(2), Some(3)]);
let a = a.slice(1, 3);
- let a: &Int32Array = a.as_primitive();
- let a_eq = eq_scalar(a, 2).unwrap();
+ let a_eq = eq_scalar(&a, 2).unwrap();
assert_eq!(
a_eq,
BooleanArray::from(vec![None, Some(true), Some(false)])
@@ -3797,14 +3796,13 @@ mod tests {
vec![Some("hi"), None, Some("hello"), Some("world"), Some("")],
);
let a = a.slice(1, 4);
- let a = a.as_string::<i32>();
- let a_eq = eq_utf8_scalar(a, "hello").unwrap();
+ let a_eq = eq_utf8_scalar(&a, "hello").unwrap();
assert_eq!(
a_eq,
BooleanArray::from(vec![None, Some(true), Some(false), Some(false)])
);
- let a_eq2 = eq_utf8_scalar(a, "").unwrap();
+ let a_eq2 = eq_utf8_scalar(&a, "").unwrap();
assert_eq!(
a_eq2,
diff --git a/arrow-select/src/concat.rs b/arrow-select/src/concat.rs
index 7d42584514f1..e34cc9edb884 100644
--- a/arrow-select/src/concat.rs
+++ b/arrow-select/src/concat.rs
@@ -243,7 +243,7 @@ mod tests {
None,
])
.slice(1, 3);
- let arr = concat(&[input_1.as_ref(), input_2.as_ref()]).unwrap();
+ let arr = concat(&[&input_1, &input_2]).unwrap();
let expected_output = Arc::new(PrimitiveArray::<Int64Type>::from(vec![
Some(-1),
@@ -399,11 +399,8 @@ mod tests {
]));
let input_struct_2 = StructArray::from(vec![(field, input_primitive_2)]);
- let arr = concat(&[
- input_struct_1.slice(1, 3).as_ref(),
- input_struct_2.slice(1, 2).as_ref(),
- ])
- .unwrap();
+ let arr =
+ concat(&[&input_struct_1.slice(1, 3), &input_struct_2.slice(1, 2)]).unwrap();
let expected_primitive_output = Arc::new(PrimitiveArray::<Int64Type>::from(vec![
Some(-1),
@@ -426,8 +423,7 @@ mod tests {
let input_1 = StringArray::from(vec!["hello", "A", "B", "C"]);
let input_2 = StringArray::from(vec!["world", "D", "E", "Z"]);
- let arr = concat(&[input_1.slice(1, 3).as_ref(), input_2.slice(1, 2).as_ref()])
- .unwrap();
+ let arr = concat(&[&input_1.slice(1, 3), &input_2.slice(1, 2)]).unwrap();
let expected_output = StringArray::from(vec!["A", "B", "C", "D", "E"]);
@@ -440,8 +436,7 @@ mod tests {
let input_1 = StringArray::from(vec![Some("hello"), None, Some("A"), Some("C")]);
let input_2 = StringArray::from(vec![None, Some("world"), Some("D"), None]);
- let arr = concat(&[input_1.slice(1, 3).as_ref(), input_2.slice(1, 2).as_ref()])
- .unwrap();
+ let arr = concat(&[&input_1.slice(1, 3), &input_2.slice(1, 2)]).unwrap();
let expected_output =
StringArray::from(vec![None, Some("A"), Some("C"), Some("world"), Some("D")]);
diff --git a/arrow-select/src/filter.rs b/arrow-select/src/filter.rs
index 567aaa58e8bf..f71a3cbc2ab0 100644
--- a/arrow-select/src/filter.rs
+++ b/arrow-select/src/filter.rs
@@ -764,13 +764,12 @@ mod tests {
#[test]
fn test_filter_array_slice() {
- let a_slice = Int32Array::from(vec![5, 6, 7, 8, 9]).slice(1, 4);
- let a = a_slice.as_ref();
+ let a = Int32Array::from(vec![5, 6, 7, 8, 9]).slice(1, 4);
let b = BooleanArray::from(vec![true, false, false, true]);
// filtering with sliced filter array is not currently supported
// let b_slice = BooleanArray::from(vec![true, false, false, true, false]).slice(1, 4);
// let b = b_slice.as_any().downcast_ref().unwrap();
- let c = filter(a, &b).unwrap();
+ let c = filter(&a, &b).unwrap();
let d = c.as_ref().as_any().downcast_ref::<Int32Array>().unwrap();
assert_eq!(2, d.len());
assert_eq!(6, d.value(0));
@@ -868,14 +867,13 @@ mod tests {
#[test]
fn test_filter_array_slice_with_null() {
- let a_slice =
+ let a =
Int32Array::from(vec![Some(5), None, Some(7), Some(8), Some(9)]).slice(1, 4);
- let a = a_slice.as_ref();
let b = BooleanArray::from(vec![true, false, false, true]);
// filtering with sliced filter array is not currently supported
// let b_slice = BooleanArray::from(vec![true, false, false, true, false]).slice(1, 4);
// let b = b_slice.as_any().downcast_ref().unwrap();
- let c = filter(a, &b).unwrap();
+ let c = filter(&a, &b).unwrap();
let d = c.as_ref().as_any().downcast_ref::<Int32Array>().unwrap();
assert_eq!(2, d.len());
assert!(d.is_null(0));
@@ -996,7 +994,7 @@ mod tests {
let mask1 = BooleanArray::from(vec![Some(true), Some(true), None]);
let out = filter(&a, &mask1).unwrap();
- assert_eq!(&out, &a.slice(0, 2));
+ assert_eq!(out.as_ref(), &a.slice(0, 2));
}
#[test]
diff --git a/arrow-select/src/nullif.rs b/arrow-select/src/nullif.rs
index a1b9c0e3e183..0fbbb3868691 100644
--- a/arrow-select/src/nullif.rs
+++ b/arrow-select/src/nullif.rs
@@ -210,7 +210,7 @@ mod tests {
let s = s.slice(2, 3);
let select = select.slice(1, 3);
let select = select.as_boolean();
- let a = nullif(s.as_ref(), select).unwrap();
+ let a = nullif(&s, select).unwrap();
let r: Vec<_> = a.as_string::<i32>().iter().collect();
assert_eq!(r, vec![None, Some("a"), None]);
}
@@ -500,7 +500,6 @@ mod tests {
for (a_offset, a_length) in a_slices {
let a = a.slice(a_offset, a_length);
- let a = a.as_primitive::<Int32Type>();
for i in 1..65 {
let b_start_offset = rng.gen_range(0..i);
@@ -512,7 +511,7 @@ mod tests {
let b = b.slice(b_start_offset, a_length);
let b = b.as_boolean();
- test_nullif(a, b);
+ test_nullif(&a, b);
}
}
}
diff --git a/arrow-select/src/take.rs b/arrow-select/src/take.rs
index 83b58519fdb8..ebac5a58dd7f 100644
--- a/arrow-select/src/take.rs
+++ b/arrow-select/src/take.rs
@@ -1561,14 +1561,8 @@ mod tests {
StringArray::from(vec![Some("hello"), None, Some("world"), None, Some("hi")]);
let indices = Int32Array::from(vec![Some(0), Some(1), None, Some(0), Some(2)]);
let indices_slice = indices.slice(1, 4);
- let indices_slice = indices_slice
- .as_ref()
- .as_any()
- .downcast_ref::<Int32Array>()
- .unwrap();
-
let expected = StringArray::from(vec![None, None, Some("hello"), Some("world")]);
- let result = take(&strings, indices_slice, None).unwrap();
+ let result = take(&strings, &indices_slice, None).unwrap();
assert_eq!(result.as_ref(), &expected);
}
diff --git a/arrow-string/src/length.rs b/arrow-string/src/length.rs
index f0c09a7ec4d8..c206fffb9166 100644
--- a/arrow-string/src/length.rs
+++ b/arrow-string/src/length.rs
@@ -426,7 +426,7 @@ mod tests {
fn length_offsets_string() {
let a = StringArray::from(vec![Some("hello"), Some(" "), Some("world"), None]);
let b = a.slice(1, 3);
- let result = length(b.as_ref()).unwrap();
+ let result = length(&b).unwrap();
let result: &Int32Array = result.as_primitive();
let expected = Int32Array::from(vec![Some(1), Some(5), None]);
@@ -439,7 +439,7 @@ mod tests {
vec![Some(b"hello"), Some(b" "), Some(&[0xff, 0xf8]), None];
let a = BinaryArray::from(value);
let b = a.slice(1, 3);
- let result = length(b.as_ref()).unwrap();
+ let result = length(&b).unwrap();
let result: &Int32Array = result.as_primitive();
let expected = Int32Array::from(vec![Some(1), Some(2), None]);
@@ -581,7 +581,7 @@ mod tests {
fn bit_length_offsets_string() {
let a = StringArray::from(vec![Some("hello"), Some(" "), Some("world"), None]);
let b = a.slice(1, 3);
- let result = bit_length(b.as_ref()).unwrap();
+ let result = bit_length(&b).unwrap();
let result: &Int32Array = result.as_primitive();
let expected = Int32Array::from(vec![Some(8), Some(40), None]);
@@ -594,7 +594,7 @@ mod tests {
vec![Some(b"hello"), Some(&[]), Some(b"world"), None];
let a = BinaryArray::from(value);
let b = a.slice(1, 3);
- let result = bit_length(b.as_ref()).unwrap();
+ let result = bit_length(&b).unwrap();
let result: &Int32Array = result.as_primitive();
let expected = Int32Array::from(vec![Some(0), Some(40), None]);
diff --git a/parquet/src/arrow/array_reader/list_array.rs b/parquet/src/arrow/array_reader/list_array.rs
index 965142f3840b..dbbac657ebd1 100644
--- a/parquet/src/arrow/array_reader/list_array.rs
+++ b/parquet/src/arrow/array_reader/list_array.rs
@@ -401,10 +401,10 @@ mod tests {
let expected_2 = expected.slice(2, 2);
let actual = l1.next_batch(2).unwrap();
- assert_eq!(expected_1.as_ref(), actual.as_ref());
+ assert_eq!(actual.as_ref(), &expected_1);
let actual = l1.next_batch(1024).unwrap();
- assert_eq!(expected_2.as_ref(), actual.as_ref());
+ assert_eq!(actual.as_ref(), &expected_2);
}
fn test_required_list<OffsetSize: OffsetSizeTrait>() {
|
diff --git a/arrow/tests/array_validation.rs b/arrow/tests/array_validation.rs
index 7e45ee7afcda..6c4249e38c58 100644
--- a/arrow/tests/array_validation.rs
+++ b/arrow/tests/array_validation.rs
@@ -941,9 +941,7 @@ fn test_try_new_sliced_struct() {
let struct_array = builder.finish();
let struct_array_slice = struct_array.slice(1, 3);
- let struct_array_data = struct_array_slice.data();
-
- let cloned = make_array(struct_array_data.clone());
+ let cloned = struct_array_slice.clone();
assert_eq!(&struct_array_slice, &cloned);
}
|
Strongly Typed Array Slicing
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
<!--
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
(This section helps Arrow developers understand the context and *why* for this feature, in addition to the *what*)
-->
Currently calling `Array::slice` returns an `ArrayRef`, even if calling on a strongly typed array. This results in a lot of code of the form
```
let a = Int32Array::from(vec![Some(15), None, Some(9), Some(8), None]);
let a = a.slice(1, 4);
let a = a.as_primitive();
```
This is not only verbose but has potential performance implications.
**Describe the solution you'd like**
<!--
A clear and concise description of what you want to happen.
-->
Arrays should provide `Array::slice(&self, offset: usize, len: usize) -> Self`
**Describe alternatives you've considered**
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
Part of #3880
|
2023-03-24T11:14:08Z
|
35.0
|
5eeccab922c377a18e54cf39ad49a2e4d54ffaf2
|
|
apache/arrow-rs
| 3,913
|
apache__arrow-rs-3913
|
[
"3889"
] |
526c57a0f65ee7aaa838f252f48c8179f7d9ce03
|
diff --git a/CHANGELOG-old.md b/CHANGELOG-old.md
index 2d7903e96a7d..8ddd7c6b6619 100644
--- a/CHANGELOG-old.md
+++ b/CHANGELOG-old.md
@@ -19,6 +19,74 @@
# Historical Changelog
+## [35.0.0](https://github.com/apache/arrow-rs/tree/35.0.0) (2023-03-10)
+
+[Full Changelog](https://github.com/apache/arrow-rs/compare/34.0.0...35.0.0)
+
+**Breaking changes:**
+
+- Add RunEndBuffer \(\#1799\) [\#3817](https://github.com/apache/arrow-rs/pull/3817) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Restrict DictionaryArray to ArrowDictionaryKeyType [\#3813](https://github.com/apache/arrow-rs/pull/3813) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- refactor: assorted `FlightSqlServiceClient` improvements [\#3788](https://github.com/apache/arrow-rs/pull/3788) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([crepererum](https://github.com/crepererum))
+- minor: make Parquet CLI input args consistent [\#3786](https://github.com/apache/arrow-rs/pull/3786) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([XinyuZeng](https://github.com/XinyuZeng))
+- Return Buffers from ArrayData::buffers instead of slice \(\#1799\) [\#3783](https://github.com/apache/arrow-rs/pull/3783) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Use NullBuffer in ArrayData \(\#3775\) [\#3778](https://github.com/apache/arrow-rs/pull/3778) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+
+**Implemented enhancements:**
+
+- Support timestamp/time and date types in json decoder [\#3834](https://github.com/apache/arrow-rs/issues/3834) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- Support decoding decimals in new raw json decoder [\#3819](https://github.com/apache/arrow-rs/issues/3819) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- Timezone Aware Timestamp Parsing [\#3794](https://github.com/apache/arrow-rs/issues/3794) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- Preallocate buffers for FixedSizeBinary array creation [\#3792](https://github.com/apache/arrow-rs/issues/3792) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- Make Parquet CLI args consistent [\#3785](https://github.com/apache/arrow-rs/issues/3785) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)]
+- Creates PrimitiveDictionaryBuilder from provided keys and values builders [\#3776](https://github.com/apache/arrow-rs/issues/3776) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- Use NullBuffer in ArrayData [\#3775](https://github.com/apache/arrow-rs/issues/3775) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- Support unary\_dict\_mut in arth [\#3710](https://github.com/apache/arrow-rs/issues/3710) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- Support cast \<\> String to interval [\#3643](https://github.com/apache/arrow-rs/issues/3643) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- Support Zero-Copy Conversion from Vec to/from MutableBuffer [\#3516](https://github.com/apache/arrow-rs/issues/3516) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+
+**Fixed bugs:**
+
+- Timestamp Unit Casts are Unchecked [\#3833](https://github.com/apache/arrow-rs/issues/3833) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- regexp\_match skips first match when returning match [\#3803](https://github.com/apache/arrow-rs/issues/3803) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- Cast to timestamp with time zone returns timestamp [\#3800](https://github.com/apache/arrow-rs/issues/3800) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- Schema-level metadata is not encoded in Flight responses [\#3779](https://github.com/apache/arrow-rs/issues/3779) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)]
+
+**Closed issues:**
+
+- FlightSQL CLI client: simple test [\#3814](https://github.com/apache/arrow-rs/issues/3814) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)]
+
+**Merged pull requests:**
+
+- refactor: timestamp overflow check [\#3840](https://github.com/apache/arrow-rs/pull/3840) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([Weijun-H](https://github.com/Weijun-H))
+- Prep for 35.0.0 [\#3836](https://github.com/apache/arrow-rs/pull/3836) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([iajoiner](https://github.com/iajoiner))
+- Support timestamp/time and date json decoding [\#3835](https://github.com/apache/arrow-rs/pull/3835) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([spebern](https://github.com/spebern))
+- Make dictionary preservation optional in row encoding [\#3831](https://github.com/apache/arrow-rs/pull/3831) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Move prettyprint to arrow-cast [\#3828](https://github.com/apache/arrow-rs/pull/3828) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([tustvold](https://github.com/tustvold))
+- Support decoding decimals in raw decoder [\#3820](https://github.com/apache/arrow-rs/pull/3820) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([spebern](https://github.com/spebern))
+- Add ArrayDataLayout, port validation \(\#1799\) [\#3818](https://github.com/apache/arrow-rs/pull/3818) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- test: add test for FlightSQL CLI client [\#3816](https://github.com/apache/arrow-rs/pull/3816) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([crepererum](https://github.com/crepererum))
+- Add regexp\_match docs [\#3812](https://github.com/apache/arrow-rs/pull/3812) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- fix: Ensure Flight schema includes parent metadata [\#3811](https://github.com/apache/arrow-rs/pull/3811) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([stuartcarnie](https://github.com/stuartcarnie))
+- fix: regexp\_match skips first match [\#3807](https://github.com/apache/arrow-rs/pull/3807) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([Weijun-H](https://github.com/Weijun-H))
+- fix: change uft8 to timestamp with timezone [\#3806](https://github.com/apache/arrow-rs/pull/3806) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([Weijun-H](https://github.com/Weijun-H))
+- Support reading decimal arrays from json [\#3805](https://github.com/apache/arrow-rs/pull/3805) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([spebern](https://github.com/spebern))
+- Add unary\_dict\_mut [\#3804](https://github.com/apache/arrow-rs/pull/3804) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([viirya](https://github.com/viirya))
+- Faster timestamp parsing \(~70-90% faster\) [\#3801](https://github.com/apache/arrow-rs/pull/3801) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Add concat\_elements\_bytes [\#3798](https://github.com/apache/arrow-rs/pull/3798) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Timezone aware timestamp parsing \(\#3794\) [\#3795](https://github.com/apache/arrow-rs/pull/3795) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Preallocate buffers for FixedSizeBinary array creation [\#3793](https://github.com/apache/arrow-rs/pull/3793) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([maxburke](https://github.com/maxburke))
+- feat: simple flight sql CLI client [\#3789](https://github.com/apache/arrow-rs/pull/3789) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([crepererum](https://github.com/crepererum))
+- Creates PrimitiveDictionaryBuilder from provided keys and values builders [\#3777](https://github.com/apache/arrow-rs/pull/3777) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([viirya](https://github.com/viirya))
+- ArrayData Enumeration for Remaining Layouts [\#3769](https://github.com/apache/arrow-rs/pull/3769) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Update prost-build requirement from =0.11.7 to =0.11.8 [\#3767](https://github.com/apache/arrow-rs/pull/3767) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([dependabot[bot]](https://github.com/apps/dependabot))
+- Implement concat\_elements\_dyn kernel [\#3763](https://github.com/apache/arrow-rs/pull/3763) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([Weijun-H](https://github.com/Weijun-H))
+- Support for casting `Utf8` and `LargeUtf8` --\> `Interval` [\#3762](https://github.com/apache/arrow-rs/pull/3762) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([doki23](https://github.com/doki23))
+- into\_inner\(\) for CSV Writer [\#3759](https://github.com/apache/arrow-rs/pull/3759) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([Weijun-H](https://github.com/Weijun-H))
+- Zero-copy Vec conversion \(\#3516\) \(\#1176\) [\#3756](https://github.com/apache/arrow-rs/pull/3756) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- ArrayData Enumeration for Primitive, Binary and UTF8 [\#3749](https://github.com/apache/arrow-rs/pull/3749) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Add `into_primitive_dict_builder` to `DictionaryArray` [\#3715](https://github.com/apache/arrow-rs/pull/3715) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([viirya](https://github.com/viirya))
+
## [34.0.0](https://github.com/apache/arrow-rs/tree/34.0.0) (2023-02-24)
[Full Changelog](https://github.com/apache/arrow-rs/compare/33.0.0...34.0.0)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4a7700ca773f..bd4a6522cfd4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,73 +19,67 @@
# Changelog
-## [35.0.0](https://github.com/apache/arrow-rs/tree/35.0.0) (2023-03-10)
+## [36.0.0](https://github.com/apache/arrow-rs/tree/36.0.0) (2023-03-23)
-[Full Changelog](https://github.com/apache/arrow-rs/compare/34.0.0...35.0.0)
+[Full Changelog](https://github.com/apache/arrow-rs/compare/35.0.0...36.0.0)
**Breaking changes:**
-- Add RunEndBuffer \(\#1799\) [\#3817](https://github.com/apache/arrow-rs/pull/3817) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Restrict DictionaryArray to ArrowDictionaryKeyType [\#3813](https://github.com/apache/arrow-rs/pull/3813) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- refactor: assorted `FlightSqlServiceClient` improvements [\#3788](https://github.com/apache/arrow-rs/pull/3788) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([crepererum](https://github.com/crepererum))
-- minor: make Parquet CLI input args consistent [\#3786](https://github.com/apache/arrow-rs/pull/3786) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([XinyuZeng](https://github.com/XinyuZeng))
-- Return Buffers from ArrayData::buffers instead of slice \(\#1799\) [\#3783](https://github.com/apache/arrow-rs/pull/3783) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Use NullBuffer in ArrayData \(\#3775\) [\#3778](https://github.com/apache/arrow-rs/pull/3778) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Return ScalarBuffer from PrimitiveArray::values \(\#3879\) [\#3896](https://github.com/apache/arrow-rs/pull/3896) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Use BooleanBuffer in BooleanArray \(\#3879\) [\#3895](https://github.com/apache/arrow-rs/pull/3895) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Seal ArrowPrimitiveType [\#3882](https://github.com/apache/arrow-rs/pull/3882) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Support compression levels [\#3847](https://github.com/apache/arrow-rs/pull/3847) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([spebern](https://github.com/spebern))
**Implemented enhancements:**
-- Support timestamp/time and date types in json decoder [\#3834](https://github.com/apache/arrow-rs/issues/3834) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
-- Support decoding decimals in new raw json decoder [\#3819](https://github.com/apache/arrow-rs/issues/3819) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
-- Timezone Aware Timestamp Parsing [\#3794](https://github.com/apache/arrow-rs/issues/3794) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
-- Preallocate buffers for FixedSizeBinary array creation [\#3792](https://github.com/apache/arrow-rs/issues/3792) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
-- Make Parquet CLI args consistent [\#3785](https://github.com/apache/arrow-rs/issues/3785) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)]
-- Creates PrimitiveDictionaryBuilder from provided keys and values builders [\#3776](https://github.com/apache/arrow-rs/issues/3776) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
-- Use NullBuffer in ArrayData [\#3775](https://github.com/apache/arrow-rs/issues/3775) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
-- Support unary\_dict\_mut in arth [\#3710](https://github.com/apache/arrow-rs/issues/3710) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
-- Support cast \<\> String to interval [\#3643](https://github.com/apache/arrow-rs/issues/3643) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
-- Support Zero-Copy Conversion from Vec to/from MutableBuffer [\#3516](https://github.com/apache/arrow-rs/issues/3516) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- Implement `ObjectStore` for trait objects [\#3865](https://github.com/apache/arrow-rs/issues/3865)
+- Add compression options \(levels\) [\#3844](https://github.com/apache/arrow-rs/issues/3844)
+- Use Unsigned Integer for Fixed Size DataType [\#3815](https://github.com/apache/arrow-rs/issues/3815)
+- Add ObjectStore::append [\#3790](https://github.com/apache/arrow-rs/issues/3790)
+- Common trait for RecordBatch and StructArray [\#3764](https://github.com/apache/arrow-rs/issues/3764) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- Support for Async JSON Writer [\#3742](https://github.com/apache/arrow-rs/issues/3742)
+- Support for Async CSV Writer [\#3740](https://github.com/apache/arrow-rs/issues/3740)
+- Allow precision loss on multiplying decimal arrays [\#3689](https://github.com/apache/arrow-rs/issues/3689)
**Fixed bugs:**
-- Timestamp Unit Casts are Unchecked [\#3833](https://github.com/apache/arrow-rs/issues/3833) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
-- regexp\_match skips first match when returning match [\#3803](https://github.com/apache/arrow-rs/issues/3803) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
-- Cast to timestamp with time zone returns timestamp [\#3800](https://github.com/apache/arrow-rs/issues/3800) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
-- Schema-level metadata is not encoded in Flight responses [\#3779](https://github.com/apache/arrow-rs/issues/3779) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)]
-
-**Closed issues:**
-
-- FlightSQL CLI client: simple test [\#3814](https://github.com/apache/arrow-rs/issues/3814) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)]
+- parquet\_derive doesn't support Vec\<u8\> [\#3864](https://github.com/apache/arrow-rs/issues/3864)
+- \[REGRESSION\] Parsing timestamps with lower case time separator [\#3863](https://github.com/apache/arrow-rs/issues/3863)
+- \[REGRESSION\] Parsing timestamps with leap seconds [\#3861](https://github.com/apache/arrow-rs/issues/3861)
+- \[REGRESSION\] Parsing timestamps with fractional seconds / microseconds / milliseconds / nanoseconds [\#3859](https://github.com/apache/arrow-rs/issues/3859)
+- PyArrowConvert Leaks Memory [\#3683](https://github.com/apache/arrow-rs/issues/3683) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
**Merged pull requests:**
-- refactor: timestamp overflow check [\#3840](https://github.com/apache/arrow-rs/pull/3840) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([Weijun-H](https://github.com/Weijun-H))
-- Prep for 35.0.0 [\#3836](https://github.com/apache/arrow-rs/pull/3836) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([iajoiner](https://github.com/iajoiner))
-- Support timestamp/time and date json decoding [\#3835](https://github.com/apache/arrow-rs/pull/3835) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([spebern](https://github.com/spebern))
-- Make dictionary preservation optional in row encoding [\#3831](https://github.com/apache/arrow-rs/pull/3831) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Move prettyprint to arrow-cast [\#3828](https://github.com/apache/arrow-rs/pull/3828) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([tustvold](https://github.com/tustvold))
-- Support decoding decimals in raw decoder [\#3820](https://github.com/apache/arrow-rs/pull/3820) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([spebern](https://github.com/spebern))
-- Add ArrayDataLayout, port validation \(\#1799\) [\#3818](https://github.com/apache/arrow-rs/pull/3818) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- test: add test for FlightSQL CLI client [\#3816](https://github.com/apache/arrow-rs/pull/3816) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([crepererum](https://github.com/crepererum))
-- Add regexp\_match docs [\#3812](https://github.com/apache/arrow-rs/pull/3812) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- fix: Ensure Flight schema includes parent metadata [\#3811](https://github.com/apache/arrow-rs/pull/3811) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([stuartcarnie](https://github.com/stuartcarnie))
-- fix: regexp\_match skips first match [\#3807](https://github.com/apache/arrow-rs/pull/3807) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([Weijun-H](https://github.com/Weijun-H))
-- fix: change uft8 to timestamp with timezone [\#3806](https://github.com/apache/arrow-rs/pull/3806) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([Weijun-H](https://github.com/Weijun-H))
-- Support reading decimal arrays from json [\#3805](https://github.com/apache/arrow-rs/pull/3805) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([spebern](https://github.com/spebern))
-- Add unary\_dict\_mut [\#3804](https://github.com/apache/arrow-rs/pull/3804) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([viirya](https://github.com/viirya))
-- Faster timestamp parsing \(~70-90% faster\) [\#3801](https://github.com/apache/arrow-rs/pull/3801) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Add concat\_elements\_bytes [\#3798](https://github.com/apache/arrow-rs/pull/3798) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Timezone aware timestamp parsing \(\#3794\) [\#3795](https://github.com/apache/arrow-rs/pull/3795) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Preallocate buffers for FixedSizeBinary array creation [\#3793](https://github.com/apache/arrow-rs/pull/3793) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([maxburke](https://github.com/maxburke))
-- feat: simple flight sql CLI client [\#3789](https://github.com/apache/arrow-rs/pull/3789) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([crepererum](https://github.com/crepererum))
-- Creates PrimitiveDictionaryBuilder from provided keys and values builders [\#3777](https://github.com/apache/arrow-rs/pull/3777) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([viirya](https://github.com/viirya))
-- ArrayData Enumeration for Remaining Layouts [\#3769](https://github.com/apache/arrow-rs/pull/3769) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Update prost-build requirement from =0.11.7 to =0.11.8 [\#3767](https://github.com/apache/arrow-rs/pull/3767) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([dependabot[bot]](https://github.com/apps/dependabot))
-- Implement concat\_elements\_dyn kernel [\#3763](https://github.com/apache/arrow-rs/pull/3763) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([Weijun-H](https://github.com/Weijun-H))
-- Support for casting `Utf8` and `LargeUtf8` --\> `Interval` [\#3762](https://github.com/apache/arrow-rs/pull/3762) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([doki23](https://github.com/doki23))
-- into\_inner\(\) for CSV Writer [\#3759](https://github.com/apache/arrow-rs/pull/3759) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([Weijun-H](https://github.com/Weijun-H))
-- Zero-copy Vec conversion \(\#3516\) \(\#1176\) [\#3756](https://github.com/apache/arrow-rs/pull/3756) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- ArrayData Enumeration for Primitive, Binary and UTF8 [\#3749](https://github.com/apache/arrow-rs/pull/3749) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Add `into_primitive_dict_builder` to `DictionaryArray` [\#3715](https://github.com/apache/arrow-rs/pull/3715) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([viirya](https://github.com/viirya))
+- Add PrimitiveArray::new \(\#3879\) [\#3909](https://github.com/apache/arrow-rs/pull/3909) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Improve ScalarBuffer debug output [\#3907](https://github.com/apache/arrow-rs/pull/3907) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Update proc-macro2 requirement from =1.0.52 to =1.0.53 [\#3905](https://github.com/apache/arrow-rs/pull/3905) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([dependabot[bot]](https://github.com/apps/dependabot))
+- Re-export parquet compression level structs [\#3903](https://github.com/apache/arrow-rs/pull/3903) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([tustvold](https://github.com/tustvold))
+- Fix parsing timestamps of exactly 32 characters [\#3902](https://github.com/apache/arrow-rs/pull/3902) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Add iterators to BooleanBuffer and NullBuffer [\#3901](https://github.com/apache/arrow-rs/pull/3901) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Array equality for &dyn Array \(\#3880\) [\#3899](https://github.com/apache/arrow-rs/pull/3899) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Add BooleanArray::new \(\#3879\) [\#3898](https://github.com/apache/arrow-rs/pull/3898) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Revert structured ArrayData \(\#3877\) [\#3894](https://github.com/apache/arrow-rs/pull/3894) ([tustvold](https://github.com/tustvold))
+- Fix pyarrow memory leak \(\#3683\) [\#3893](https://github.com/apache/arrow-rs/pull/3893) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Minor: add examples for `ListBuilder` and `GenericListBuilder` [\#3891](https://github.com/apache/arrow-rs/pull/3891) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([alamb](https://github.com/alamb))
+- Update syn requirement from 1.0 to 2.0 [\#3890](https://github.com/apache/arrow-rs/pull/3890) ([dependabot[bot]](https://github.com/apps/dependabot))
+- Use of `mul_checked` to avoid silent overflow in interval arithmetic [\#3886](https://github.com/apache/arrow-rs/pull/3886) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([Weijun-H](https://github.com/Weijun-H))
+- Flesh out NullBuffer abstraction \(\#3880\) [\#3885](https://github.com/apache/arrow-rs/pull/3885) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Implement Bit Operations for i256 [\#3884](https://github.com/apache/arrow-rs/pull/3884) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Flatten arrow\_buffer [\#3883](https://github.com/apache/arrow-rs/pull/3883) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Add Array::to\_data and Array::nulls \(\#3880\) [\#3881](https://github.com/apache/arrow-rs/pull/3881) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Added support for byte vectors and slices to parquet\_derive \(\#3864\) [\#3878](https://github.com/apache/arrow-rs/pull/3878) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([waymost](https://github.com/waymost))
+- chore: remove LevelDecoder [\#3872](https://github.com/apache/arrow-rs/pull/3872) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([Weijun-H](https://github.com/Weijun-H))
+- Parse timestamps with leap seconds \(\#3861\) [\#3862](https://github.com/apache/arrow-rs/pull/3862) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Faster time parsing \(~93% faster\) [\#3860](https://github.com/apache/arrow-rs/pull/3860) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Parse timestamps with arbitrary seconds fraction [\#3858](https://github.com/apache/arrow-rs/pull/3858) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Add BitIterator [\#3856](https://github.com/apache/arrow-rs/pull/3856) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Improve decimal parsing performance [\#3854](https://github.com/apache/arrow-rs/pull/3854) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([spebern](https://github.com/spebern))
+- Update proc-macro2 requirement from =1.0.51 to =1.0.52 [\#3853](https://github.com/apache/arrow-rs/pull/3853) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([dependabot[bot]](https://github.com/apps/dependabot))
+- Update bitflags requirement from 1.2.1 to 2.0.0 [\#3852](https://github.com/apache/arrow-rs/pull/3852) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([dependabot[bot]](https://github.com/apps/dependabot))
+- Add offset pushdown to parquet [\#3848](https://github.com/apache/arrow-rs/pull/3848) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([tustvold](https://github.com/tustvold))
+- Add timezone support to JSON reader [\#3845](https://github.com/apache/arrow-rs/pull/3845) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Allow precision loss on multiplying decimal arrays [\#3690](https://github.com/apache/arrow-rs/pull/3690) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([viirya](https://github.com/viirya))
diff --git a/arrow-arith/Cargo.toml b/arrow-arith/Cargo.toml
index 4360332d9c7a..f509af76b733 100644
--- a/arrow-arith/Cargo.toml
+++ b/arrow-arith/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-arith"
-version = "35.0.0"
+version = "36.0.0"
description = "Arrow arithmetic kernels"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,10 +38,10 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow-array = { version = "35.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "35.0.0", path = "../arrow-buffer" }
-arrow-data = { version = "35.0.0", path = "../arrow-data" }
-arrow-schema = { version = "35.0.0", path = "../arrow-schema" }
+arrow-array = { version = "36.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "36.0.0", path = "../arrow-buffer" }
+arrow-data = { version = "36.0.0", path = "../arrow-data" }
+arrow-schema = { version = "36.0.0", path = "../arrow-schema" }
chrono = { version = "0.4.23", default-features = false }
half = { version = "2.1", default-features = false }
num = { version = "0.4", default-features = false, features = ["std"] }
diff --git a/arrow-array/Cargo.toml b/arrow-array/Cargo.toml
index 1675f59838a7..7ea969a03f7d 100644
--- a/arrow-array/Cargo.toml
+++ b/arrow-array/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-array"
-version = "35.0.0"
+version = "36.0.0"
description = "Array abstractions for Apache Arrow"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -45,9 +45,9 @@ ahash = { version = "0.8", default-features = false, features = ["compile-time-r
ahash = { version = "0.8", default-features = false, features = ["runtime-rng"] }
[dependencies]
-arrow-buffer = { version = "35.0.0", path = "../arrow-buffer" }
-arrow-schema = { version = "35.0.0", path = "../arrow-schema" }
-arrow-data = { version = "35.0.0", path = "../arrow-data" }
+arrow-buffer = { version = "36.0.0", path = "../arrow-buffer" }
+arrow-schema = { version = "36.0.0", path = "../arrow-schema" }
+arrow-data = { version = "36.0.0", path = "../arrow-data" }
chrono = { version = "0.4.23", default-features = false, features = ["clock"] }
chrono-tz = { version = "0.8", optional = true }
num = { version = "0.4", default-features = false, features = ["std"] }
diff --git a/arrow-buffer/Cargo.toml b/arrow-buffer/Cargo.toml
index 699a1000132f..be9a08eb8333 100644
--- a/arrow-buffer/Cargo.toml
+++ b/arrow-buffer/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-buffer"
-version = "35.0.0"
+version = "36.0.0"
description = "Buffer abstractions for Apache Arrow"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
diff --git a/arrow-cast/Cargo.toml b/arrow-cast/Cargo.toml
index 53c62ffb60d3..1eee7108f139 100644
--- a/arrow-cast/Cargo.toml
+++ b/arrow-cast/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-cast"
-version = "35.0.0"
+version = "36.0.0"
description = "Cast kernel and utilities for Apache Arrow"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -44,11 +44,11 @@ features = ["prettyprint"]
prettyprint = ["comfy-table"]
[dependencies]
-arrow-array = { version = "35.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "35.0.0", path = "../arrow-buffer" }
-arrow-data = { version = "35.0.0", path = "../arrow-data" }
-arrow-schema = { version = "35.0.0", path = "../arrow-schema" }
-arrow-select = { version = "35.0.0", path = "../arrow-select" }
+arrow-array = { version = "36.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "36.0.0", path = "../arrow-buffer" }
+arrow-data = { version = "36.0.0", path = "../arrow-data" }
+arrow-schema = { version = "36.0.0", path = "../arrow-schema" }
+arrow-select = { version = "36.0.0", path = "../arrow-select" }
chrono = { version = "0.4.23", default-features = false, features = ["clock"] }
num = { version = "0.4", default-features = false, features = ["std"] }
lexical-core = { version = "^0.8", default-features = false, features = ["write-integers", "write-floats", "parse-integers", "parse-floats"] }
diff --git a/arrow-csv/Cargo.toml b/arrow-csv/Cargo.toml
index 7ceb1401d1c0..9f8015f1eec8 100644
--- a/arrow-csv/Cargo.toml
+++ b/arrow-csv/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-csv"
-version = "35.0.0"
+version = "36.0.0"
description = "Support for parsing CSV format into the Arrow format"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,11 +38,11 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow-array = { version = "35.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "35.0.0", path = "../arrow-buffer" }
-arrow-cast = { version = "35.0.0", path = "../arrow-cast" }
-arrow-data = { version = "35.0.0", path = "../arrow-data" }
-arrow-schema = { version = "35.0.0", path = "../arrow-schema" }
+arrow-array = { version = "36.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "36.0.0", path = "../arrow-buffer" }
+arrow-cast = { version = "36.0.0", path = "../arrow-cast" }
+arrow-data = { version = "36.0.0", path = "../arrow-data" }
+arrow-schema = { version = "36.0.0", path = "../arrow-schema" }
chrono = { version = "0.4.23", default-features = false, features = ["clock"] }
csv = { version = "1.1", default-features = false }
csv-core = { version = "0.1"}
diff --git a/arrow-data/Cargo.toml b/arrow-data/Cargo.toml
index d58413a762bd..c3630d2c9164 100644
--- a/arrow-data/Cargo.toml
+++ b/arrow-data/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-data"
-version = "35.0.0"
+version = "36.0.0"
description = "Array data abstractions for Apache Arrow"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -50,8 +50,8 @@ features = ["ffi"]
[dependencies]
-arrow-buffer = { version = "35.0.0", path = "../arrow-buffer" }
-arrow-schema = { version = "35.0.0", path = "../arrow-schema" }
+arrow-buffer = { version = "36.0.0", path = "../arrow-buffer" }
+arrow-schema = { version = "36.0.0", path = "../arrow-schema" }
num = { version = "0.4", default-features = false, features = ["std"] }
half = { version = "2.1", default-features = false }
diff --git a/arrow-flight/Cargo.toml b/arrow-flight/Cargo.toml
index 5f839ca6838a..1c8d11aa03b2 100644
--- a/arrow-flight/Cargo.toml
+++ b/arrow-flight/Cargo.toml
@@ -18,7 +18,7 @@
[package]
name = "arrow-flight"
description = "Apache Arrow Flight"
-version = "35.0.0"
+version = "36.0.0"
edition = "2021"
rust-version = "1.62"
authors = ["Apache Arrow <dev@arrow.apache.org>"]
@@ -27,12 +27,12 @@ repository = "https://github.com/apache/arrow-rs"
license = "Apache-2.0"
[dependencies]
-arrow-array = { version = "35.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "35.0.0", path = "../arrow-buffer" }
+arrow-array = { version = "36.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "36.0.0", path = "../arrow-buffer" }
# Cast is needed to work around https://github.com/apache/arrow-rs/issues/3389
-arrow-cast = { version = "35.0.0", path = "../arrow-cast" }
-arrow-ipc = { version = "35.0.0", path = "../arrow-ipc" }
-arrow-schema = { version = "35.0.0", path = "../arrow-schema" }
+arrow-cast = { version = "36.0.0", path = "../arrow-cast" }
+arrow-ipc = { version = "36.0.0", path = "../arrow-ipc" }
+arrow-schema = { version = "36.0.0", path = "../arrow-schema" }
base64 = { version = "0.21", default-features = false, features = ["std"] }
tonic = { version = "0.8", default-features = false, features = ["transport", "codegen", "prost"] }
bytes = { version = "1", default-features = false }
@@ -58,7 +58,7 @@ tls = ["tonic/tls"]
cli = ["arrow-cast/prettyprint", "clap", "tracing-log", "tracing-subscriber", "tonic/tls-webpki-roots"]
[dev-dependencies]
-arrow-cast = { version = "35.0.0", path = "../arrow-cast", features = ["prettyprint"] }
+arrow-cast = { version = "36.0.0", path = "../arrow-cast", features = ["prettyprint"] }
assert_cmd = "2.0.8"
tempfile = "3.3"
tokio-stream = { version = "0.1", features = ["net"] }
diff --git a/arrow-flight/README.md b/arrow-flight/README.md
index 41312cc0c559..f8f9e95d8377 100644
--- a/arrow-flight/README.md
+++ b/arrow-flight/README.md
@@ -27,7 +27,7 @@ Add this to your Cargo.toml:
```toml
[dependencies]
-arrow-flight = "35.0.0"
+arrow-flight = "36.0.0"
```
Apache Arrow Flight is a gRPC based protocol for exchanging Arrow data between processes. See the blog post [Introducing Apache Arrow Flight: A Framework for Fast Data Transport](https://arrow.apache.org/blog/2019/10/13/introducing-arrow-flight/) for more information.
diff --git a/arrow-ipc/Cargo.toml b/arrow-ipc/Cargo.toml
index 8bd7d31485e4..0c358170bc16 100644
--- a/arrow-ipc/Cargo.toml
+++ b/arrow-ipc/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-ipc"
-version = "35.0.0"
+version = "36.0.0"
description = "Support for the Arrow IPC format"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,11 +38,11 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow-array = { version = "35.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "35.0.0", path = "../arrow-buffer" }
-arrow-cast = { version = "35.0.0", path = "../arrow-cast" }
-arrow-data = { version = "35.0.0", path = "../arrow-data" }
-arrow-schema = { version = "35.0.0", path = "../arrow-schema" }
+arrow-array = { version = "36.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "36.0.0", path = "../arrow-buffer" }
+arrow-cast = { version = "36.0.0", path = "../arrow-cast" }
+arrow-data = { version = "36.0.0", path = "../arrow-data" }
+arrow-schema = { version = "36.0.0", path = "../arrow-schema" }
flatbuffers = { version = "23.1.21", default-features = false }
lz4 = { version = "1.23", default-features = false, optional = true }
zstd = { version = "0.12.0", default-features = false, optional = true }
diff --git a/arrow-json/Cargo.toml b/arrow-json/Cargo.toml
index 92c1a3eb282f..91bac277b1f6 100644
--- a/arrow-json/Cargo.toml
+++ b/arrow-json/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-json"
-version = "35.0.0"
+version = "36.0.0"
description = "Support for parsing JSON format into the Arrow format"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,11 +38,11 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow-array = { version = "35.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "35.0.0", path = "../arrow-buffer" }
-arrow-cast = { version = "35.0.0", path = "../arrow-cast" }
-arrow-data = { version = "35.0.0", path = "../arrow-data" }
-arrow-schema = { version = "35.0.0", path = "../arrow-schema" }
+arrow-array = { version = "36.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "36.0.0", path = "../arrow-buffer" }
+arrow-cast = { version = "36.0.0", path = "../arrow-cast" }
+arrow-data = { version = "36.0.0", path = "../arrow-data" }
+arrow-schema = { version = "36.0.0", path = "../arrow-schema" }
half = { version = "2.1", default-features = false }
indexmap = { version = "1.9", default-features = false, features = ["std"] }
num = { version = "0.4", default-features = false, features = ["std"] }
diff --git a/arrow-ord/Cargo.toml b/arrow-ord/Cargo.toml
index bc6feb4f2a29..75746d64d5d6 100644
--- a/arrow-ord/Cargo.toml
+++ b/arrow-ord/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-ord"
-version = "35.0.0"
+version = "36.0.0"
description = "Ordering kernels for arrow arrays"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,11 +38,11 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow-array = { version = "35.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "35.0.0", path = "../arrow-buffer" }
-arrow-data = { version = "35.0.0", path = "../arrow-data" }
-arrow-schema = { version = "35.0.0", path = "../arrow-schema" }
-arrow-select = { version = "35.0.0", path = "../arrow-select" }
+arrow-array = { version = "36.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "36.0.0", path = "../arrow-buffer" }
+arrow-data = { version = "36.0.0", path = "../arrow-data" }
+arrow-schema = { version = "36.0.0", path = "../arrow-schema" }
+arrow-select = { version = "36.0.0", path = "../arrow-select" }
num = { version = "0.4", default-features = false, features = ["std"] }
[dev-dependencies]
diff --git a/arrow-row/Cargo.toml b/arrow-row/Cargo.toml
index e2796fbe134c..96d494077026 100644
--- a/arrow-row/Cargo.toml
+++ b/arrow-row/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-row"
-version = "35.0.0"
+version = "36.0.0"
description = "Arrow row format"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -44,17 +44,17 @@ ahash = { version = "0.8", default-features = false, features = ["compile-time-r
ahash = { version = "0.8", default-features = false, features = ["runtime-rng"] }
[dependencies]
-arrow-array = { version = "35.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "35.0.0", path = "../arrow-buffer" }
-arrow-data = { version = "35.0.0", path = "../arrow-data" }
-arrow-schema = { version = "35.0.0", path = "../arrow-schema" }
+arrow-array = { version = "36.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "36.0.0", path = "../arrow-buffer" }
+arrow-data = { version = "36.0.0", path = "../arrow-data" }
+arrow-schema = { version = "36.0.0", path = "../arrow-schema" }
half = { version = "2.1", default-features = false }
hashbrown = { version = "0.13", default-features = false }
[dev-dependencies]
-arrow-cast = { version = "35.0.0", path = "../arrow-cast" }
-arrow-ord = { version = "35.0.0", path = "../arrow-ord" }
+arrow-cast = { version = "36.0.0", path = "../arrow-cast" }
+arrow-ord = { version = "36.0.0", path = "../arrow-ord" }
rand = { version = "0.8", default-features = false, features = ["std", "std_rng"] }
[features]
diff --git a/arrow-schema/Cargo.toml b/arrow-schema/Cargo.toml
index 62cb9f3c257e..89e82a0ff164 100644
--- a/arrow-schema/Cargo.toml
+++ b/arrow-schema/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-schema"
-version = "35.0.0"
+version = "36.0.0"
description = "Defines the logical types for arrow arrays"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
diff --git a/arrow-select/Cargo.toml b/arrow-select/Cargo.toml
index 35c51c2da3ea..c0aa9444c1f1 100644
--- a/arrow-select/Cargo.toml
+++ b/arrow-select/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-select"
-version = "35.0.0"
+version = "36.0.0"
description = "Selection kernels for arrow arrays"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,10 +38,10 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow-buffer = { version = "35.0.0", path = "../arrow-buffer" }
-arrow-data = { version = "35.0.0", path = "../arrow-data" }
-arrow-schema = { version = "35.0.0", path = "../arrow-schema" }
-arrow-array = { version = "35.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "36.0.0", path = "../arrow-buffer" }
+arrow-data = { version = "36.0.0", path = "../arrow-data" }
+arrow-schema = { version = "36.0.0", path = "../arrow-schema" }
+arrow-array = { version = "36.0.0", path = "../arrow-array" }
num = { version = "0.4", default-features = false, features = ["std"] }
[features]
diff --git a/arrow-string/Cargo.toml b/arrow-string/Cargo.toml
index 923b8e8c00c4..90746e9395e3 100644
--- a/arrow-string/Cargo.toml
+++ b/arrow-string/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-string"
-version = "35.0.0"
+version = "36.0.0"
description = "String kernels for arrow arrays"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,11 +38,11 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow-buffer = { version = "35.0.0", path = "../arrow-buffer" }
-arrow-data = { version = "35.0.0", path = "../arrow-data" }
-arrow-schema = { version = "35.0.0", path = "../arrow-schema" }
-arrow-array = { version = "35.0.0", path = "../arrow-array" }
-arrow-select = { version = "35.0.0", path = "../arrow-select" }
+arrow-buffer = { version = "36.0.0", path = "../arrow-buffer" }
+arrow-data = { version = "36.0.0", path = "../arrow-data" }
+arrow-schema = { version = "36.0.0", path = "../arrow-schema" }
+arrow-array = { version = "36.0.0", path = "../arrow-array" }
+arrow-select = { version = "36.0.0", path = "../arrow-select" }
regex = { version = "1.7.0", default-features = false, features = ["std", "unicode", "perf"] }
regex-syntax = { version = "0.6.27", default-features = false, features = ["unicode"] }
diff --git a/arrow/Cargo.toml b/arrow/Cargo.toml
index 8814f233bad1..0e8ea3cac124 100644
--- a/arrow/Cargo.toml
+++ b/arrow/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow"
-version = "35.0.0"
+version = "36.0.0"
description = "Rust implementation of Apache Arrow"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -45,19 +45,19 @@ ahash = { version = "0.8", default-features = false, features = ["compile-time-r
ahash = { version = "0.8", default-features = false, features = ["runtime-rng"] }
[dependencies]
-arrow-arith = { version = "35.0.0", path = "../arrow-arith" }
-arrow-array = { version = "35.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "35.0.0", path = "../arrow-buffer" }
-arrow-cast = { version = "35.0.0", path = "../arrow-cast" }
-arrow-csv = { version = "35.0.0", path = "../arrow-csv", optional = true }
-arrow-data = { version = "35.0.0", path = "../arrow-data" }
-arrow-ipc = { version = "35.0.0", path = "../arrow-ipc", optional = true }
-arrow-json = { version = "35.0.0", path = "../arrow-json", optional = true }
-arrow-ord = { version = "35.0.0", path = "../arrow-ord" }
-arrow-row = { version = "35.0.0", path = "../arrow-row" }
-arrow-schema = { version = "35.0.0", path = "../arrow-schema" }
-arrow-select = { version = "35.0.0", path = "../arrow-select" }
-arrow-string = { version = "35.0.0", path = "../arrow-string" }
+arrow-arith = { version = "36.0.0", path = "../arrow-arith" }
+arrow-array = { version = "36.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "36.0.0", path = "../arrow-buffer" }
+arrow-cast = { version = "36.0.0", path = "../arrow-cast" }
+arrow-csv = { version = "36.0.0", path = "../arrow-csv", optional = true }
+arrow-data = { version = "36.0.0", path = "../arrow-data" }
+arrow-ipc = { version = "36.0.0", path = "../arrow-ipc", optional = true }
+arrow-json = { version = "36.0.0", path = "../arrow-json", optional = true }
+arrow-ord = { version = "36.0.0", path = "../arrow-ord" }
+arrow-row = { version = "36.0.0", path = "../arrow-row" }
+arrow-schema = { version = "36.0.0", path = "../arrow-schema" }
+arrow-select = { version = "36.0.0", path = "../arrow-select" }
+arrow-string = { version = "36.0.0", path = "../arrow-string" }
rand = { version = "0.8", default-features = false, features = ["std", "std_rng"], optional = true }
pyo3 = { version = "0.18", default-features = false, optional = true }
diff --git a/arrow/README.md b/arrow/README.md
index 479213833244..d7a5877b49fa 100644
--- a/arrow/README.md
+++ b/arrow/README.md
@@ -35,7 +35,7 @@ This crate is tested with the latest stable version of Rust. We do not currently
The arrow crate follows the [SemVer standard](https://doc.rust-lang.org/cargo/reference/semver.html) defined by Cargo and works well within the Rust crate ecosystem.
-However, for historical reasons, this crate uses versions with major numbers greater than `0.x` (e.g. `35.0.0`), unlike many other crates in the Rust ecosystem which spend extended time releasing versions `0.x` to signal planned ongoing API changes. Minor arrow releases contain only compatible changes, while major releases may contain breaking API changes.
+However, for historical reasons, this crate uses versions with major numbers greater than `0.x` (e.g. `36.0.0`), unlike many other crates in the Rust ecosystem which spend extended time releasing versions `0.x` to signal planned ongoing API changes. Minor arrow releases contain only compatible changes, while major releases may contain breaking API changes.
## Feature Flags
diff --git a/dev/release/README.md b/dev/release/README.md
index c7c14b8d58c1..11bcbe866e32 100644
--- a/dev/release/README.md
+++ b/dev/release/README.md
@@ -70,7 +70,7 @@ git pull
git checkout -b <RELEASE_BRANCH>
# Update versions. Make sure to run it before the next step since we do not want CHANGELOG-old.md affected.
-sed -i '' -e 's/14.0.0/35.0.0/g' `find . -name 'Cargo.toml' -or -name '*.md' | grep -v CHANGELOG.md`
+sed -i '' -e 's/14.0.0/36.0.0/g' `find . -name 'Cargo.toml' -or -name '*.md' | grep -v CHANGELOG.md`
git commit -a -m 'Update version'
# Copy the content of CHANGELOG.md to the beginning of CHANGELOG-old.md
diff --git a/dev/release/update_change_log.sh b/dev/release/update_change_log.sh
index b01d190a4f38..77f9c5f9780b 100755
--- a/dev/release/update_change_log.sh
+++ b/dev/release/update_change_log.sh
@@ -29,8 +29,8 @@
set -e
-SINCE_TAG="34.0.0"
-FUTURE_RELEASE="35.0.0"
+SINCE_TAG="35.0.0"
+FUTURE_RELEASE="36.0.0"
SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SOURCE_TOP_DIR="$(cd "${SOURCE_DIR}/../../" && pwd)"
diff --git a/parquet/Cargo.toml b/parquet/Cargo.toml
index a822a966f29d..46a6aa441271 100644
--- a/parquet/Cargo.toml
+++ b/parquet/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "parquet"
-version = "35.0.0"
+version = "36.0.0"
license = "Apache-2.0"
description = "Apache Parquet implementation in Rust"
homepage = "https://github.com/apache/arrow-rs"
@@ -35,14 +35,14 @@ ahash = { version = "0.8", default-features = false, features = ["compile-time-r
ahash = { version = "0.8", default-features = false, features = ["runtime-rng"] }
[dependencies]
-arrow-array = { version = "35.0.0", path = "../arrow-array", default-features = false, optional = true }
-arrow-buffer = { version = "35.0.0", path = "../arrow-buffer", default-features = false, optional = true }
-arrow-cast = { version = "35.0.0", path = "../arrow-cast", default-features = false, optional = true }
-arrow-csv = { version = "35.0.0", path = "../arrow-csv", default-features = false, optional = true }
-arrow-data = { version = "35.0.0", path = "../arrow-data", default-features = false, optional = true }
-arrow-schema = { version = "35.0.0", path = "../arrow-schema", default-features = false, optional = true }
-arrow-select = { version = "35.0.0", path = "../arrow-select", default-features = false, optional = true }
-arrow-ipc = { version = "35.0.0", path = "../arrow-ipc", default-features = false, optional = true }
+arrow-array = { version = "36.0.0", path = "../arrow-array", default-features = false, optional = true }
+arrow-buffer = { version = "36.0.0", path = "../arrow-buffer", default-features = false, optional = true }
+arrow-cast = { version = "36.0.0", path = "../arrow-cast", default-features = false, optional = true }
+arrow-csv = { version = "36.0.0", path = "../arrow-csv", default-features = false, optional = true }
+arrow-data = { version = "36.0.0", path = "../arrow-data", default-features = false, optional = true }
+arrow-schema = { version = "36.0.0", path = "../arrow-schema", default-features = false, optional = true }
+arrow-select = { version = "36.0.0", path = "../arrow-select", default-features = false, optional = true }
+arrow-ipc = { version = "36.0.0", path = "../arrow-ipc", default-features = false, optional = true }
object_store = { version = "0.5", path = "../object_store", default-features = false, optional = true }
bytes = { version = "1.1", default-features = false, features = ["std"] }
@@ -76,7 +76,7 @@ flate2 = { version = "1.0", default-features = false, features = ["rust_backend"
lz4 = { version = "1.23", default-features = false }
zstd = { version = "0.12", default-features = false }
serde_json = { version = "1.0", features = ["std"], default-features = false }
-arrow = { path = "../arrow", version = "35.0.0", default-features = false, features = ["ipc", "test_utils", "prettyprint", "json"] }
+arrow = { path = "../arrow", version = "36.0.0", default-features = false, features = ["ipc", "test_utils", "prettyprint", "json"] }
tokio = { version = "1.0", default-features = false, features = ["macros", "rt", "io-util", "fs"] }
rand = { version = "0.8", default-features = false, features = ["std", "std_rng"] }
diff --git a/parquet_derive/Cargo.toml b/parquet_derive/Cargo.toml
index ddf34c4bf793..9ecb40cc4729 100644
--- a/parquet_derive/Cargo.toml
+++ b/parquet_derive/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "parquet_derive"
-version = "35.0.0"
+version = "36.0.0"
license = "Apache-2.0"
description = "Derive macros for the Rust implementation of Apache Parquet"
homepage = "https://github.com/apache/arrow-rs"
@@ -35,4 +35,4 @@ proc-macro = true
proc-macro2 = { version = "1.0", default-features = false }
quote = { version = "1.0", default-features = false }
syn = { version = "2.0", features = ["extra-traits"] }
-parquet = { path = "../parquet", version = "35.0.0", default-features = false }
+parquet = { path = "../parquet", version = "36.0.0", default-features = false }
diff --git a/parquet_derive/README.md b/parquet_derive/README.md
index 2bed2d550e62..70be54015c56 100644
--- a/parquet_derive/README.md
+++ b/parquet_derive/README.md
@@ -32,8 +32,8 @@ Add this to your Cargo.toml:
```toml
[dependencies]
-parquet = "35.0.0"
-parquet_derive = "35.0.0"
+parquet = "36.0.0"
+parquet_derive = "36.0.0"
```
and this to your crate root:
|
diff --git a/arrow-integration-test/Cargo.toml b/arrow-integration-test/Cargo.toml
index ca14401b6899..61ffae23fbe7 100644
--- a/arrow-integration-test/Cargo.toml
+++ b/arrow-integration-test/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-integration-test"
-version = "35.0.0"
+version = "36.0.0"
description = "Support for the Apache Arrow JSON test data format"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,8 +38,8 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow = { version = "35.0.0", path = "../arrow", default-features = false }
-arrow-buffer = { version = "35.0.0", path = "../arrow-buffer" }
+arrow = { version = "36.0.0", path = "../arrow", default-features = false }
+arrow-buffer = { version = "36.0.0", path = "../arrow-buffer" }
hex = { version = "0.4", default-features = false, features = ["std"] }
serde = { version = "1.0", default-features = false, features = ["rc", "derive"] }
serde_json = { version = "1.0", default-features = false, features = ["std"] }
diff --git a/arrow-integration-testing/Cargo.toml b/arrow-integration-testing/Cargo.toml
index 48700bbe90d3..81691c4b370f 100644
--- a/arrow-integration-testing/Cargo.toml
+++ b/arrow-integration-testing/Cargo.toml
@@ -18,7 +18,7 @@
[package]
name = "arrow-integration-testing"
description = "Binaries used in the Arrow integration tests (NOT PUBLISHED TO crates.io)"
-version = "35.0.0"
+version = "36.0.0"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
authors = ["Apache Arrow <dev@arrow.apache.org>"]
diff --git a/arrow-pyarrow-integration-testing/Cargo.toml b/arrow-pyarrow-integration-testing/Cargo.toml
index ba084c435e64..8aaf20b498fe 100644
--- a/arrow-pyarrow-integration-testing/Cargo.toml
+++ b/arrow-pyarrow-integration-testing/Cargo.toml
@@ -18,7 +18,7 @@
[package]
name = "arrow-pyarrow-integration-testing"
description = ""
-version = "35.0.0"
+version = "36.0.0"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
authors = ["Apache Arrow <dev@arrow.apache.org>"]
@@ -32,5 +32,5 @@ name = "arrow_pyarrow_integration_testing"
crate-type = ["cdylib"]
[dependencies]
-arrow = { path = "../arrow", version = "35.0.0", features = ["pyarrow"] }
+arrow = { path = "../arrow", version = "36.0.0", features = ["pyarrow"] }
pyo3 = { version = "0.18", features = ["extension-module"] }
diff --git a/parquet_derive_test/Cargo.toml b/parquet_derive_test/Cargo.toml
index cca778d6f51b..10694851c938 100644
--- a/parquet_derive_test/Cargo.toml
+++ b/parquet_derive_test/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "parquet_derive_test"
-version = "35.0.0"
+version = "36.0.0"
license = "Apache-2.0"
description = "Integration test package for parquet-derive"
homepage = "https://github.com/apache/arrow-rs"
@@ -29,6 +29,6 @@ publish = false
rust-version = "1.62"
[dependencies]
-parquet = { path = "../parquet", version = "35.0.0", default-features = false }
-parquet_derive = { path = "../parquet_derive", version = "35.0.0", default-features = false }
+parquet = { path = "../parquet", version = "36.0.0", default-features = false }
+parquet_derive = { path = "../parquet_derive", version = "36.0.0", default-features = false }
chrono = { version="0.4.23", default-features = false, features = [ "clock" ] }
|
Release 36.0.0 of arrow/arrow-flight/parquet/parquet-derive (next release after 35.0.0)
Follow on from https://github.com/apache/arrow-rs/issues/3830
- Planned Release Candidate: 2023-03-25
- Planned Release and Publish to crates.io: 2023-03-27
Items (from [dev/release/README.md](https://github.com/apache/arrow-rs/blob/master/dev/release/README.md)):
- [ ] PR to update version and CHANGELOG:
- [ ] Release candidate created:
- [ ] Release candidate approved:
- [ ] Release to crates.io:
- [ ] Make ticket for next release
See full list here:
https://github.com/apache/arrow-rs/compare/35.0.0...master
cc @alamb @tustvold @viirya @iajoiner
|
This release will include fixes for:
- [x] https://github.com/apache/arrow-rs/issues/3859
- [x] https://github.com/apache/arrow-rs/issues/3861
- [x] https://github.com/apache/arrow-rs/issues/3859
Also https://github.com/apache/arrow-rs/pull/3902
|
2023-03-23T14:15:03Z
|
35.0
|
5eeccab922c377a18e54cf39ad49a2e4d54ffaf2
|
apache/arrow-rs
| 3,878
|
apache__arrow-rs-3878
|
[
"3864"
] |
0df21883cb7a5f414894a833ae301fcd8d8e464c
|
diff --git a/parquet/src/data_type.rs b/parquet/src/data_type.rs
index 40d54c78ed1d..48ee7f89fc5d 100644
--- a/parquet/src/data_type.rs
+++ b/parquet/src/data_type.rs
@@ -199,6 +199,16 @@ impl From<Vec<u8>> for ByteArray {
}
}
+impl<'a> From<&'a [u8]> for ByteArray {
+ fn from(b: &'a [u8]) -> ByteArray {
+ let mut v = Vec::new();
+ v.extend_from_slice(b);
+ Self {
+ data: Some(ByteBufferPtr::new(v)),
+ }
+ }
+}
+
impl<'a> From<&'a str> for ByteArray {
fn from(s: &'a str) -> ByteArray {
let mut v = Vec::new();
diff --git a/parquet_derive/src/parquet_field.rs b/parquet_derive/src/parquet_field.rs
index 48b6d3ac41b8..ea6878283a33 100644
--- a/parquet_derive/src/parquet_field.rs
+++ b/parquet_derive/src/parquet_field.rs
@@ -92,6 +92,10 @@ impl Field {
Type::TypePath(_) => self.option_into_vals(),
_ => unimplemented!("Unsupported type encountered"),
},
+ Type::Vec(ref first_type) => match **first_type {
+ Type::TypePath(_) => self.option_into_vals(),
+ _ => unimplemented!("Unsupported type encountered"),
+ },
ref f => unimplemented!("Unsupported: {:#?}", f),
},
Type::Reference(_, ref first_type) => match **first_type {
@@ -99,11 +103,27 @@ impl Field {
Type::Option(ref second_type) => match **second_type {
Type::TypePath(_) => self.option_into_vals(),
Type::Reference(_, ref second_type) => match **second_type {
+ Type::TypePath(_) => self.option_into_vals(),
+ Type::Slice(ref second_type) => match **second_type {
+ Type::TypePath(_) => self.option_into_vals(),
+ ref f => unimplemented!("Unsupported: {:#?}", f),
+ },
+ _ => unimplemented!("Unsupported type encountered"),
+ },
+ Type::Vec(ref first_type) => match **first_type {
Type::TypePath(_) => self.option_into_vals(),
_ => unimplemented!("Unsupported type encountered"),
},
ref f => unimplemented!("Unsupported: {:#?}", f),
},
+ Type::Slice(ref second_type) => match **second_type {
+ Type::TypePath(_) => self.copied_direct_vals(),
+ ref f => unimplemented!("Unsupported: {:#?}", f),
+ },
+ ref f => unimplemented!("Unsupported: {:#?}", f),
+ },
+ Type::Vec(ref first_type) => match **first_type {
+ Type::TypePath(_) => self.copied_direct_vals(),
ref f => unimplemented!("Unsupported: {:#?}", f),
},
f => unimplemented!("Unsupported: {:#?}", f),
@@ -116,26 +136,55 @@ impl Field {
Type::Option(_) => unimplemented!("Unsupported nesting encountered"),
Type::Reference(_, ref second_type)
| Type::Vec(ref second_type)
- | Type::Array(ref second_type) => match **second_type {
+ | Type::Array(ref second_type)
+ | Type::Slice(ref second_type) => match **second_type {
Type::TypePath(_) => Some(self.optional_definition_levels()),
_ => unimplemented!("Unsupported nesting encountered"),
},
},
Type::Reference(_, ref first_type)
| Type::Vec(ref first_type)
- | Type::Array(ref first_type) => match **first_type {
+ | Type::Array(ref first_type)
+ | Type::Slice(ref first_type) => match **first_type {
Type::TypePath(_) => None,
- Type::Reference(_, ref second_type)
- | Type::Vec(ref second_type)
+ Type::Vec(ref second_type)
| Type::Array(ref second_type)
- | Type::Option(ref second_type) => match **second_type {
- Type::TypePath(_) => Some(self.optional_definition_levels()),
+ | Type::Slice(ref second_type) => match **second_type {
+ Type::TypePath(_) => None,
Type::Reference(_, ref third_type) => match **third_type {
- Type::TypePath(_) => Some(self.optional_definition_levels()),
+ Type::TypePath(_) => None,
_ => unimplemented!("Unsupported definition encountered"),
},
_ => unimplemented!("Unsupported definition encountered"),
},
+ Type::Reference(_, ref second_type) | Type::Option(ref second_type) => {
+ match **second_type {
+ Type::TypePath(_) => Some(self.optional_definition_levels()),
+ Type::Vec(ref third_type)
+ | Type::Array(ref third_type)
+ | Type::Slice(ref third_type) => match **third_type {
+ Type::TypePath(_) => Some(self.optional_definition_levels()),
+ Type::Reference(_, ref fourth_type) => match **fourth_type {
+ Type::TypePath(_) => {
+ Some(self.optional_definition_levels())
+ }
+ _ => unimplemented!("Unsupported definition encountered"),
+ },
+ _ => unimplemented!("Unsupported definition encountered"),
+ },
+ Type::Reference(_, ref third_type) => match **third_type {
+ Type::TypePath(_) => Some(self.optional_definition_levels()),
+ Type::Slice(ref fourth_type) => match **fourth_type {
+ Type::TypePath(_) => {
+ Some(self.optional_definition_levels())
+ }
+ _ => unimplemented!("Unsupported definition encountered"),
+ },
+ _ => unimplemented!("Unsupported definition encountered"),
+ },
+ _ => unimplemented!("Unsupported definition encountered"),
+ }
+ }
},
};
@@ -323,6 +372,7 @@ impl Field {
enum Type {
Array(Box<Type>),
Option(Box<Type>),
+ Slice(Box<Type>),
Vec(Box<Type>),
TypePath(syn::Type),
Reference(Option<syn::Lifetime>, Box<Type>),
@@ -374,6 +424,7 @@ impl Type {
Type::Option(ref first_type)
| Type::Vec(ref first_type)
| Type::Array(ref first_type)
+ | Type::Slice(ref first_type)
| Type::Reference(_, ref first_type) => {
Type::leaf_type_recursive_helper(first_type, Some(ty))
}
@@ -391,6 +442,7 @@ impl Type {
Type::Option(ref first_type)
| Type::Vec(ref first_type)
| Type::Array(ref first_type)
+ | Type::Slice(ref first_type)
| Type::Reference(_, ref first_type) => match **first_type {
Type::TypePath(ref type_) => type_,
_ => unimplemented!("leaf_type() should only return shallow types"),
@@ -443,7 +495,7 @@ impl Type {
}
}
}
- Type::Vec(ref first_type) => {
+ Type::Vec(ref first_type) | Type::Slice(ref first_type) => {
if let Type::TypePath(_) = **first_type {
if last_part == "u8" {
return BasicType::BYTE_ARRAY;
@@ -484,7 +536,7 @@ impl Type {
}
}
}
- Type::Vec(ref first_type) => {
+ Type::Vec(ref first_type) | Type::Slice(ref first_type) => {
if let Type::TypePath(_) = **first_type {
if last_part == "u8" {
return quote! { None };
@@ -572,6 +624,7 @@ impl Type {
syn::Type::Path(ref p) => Type::from_type_path(f, p),
syn::Type::Reference(ref tr) => Type::from_type_reference(f, tr),
syn::Type::Array(ref ta) => Type::from_type_array(f, ta),
+ syn::Type::Slice(ref ts) => Type::from_type_slice(f, ts),
other => unimplemented!(
"Unable to derive {:?} - it is currently an unsupported type\n{:#?}",
f.ident.as_ref().unwrap(),
@@ -622,6 +675,11 @@ impl Type {
let inner_type = Type::from_type(f, ta.elem.as_ref());
Type::Array(Box::new(inner_type))
}
+
+ fn from_type_slice(f: &syn::Field, ts: &syn::TypeSlice) -> Self {
+ let inner_type = Type::from_type(f, ts.elem.as_ref());
+ Type::Slice(Box::new(inner_type))
+ }
}
#[cfg(test)]
|
diff --git a/parquet_derive_test/src/lib.rs b/parquet_derive_test/src/lib.rs
index 746644793ff2..2aa174974aba 100644
--- a/parquet_derive_test/src/lib.rs
+++ b/parquet_derive_test/src/lib.rs
@@ -42,6 +42,11 @@ struct ACompleteRecord<'a> {
pub borrowed_maybe_a_string: &'a Option<String>,
pub borrowed_maybe_a_str: &'a Option<&'a str>,
pub now: chrono::NaiveDateTime,
+ pub byte_vec: Vec<u8>,
+ pub maybe_byte_vec: Option<Vec<u8>>,
+ pub borrowed_byte_vec: &'a [u8],
+ pub borrowed_maybe_byte_vec: &'a Option<Vec<u8>>,
+ pub borrowed_maybe_borrowed_byte_vec: &'a Option<&'a [u8]>,
}
#[cfg(test)]
@@ -84,6 +89,11 @@ mod tests {
OPTIONAL BINARY borrowed_maybe_a_string (STRING);
OPTIONAL BINARY borrowed_maybe_a_str (STRING);
REQUIRED INT64 now (TIMESTAMP_MILLIS);
+ REQUIRED BINARY byte_vec;
+ OPTIONAL BINARY maybe_byte_vec;
+ REQUIRED BINARY borrowed_byte_vec;
+ OPTIONAL BINARY borrowed_maybe_byte_vec;
+ OPTIONAL BINARY borrowed_maybe_borrowed_byte_vec;
}";
let schema = Arc::new(parse_message_type(schema_str).unwrap());
@@ -92,6 +102,9 @@ mod tests {
let a_borrowed_string = "cool news".to_owned();
let maybe_a_string = Some("it's true, I'm a string".to_owned());
let maybe_a_str = Some(&a_str[..]);
+ let borrowed_byte_vec = vec![0x68, 0x69, 0x70];
+ let borrowed_maybe_byte_vec = Some(vec![0x71, 0x72]);
+ let borrowed_maybe_borrowed_byte_vec = Some(&borrowed_byte_vec[..]);
let drs: Vec<ACompleteRecord> = vec![ACompleteRecord {
a_bool: true,
@@ -115,6 +128,11 @@ mod tests {
borrowed_maybe_a_string: &maybe_a_string,
borrowed_maybe_a_str: &maybe_a_str,
now: chrono::Utc::now().naive_local(),
+ byte_vec: vec![0x65, 0x66, 0x67],
+ maybe_byte_vec: Some(vec![0x88, 0x89, 0x90]),
+ borrowed_byte_vec: &borrowed_byte_vec,
+ borrowed_maybe_byte_vec: &borrowed_maybe_byte_vec,
+ borrowed_maybe_borrowed_byte_vec: &borrowed_maybe_borrowed_byte_vec,
}];
let generated_schema = drs.as_slice().schema().unwrap();
|
parquet_derive doesn't support Vec<u8>
**Describe the bug**
When I attempt to `#[derive(ParquetRecordWriter)]` on a struct that contains fields of type `Vec<u8>`, the proc-macro panics.
**To Reproduce**
```
#[derive(ParquetRecordWriter)]
pub struct Row {
foo: Vec<u8>,
}
```
results in
```
message: not implemented: Unsupported: Vec(
TypePath(
Path(
TypePath {
qself: None,
path: Path {
leading_colon: None,
segments: [
PathSegment {
ident: Ident {
ident: "u8",
span: #0 bytes(4505..4507),
},
arguments: None,
},
],
},
},
),
),
)
```
**Expected behavior**
Macro successfully generates the code to write a Vec<u8> to a parquet file.
**Additional context**
Support for `Vec<u8>` is explicitly mentioned in the `parquet_derive` readme, but a field of that type is not present in the integration test crate (separately, neither is `Uuid`).
|
2023-03-17T00:10:25Z
|
35.0
|
5eeccab922c377a18e54cf39ad49a2e4d54ffaf2
|
|
apache/arrow-rs
| 3,836
|
apache__arrow-rs-3836
|
[
"3830"
] |
495682aa72ffe92bbd0d6d8d93e0c00b5483ff7d
|
diff --git a/arrow-arith/Cargo.toml b/arrow-arith/Cargo.toml
index 6b3d82c9c906..4360332d9c7a 100644
--- a/arrow-arith/Cargo.toml
+++ b/arrow-arith/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-arith"
-version = "34.0.0"
+version = "35.0.0"
description = "Arrow arithmetic kernels"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,10 +38,10 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow-array = { version = "34.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "34.0.0", path = "../arrow-buffer" }
-arrow-data = { version = "34.0.0", path = "../arrow-data" }
-arrow-schema = { version = "34.0.0", path = "../arrow-schema" }
+arrow-array = { version = "35.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "35.0.0", path = "../arrow-buffer" }
+arrow-data = { version = "35.0.0", path = "../arrow-data" }
+arrow-schema = { version = "35.0.0", path = "../arrow-schema" }
chrono = { version = "0.4.23", default-features = false }
half = { version = "2.1", default-features = false }
num = { version = "0.4", default-features = false, features = ["std"] }
diff --git a/arrow-array/Cargo.toml b/arrow-array/Cargo.toml
index 5f839426edba..1675f59838a7 100644
--- a/arrow-array/Cargo.toml
+++ b/arrow-array/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-array"
-version = "34.0.0"
+version = "35.0.0"
description = "Array abstractions for Apache Arrow"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -45,9 +45,9 @@ ahash = { version = "0.8", default-features = false, features = ["compile-time-r
ahash = { version = "0.8", default-features = false, features = ["runtime-rng"] }
[dependencies]
-arrow-buffer = { version = "34.0.0", path = "../arrow-buffer" }
-arrow-schema = { version = "34.0.0", path = "../arrow-schema" }
-arrow-data = { version = "34.0.0", path = "../arrow-data" }
+arrow-buffer = { version = "35.0.0", path = "../arrow-buffer" }
+arrow-schema = { version = "35.0.0", path = "../arrow-schema" }
+arrow-data = { version = "35.0.0", path = "../arrow-data" }
chrono = { version = "0.4.23", default-features = false, features = ["clock"] }
chrono-tz = { version = "0.8", optional = true }
num = { version = "0.4", default-features = false, features = ["std"] }
diff --git a/arrow-buffer/Cargo.toml b/arrow-buffer/Cargo.toml
index 63e5aaa4476d..699a1000132f 100644
--- a/arrow-buffer/Cargo.toml
+++ b/arrow-buffer/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-buffer"
-version = "34.0.0"
+version = "35.0.0"
description = "Buffer abstractions for Apache Arrow"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
diff --git a/arrow-cast/Cargo.toml b/arrow-cast/Cargo.toml
index 79c073b9dd4f..235dca135e5a 100644
--- a/arrow-cast/Cargo.toml
+++ b/arrow-cast/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-cast"
-version = "34.0.0"
+version = "35.0.0"
description = "Cast kernel and utilities for Apache Arrow"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -44,11 +44,11 @@ features = ["prettyprint"]
prettyprint = ["comfy-table"]
[dependencies]
-arrow-array = { version = "34.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "34.0.0", path = "../arrow-buffer" }
-arrow-data = { version = "34.0.0", path = "../arrow-data" }
-arrow-schema = { version = "34.0.0", path = "../arrow-schema" }
-arrow-select = { version = "34.0.0", path = "../arrow-select" }
+arrow-array = { version = "35.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "35.0.0", path = "../arrow-buffer" }
+arrow-data = { version = "35.0.0", path = "../arrow-data" }
+arrow-schema = { version = "35.0.0", path = "../arrow-schema" }
+arrow-select = { version = "35.0.0", path = "../arrow-select" }
chrono = { version = "0.4.23", default-features = false, features = ["clock"] }
num = { version = "0.4", default-features = false, features = ["std"] }
lexical-core = { version = "^0.8", default-features = false, features = ["write-integers", "write-floats", "parse-integers", "parse-floats"] }
diff --git a/arrow-csv/Cargo.toml b/arrow-csv/Cargo.toml
index 62ca69bcaf9b..7ceb1401d1c0 100644
--- a/arrow-csv/Cargo.toml
+++ b/arrow-csv/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-csv"
-version = "34.0.0"
+version = "35.0.0"
description = "Support for parsing CSV format into the Arrow format"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,11 +38,11 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow-array = { version = "34.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "34.0.0", path = "../arrow-buffer" }
-arrow-cast = { version = "34.0.0", path = "../arrow-cast" }
-arrow-data = { version = "34.0.0", path = "../arrow-data" }
-arrow-schema = { version = "34.0.0", path = "../arrow-schema" }
+arrow-array = { version = "35.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "35.0.0", path = "../arrow-buffer" }
+arrow-cast = { version = "35.0.0", path = "../arrow-cast" }
+arrow-data = { version = "35.0.0", path = "../arrow-data" }
+arrow-schema = { version = "35.0.0", path = "../arrow-schema" }
chrono = { version = "0.4.23", default-features = false, features = ["clock"] }
csv = { version = "1.1", default-features = false }
csv-core = { version = "0.1"}
diff --git a/arrow-data/Cargo.toml b/arrow-data/Cargo.toml
index 33de17339131..d58413a762bd 100644
--- a/arrow-data/Cargo.toml
+++ b/arrow-data/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-data"
-version = "34.0.0"
+version = "35.0.0"
description = "Array data abstractions for Apache Arrow"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -50,8 +50,8 @@ features = ["ffi"]
[dependencies]
-arrow-buffer = { version = "34.0.0", path = "../arrow-buffer" }
-arrow-schema = { version = "34.0.0", path = "../arrow-schema" }
+arrow-buffer = { version = "35.0.0", path = "../arrow-buffer" }
+arrow-schema = { version = "35.0.0", path = "../arrow-schema" }
num = { version = "0.4", default-features = false, features = ["std"] }
half = { version = "2.1", default-features = false }
diff --git a/arrow-flight/Cargo.toml b/arrow-flight/Cargo.toml
index 819818191c83..827be6d058df 100644
--- a/arrow-flight/Cargo.toml
+++ b/arrow-flight/Cargo.toml
@@ -18,7 +18,7 @@
[package]
name = "arrow-flight"
description = "Apache Arrow Flight"
-version = "34.0.0"
+version = "35.0.0"
edition = "2021"
rust-version = "1.62"
authors = ["Apache Arrow <dev@arrow.apache.org>"]
@@ -27,12 +27,12 @@ repository = "https://github.com/apache/arrow-rs"
license = "Apache-2.0"
[dependencies]
-arrow-array = { version = "34.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "34.0.0", path = "../arrow-buffer" }
+arrow-array = { version = "35.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "35.0.0", path = "../arrow-buffer" }
# Cast is needed to work around https://github.com/apache/arrow-rs/issues/3389
-arrow-cast = { version = "34.0.0", path = "../arrow-cast" }
-arrow-ipc = { version = "34.0.0", path = "../arrow-ipc" }
-arrow-schema = { version = "34.0.0", path = "../arrow-schema" }
+arrow-cast = { version = "35.0.0", path = "../arrow-cast" }
+arrow-ipc = { version = "35.0.0", path = "../arrow-ipc" }
+arrow-schema = { version = "35.0.0", path = "../arrow-schema" }
base64 = { version = "0.21", default-features = false, features = ["std"] }
tonic = { version = "0.8", default-features = false, features = ["transport", "codegen", "prost"] }
bytes = { version = "1", default-features = false }
@@ -58,7 +58,7 @@ tls = ["tonic/tls"]
cli = ["arrow-cast/prettyprint", "clap", "tracing-log", "tracing-subscriber", "tonic/tls-webpki-roots"]
[dev-dependencies]
-arrow-cast = { version = "34.0.0", path = "../arrow-cast", features = ["prettyprint"] }
+arrow-cast = { version = "35.0.0", path = "../arrow-cast", features = ["prettyprint"] }
assert_cmd = "2.0.8"
tempfile = "3.3"
tokio-stream = { version = "0.1", features = ["net"] }
diff --git a/arrow-flight/README.md b/arrow-flight/README.md
index 1f8026887485..41312cc0c559 100644
--- a/arrow-flight/README.md
+++ b/arrow-flight/README.md
@@ -27,7 +27,7 @@ Add this to your Cargo.toml:
```toml
[dependencies]
-arrow-flight = "34.0.0"
+arrow-flight = "35.0.0"
```
Apache Arrow Flight is a gRPC based protocol for exchanging Arrow data between processes. See the blog post [Introducing Apache Arrow Flight: A Framework for Fast Data Transport](https://arrow.apache.org/blog/2019/10/13/introducing-arrow-flight/) for more information.
diff --git a/arrow-ipc/Cargo.toml b/arrow-ipc/Cargo.toml
index 040d1c113a5c..8bd7d31485e4 100644
--- a/arrow-ipc/Cargo.toml
+++ b/arrow-ipc/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-ipc"
-version = "34.0.0"
+version = "35.0.0"
description = "Support for the Arrow IPC format"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,11 +38,11 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow-array = { version = "34.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "34.0.0", path = "../arrow-buffer" }
-arrow-cast = { version = "34.0.0", path = "../arrow-cast" }
-arrow-data = { version = "34.0.0", path = "../arrow-data" }
-arrow-schema = { version = "34.0.0", path = "../arrow-schema" }
+arrow-array = { version = "35.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "35.0.0", path = "../arrow-buffer" }
+arrow-cast = { version = "35.0.0", path = "../arrow-cast" }
+arrow-data = { version = "35.0.0", path = "../arrow-data" }
+arrow-schema = { version = "35.0.0", path = "../arrow-schema" }
flatbuffers = { version = "23.1.21", default-features = false }
lz4 = { version = "1.23", default-features = false, optional = true }
zstd = { version = "0.12.0", default-features = false, optional = true }
diff --git a/arrow-json/Cargo.toml b/arrow-json/Cargo.toml
index 3869bfd90b19..92c1a3eb282f 100644
--- a/arrow-json/Cargo.toml
+++ b/arrow-json/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-json"
-version = "34.0.0"
+version = "35.0.0"
description = "Support for parsing JSON format into the Arrow format"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,11 +38,11 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow-array = { version = "34.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "34.0.0", path = "../arrow-buffer" }
-arrow-cast = { version = "34.0.0", path = "../arrow-cast" }
-arrow-data = { version = "34.0.0", path = "../arrow-data" }
-arrow-schema = { version = "34.0.0", path = "../arrow-schema" }
+arrow-array = { version = "35.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "35.0.0", path = "../arrow-buffer" }
+arrow-cast = { version = "35.0.0", path = "../arrow-cast" }
+arrow-data = { version = "35.0.0", path = "../arrow-data" }
+arrow-schema = { version = "35.0.0", path = "../arrow-schema" }
half = { version = "2.1", default-features = false }
indexmap = { version = "1.9", default-features = false, features = ["std"] }
num = { version = "0.4", default-features = false, features = ["std"] }
diff --git a/arrow-ord/Cargo.toml b/arrow-ord/Cargo.toml
index 7e7ec7d4fedd..bc6feb4f2a29 100644
--- a/arrow-ord/Cargo.toml
+++ b/arrow-ord/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-ord"
-version = "34.0.0"
+version = "35.0.0"
description = "Ordering kernels for arrow arrays"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,11 +38,11 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow-array = { version = "34.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "34.0.0", path = "../arrow-buffer" }
-arrow-data = { version = "34.0.0", path = "../arrow-data" }
-arrow-schema = { version = "34.0.0", path = "../arrow-schema" }
-arrow-select = { version = "34.0.0", path = "../arrow-select" }
+arrow-array = { version = "35.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "35.0.0", path = "../arrow-buffer" }
+arrow-data = { version = "35.0.0", path = "../arrow-data" }
+arrow-schema = { version = "35.0.0", path = "../arrow-schema" }
+arrow-select = { version = "35.0.0", path = "../arrow-select" }
num = { version = "0.4", default-features = false, features = ["std"] }
[dev-dependencies]
diff --git a/arrow-row/Cargo.toml b/arrow-row/Cargo.toml
index 3ddc195c39a0..e2796fbe134c 100644
--- a/arrow-row/Cargo.toml
+++ b/arrow-row/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-row"
-version = "34.0.0"
+version = "35.0.0"
description = "Arrow row format"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -44,17 +44,17 @@ ahash = { version = "0.8", default-features = false, features = ["compile-time-r
ahash = { version = "0.8", default-features = false, features = ["runtime-rng"] }
[dependencies]
-arrow-array = { version = "34.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "34.0.0", path = "../arrow-buffer" }
-arrow-data = { version = "34.0.0", path = "../arrow-data" }
-arrow-schema = { version = "34.0.0", path = "../arrow-schema" }
+arrow-array = { version = "35.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "35.0.0", path = "../arrow-buffer" }
+arrow-data = { version = "35.0.0", path = "../arrow-data" }
+arrow-schema = { version = "35.0.0", path = "../arrow-schema" }
half = { version = "2.1", default-features = false }
hashbrown = { version = "0.13", default-features = false }
[dev-dependencies]
-arrow-cast = { version = "34.0.0", path = "../arrow-cast" }
-arrow-ord = { version = "34.0.0", path = "../arrow-ord" }
+arrow-cast = { version = "35.0.0", path = "../arrow-cast" }
+arrow-ord = { version = "35.0.0", path = "../arrow-ord" }
rand = { version = "0.8", default-features = false, features = ["std", "std_rng"] }
[features]
diff --git a/arrow-schema/Cargo.toml b/arrow-schema/Cargo.toml
index acf6c43b8342..7b240e1ac69c 100644
--- a/arrow-schema/Cargo.toml
+++ b/arrow-schema/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-schema"
-version = "34.0.0"
+version = "35.0.0"
description = "Defines the logical types for arrow arrays"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
diff --git a/arrow-select/Cargo.toml b/arrow-select/Cargo.toml
index 540d37cb5aa8..35c51c2da3ea 100644
--- a/arrow-select/Cargo.toml
+++ b/arrow-select/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-select"
-version = "34.0.0"
+version = "35.0.0"
description = "Selection kernels for arrow arrays"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,10 +38,10 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow-buffer = { version = "34.0.0", path = "../arrow-buffer" }
-arrow-data = { version = "34.0.0", path = "../arrow-data" }
-arrow-schema = { version = "34.0.0", path = "../arrow-schema" }
-arrow-array = { version = "34.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "35.0.0", path = "../arrow-buffer" }
+arrow-data = { version = "35.0.0", path = "../arrow-data" }
+arrow-schema = { version = "35.0.0", path = "../arrow-schema" }
+arrow-array = { version = "35.0.0", path = "../arrow-array" }
num = { version = "0.4", default-features = false, features = ["std"] }
[features]
diff --git a/arrow-string/Cargo.toml b/arrow-string/Cargo.toml
index 2e8067051644..923b8e8c00c4 100644
--- a/arrow-string/Cargo.toml
+++ b/arrow-string/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-string"
-version = "34.0.0"
+version = "35.0.0"
description = "String kernels for arrow arrays"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,11 +38,11 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow-buffer = { version = "34.0.0", path = "../arrow-buffer" }
-arrow-data = { version = "34.0.0", path = "../arrow-data" }
-arrow-schema = { version = "34.0.0", path = "../arrow-schema" }
-arrow-array = { version = "34.0.0", path = "../arrow-array" }
-arrow-select = { version = "34.0.0", path = "../arrow-select" }
+arrow-buffer = { version = "35.0.0", path = "../arrow-buffer" }
+arrow-data = { version = "35.0.0", path = "../arrow-data" }
+arrow-schema = { version = "35.0.0", path = "../arrow-schema" }
+arrow-array = { version = "35.0.0", path = "../arrow-array" }
+arrow-select = { version = "35.0.0", path = "../arrow-select" }
regex = { version = "1.7.0", default-features = false, features = ["std", "unicode", "perf"] }
regex-syntax = { version = "0.6.27", default-features = false, features = ["unicode"] }
diff --git a/arrow/Cargo.toml b/arrow/Cargo.toml
index 0c387f305a8e..8814f233bad1 100644
--- a/arrow/Cargo.toml
+++ b/arrow/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow"
-version = "34.0.0"
+version = "35.0.0"
description = "Rust implementation of Apache Arrow"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -45,19 +45,19 @@ ahash = { version = "0.8", default-features = false, features = ["compile-time-r
ahash = { version = "0.8", default-features = false, features = ["runtime-rng"] }
[dependencies]
-arrow-arith = { version = "34.0.0", path = "../arrow-arith" }
-arrow-array = { version = "34.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "34.0.0", path = "../arrow-buffer" }
-arrow-cast = { version = "34.0.0", path = "../arrow-cast" }
-arrow-csv = { version = "34.0.0", path = "../arrow-csv", optional = true }
-arrow-data = { version = "34.0.0", path = "../arrow-data" }
-arrow-ipc = { version = "34.0.0", path = "../arrow-ipc", optional = true }
-arrow-json = { version = "34.0.0", path = "../arrow-json", optional = true }
-arrow-ord = { version = "34.0.0", path = "../arrow-ord" }
-arrow-row = { version = "34.0.0", path = "../arrow-row" }
-arrow-schema = { version = "34.0.0", path = "../arrow-schema" }
-arrow-select = { version = "34.0.0", path = "../arrow-select" }
-arrow-string = { version = "34.0.0", path = "../arrow-string" }
+arrow-arith = { version = "35.0.0", path = "../arrow-arith" }
+arrow-array = { version = "35.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "35.0.0", path = "../arrow-buffer" }
+arrow-cast = { version = "35.0.0", path = "../arrow-cast" }
+arrow-csv = { version = "35.0.0", path = "../arrow-csv", optional = true }
+arrow-data = { version = "35.0.0", path = "../arrow-data" }
+arrow-ipc = { version = "35.0.0", path = "../arrow-ipc", optional = true }
+arrow-json = { version = "35.0.0", path = "../arrow-json", optional = true }
+arrow-ord = { version = "35.0.0", path = "../arrow-ord" }
+arrow-row = { version = "35.0.0", path = "../arrow-row" }
+arrow-schema = { version = "35.0.0", path = "../arrow-schema" }
+arrow-select = { version = "35.0.0", path = "../arrow-select" }
+arrow-string = { version = "35.0.0", path = "../arrow-string" }
rand = { version = "0.8", default-features = false, features = ["std", "std_rng"], optional = true }
pyo3 = { version = "0.18", default-features = false, optional = true }
diff --git a/arrow/README.md b/arrow/README.md
index 6d0772e2d956..479213833244 100644
--- a/arrow/README.md
+++ b/arrow/README.md
@@ -35,7 +35,7 @@ This crate is tested with the latest stable version of Rust. We do not currently
The arrow crate follows the [SemVer standard](https://doc.rust-lang.org/cargo/reference/semver.html) defined by Cargo and works well within the Rust crate ecosystem.
-However, for historical reasons, this crate uses versions with major numbers greater than `0.x` (e.g. `34.0.0`), unlike many other crates in the Rust ecosystem which spend extended time releasing versions `0.x` to signal planned ongoing API changes. Minor arrow releases contain only compatible changes, while major releases may contain breaking API changes.
+However, for historical reasons, this crate uses versions with major numbers greater than `0.x` (e.g. `35.0.0`), unlike many other crates in the Rust ecosystem which spend extended time releasing versions `0.x` to signal planned ongoing API changes. Minor arrow releases contain only compatible changes, while major releases may contain breaking API changes.
## Feature Flags
diff --git a/dev/release/README.md b/dev/release/README.md
index 70921dd024da..c7c14b8d58c1 100644
--- a/dev/release/README.md
+++ b/dev/release/README.md
@@ -70,7 +70,7 @@ git pull
git checkout -b <RELEASE_BRANCH>
# Update versions. Make sure to run it before the next step since we do not want CHANGELOG-old.md affected.
-sed -i '' -e 's/14.0.0/34.0.0/g' `find . -name 'Cargo.toml' -or -name '*.md' | grep -v CHANGELOG.md`
+sed -i '' -e 's/14.0.0/35.0.0/g' `find . -name 'Cargo.toml' -or -name '*.md' | grep -v CHANGELOG.md`
git commit -a -m 'Update version'
# Copy the content of CHANGELOG.md to the beginning of CHANGELOG-old.md
diff --git a/dev/release/file_release_pr.sh b/dev/release/file_release_pr.sh
index 2db3d7986d3f..081b7c436aa5 100644
--- a/dev/release/file_release_pr.sh
+++ b/dev/release/file_release_pr.sh
@@ -25,8 +25,8 @@
set -e
-FUTURE_RELEASE="29.0.0"
-ISSUE_NUMBER=3216
+FUTURE_RELEASE="35.0.0"
+ISSUE_NUMBER=3830
TITLE="Update version to \`$FUTURE_RELEASE\` and update \`CHANGELOG\`"
BODY="# Which issue does this PR close?\n\nCloses #$ISSUE_NUMBER.\n\n# Rationale for this change\nPrepare for biweekly release\n\n# What changes are included in this PR?\n\n# Are there any user-facing changes?\nYes"
diff --git a/dev/release/update_change_log.sh b/dev/release/update_change_log.sh
index 920498905ccd..b01d190a4f38 100755
--- a/dev/release/update_change_log.sh
+++ b/dev/release/update_change_log.sh
@@ -29,8 +29,8 @@
set -e
-SINCE_TAG="33.0.0"
-FUTURE_RELEASE="34.0.0"
+SINCE_TAG="34.0.0"
+FUTURE_RELEASE="35.0.0"
SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SOURCE_TOP_DIR="$(cd "${SOURCE_DIR}/../../" && pwd)"
diff --git a/parquet/Cargo.toml b/parquet/Cargo.toml
index 87f552fbd36a..a822a966f29d 100644
--- a/parquet/Cargo.toml
+++ b/parquet/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "parquet"
-version = "34.0.0"
+version = "35.0.0"
license = "Apache-2.0"
description = "Apache Parquet implementation in Rust"
homepage = "https://github.com/apache/arrow-rs"
@@ -35,14 +35,14 @@ ahash = { version = "0.8", default-features = false, features = ["compile-time-r
ahash = { version = "0.8", default-features = false, features = ["runtime-rng"] }
[dependencies]
-arrow-array = { version = "34.0.0", path = "../arrow-array", default-features = false, optional = true }
-arrow-buffer = { version = "34.0.0", path = "../arrow-buffer", default-features = false, optional = true }
-arrow-cast = { version = "34.0.0", path = "../arrow-cast", default-features = false, optional = true }
-arrow-csv = { version = "34.0.0", path = "../arrow-csv", default-features = false, optional = true }
-arrow-data = { version = "34.0.0", path = "../arrow-data", default-features = false, optional = true }
-arrow-schema = { version = "34.0.0", path = "../arrow-schema", default-features = false, optional = true }
-arrow-select = { version = "34.0.0", path = "../arrow-select", default-features = false, optional = true }
-arrow-ipc = { version = "34.0.0", path = "../arrow-ipc", default-features = false, optional = true }
+arrow-array = { version = "35.0.0", path = "../arrow-array", default-features = false, optional = true }
+arrow-buffer = { version = "35.0.0", path = "../arrow-buffer", default-features = false, optional = true }
+arrow-cast = { version = "35.0.0", path = "../arrow-cast", default-features = false, optional = true }
+arrow-csv = { version = "35.0.0", path = "../arrow-csv", default-features = false, optional = true }
+arrow-data = { version = "35.0.0", path = "../arrow-data", default-features = false, optional = true }
+arrow-schema = { version = "35.0.0", path = "../arrow-schema", default-features = false, optional = true }
+arrow-select = { version = "35.0.0", path = "../arrow-select", default-features = false, optional = true }
+arrow-ipc = { version = "35.0.0", path = "../arrow-ipc", default-features = false, optional = true }
object_store = { version = "0.5", path = "../object_store", default-features = false, optional = true }
bytes = { version = "1.1", default-features = false, features = ["std"] }
@@ -76,7 +76,7 @@ flate2 = { version = "1.0", default-features = false, features = ["rust_backend"
lz4 = { version = "1.23", default-features = false }
zstd = { version = "0.12", default-features = false }
serde_json = { version = "1.0", features = ["std"], default-features = false }
-arrow = { path = "../arrow", version = "34.0.0", default-features = false, features = ["ipc", "test_utils", "prettyprint", "json"] }
+arrow = { path = "../arrow", version = "35.0.0", default-features = false, features = ["ipc", "test_utils", "prettyprint", "json"] }
tokio = { version = "1.0", default-features = false, features = ["macros", "rt", "io-util", "fs"] }
rand = { version = "0.8", default-features = false, features = ["std", "std_rng"] }
diff --git a/parquet_derive/Cargo.toml b/parquet_derive/Cargo.toml
index cb16846b0fb1..e41ba19086d7 100644
--- a/parquet_derive/Cargo.toml
+++ b/parquet_derive/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "parquet_derive"
-version = "34.0.0"
+version = "35.0.0"
license = "Apache-2.0"
description = "Derive macros for the Rust implementation of Apache Parquet"
homepage = "https://github.com/apache/arrow-rs"
@@ -35,4 +35,4 @@ proc-macro = true
proc-macro2 = { version = "1.0", default-features = false }
quote = { version = "1.0", default-features = false }
syn = { version = "1.0", features = ["extra-traits"] }
-parquet = { path = "../parquet", version = "34.0.0", default-features = false }
+parquet = { path = "../parquet", version = "35.0.0", default-features = false }
diff --git a/parquet_derive/README.md b/parquet_derive/README.md
index f3f66c45bc98..2bed2d550e62 100644
--- a/parquet_derive/README.md
+++ b/parquet_derive/README.md
@@ -32,8 +32,8 @@ Add this to your Cargo.toml:
```toml
[dependencies]
-parquet = "34.0.0"
-parquet_derive = "34.0.0"
+parquet = "35.0.0"
+parquet_derive = "35.0.0"
```
and this to your crate root:
|
diff --git a/arrow-integration-test/Cargo.toml b/arrow-integration-test/Cargo.toml
index 2d92e6292ded..ca14401b6899 100644
--- a/arrow-integration-test/Cargo.toml
+++ b/arrow-integration-test/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-integration-test"
-version = "34.0.0"
+version = "35.0.0"
description = "Support for the Apache Arrow JSON test data format"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,8 +38,8 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow = { version = "34.0.0", path = "../arrow", default-features = false }
-arrow-buffer = { version = "34.0.0", path = "../arrow-buffer" }
+arrow = { version = "35.0.0", path = "../arrow", default-features = false }
+arrow-buffer = { version = "35.0.0", path = "../arrow-buffer" }
hex = { version = "0.4", default-features = false, features = ["std"] }
serde = { version = "1.0", default-features = false, features = ["rc", "derive"] }
serde_json = { version = "1.0", default-features = false, features = ["std"] }
diff --git a/arrow-integration-testing/Cargo.toml b/arrow-integration-testing/Cargo.toml
index 67d5b7d2745a..48700bbe90d3 100644
--- a/arrow-integration-testing/Cargo.toml
+++ b/arrow-integration-testing/Cargo.toml
@@ -18,7 +18,7 @@
[package]
name = "arrow-integration-testing"
description = "Binaries used in the Arrow integration tests (NOT PUBLISHED TO crates.io)"
-version = "34.0.0"
+version = "35.0.0"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
authors = ["Apache Arrow <dev@arrow.apache.org>"]
diff --git a/arrow-pyarrow-integration-testing/Cargo.toml b/arrow-pyarrow-integration-testing/Cargo.toml
index cbf2e9cf29d9..ba084c435e64 100644
--- a/arrow-pyarrow-integration-testing/Cargo.toml
+++ b/arrow-pyarrow-integration-testing/Cargo.toml
@@ -18,7 +18,7 @@
[package]
name = "arrow-pyarrow-integration-testing"
description = ""
-version = "34.0.0"
+version = "35.0.0"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
authors = ["Apache Arrow <dev@arrow.apache.org>"]
@@ -32,5 +32,5 @@ name = "arrow_pyarrow_integration_testing"
crate-type = ["cdylib"]
[dependencies]
-arrow = { path = "../arrow", version = "34.0.0", features = ["pyarrow"] }
+arrow = { path = "../arrow", version = "35.0.0", features = ["pyarrow"] }
pyo3 = { version = "0.18", features = ["extension-module"] }
diff --git a/parquet_derive_test/Cargo.toml b/parquet_derive_test/Cargo.toml
index 33f7675a30ef..cca778d6f51b 100644
--- a/parquet_derive_test/Cargo.toml
+++ b/parquet_derive_test/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "parquet_derive_test"
-version = "34.0.0"
+version = "35.0.0"
license = "Apache-2.0"
description = "Integration test package for parquet-derive"
homepage = "https://github.com/apache/arrow-rs"
@@ -29,6 +29,6 @@ publish = false
rust-version = "1.62"
[dependencies]
-parquet = { path = "../parquet", version = "34.0.0", default-features = false }
-parquet_derive = { path = "../parquet_derive", version = "34.0.0", default-features = false }
+parquet = { path = "../parquet", version = "35.0.0", default-features = false }
+parquet_derive = { path = "../parquet_derive", version = "35.0.0", default-features = false }
chrono = { version="0.4.23", default-features = false, features = [ "clock" ] }
|
Release 35.0.0 of arrow/arrow-flight/parquet/parquet-derive (next release after 34.0.0)
Follow on from https://github.com/apache/arrow-rs/issues/3755
- Planned Release Candidate: 2023-03-10
- Planned Release and Publish to crates.io: 2023-03-13
Items (from [dev/release/README.md](https://github.com/apache/arrow-rs/blob/master/dev/release/README.md)):
- [ ] PR to update version and CHANGELOG:
- [ ] Release candidate created:
- [ ] Release candidate approved:
- [ ] Release to crates.io:
- [ ] Make ticket for next release
See full list here:
https://github.com/apache/arrow-rs/compare/34.0.0...master
cc @alamb @tustvold @viirya
|
2023-03-09T22:34:44Z
|
34.0
|
495682aa72ffe92bbd0d6d8d93e0c00b5483ff7d
|
|
apache/arrow-rs
| 3,816
|
apache__arrow-rs-3816
|
[
"3814"
] |
1883bb691a33c39ce13e355e7f0a82414fc74010
|
diff --git a/arrow-flight/Cargo.toml b/arrow-flight/Cargo.toml
index f1cd7d4fb23b..db9f0a023bf4 100644
--- a/arrow-flight/Cargo.toml
+++ b/arrow-flight/Cargo.toml
@@ -60,6 +60,7 @@ cli = ["arrow/prettyprint", "clap", "tracing-log", "tracing-subscriber", "tonic/
[dev-dependencies]
arrow = { version = "34.0.0", path = "../arrow", features = ["prettyprint"] }
+assert_cmd = "2.0.8"
tempfile = "3.3"
tokio-stream = { version = "0.1", features = ["net"] }
tower = "0.4.13"
@@ -78,3 +79,8 @@ required-features = ["flight-sql-experimental", "tls"]
[[bin]]
name = "flight_sql_client"
required-features = ["cli", "flight-sql-experimental", "tls"]
+
+[[test]]
+name = "flight_sql_client_cli"
+path = "tests/flight_sql_client_cli.rs"
+required-features = ["cli", "flight-sql-experimental", "tls"]
diff --git a/arrow-flight/src/bin/flight_sql_client.rs b/arrow-flight/src/bin/flight_sql_client.rs
index 9f211eaf63bc..d05efc227e2d 100644
--- a/arrow-flight/src/bin/flight_sql_client.rs
+++ b/arrow-flight/src/bin/flight_sql_client.rs
@@ -144,7 +144,9 @@ fn setup_logging() {
async fn setup_client(args: ClientArgs) -> Result<FlightSqlServiceClient> {
let port = args.port.unwrap_or(if args.tls { 443 } else { 80 });
- let mut endpoint = Endpoint::new(format!("https://{}:{}", args.host, port))
+ let protocol = if args.tls { "https" } else { "http" };
+
+ let mut endpoint = Endpoint::new(format!("{}://{}:{}", protocol, args.host, port))
.map_err(|_| ArrowError::IoError("Cannot create endpoint".to_string()))?
.connect_timeout(Duration::from_secs(20))
.timeout(Duration::from_secs(20))
|
diff --git a/arrow-flight/tests/flight_sql_client_cli.rs b/arrow-flight/tests/flight_sql_client_cli.rs
new file mode 100644
index 000000000000..2c54bd263fdb
--- /dev/null
+++ b/arrow-flight/tests/flight_sql_client_cli.rs
@@ -0,0 +1,545 @@
+// 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.
+
+use std::{net::SocketAddr, pin::Pin, sync::Arc, time::Duration};
+
+use arrow_array::{ArrayRef, Int64Array, RecordBatch, StringArray};
+use arrow_flight::{
+ flight_service_server::{FlightService, FlightServiceServer},
+ sql::{
+ server::FlightSqlService, ActionClosePreparedStatementRequest,
+ ActionCreatePreparedStatementRequest, ActionCreatePreparedStatementResult, Any,
+ CommandGetCatalogs, CommandGetCrossReference, CommandGetDbSchemas,
+ CommandGetExportedKeys, CommandGetImportedKeys, CommandGetPrimaryKeys,
+ CommandGetSqlInfo, CommandGetTableTypes, CommandGetTables,
+ CommandPreparedStatementQuery, CommandPreparedStatementUpdate,
+ CommandStatementQuery, CommandStatementUpdate, ProstMessageExt, SqlInfo,
+ TicketStatementQuery,
+ },
+ utils::batches_to_flight_data,
+ Action, FlightData, FlightDescriptor, FlightEndpoint, FlightInfo, HandshakeRequest,
+ HandshakeResponse, IpcMessage, SchemaAsIpc, Ticket,
+};
+use arrow_ipc::writer::IpcWriteOptions;
+use arrow_schema::{ArrowError, DataType, Field, Schema};
+use assert_cmd::Command;
+use futures::Stream;
+use prost::Message;
+use tokio::{net::TcpListener, task::JoinHandle};
+use tonic::{Request, Response, Status, Streaming};
+
+const QUERY: &str = "SELECT * FROM table;";
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
+async fn test_simple() {
+ let test_server = FlightSqlServiceImpl {};
+ let fixture = TestFixture::new(&test_server).await;
+ let addr = fixture.addr;
+
+ let stdout = tokio::task::spawn_blocking(move || {
+ Command::cargo_bin("flight_sql_client")
+ .unwrap()
+ .env_clear()
+ .env("RUST_BACKTRACE", "1")
+ .env("RUST_LOG", "warn")
+ .arg("--host")
+ .arg(addr.ip().to_string())
+ .arg("--port")
+ .arg(addr.port().to_string())
+ .arg(QUERY)
+ .assert()
+ .success()
+ .get_output()
+ .stdout
+ .clone()
+ })
+ .await
+ .unwrap();
+
+ fixture.shutdown_and_wait().await;
+
+ assert_eq!(
+ std::str::from_utf8(&stdout).unwrap().trim(),
+ "+--------------+-----------+\
+ \n| field_string | field_int |\
+ \n+--------------+-----------+\
+ \n| Hello | 42 |\
+ \n| lovely | |\
+ \n| FlightSQL! | 1337 |\
+ \n+--------------+-----------+",
+ );
+}
+
+/// All tests must complete within this many seconds or else the test server is shutdown
+const DEFAULT_TIMEOUT_SECONDS: u64 = 30;
+
+#[derive(Clone)]
+pub struct FlightSqlServiceImpl {}
+
+impl FlightSqlServiceImpl {
+ /// Return an [`FlightServiceServer`] that can be used with a
+ /// [`Server`](tonic::transport::Server)
+ pub fn service(&self) -> FlightServiceServer<Self> {
+ // wrap up tonic goop
+ FlightServiceServer::new(self.clone())
+ }
+
+ fn fake_result() -> Result<RecordBatch, ArrowError> {
+ let schema = Schema::new(vec![
+ Field::new("field_string", DataType::Utf8, false),
+ Field::new("field_int", DataType::Int64, true),
+ ]);
+
+ let string_array = StringArray::from(vec!["Hello", "lovely", "FlightSQL!"]);
+ let int_array = Int64Array::from(vec![Some(42), None, Some(1337)]);
+
+ let cols = vec![
+ Arc::new(string_array) as ArrayRef,
+ Arc::new(int_array) as ArrayRef,
+ ];
+ RecordBatch::try_new(Arc::new(schema), cols)
+ }
+}
+
+#[tonic::async_trait]
+impl FlightSqlService for FlightSqlServiceImpl {
+ type FlightService = FlightSqlServiceImpl;
+
+ async fn do_handshake(
+ &self,
+ _request: Request<Streaming<HandshakeRequest>>,
+ ) -> Result<
+ Response<Pin<Box<dyn Stream<Item = Result<HandshakeResponse, Status>> + Send>>>,
+ Status,
+ > {
+ Err(Status::unimplemented("do_handshake not implemented"))
+ }
+
+ async fn do_get_fallback(
+ &self,
+ _request: Request<Ticket>,
+ message: Any,
+ ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
+ let part = message.unpack::<FetchResults>().unwrap().unwrap().handle;
+ let batch = Self::fake_result().unwrap();
+ let batch = match part.as_str() {
+ "part_1" => batch.slice(0, 2),
+ "part_2" => batch.slice(2, 1),
+ ticket => panic!("Invalid ticket: {ticket:?}"),
+ };
+ let schema = (*batch.schema()).clone();
+ let batches = vec![batch];
+ let flight_data = batches_to_flight_data(schema, batches)
+ .unwrap()
+ .into_iter()
+ .map(Ok);
+
+ let stream: Pin<Box<dyn Stream<Item = Result<FlightData, Status>> + Send>> =
+ Box::pin(futures::stream::iter(flight_data));
+ let resp = Response::new(stream);
+ Ok(resp)
+ }
+
+ async fn get_flight_info_statement(
+ &self,
+ query: CommandStatementQuery,
+ _request: Request<FlightDescriptor>,
+ ) -> Result<Response<FlightInfo>, Status> {
+ assert_eq!(query.query, QUERY);
+
+ let batch = Self::fake_result().unwrap();
+
+ let IpcMessage(schema_bytes) =
+ SchemaAsIpc::new(batch.schema().as_ref(), &IpcWriteOptions::default())
+ .try_into()
+ .unwrap();
+
+ let info = FlightInfo {
+ schema: schema_bytes,
+ flight_descriptor: None,
+ endpoint: vec![
+ FlightEndpoint {
+ ticket: Some(Ticket {
+ ticket: FetchResults {
+ handle: String::from("part_1"),
+ }
+ .as_any()
+ .encode_to_vec()
+ .into(),
+ }),
+ location: vec![],
+ },
+ FlightEndpoint {
+ ticket: Some(Ticket {
+ ticket: FetchResults {
+ handle: String::from("part_2"),
+ }
+ .as_any()
+ .encode_to_vec()
+ .into(),
+ }),
+ location: vec![],
+ },
+ ],
+ total_records: batch.num_rows() as i64,
+ total_bytes: batch.get_array_memory_size() as i64,
+ };
+ let resp = Response::new(info);
+ Ok(resp)
+ }
+
+ async fn get_flight_info_prepared_statement(
+ &self,
+ _cmd: CommandPreparedStatementQuery,
+ _request: Request<FlightDescriptor>,
+ ) -> Result<Response<FlightInfo>, Status> {
+ Err(Status::unimplemented(
+ "get_flight_info_prepared_statement not implemented",
+ ))
+ }
+
+ async fn get_flight_info_catalogs(
+ &self,
+ _query: CommandGetCatalogs,
+ _request: Request<FlightDescriptor>,
+ ) -> Result<Response<FlightInfo>, Status> {
+ Err(Status::unimplemented(
+ "get_flight_info_catalogs not implemented",
+ ))
+ }
+
+ async fn get_flight_info_schemas(
+ &self,
+ _query: CommandGetDbSchemas,
+ _request: Request<FlightDescriptor>,
+ ) -> Result<Response<FlightInfo>, Status> {
+ Err(Status::unimplemented(
+ "get_flight_info_schemas not implemented",
+ ))
+ }
+
+ async fn get_flight_info_tables(
+ &self,
+ _query: CommandGetTables,
+ _request: Request<FlightDescriptor>,
+ ) -> Result<Response<FlightInfo>, Status> {
+ Err(Status::unimplemented(
+ "get_flight_info_tables not implemented",
+ ))
+ }
+
+ async fn get_flight_info_table_types(
+ &self,
+ _query: CommandGetTableTypes,
+ _request: Request<FlightDescriptor>,
+ ) -> Result<Response<FlightInfo>, Status> {
+ Err(Status::unimplemented(
+ "get_flight_info_table_types not implemented",
+ ))
+ }
+
+ async fn get_flight_info_sql_info(
+ &self,
+ _query: CommandGetSqlInfo,
+ _request: Request<FlightDescriptor>,
+ ) -> Result<Response<FlightInfo>, Status> {
+ Err(Status::unimplemented(
+ "get_flight_info_sql_info not implemented",
+ ))
+ }
+
+ async fn get_flight_info_primary_keys(
+ &self,
+ _query: CommandGetPrimaryKeys,
+ _request: Request<FlightDescriptor>,
+ ) -> Result<Response<FlightInfo>, Status> {
+ Err(Status::unimplemented(
+ "get_flight_info_primary_keys not implemented",
+ ))
+ }
+
+ async fn get_flight_info_exported_keys(
+ &self,
+ _query: CommandGetExportedKeys,
+ _request: Request<FlightDescriptor>,
+ ) -> Result<Response<FlightInfo>, Status> {
+ Err(Status::unimplemented(
+ "get_flight_info_exported_keys not implemented",
+ ))
+ }
+
+ async fn get_flight_info_imported_keys(
+ &self,
+ _query: CommandGetImportedKeys,
+ _request: Request<FlightDescriptor>,
+ ) -> Result<Response<FlightInfo>, Status> {
+ Err(Status::unimplemented(
+ "get_flight_info_imported_keys not implemented",
+ ))
+ }
+
+ async fn get_flight_info_cross_reference(
+ &self,
+ _query: CommandGetCrossReference,
+ _request: Request<FlightDescriptor>,
+ ) -> Result<Response<FlightInfo>, Status> {
+ Err(Status::unimplemented(
+ "get_flight_info_imported_keys not implemented",
+ ))
+ }
+
+ // do_get
+ async fn do_get_statement(
+ &self,
+ _ticket: TicketStatementQuery,
+ _request: Request<Ticket>,
+ ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
+ Err(Status::unimplemented("do_get_statement not implemented"))
+ }
+
+ async fn do_get_prepared_statement(
+ &self,
+ _query: CommandPreparedStatementQuery,
+ _request: Request<Ticket>,
+ ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
+ Err(Status::unimplemented(
+ "do_get_prepared_statement not implemented",
+ ))
+ }
+
+ async fn do_get_catalogs(
+ &self,
+ _query: CommandGetCatalogs,
+ _request: Request<Ticket>,
+ ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
+ Err(Status::unimplemented("do_get_catalogs not implemented"))
+ }
+
+ async fn do_get_schemas(
+ &self,
+ _query: CommandGetDbSchemas,
+ _request: Request<Ticket>,
+ ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
+ Err(Status::unimplemented("do_get_schemas not implemented"))
+ }
+
+ async fn do_get_tables(
+ &self,
+ _query: CommandGetTables,
+ _request: Request<Ticket>,
+ ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
+ Err(Status::unimplemented("do_get_tables not implemented"))
+ }
+
+ async fn do_get_table_types(
+ &self,
+ _query: CommandGetTableTypes,
+ _request: Request<Ticket>,
+ ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
+ Err(Status::unimplemented("do_get_table_types not implemented"))
+ }
+
+ async fn do_get_sql_info(
+ &self,
+ _query: CommandGetSqlInfo,
+ _request: Request<Ticket>,
+ ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
+ Err(Status::unimplemented("do_get_sql_info not implemented"))
+ }
+
+ async fn do_get_primary_keys(
+ &self,
+ _query: CommandGetPrimaryKeys,
+ _request: Request<Ticket>,
+ ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
+ Err(Status::unimplemented("do_get_primary_keys not implemented"))
+ }
+
+ async fn do_get_exported_keys(
+ &self,
+ _query: CommandGetExportedKeys,
+ _request: Request<Ticket>,
+ ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
+ Err(Status::unimplemented(
+ "do_get_exported_keys not implemented",
+ ))
+ }
+
+ async fn do_get_imported_keys(
+ &self,
+ _query: CommandGetImportedKeys,
+ _request: Request<Ticket>,
+ ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
+ Err(Status::unimplemented(
+ "do_get_imported_keys not implemented",
+ ))
+ }
+
+ async fn do_get_cross_reference(
+ &self,
+ _query: CommandGetCrossReference,
+ _request: Request<Ticket>,
+ ) -> Result<Response<<Self as FlightService>::DoGetStream>, Status> {
+ Err(Status::unimplemented(
+ "do_get_cross_reference not implemented",
+ ))
+ }
+
+ // do_put
+ async fn do_put_statement_update(
+ &self,
+ _ticket: CommandStatementUpdate,
+ _request: Request<Streaming<FlightData>>,
+ ) -> Result<i64, Status> {
+ Err(Status::unimplemented(
+ "do_put_statement_update not implemented",
+ ))
+ }
+
+ async fn do_put_prepared_statement_query(
+ &self,
+ _query: CommandPreparedStatementQuery,
+ _request: Request<Streaming<FlightData>>,
+ ) -> Result<Response<<Self as FlightService>::DoPutStream>, Status> {
+ Err(Status::unimplemented(
+ "do_put_prepared_statement_query not implemented",
+ ))
+ }
+
+ async fn do_put_prepared_statement_update(
+ &self,
+ _query: CommandPreparedStatementUpdate,
+ _request: Request<Streaming<FlightData>>,
+ ) -> Result<i64, Status> {
+ Err(Status::unimplemented(
+ "do_put_prepared_statement_update not implemented",
+ ))
+ }
+
+ async fn do_action_create_prepared_statement(
+ &self,
+ _query: ActionCreatePreparedStatementRequest,
+ _request: Request<Action>,
+ ) -> Result<ActionCreatePreparedStatementResult, Status> {
+ Err(Status::unimplemented(
+ "do_action_create_prepared_statement not implemented",
+ ))
+ }
+
+ async fn do_action_close_prepared_statement(
+ &self,
+ _query: ActionClosePreparedStatementRequest,
+ _request: Request<Action>,
+ ) {
+ }
+
+ async fn register_sql_info(&self, _id: i32, _result: &SqlInfo) {}
+}
+
+/// Creates and manages a running TestServer with a background task
+struct TestFixture {
+ /// channel to send shutdown command
+ shutdown: Option<tokio::sync::oneshot::Sender<()>>,
+
+ /// Address the server is listening on
+ addr: SocketAddr,
+
+ // handle for the server task
+ handle: Option<JoinHandle<Result<(), tonic::transport::Error>>>,
+}
+
+impl TestFixture {
+ /// create a new test fixture from the server
+ pub async fn new(test_server: &FlightSqlServiceImpl) -> Self {
+ // let OS choose a a free port
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+
+ println!("Listening on {addr}");
+
+ // prepare the shutdown channel
+ let (tx, rx) = tokio::sync::oneshot::channel();
+
+ let server_timeout = Duration::from_secs(DEFAULT_TIMEOUT_SECONDS);
+
+ let shutdown_future = async move {
+ rx.await.ok();
+ };
+
+ let serve_future = tonic::transport::Server::builder()
+ .timeout(server_timeout)
+ .add_service(test_server.service())
+ .serve_with_incoming_shutdown(
+ tokio_stream::wrappers::TcpListenerStream::new(listener),
+ shutdown_future,
+ );
+
+ // Run the server in its own background task
+ let handle = tokio::task::spawn(serve_future);
+
+ Self {
+ shutdown: Some(tx),
+ addr,
+ handle: Some(handle),
+ }
+ }
+
+ /// Stops the test server and waits for the server to shutdown
+ pub async fn shutdown_and_wait(mut self) {
+ if let Some(shutdown) = self.shutdown.take() {
+ shutdown.send(()).expect("server quit early");
+ }
+ if let Some(handle) = self.handle.take() {
+ println!("Waiting on server to finish");
+ handle
+ .await
+ .expect("task join error (panic?)")
+ .expect("Server Error found at shutdown");
+ }
+ }
+}
+
+impl Drop for TestFixture {
+ fn drop(&mut self) {
+ if let Some(shutdown) = self.shutdown.take() {
+ shutdown.send(()).ok();
+ }
+ if self.handle.is_some() {
+ // tests should properly clean up TestFixture
+ println!("TestFixture::Drop called prior to `shutdown_and_wait`");
+ }
+ }
+}
+
+#[derive(Clone, PartialEq, ::prost::Message)]
+pub struct FetchResults {
+ #[prost(string, tag = "1")]
+ pub handle: ::prost::alloc::string::String,
+}
+
+impl ProstMessageExt for FetchResults {
+ fn type_url() -> &'static str {
+ "type.googleapis.com/arrow.flight.protocol.sql.FetchResults"
+ }
+
+ fn as_any(&self) -> Any {
+ Any {
+ type_url: FetchResults::type_url().to_string(),
+ value: ::prost::Message::encode_to_vec(self).into(),
+ }
+ }
+}
|
FlightSQL CLI client: simple test
Let's ave a simple integration test for the FlightSQL CLI client that connects to a server that returns 2 endpoints (both pointing to itself) and prints out the record batches. The setup can be used to test more upcoming features.
|
self-assign
|
2023-03-07T15:11:34Z
|
34.0
|
495682aa72ffe92bbd0d6d8d93e0c00b5483ff7d
|
apache/arrow-rs
| 3,811
|
apache__arrow-rs-3811
|
[
"3779"
] |
3df7c00a358cff34da8bacd819e791892755d3a9
|
diff --git a/arrow-flight/src/encode.rs b/arrow-flight/src/encode.rs
index 2e93acb0931c..557663922121 100644
--- a/arrow-flight/src/encode.rs
+++ b/arrow-flight/src/encode.rs
@@ -323,7 +323,7 @@ fn prepare_schema_for_flight(schema: &Schema) -> Schema {
})
.collect();
- Schema::new(fields)
+ Schema::new(fields).with_metadata(schema.metadata().clone())
}
/// Split [`RecordBatch`] so it hopefully fits into a gRPC response.
@@ -461,6 +461,7 @@ mod tests {
use arrow_array::{
DictionaryArray, Int16Array, Int32Array, Int64Array, StringArray, UInt64Array,
};
+ use std::collections::HashMap;
use super::*;
@@ -502,6 +503,17 @@ mod tests {
);
}
+ #[test]
+ fn test_schema_metadata_encoded() {
+ let schema =
+ Schema::new(vec![Field::new("data", DataType::Int32, false)]).with_metadata(
+ HashMap::from([("some_key".to_owned(), "some_value".to_owned())]),
+ );
+
+ let got = prepare_schema_for_flight(&schema);
+ assert!(got.metadata().contains_key("some_key"));
+ }
+
#[test]
fn test_encode_no_column_batch() {
let batch = RecordBatch::try_new_with_options(
|
diff --git a/arrow-flight/tests/encode_decode.rs b/arrow-flight/tests/encode_decode.rs
index 25e74cb3b6bc..8c73a516b2b0 100644
--- a/arrow-flight/tests/encode_decode.rs
+++ b/arrow-flight/tests/encode_decode.rs
@@ -17,7 +17,7 @@
//! Tests for round trip encoding / decoding
-use std::sync::Arc;
+use std::{collections::HashMap, sync::Arc};
use arrow::{compute::concat_batches, datatypes::Int32Type};
use arrow_array::{ArrayRef, DictionaryArray, Float64Array, RecordBatch, UInt8Array};
@@ -62,6 +62,18 @@ async fn test_primative_one() {
roundtrip(vec![make_primative_batch(5)]).await;
}
+#[tokio::test]
+async fn test_schema_metadata() {
+ let batch = make_primative_batch(5);
+ let metadata = HashMap::from([("some_key".to_owned(), "some_value".to_owned())]);
+
+ // create a batch that has schema level metadata
+ let schema = Arc::new(batch.schema().as_ref().clone().with_metadata(metadata));
+ let batch = RecordBatch::try_new(schema, batch.columns().to_vec()).unwrap();
+
+ roundtrip(vec![batch]).await;
+}
+
#[tokio::test]
async fn test_primative_many() {
roundtrip(vec![
|
Schema-level metadata is not encoded in Flight responses
**Describe the bug**
When preparing schema for encoding into a Flight response, the schema-level metadata from the source schema is dropped:
https://github.com/apache/arrow-rs/blob/e7eb304dac442a943c434f8ea248de909f82aa88/arrow-flight/src/encode.rs#L326
**To Reproduce**
```patch
Index: arrow-flight/src/encode.rs
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
diff --git a/arrow-flight/src/encode.rs b/arrow-flight/src/encode.rs
--- a/arrow-flight/src/encode.rs (revision e7eb304dac442a943c434f8ea248de909f82aa88)
+++ b/arrow-flight/src/encode.rs (date 1677611826249)
@@ -453,6 +453,7 @@
#[cfg(test)]
mod tests {
+ use std::collections::HashMap;
use arrow::{
array::{UInt32Array, UInt8Array},
compute::concat_batches,
@@ -502,6 +503,16 @@
);
}
+ #[test]
+ fn test_schema_metadata_encoded() {
+ let schema = Schema::new(vec![
+ Field::new("data", DataType::Int32, false),
+ ]).with_metadata(HashMap::from([("some_key".to_owned(), "some_value".to_owned())]));
+
+ let got = prepare_schema_for_flight(&schema);
+ assert!(got.metadata().contains_key("some_key"));
+ }
+
#[test]
fn test_encode_no_column_batch() {
let batch = RecordBatch::try_new_with_options(
```
**Expected behavior**
Schema-level metadata should be included permitting test to pass.
**Additional context**
<!--
Add any other context about the problem here.
-->
|
@alamb I can confirm that with this patch:
```patch
Index: arrow-flight/src/encode.rs
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
diff --git a/arrow-flight/src/encode.rs b/arrow-flight/src/encode.rs
--- a/arrow-flight/src/encode.rs (revision bbc1469077e13ba2e5a61f130917ad7eccfcb569)
+++ b/arrow-flight/src/encode.rs (date 1677712010122)
@@ -323,7 +323,7 @@
})
.collect();
- Schema::new(fields)
+ Schema::new(fields).with_metadata(schema.metadata().clone())
}
/// Split [`RecordBatch`] so it hopefully fits into a gRPC response.
@@ -453,6 +453,7 @@
#[cfg(test)]
mod tests {
+ use std::collections::HashMap;
use arrow::{
array::{UInt32Array, UInt8Array},
compute::concat_batches,
@@ -502,6 +503,16 @@
);
}
+ #[test]
+ fn test_schema_metadata_encoded() {
+ let schema = Schema::new(vec![
+ Field::new("data", DataType::Int32, false),
+ ]).with_metadata(HashMap::from([("some_key".to_owned(), "some_value".to_owned())]));
+
+ let got = prepare_schema_for_flight(&schema);
+ assert!(got.metadata().contains_key("some_key"));
+ }
+
#[test]
fn test_encode_no_column_batch() {
let batch = RecordBatch::try_new_with_options(
```
and minor fixes in IOx, the schema metadata propagates across RPC requests
|
2023-03-07T05:35:13Z
|
34.0
|
495682aa72ffe92bbd0d6d8d93e0c00b5483ff7d
|
apache/arrow-rs
| 3,805
|
apache__arrow-rs-3805
|
[
"2900"
] |
7eb588d7a9cee6516d53be6228130eda24810d37
|
diff --git a/arrow-cast/src/parse.rs b/arrow-cast/src/parse.rs
index a48dd2bac7d2..f498bf142bd7 100644
--- a/arrow-cast/src/parse.rs
+++ b/arrow-cast/src/parse.rs
@@ -16,7 +16,8 @@
// under the License.
use arrow_array::types::*;
-use arrow_array::ArrowPrimitiveType;
+use arrow_array::{ArrowNativeTypeOp, ArrowPrimitiveType};
+use arrow_buffer::ArrowNativeType;
use arrow_schema::ArrowError;
use chrono::prelude::*;
@@ -459,10 +460,114 @@ impl Parser for Date64Type {
}
}
+/// Parse the string format decimal value to i128/i256 format and checking the precision and scale.
+/// The result value can't be out of bounds.
+pub fn parse_decimal<T: DecimalType>(
+ s: &str,
+ precision: u8,
+ scale: i8,
+) -> Result<T::Native, ArrowError> {
+ if !is_valid_decimal(s) {
+ return Err(ArrowError::ParseError(format!(
+ "can't parse the string value {s} to decimal"
+ )));
+ }
+ let mut offset = s.len();
+ let len = s.len();
+ let mut base = T::Native::usize_as(1);
+ let scale_usize = usize::from(scale as u8);
+
+ // handle the value after the '.' and meet the scale
+ let delimiter_position = s.find('.');
+ match delimiter_position {
+ None => {
+ // there is no '.'
+ base = T::Native::usize_as(10).pow_checked(scale as u32)?;
+ }
+ Some(mid) => {
+ // there is the '.'
+ if len - mid >= scale_usize + 1 {
+ // If the string value is "123.12345" and the scale is 2, we should just remain '.12' and drop the '345' value.
+ offset -= len - mid - 1 - scale_usize;
+ } else {
+ // If the string value is "123.12" and the scale is 4, we should append '00' to the tail.
+ base = T::Native::usize_as(10)
+ .pow_checked((scale_usize + 1 + mid - len) as u32)?;
+ }
+ }
+ };
+
+ // each byte is digit、'-' or '.'
+ let bytes = s.as_bytes();
+ let mut negative = false;
+ let mut result = T::Native::usize_as(0);
+
+ bytes[0..offset]
+ .iter()
+ .rev()
+ .try_for_each::<_, Result<(), ArrowError>>(|&byte| {
+ match byte {
+ b'-' => {
+ negative = true;
+ }
+ b'0'..=b'9' => {
+ let add =
+ T::Native::usize_as((byte - b'0') as usize).mul_checked(base)?;
+ result = result.add_checked(add)?;
+ base = base.mul_checked(T::Native::usize_as(10))?;
+ }
+ // because we have checked the string value
+ _ => (),
+ }
+ Ok(())
+ })?;
+
+ if negative {
+ result = result.neg_checked()?;
+ }
+
+ match T::validate_decimal_precision(result, precision) {
+ Ok(_) => Ok(result),
+ Err(e) => Err(ArrowError::ParseError(format!(
+ "parse decimal overflow: {e}"
+ ))),
+ }
+}
+
+fn is_valid_decimal(s: &str) -> bool {
+ let mut seen_dot = false;
+ let mut seen_digit = false;
+ let mut seen_sign = false;
+
+ for c in s.as_bytes() {
+ match c {
+ b'-' | b'+' => {
+ if seen_digit || seen_dot || seen_sign {
+ return false;
+ }
+ seen_sign = true;
+ }
+ b'.' => {
+ if seen_dot {
+ return false;
+ }
+ seen_dot = true;
+ }
+ b'0'..=b'9' => {
+ seen_digit = true;
+ }
+ _ => return false,
+ }
+ }
+
+ seen_digit
+}
+
#[cfg(test)]
mod tests {
use super::*;
use arrow_array::timezone::Tz;
+ use arrow_buffer::i256;
#[test]
fn string_to_timestamp_timezone() {
@@ -920,4 +1025,70 @@ mod tests {
.map_err(|e| assert!(e.to_string().ends_with(ERR_NANOSECONDS_NOT_SUPPORTED)))
.unwrap_err();
}
+
+ #[test]
+ fn test_parse_decimal_with_parameter() {
+ let tests = [
+ ("123.123", 123123i128),
+ ("123.1234", 123123i128),
+ ("123.1", 123100i128),
+ ("123", 123000i128),
+ ("-123.123", -123123i128),
+ ("-123.1234", -123123i128),
+ ("-123.1", -123100i128),
+ ("-123", -123000i128),
+ ("0.0000123", 0i128),
+ ("12.", 12000i128),
+ ("-12.", -12000i128),
+ ("00.1", 100i128),
+ ("-00.1", -100i128),
+ ("12345678912345678.1234", 12345678912345678123i128),
+ ("-12345678912345678.1234", -12345678912345678123i128),
+ ("99999999999999999.999", 99999999999999999999i128),
+ ("-99999999999999999.999", -99999999999999999999i128),
+ (".123", 123i128),
+ ("-.123", -123i128),
+ ("123.", 123000i128),
+ ("-123.", -123000i128),
+ ];
+ for (s, i) in tests {
+ let result_128 = parse_decimal::<Decimal128Type>(s, 20, 3);
+ assert_eq!(i, result_128.unwrap());
+ let result_256 = parse_decimal::<Decimal256Type>(s, 20, 3);
+ assert_eq!(i256::from_i128(i), result_256.unwrap());
+ }
+ let can_not_parse_tests = ["123,123", ".", "123.123.123"];
+ for s in can_not_parse_tests {
+ let result_128 = parse_decimal::<Decimal128Type>(s, 20, 3);
+ assert_eq!(
+ format!("Parser error: can't parse the string value {s} to decimal"),
+ result_128.unwrap_err().to_string()
+ );
+ let result_256 = parse_decimal::<Decimal256Type>(s, 20, 3);
+ assert_eq!(
+ format!("Parser error: can't parse the string value {s} to decimal"),
+ result_256.unwrap_err().to_string()
+ );
+ }
+ let overflow_parse_tests = ["12345678", "12345678.9", "99999999.99"];
+ for s in overflow_parse_tests {
+ let result_128 = parse_decimal::<Decimal128Type>(s, 10, 3);
+ let expected_128 = "Parser error: parse decimal overflow";
+ let actual_128 = result_128.unwrap_err().to_string();
+
+ assert!(
+ actual_128.contains(expected_128),
+ "actual: '{actual_128}', expected: '{expected_128}'"
+ );
+
+ let result_256 = parse_decimal::<Decimal256Type>(s, 10, 3);
+ let expected_256 = "Parser error: parse decimal overflow";
+ let actual_256 = result_256.unwrap_err().to_string();
+
+ assert!(
+ actual_256.contains(expected_256),
+ "actual: '{actual_256}', expected: '{expected_256}'"
+ );
+ }
+ }
}
diff --git a/arrow-csv/src/reader/mod.rs b/arrow-csv/src/reader/mod.rs
index 84d55c4ae24b..8b1cd2f79930 100644
--- a/arrow-csv/src/reader/mod.rs
+++ b/arrow-csv/src/reader/mod.rs
@@ -44,10 +44,8 @@ mod records;
use arrow_array::builder::PrimitiveBuilder;
use arrow_array::types::*;
-use arrow_array::ArrowNativeTypeOp;
use arrow_array::*;
-use arrow_buffer::ArrowNativeType;
-use arrow_cast::parse::Parser;
+use arrow_cast::parse::{parse_decimal, Parser};
use arrow_schema::*;
use lazy_static::lazy_static;
use regex::{Regex, RegexSet};
@@ -72,8 +70,6 @@ lazy_static! {
r"^\d{4}-\d\d-\d\d[T ]\d\d:\d\d:\d\d.\d{1,6}$", //Timestamp(Microsecond)
r"^\d{4}-\d\d-\d\d[T ]\d\d:\d\d:\d\d.\d{1,9}$", //Timestamp(Nanosecond)
]).unwrap();
- static ref PARSE_DECIMAL_RE: Regex =
- Regex::new(r"^-?(\d+\.?\d*|\d*\.?\d+)$").unwrap();
}
#[derive(Default, Copy, Clone)]
@@ -823,7 +819,7 @@ fn build_decimal_array<T: DecimalType>(
decimal_builder.append_null();
} else {
let decimal_value: Result<T::Native, _> =
- parse_decimal_with_parameter::<T>(s, precision, scale);
+ parse_decimal::<T>(s, precision, scale);
match decimal_value {
Ok(v) => {
decimal_builder.append_value(v);
@@ -841,127 +837,6 @@ fn build_decimal_array<T: DecimalType>(
))
}
-// Parse the string format decimal value to i128/i256 format and checking the precision and scale.
-// The result value can't be out of bounds.
-fn parse_decimal_with_parameter<T: DecimalType>(
- s: &str,
- precision: u8,
- scale: i8,
-) -> Result<T::Native, ArrowError> {
- if PARSE_DECIMAL_RE.is_match(s) {
- let mut offset = s.len();
- let len = s.len();
- let mut base = T::Native::usize_as(1);
- let scale_usize = usize::from(scale as u8);
-
- // handle the value after the '.' and meet the scale
- let delimiter_position = s.find('.');
- match delimiter_position {
- None => {
- // there is no '.'
- base = T::Native::usize_as(10).pow_checked(scale as u32)?;
- }
- Some(mid) => {
- // there is the '.'
- if len - mid >= scale_usize + 1 {
- // If the string value is "123.12345" and the scale is 2, we should just remain '.12' and drop the '345' value.
- offset -= len - mid - 1 - scale_usize;
- } else {
- // If the string value is "123.12" and the scale is 4, we should append '00' to the tail.
- base = T::Native::usize_as(10)
- .pow_checked((scale_usize + 1 + mid - len) as u32)?;
- }
- }
- };
-
- // each byte is digit、'-' or '.'
- let bytes = s.as_bytes();
- let mut negative = false;
- let mut result = T::Native::usize_as(0);
-
- bytes[0..offset]
- .iter()
- .rev()
- .try_for_each::<_, Result<(), ArrowError>>(|&byte| {
- match byte {
- b'-' => {
- negative = true;
- }
- b'0'..=b'9' => {
- let add = T::Native::usize_as((byte - b'0') as usize)
- .mul_checked(base)?;
- result = result.add_checked(add)?;
- base = base.mul_checked(T::Native::usize_as(10))?;
- }
- // because of the PARSE_DECIMAL_RE, bytes just contains digit、'-' and '.'.
- _ => (),
- }
- Ok(())
- })?;
-
- if negative {
- result = result.neg_checked()?;
- }
-
- match T::validate_decimal_precision(result, precision) {
- Ok(_) => Ok(result),
- Err(e) => Err(ArrowError::ParseError(format!(
- "parse decimal overflow: {e}"
- ))),
- }
- } else {
- Err(ArrowError::ParseError(format!(
- "can't parse the string value {s} to decimal"
- )))
- }
-}
-
-// Parse the string format decimal value to i128 format without checking the precision and scale.
-// Like "125.12" to 12512_i128.
-#[cfg(test)]
-fn parse_decimal(s: &str) -> Result<i128, ArrowError> {
- use std::ops::Neg;
-
- if PARSE_DECIMAL_RE.is_match(s) {
- let mut offset = s.len();
- // each byte is digit、'-' or '.'
- let bytes = s.as_bytes();
- let mut negative = false;
- let mut result: i128 = 0;
- let mut base = 1;
- while offset > 0 {
- match bytes[offset - 1] {
- b'-' => {
- negative = true;
- }
- b'.' => {
- // do nothing
- }
- b'0'..=b'9' => {
- result += i128::from(bytes[offset - 1] - b'0') * base;
- base *= 10;
- }
- _ => {
- return Err(ArrowError::ParseError(format!(
- "can't match byte {}",
- bytes[offset - 1]
- )));
- }
- }
- offset -= 1;
- }
- if negative {
- Ok(result.neg())
- } else {
- Ok(result)
- }
- } else {
- Err(ArrowError::ParseError(format!(
- "can't parse the string value {s} to decimal"
- )))
- }
-}
-
// parses a specific column (col_idx) into an Arrow Array.
fn build_primitive_array<T: ArrowPrimitiveType + Parser>(
line_number: usize,
@@ -1268,7 +1143,6 @@ impl ReaderBuilder {
mod tests {
use super::*;
- use arrow_buffer::i256;
use std::io::{Cursor, Write};
use tempfile::NamedTempFile;
@@ -1812,88 +1686,6 @@ mod tests {
);
}
- #[test]
- fn test_parse_decimal() {
- let tests = [
- ("123.00", 12300i128),
- ("123.123", 123123i128),
- ("0.0123", 123i128),
- ("0.12300", 12300i128),
- ("-5.123", -5123i128),
- ("-45.432432", -45432432i128),
- ];
- for (s, i) in tests {
- let result = parse_decimal(s);
- assert_eq!(i, result.unwrap());
- }
- }
-
- #[test]
- fn test_parse_decimal_with_parameter() {
- let tests = [
- ("123.123", 123123i128),
- ("123.1234", 123123i128),
- ("123.1", 123100i128),
- ("123", 123000i128),
- ("-123.123", -123123i128),
- ("-123.1234", -123123i128),
- ("-123.1", -123100i128),
- ("-123", -123000i128),
- ("0.0000123", 0i128),
- ("12.", 12000i128),
- ("-12.", -12000i128),
- ("00.1", 100i128),
- ("-00.1", -100i128),
- ("12345678912345678.1234", 12345678912345678123i128),
- ("-12345678912345678.1234", -12345678912345678123i128),
- ("99999999999999999.999", 99999999999999999999i128),
- ("-99999999999999999.999", -99999999999999999999i128),
- (".123", 123i128),
- ("-.123", -123i128),
- ("123.", 123000i128),
- ("-123.", -123000i128),
- ];
- for (s, i) in tests {
- let result_128 = parse_decimal_with_parameter::<Decimal128Type>(s, 20, 3);
- assert_eq!(i, result_128.unwrap());
- let result_256 = parse_decimal_with_parameter::<Decimal256Type>(s, 20, 3);
- assert_eq!(i256::from_i128(i), result_256.unwrap());
- }
- let can_not_parse_tests = ["123,123", ".", "123.123.123"];
- for s in can_not_parse_tests {
- let result_128 = parse_decimal_with_parameter::<Decimal128Type>(s, 20, 3);
- assert_eq!(
- format!("Parser error: can't parse the string value {s} to decimal"),
- result_128.unwrap_err().to_string()
- );
- let result_256 = parse_decimal_with_parameter::<Decimal256Type>(s, 20, 3);
- assert_eq!(
- format!("Parser error: can't parse the string value {s} to decimal"),
- result_256.unwrap_err().to_string()
- );
- }
- let overflow_parse_tests = ["12345678", "12345678.9", "99999999.99"];
- for s in overflow_parse_tests {
- let result_128 = parse_decimal_with_parameter::<Decimal128Type>(s, 10, 3);
- let expected_128 = "Parser error: parse decimal overflow";
- let actual_128 = result_128.unwrap_err().to_string();
-
- assert!(
- actual_128.contains(expected_128),
- "actual: '{actual_128}', expected: '{expected_128}'"
- );
-
- let result_256 = parse_decimal_with_parameter::<Decimal256Type>(s, 10, 3);
- let expected_256 = "Parser error: parse decimal overflow";
- let actual_256 = result_256.unwrap_err().to_string();
-
- assert!(
- actual_256.contains(expected_256),
- "actual: '{actual_256}', expected: '{expected_256}'"
- );
- }
- }
-
#[test]
fn test_parse_timestamp_microseconds() {
assert_eq!(
diff --git a/arrow-json/src/reader.rs b/arrow-json/src/reader.rs
index 3ac39c110fc9..f4610eb345ea 100644
--- a/arrow-json/src/reader.rs
+++ b/arrow-json/src/reader.rs
@@ -58,8 +58,8 @@ use serde_json::{map::Map as JsonMap, Value};
use arrow_array::builder::*;
use arrow_array::types::*;
use arrow_array::*;
-use arrow_buffer::{bit_util, Buffer, MutableBuffer};
-use arrow_cast::parse::Parser;
+use arrow_buffer::{bit_util, i256, Buffer, MutableBuffer};
+use arrow_cast::parse::{parse_decimal, Parser};
use arrow_data::{ArrayData, ArrayDataBuilder};
use arrow_schema::*;
@@ -1019,6 +1019,76 @@ impl Decoder {
))
}
+ fn build_decimal128_array(
+ &self,
+ rows: &[Value],
+ col_name: &str,
+ precision: u8,
+ scale: i8,
+ ) -> Result<ArrayRef, ArrowError> {
+ Ok(Arc::new(
+ rows.iter()
+ .map(|row| {
+ row.get(col_name).and_then(|value| {
+ if value.is_i64() {
+ let mul = 10i128.pow(scale as _);
+ value
+ .as_i64()
+ .and_then(num::cast::cast)
+ .map(|v: i128| v * mul)
+ } else if value.is_u64() {
+ let mul = 10i128.pow(scale as _);
+ value
+ .as_u64()
+ .and_then(num::cast::cast)
+ .map(|v: i128| v * mul)
+ } else if value.is_string() {
+ value.as_str().and_then(|s| {
+ parse_decimal::<Decimal128Type>(s, precision, scale).ok()
+ })
+ } else {
+ let mul = 10_f64.powi(scale as i32);
+ value.as_f64().map(|f| (f * mul).round() as i128)
+ }
+ })
+ })
+ .collect::<Decimal128Array>()
+ .with_precision_and_scale(precision, scale)?,
+ ))
+ }
+
+ fn build_decimal256_array(
+ &self,
+ rows: &[Value],
+ col_name: &str,
+ precision: u8,
+ scale: i8,
+ ) -> Result<ArrayRef, ArrowError> {
+ let mul = 10_f64.powi(scale as i32);
+ Ok(Arc::new(
+ rows.iter()
+ .map(|row| {
+ row.get(col_name).and_then(|value| {
+ if value.is_i64() {
+ let mul = i256::from_i128(10).pow_wrapping(scale as _);
+ value.as_i64().map(|i| i256::from_i128(i as _) * mul)
+ } else if value.is_u64() {
+ let mul = i256::from_i128(10).pow_wrapping(scale as _);
+ value.as_u64().map(|i| i256::from_i128(i as _) * mul)
+ } else if value.is_string() {
+ value.as_str().and_then(|s| {
+ parse_decimal::<Decimal256Type>(s, precision, scale).ok()
+ })
+ } else {
+ value.as_f64().and_then(|f| i256::from_f64(f * mul.round()))
+ }
+ })
+ })
+ .collect::<Decimal256Array>()
+ .with_precision_and_scale(precision, scale)?,
+ ))
+ }
+
/// Build a nested GenericListArray from a list of unnested `Value`s
fn build_nested_list_array<OffsetSize: OffsetSizeTrait>(
&self,
@@ -1379,6 +1449,10 @@ impl Decoder {
field.data_type(),
map_field,
),
+ DataType::Decimal128(precision, scale) => self
+ .build_decimal128_array(rows, field.name(), *precision, *scale),
+ DataType::Decimal256(precision, scale) => self
+ .build_decimal256_array(rows, field.name(), *precision, *scale),
_ => Err(ArrowError::JsonError(format!(
"{:?} type is not supported",
field.data_type()
@@ -1776,7 +1850,7 @@ mod tests {
as_boolean_array, as_dictionary_array, as_primitive_array, as_string_array,
as_struct_array,
};
- use arrow_buffer::ToByteSlice;
+ use arrow_buffer::{ArrowNativeType, ToByteSlice};
use arrow_schema::DataType::{Dictionary, List};
use flate2::read::GzDecoder;
use std::fs::File;
@@ -1790,7 +1864,7 @@ mod tests {
.unwrap();
let batch = reader.next().unwrap().unwrap();
- assert_eq!(5, batch.num_columns());
+ assert_eq!(6, batch.num_columns());
assert_eq!(12, batch.num_rows());
let schema = reader.schema();
@@ -3328,7 +3402,7 @@ mod tests {
let mut sum_a = 0;
for batch in reader {
let batch = batch.unwrap();
- assert_eq!(5, batch.num_columns());
+ assert_eq!(6, batch.num_columns());
sum_num_rows += batch.num_rows();
num_batches += 1;
let batch_schema = batch.schema();
@@ -3352,4 +3426,70 @@ mod tests {
let cloned = options.clone();
assert_eq!(options, cloned);
}
+
+ pub fn decimal_json_tests<T: DecimalType>(data_type: DataType) {
+ let schema = Schema::new(vec![
+ Field::new("a", data_type.clone(), true),
+ Field::new("b", data_type.clone(), true),
+ Field::new("f", data_type.clone(), true),
+ ]);
+
+ let builder = ReaderBuilder::new()
+ .with_schema(Arc::new(schema))
+ .with_batch_size(64);
+ let mut reader: Reader<File> = builder
+ .build::<File>(File::open("test/data/basic.json").unwrap())
+ .unwrap();
+ let batch = reader.next().unwrap().unwrap();
+
+ assert_eq!(3, batch.num_columns());
+ assert_eq!(12, batch.num_rows());
+
+ let schema = reader.schema();
+ let batch_schema = batch.schema();
+ assert_eq!(schema, batch_schema);
+
+ let a = schema.column_with_name("a").unwrap();
+ let b = schema.column_with_name("b").unwrap();
+ let f = schema.column_with_name("f").unwrap();
+ assert_eq!(&data_type, a.1.data_type());
+ assert_eq!(&data_type, b.1.data_type());
+ assert_eq!(&data_type, f.1.data_type());
+
+ let aa = batch
+ .column(a.0)
+ .as_any()
+ .downcast_ref::<PrimitiveArray<T>>()
+ .unwrap();
+ assert_eq!(T::Native::usize_as(100), aa.value(0));
+ assert_eq!(T::Native::usize_as(100), aa.value(3));
+ assert_eq!(T::Native::usize_as(500), aa.value(7));
+
+ let bb = batch
+ .column(b.0)
+ .as_any()
+ .downcast_ref::<PrimitiveArray<T>>()
+ .unwrap();
+ assert_eq!(T::Native::usize_as(200), bb.value(0));
+ assert_eq!(T::Native::usize_as(350).neg_wrapping(), bb.value(1));
+ assert_eq!(T::Native::usize_as(60), bb.value(8));
+
+ let ff = batch
+ .column(f.0)
+ .as_any()
+ .downcast_ref::<PrimitiveArray<T>>()
+ .unwrap();
+ assert_eq!(T::Native::usize_as(102), ff.value(0));
+ assert_eq!(T::Native::usize_as(30).neg_wrapping(), ff.value(1));
+ assert_eq!(T::Native::usize_as(137722), ff.value(2));
+
+ assert_eq!(T::Native::usize_as(133700), ff.value(3));
+ assert_eq!(T::Native::usize_as(9999999999), ff.value(7));
+ }
+
+ #[test]
+ fn test_decimal_from_json() {
+ decimal_json_tests::<Decimal128Type>(DataType::Decimal128(10, 2));
+ decimal_json_tests::<Decimal256Type>(DataType::Decimal256(10, 2));
+ }
}
|
diff --git a/arrow-json/test/data/basic.json b/arrow-json/test/data/basic.json
index 556c39c46be9..8de246e1ac28 100644
--- a/arrow-json/test/data/basic.json
+++ b/arrow-json/test/data/basic.json
@@ -1,12 +1,12 @@
-{"a":1, "b":2.0, "c":false, "d":"4", "e":"1970-1-2"}
-{"a":-10, "b":-3.5, "c":true, "d":"4", "e": "1969-12-31"}
-{"a":2, "b":0.6, "c":false, "d":"text", "e": "1970-01-02 11:11:11"}
-{"a":1, "b":2.0, "c":false, "d":"4"}
-{"a":7, "b":-3.5, "c":true, "d":"4"}
-{"a":1, "b":0.6, "c":false, "d":"text"}
-{"a":1, "b":2.0, "c":false, "d":"4"}
-{"a":5, "b":-3.5, "c":true, "d":"4"}
-{"a":1, "b":0.6, "c":false, "d":"text"}
-{"a":1, "b":2.0, "c":false, "d":"4"}
-{"a":1, "b":-3.5, "c":true, "d":"4"}
-{"a":100000000000000, "b":0.6, "c":false, "d":"text"}
+{"a":1, "b":2.0, "c":false, "d":"4", "e":"1970-1-2", "f": "1.02"}
+{"a":-10, "b":-3.5, "c":true, "d":"4", "e": "1969-12-31", "f": "-0.3"}
+{"a":2, "b":0.6, "c":false, "d":"text", "e": "1970-01-02 11:11:11", "f": "1377.223"}
+{"a":1, "b":2.0, "c":false, "d":"4", "f": "1337.009"}
+{"a":7, "b":-3.5, "c":true, "d":"4", "f": "1"}
+{"a":1, "b":0.6, "c":false, "d":"text", "f": "1338"}
+{"a":1, "b":2.0, "c":false, "d":"4", "f": "12345829100000"}
+{"a":5, "b":-3.5, "c":true, "d":"4", "f": "99999999.99"}
+{"a":1, "b":0.6, "c":false, "d":"text", "f": "1"}
+{"a":1, "b":2.0, "c":false, "d":"4", "f": "1"}
+{"a":1, "b":-3.5, "c":true, "d":"4", "f": "1"}
+{"a":100000000000000, "b":0.6, "c":false, "d":"text", "f": "1"}
|
Support reading DecimalArray from JSON data
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
The JSON reader doesn't support producing DecimalArray types. I have a `TODO: this is incomplete` that I left on the reader 2 years ago, which was from when DecimalArray support was incomplete/not implemented.
**Describe the solution you'd like**
For the JSON reader to be able to produce decimal arrays if specified in the schema.
**Describe alternatives you've considered**
Coercing decimals to strings or f64, and then casting them after reading. This is inefficient and requires one to programmatically check each field of a schema for JSON fields in order to cast them. Worse as the decimal could be nested inside a list or struct.
**Additional context**
Systems have some freedom when producing JSON data. For example, Debezium has 3 modes for handling decimals [0], where decimals can either be binary, strings or floats. I also vaguely remember some system/process writing the data as bytes.
It would be useful for us to be able to handle at least the modes supported by Debezium.
[0] https://debezium.io/documentation/reference/stable/connectors/sqlserver.html#sqlserver-property-decimal-handling-mode
|
#2580 is possibly related / could share some logic
|
2023-03-05T21:48:49Z
|
34.0
|
495682aa72ffe92bbd0d6d8d93e0c00b5483ff7d
|
apache/arrow-rs
| 3,786
|
apache__arrow-rs-3786
|
[
"3785"
] |
7852e763fea66b33a2766b6d6421cafcf6a58c29
|
diff --git a/parquet/src/bin/parquet-read.rs b/parquet/src/bin/parquet-read.rs
index c1e08387a550..a8a835ab870d 100644
--- a/parquet/src/bin/parquet-read.rs
+++ b/parquet/src/bin/parquet-read.rs
@@ -45,7 +45,7 @@ use std::{fs::File, path::Path};
#[derive(Debug, Parser)]
#[clap(author, version, about("Binary file to read data from a Parquet file"), long_about = None)]
struct Args {
- #[clap(short, long, help("Path to a parquet file, or - for stdin"))]
+ #[clap(help("Path to a parquet file, or - for stdin"))]
file_name: String,
#[clap(
short,
diff --git a/parquet/src/bin/parquet-rowcount.rs b/parquet/src/bin/parquet-rowcount.rs
index 45eb1c9a476f..55c76c5f73e4 100644
--- a/parquet/src/bin/parquet-rowcount.rs
+++ b/parquet/src/bin/parquet-rowcount.rs
@@ -44,8 +44,6 @@ use std::{fs::File, path::Path};
#[clap(author, version, about("Binary file to return the number of rows found from Parquet file(s)"), long_about = None)]
struct Args {
#[clap(
- short,
- long,
number_of_values(1),
help("List of Parquet files to read from separated by space")
)]
diff --git a/parquet/src/bin/parquet-schema.rs b/parquet/src/bin/parquet-schema.rs
index ae79fe4296c3..bfcb77d67b2e 100644
--- a/parquet/src/bin/parquet-schema.rs
+++ b/parquet/src/bin/parquet-schema.rs
@@ -46,7 +46,7 @@ use std::{fs::File, path::Path};
#[derive(Debug, Parser)]
#[clap(author, version, about("Binary file to print the schema and metadata of a Parquet file"), long_about = None)]
struct Args {
- #[clap(short, long)]
+ #[clap(help("Path to the parquet file"))]
file_path: String,
#[clap(short, long, help("Enable printing full file metadata"))]
verbose: bool,
diff --git a/parquet/src/bin/parquet-show-bloom-filter.rs b/parquet/src/bin/parquet-show-bloom-filter.rs
index 77e29c6fb282..80db51978433 100644
--- a/parquet/src/bin/parquet-show-bloom-filter.rs
+++ b/parquet/src/bin/parquet-show-bloom-filter.rs
@@ -25,7 +25,7 @@
//! ```
//! After this `parquet-show-bloom-filter` should be available:
//! ```
-//! parquet-show-bloom-filter --file-name XYZ.parquet --column id --values a
+//! parquet-show-bloom-filter XYZ.parquet id a
//! ```
//!
//! The binary can also be built from the source code and run as follows:
@@ -44,17 +44,11 @@ use std::{fs::File, path::Path};
#[derive(Debug, Parser)]
#[clap(author, version, about("Binary file to read bloom filter data from a Parquet file"), long_about = None)]
struct Args {
- #[clap(short, long, help("Path to the parquet file"))]
+ #[clap(help("Path to the parquet file"))]
file_name: String,
- #[clap(
- short,
- long,
- help("Check the bloom filter indexes for the given column")
- )]
+ #[clap(help("Check the bloom filter indexes for the given column"))]
column: String,
#[clap(
- short,
- long,
help("Check if the given values match bloom filter, the values will be evaluated as strings"),
required = true
)]
|
diff --git a/parquet/pytest/test_parquet_integration.py b/parquet/pytest/test_parquet_integration.py
index 268caa8fab06..e0846d4e779f 100755
--- a/parquet/pytest/test_parquet_integration.py
+++ b/parquet/pytest/test_parquet_integration.py
@@ -68,15 +68,13 @@ def get_show_filter_cli_output(output_dir, data, col_name="id"):
(parquet_file,) = sorted(pathlib.Path(output_dir).glob("*.parquet"))
args = [
"parquet-show-bloom-filter",
- "--file-name",
parquet_file,
- "--column",
col_name,
]
for v in data:
- args.extend(["--values", v[0]])
+ args.extend([v[0]])
for v in data:
- args.extend(["--values", v[1]])
+ args.extend([v[1]])
return subprocess.check_output(args)
|
Make Parquet CLI args consistent
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
The current input argument format is inconsistent across CLI tools. E.g., parquet-layout does not need passing "-f" or "--file" for the input file name. This should be consistent across the binary tools.
**Describe the solution you'd like**
One solution is to flag all clap arguments with short and long.
**Describe alternatives you've considered**
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
|
2023-03-02T07:44:29Z
|
34.0
|
495682aa72ffe92bbd0d6d8d93e0c00b5483ff7d
|
|
apache/arrow-rs
| 3,778
|
apache__arrow-rs-3778
|
[
"3775"
] |
e7eb304dac442a943c434f8ea248de909f82aa88
|
diff --git a/arrow-arith/src/aggregate.rs b/arrow-arith/src/aggregate.rs
index b578dbd4a94c..7777bb0ede43 100644
--- a/arrow-arith/src/aggregate.rs
+++ b/arrow-arith/src/aggregate.rs
@@ -117,8 +117,8 @@ where
.map(|i| unsafe { array.value_unchecked(i) })
.reduce(|acc, item| if cmp(&acc, &item) { item } else { acc })
} else {
- let null_buffer = array.data_ref().null_buffer().unwrap();
- let iter = BitIndexIterator::new(null_buffer, array.offset(), array.len());
+ let nulls = array.data().nulls().unwrap();
+ let iter = BitIndexIterator::new(nulls.validity(), nulls.offset(), nulls.len());
unsafe {
let idx = iter.reduce(|acc_idx, idx| {
let acc = array.value_unchecked(acc_idx);
@@ -288,7 +288,7 @@ where
let data: &[T::Native] = array.values();
- match array.data().null_buffer() {
+ match array.data().nulls() {
None => {
let sum = data.iter().fold(T::default_value(), |accumulator, value| {
accumulator.add_wrapping(*value)
@@ -296,12 +296,12 @@ where
Some(sum)
}
- Some(buffer) => {
+ Some(nulls) => {
let mut sum = T::default_value();
let data_chunks = data.chunks_exact(64);
let remainder = data_chunks.remainder();
- let bit_chunks = buffer.bit_chunks(array.offset(), array.len());
+ let bit_chunks = nulls.inner().bit_chunks();
data_chunks
.zip(bit_chunks.iter())
.for_each(|(chunk, mask)| {
@@ -347,7 +347,7 @@ where
let data: &[T::Native] = array.values();
- match array.data().null_buffer() {
+ match array.data().nulls() {
None => {
let sum = data
.iter()
@@ -357,14 +357,14 @@ where
Ok(Some(sum))
}
- Some(buffer) => {
+ Some(nulls) => {
let mut sum = T::default_value();
try_for_each_valid_idx(
- array.len(),
- array.offset(),
- null_count,
- Some(buffer.as_slice()),
+ nulls.len(),
+ nulls.offset(),
+ nulls.null_count(),
+ Some(nulls.validity()),
|idx| {
unsafe { sum = sum.add_checked(array.value_unchecked(idx))? };
Ok::<_, ArrowError>(())
@@ -665,7 +665,7 @@ mod simd {
let mut chunk_acc = A::init_accumulator_chunk();
let mut rem_acc = A::init_accumulator_scalar();
- match array.data().null_buffer() {
+ match array.data().nulls() {
None => {
let data_chunks = data.chunks_exact(64);
let remainder = data_chunks.remainder();
@@ -681,12 +681,12 @@ mod simd {
A::accumulate_scalar(&mut rem_acc, *value);
});
}
- Some(buffer) => {
+ Some(nulls) => {
// process data in chunks of 64 elements since we also get 64 bits of validity information at a time
let data_chunks = data.chunks_exact(64);
let remainder = data_chunks.remainder();
- let bit_chunks = buffer.bit_chunks(array.offset(), array.len());
+ let bit_chunks = nulls.inner().bit_chunks();
let remainder_bits = bit_chunks.remainder_bits();
data_chunks.zip(bit_chunks).for_each(|(chunk, mut mask)| {
diff --git a/arrow-arith/src/arithmetic.rs b/arrow-arith/src/arithmetic.rs
index 40e7d6780377..0fb559f0651f 100644
--- a/arrow-arith/src/arithmetic.rs
+++ b/arrow-arith/src/arithmetic.rs
@@ -1572,6 +1572,7 @@ mod tests {
use arrow_array::builder::{
BooleanBufferBuilder, BufferBuilder, PrimitiveDictionaryBuilder,
};
+ use arrow_buffer::buffer::{BooleanBuffer, NullBuffer};
use arrow_buffer::i256;
use arrow_data::ArrayDataBuilder;
use chrono::NaiveDate;
@@ -3057,15 +3058,19 @@ mod tests {
// `count_set_bits_offset` takes len in bits as parameter.
assert_eq!(null_buffer.count_set_bits_offset(0, 13), 0);
+ let nulls = BooleanBuffer::new(null_buffer, 0, 13);
+ assert_eq!(nulls.count_set_bits(), 0);
+ let nulls = NullBuffer::new(nulls);
+ assert_eq!(nulls.null_count(), 13);
+
let mut data_buffer_builder = BufferBuilder::<i32>::new(13);
data_buffer_builder.append_slice(&[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
let data_buffer = data_buffer_builder.finish();
let arg1: Int32Array = ArrayDataBuilder::new(DataType::Int32)
.len(13)
- .null_count(13)
+ .nulls(Some(nulls))
.buffers(vec![data_buffer])
- .null_bit_buffer(Some(null_buffer))
.build()
.unwrap()
.into();
@@ -3078,9 +3083,7 @@ mod tests {
let arg2: Int32Array = ArrayDataBuilder::new(DataType::Int32)
.len(13)
- .null_count(0)
.buffers(vec![data_buffer])
- .null_bit_buffer(None)
.build()
.unwrap()
.into();
diff --git a/arrow-arith/src/arity.rs b/arrow-arith/src/arity.rs
index 3e7a81862927..ea078765df1a 100644
--- a/arrow-arith/src/arity.rs
+++ b/arrow-arith/src/arity.rs
@@ -20,6 +20,7 @@
use arrow_array::builder::BufferBuilder;
use arrow_array::iterator::ArrayIter;
use arrow_array::*;
+use arrow_buffer::buffer::{BooleanBuffer, NullBuffer};
use arrow_buffer::{Buffer, MutableBuffer};
use arrow_data::bit_iterator::try_for_each_valid_idx;
use arrow_data::bit_mask::combine_option_bitmap;
@@ -276,10 +277,7 @@ where
let len = a.len();
let null_buffer = combine_option_bitmap(&[a.data(), b.data()], len);
- let null_count = null_buffer
- .as_ref()
- .map(|x| len - x.count_set_bits_offset(0, len))
- .unwrap_or_default();
+ let nulls = null_buffer.map(|b| NullBuffer::new(BooleanBuffer::new(b, 0, len)));
let mut builder = a.into_builder()?;
@@ -289,13 +287,7 @@ where
.zip(b.values())
.for_each(|(l, r)| *l = op(*l, *r));
- let array_builder = builder
- .finish()
- .data()
- .clone()
- .into_builder()
- .null_bit_buffer(null_buffer)
- .null_count(null_count);
+ let array_builder = builder.finish().into_data().into_builder().nulls(nulls);
let array_data = unsafe { array_builder.build_unchecked() };
Ok(Ok(PrimitiveArray::<T>::from(array_data)))
diff --git a/arrow-arith/src/boolean.rs b/arrow-arith/src/boolean.rs
index 4c1a02ad7498..5bd39a673426 100644
--- a/arrow-arith/src/boolean.rs
+++ b/arrow-arith/src/boolean.rs
@@ -39,16 +39,13 @@ use arrow_schema::{ArrowError, DataType};
/// of one side if other side is a false value.
pub(crate) fn build_null_buffer_for_and_kleene(
left_data: &ArrayData,
- left_offset: usize,
right_data: &ArrayData,
- right_offset: usize,
- len_in_bits: usize,
) -> Option<Buffer> {
let left_buffer = &left_data.buffers()[0];
let right_buffer = &right_data.buffers()[0];
- let left_null_buffer = left_data.null_buffer();
- let right_null_buffer = right_data.null_buffer();
+ let left_null_buffer = left_data.nulls();
+ let right_null_buffer = right_data.nulls();
match (left_null_buffer, right_null_buffer) {
(None, None) => None,
@@ -58,22 +55,22 @@ pub(crate) fn build_null_buffer_for_and_kleene(
// 1. left null bit is set, or
// 2. right data bit is false (because null AND false = false).
Some(bitwise_bin_op_helper(
- left_null_buffer,
- left_offset,
+ left_null_buffer.buffer(),
+ left_null_buffer.offset(),
right_buffer,
- right_offset,
- len_in_bits,
+ right_data.offset(),
+ left_data.len(),
|a, b| a | !b,
))
}
(None, Some(right_null_buffer)) => {
// Same as above
Some(bitwise_bin_op_helper(
- right_null_buffer,
- right_offset,
+ right_null_buffer.buffer(),
+ right_null_buffer.offset(),
left_buffer,
- left_offset,
- len_in_bits,
+ left_data.offset(),
+ left_data.len(),
|a, b| a | !b,
))
}
@@ -85,13 +82,18 @@ pub(crate) fn build_null_buffer_for_and_kleene(
// (a | (c & !d)) & (c | (a & !b))
Some(bitwise_quaternary_op_helper(
[
- left_null_buffer,
+ left_null_buffer.buffer(),
left_buffer,
- right_null_buffer,
+ right_null_buffer.buffer(),
right_buffer,
],
- [left_offset, left_offset, right_offset, right_offset],
- len_in_bits,
+ [
+ left_null_buffer.offset(),
+ left_data.offset(),
+ right_null_buffer.offset(),
+ right_data.offset(),
+ ],
+ left_data.len(),
|a, b, c, d| (a | (c & !d)) & (c | (a & !b)),
))
}
@@ -101,13 +103,10 @@ pub(crate) fn build_null_buffer_for_and_kleene(
/// For AND/OR kernels, the result of null buffer is simply a bitwise `and` operation.
pub(crate) fn build_null_buffer_for_and_or(
left_data: &ArrayData,
- _left_offset: usize,
right_data: &ArrayData,
- _right_offset: usize,
- len_in_bits: usize,
) -> Option<Buffer> {
// `arrays` are not empty, so safely do `unwrap` directly.
- combine_option_bitmap(&[left_data, right_data], len_in_bits)
+ combine_option_bitmap(&[left_data, right_data], left_data.len())
}
/// Updates null buffer based on data buffer and null buffer of the operand at other side
@@ -116,45 +115,39 @@ pub(crate) fn build_null_buffer_for_and_or(
/// buffer of one side if other side is a true value.
pub(crate) fn build_null_buffer_for_or_kleene(
left_data: &ArrayData,
- left_offset: usize,
right_data: &ArrayData,
- right_offset: usize,
- len_in_bits: usize,
) -> Option<Buffer> {
let left_buffer = &left_data.buffers()[0];
let right_buffer = &right_data.buffers()[0];
- let left_null_buffer = left_data.null_buffer();
- let right_null_buffer = right_data.null_buffer();
-
- match (left_null_buffer, right_null_buffer) {
+ match (left_data.nulls(), right_data.nulls()) {
(None, None) => None,
- (Some(left_null_buffer), None) => {
+ (Some(left_nulls), None) => {
// The right side has no null values.
// The final null bit is set only if:
// 1. left null bit is set, or
// 2. right data bit is true (because null OR true = true).
Some(bitwise_bin_op_helper(
- left_null_buffer,
- left_offset,
+ left_nulls.buffer(),
+ left_nulls.offset(),
right_buffer,
- right_offset,
- len_in_bits,
+ right_data.offset(),
+ right_data.len(),
|a, b| a | b,
))
}
- (None, Some(right_null_buffer)) => {
+ (None, Some(right_nulls)) => {
// Same as above
Some(bitwise_bin_op_helper(
- right_null_buffer,
- right_offset,
+ right_nulls.buffer(),
+ right_nulls.offset(),
left_buffer,
- left_offset,
- len_in_bits,
+ left_data.offset(),
+ left_data.len(),
|a, b| a | b,
))
}
- (Some(left_null_buffer), Some(right_null_buffer)) => {
+ (Some(left_nulls), Some(right_nulls)) => {
// Follow the same logic above. Both sides have null values.
// Assume a is left null bits, b is left data bits, c is right null bits,
// d is right data bits.
@@ -162,13 +155,18 @@ pub(crate) fn build_null_buffer_for_or_kleene(
// (a | (c & d)) & (c | (a & b))
Some(bitwise_quaternary_op_helper(
[
- left_null_buffer,
+ left_nulls.buffer(),
left_buffer,
- right_null_buffer,
+ right_nulls.buffer(),
right_buffer,
],
- [left_offset, left_offset, right_offset, right_offset],
- len_in_bits,
+ [
+ left_nulls.offset(),
+ left_data.offset(),
+ right_nulls.offset(),
+ right_data.offset(),
+ ],
+ left_data.len(),
|a, b, c, d| (a | (c & d)) & (c | (a & b)),
))
}
@@ -184,7 +182,7 @@ pub(crate) fn binary_boolean_kernel<F, U>(
) -> Result<BooleanArray, ArrowError>
where
F: Fn(&Buffer, usize, &Buffer, usize, usize) -> Buffer,
- U: Fn(&ArrayData, usize, &ArrayData, usize, usize) -> Option<Buffer>,
+ U: Fn(&ArrayData, &ArrayData) -> Option<Buffer>,
{
if left.len() != right.len() {
return Err(ArrowError::ComputeError(
@@ -202,7 +200,7 @@ where
let left_offset = left.offset();
let right_offset = right.offset();
- let null_bit_buffer = null_op(left_data, left_offset, right_data, right_offset, len);
+ let null_bit_buffer = null_op(left_data, right_data);
let values = op(left_buffer, left_offset, right_buffer, right_offset, len);
@@ -353,10 +351,7 @@ pub fn not(left: &BooleanArray) -> Result<BooleanArray, ArrowError> {
let len = left.len();
let data = left.data_ref();
- let null_bit_buffer = data
- .null_bitmap()
- .as_ref()
- .map(|b| b.buffer().bit_slice(left_offset, len));
+ let null_bit_buffer = data.nulls().map(|b| b.inner().sliced());
let values = buffer_unary_not(&data.buffers()[0], left_offset, len);
@@ -388,12 +383,12 @@ pub fn not(left: &BooleanArray) -> Result<BooleanArray, ArrowError> {
pub fn is_null(input: &dyn Array) -> Result<BooleanArray, ArrowError> {
let len = input.len();
- let output = match input.data_ref().null_buffer() {
+ let output = match input.data_ref().nulls() {
None => {
let len_bytes = ceil(len, 8);
MutableBuffer::from_len_zeroed(len_bytes).into()
}
- Some(buffer) => buffer_unary_not(buffer, input.offset(), len),
+ Some(nulls) => buffer_unary_not(nulls.buffer(), nulls.offset(), nulls.len()),
};
let data = unsafe {
@@ -425,14 +420,14 @@ pub fn is_null(input: &dyn Array) -> Result<BooleanArray, ArrowError> {
pub fn is_not_null(input: &dyn Array) -> Result<BooleanArray, ArrowError> {
let len = input.len();
- let output = match input.data_ref().null_buffer() {
+ let output = match input.data_ref().nulls() {
None => {
let len_bytes = ceil(len, 8);
MutableBuffer::new(len_bytes)
.with_bitset(len_bytes, true)
.into()
}
- Some(buffer) => buffer.bit_slice(input.offset(), len),
+ Some(nulls) => nulls.inner().sliced(),
};
let data = unsafe {
@@ -615,7 +610,7 @@ mod tests {
let a = BooleanArray::from(vec![false, false, false, true, true, true]);
// ensure null bitmap of a is absent
- assert!(a.data_ref().null_bitmap().is_none());
+ assert!(a.data().nulls().is_none());
let b = BooleanArray::from(vec![
Some(true),
@@ -627,7 +622,7 @@ mod tests {
]);
// ensure null bitmap of b is present
- assert!(b.data_ref().null_bitmap().is_some());
+ assert!(b.data().nulls().is_some());
let c = or_kleene(&a, &b).unwrap();
@@ -655,12 +650,12 @@ mod tests {
]);
// ensure null bitmap of b is absent
- assert!(a.data_ref().null_bitmap().is_some());
+ assert!(a.data().nulls().is_some());
let b = BooleanArray::from(vec![false, false, false, true, true, true]);
// ensure null bitmap of a is present
- assert!(b.data_ref().null_bitmap().is_none());
+ assert!(b.data().nulls().is_none());
let c = or_kleene(&a, &b).unwrap();
@@ -857,7 +852,7 @@ mod tests {
let expected = BooleanArray::from(vec![false, false, false, false]);
assert_eq!(expected, res);
- assert_eq!(None, res.data_ref().null_bitmap());
+ assert!(res.data().nulls().is_none());
}
#[test]
@@ -870,7 +865,7 @@ mod tests {
let expected = BooleanArray::from(vec![false, false, false, false]);
assert_eq!(expected, res);
- assert_eq!(None, res.data_ref().null_bitmap());
+ assert!(res.data().nulls().is_none());
}
#[test]
@@ -882,7 +877,7 @@ mod tests {
let expected = BooleanArray::from(vec![true, true, true, true]);
assert_eq!(expected, res);
- assert_eq!(None, res.data_ref().null_bitmap());
+ assert!(res.data().nulls().is_none());
}
#[test]
@@ -895,7 +890,7 @@ mod tests {
let expected = BooleanArray::from(vec![true, true, true, true]);
assert_eq!(expected, res);
- assert_eq!(None, res.data_ref().null_bitmap());
+ assert!(res.data().nulls().is_none());
}
#[test]
@@ -907,7 +902,7 @@ mod tests {
let expected = BooleanArray::from(vec![false, true, false, true]);
assert_eq!(expected, res);
- assert_eq!(None, res.data_ref().null_bitmap());
+ assert!(res.data().nulls().is_none());
}
#[test]
@@ -938,7 +933,7 @@ mod tests {
let expected = BooleanArray::from(vec![false, true, false, true]);
assert_eq!(expected, res);
- assert_eq!(None, res.data_ref().null_bitmap());
+ assert!(res.data().nulls().is_none());
}
#[test]
@@ -950,7 +945,7 @@ mod tests {
let expected = BooleanArray::from(vec![true, false, true, false]);
assert_eq!(expected, res);
- assert_eq!(None, res.data_ref().null_bitmap());
+ assert!(res.data().nulls().is_none());
}
#[test]
@@ -981,6 +976,6 @@ mod tests {
let expected = BooleanArray::from(vec![true, false, true, false]);
assert_eq!(expected, res);
- assert_eq!(None, res.data_ref().null_bitmap());
+ assert!(res.data().nulls().is_none());
}
}
diff --git a/arrow-array/src/array/binary_array.rs b/arrow-array/src/array/binary_array.rs
index 50757dcbe1b6..1a3270a70d80 100644
--- a/arrow-array/src/array/binary_array.rs
+++ b/arrow-array/src/array/binary_array.rs
@@ -77,7 +77,7 @@ impl<OffsetSize: OffsetSizeTrait> GenericBinaryArray<OffsetSize> {
.offset(v.offset())
.add_buffer(v.data_ref().buffers()[0].clone())
.add_buffer(child_data.buffers()[0].slice(child_data.offset()))
- .null_bit_buffer(v.data_ref().null_buffer().cloned());
+ .nulls(v.data().nulls().cloned());
let data = unsafe { builder.build_unchecked() };
Self::from(data)
diff --git a/arrow-array/src/array/boolean_array.rs b/arrow-array/src/array/boolean_array.rs
index 8d1296c662fc..e924824e75ea 100644
--- a/arrow-array/src/array/boolean_array.rs
+++ b/arrow-array/src/array/boolean_array.rs
@@ -105,9 +105,9 @@ impl BooleanArray {
/// Returns the number of non null, true values within this array
pub fn true_count(&self) -> usize {
- match self.data.null_buffer() {
+ match self.data.nulls() {
Some(nulls) => {
- let null_chunks = nulls.bit_chunks(self.offset(), self.len());
+ let null_chunks = nulls.inner().bit_chunks();
let value_chunks = self.values().bit_chunks(self.offset(), self.len());
null_chunks
.iter()
@@ -187,11 +187,7 @@ impl BooleanArray {
where
F: FnMut(T::Item) -> bool,
{
- let null_bit_buffer = left
- .data()
- .null_buffer()
- .map(|b| b.bit_slice(left.offset(), left.len()));
-
+ let null_bit_buffer = left.data().nulls().map(|x| x.inner().sliced());
let buffer = MutableBuffer::collect_bool(left.len(), |i| unsafe {
// SAFETY: i in range 0..len
op(left.value_unchecked(i))
@@ -459,7 +455,7 @@ mod tests {
assert_eq!(4, arr.len());
assert_eq!(0, arr.offset());
assert_eq!(0, arr.null_count());
- assert!(arr.data().null_buffer().is_none());
+ assert!(arr.data().nulls().is_none());
for i in 0..3 {
assert!(!arr.is_null(i));
assert!(arr.is_valid(i));
@@ -474,7 +470,7 @@ mod tests {
assert_eq!(4, arr.len());
assert_eq!(0, arr.offset());
assert_eq!(2, arr.null_count());
- assert!(arr.data().null_buffer().is_some());
+ assert!(arr.data().nulls().is_some());
assert!(arr.is_valid(0));
assert!(arr.is_null(1));
diff --git a/arrow-array/src/array/byte_array.rs b/arrow-array/src/array/byte_array.rs
index f6946228c85c..442e795cec52 100644
--- a/arrow-array/src/array/byte_array.rs
+++ b/arrow-array/src/array/byte_array.rs
@@ -137,10 +137,7 @@ impl<T: ByteArrayType> GenericByteArray<T> {
/// offset and data buffers are not shared by others.
pub fn into_builder(self) -> Result<GenericByteBuilder<T>, Self> {
let len = self.len();
- let null_bit_buffer = self
- .data
- .null_buffer()
- .map(|b| b.bit_slice(self.data.offset(), len));
+ let null_bit_buffer = self.data.nulls().map(|b| b.inner().sliced());
let element_len = std::mem::size_of::<T::Offset>();
let offset_buffer = self.data.buffers()[0]
diff --git a/arrow-array/src/array/dictionary_array.rs b/arrow-array/src/array/dictionary_array.rs
index eb2f1b606bb1..60426e5b3c4d 100644
--- a/arrow-array/src/array/dictionary_array.rs
+++ b/arrow-array/src/array/dictionary_array.rs
@@ -249,23 +249,15 @@ impl<K: ArrowPrimitiveType> DictionaryArray<K> {
// Note: This use the ArrayDataBuilder::build_unchecked and afterwards
// call the new function which only validates that the keys are in bounds.
- let mut data = ArrayData::builder(dict_data_type)
- .len(keys.len())
- .add_buffer(keys.data().buffers()[0].clone())
+ let data = keys.data().clone();
+ let builder = data
+ .into_builder()
+ .data_type(dict_data_type)
.add_child_data(values.data().clone());
- match keys.data().null_buffer() {
- Some(buffer) if keys.data().null_count() > 0 => {
- data = data
- .null_bit_buffer(Some(buffer.clone()))
- .null_count(keys.data().null_count());
- }
- _ => data = data.null_count(0),
- }
-
// Safety: `validate` ensures key type is correct, and
// `validate_values` ensures all offsets are within range
- let array = unsafe { data.build_unchecked() };
+ let array = unsafe { builder.build_unchecked() };
array.validate()?;
array.validate_values()?;
@@ -430,16 +422,13 @@ impl<T: ArrowPrimitiveType> From<ArrayData> for DictionaryArray<T> {
// create a zero-copy of the keys' data
// SAFETY:
// ArrayData is valid and verified type above
+
let keys = PrimitiveArray::<T>::from(unsafe {
- ArrayData::new_unchecked(
- T::DATA_TYPE,
- data.len(),
- Some(data.null_count()),
- data.null_buffer().cloned(),
- data.offset(),
- data.buffers().to_vec(),
- vec![],
- )
+ data.clone()
+ .into_builder()
+ .data_type(T::DATA_TYPE)
+ .child_data(vec![])
+ .build_unchecked()
});
let values = make_array(data.child_data()[0].clone());
Self {
diff --git a/arrow-array/src/array/fixed_size_binary_array.rs b/arrow-array/src/array/fixed_size_binary_array.rs
index 89ace430d8af..e927c8d8ae58 100644
--- a/arrow-array/src/array/fixed_size_binary_array.rs
+++ b/arrow-array/src/array/fixed_size_binary_array.rs
@@ -408,7 +408,7 @@ impl From<FixedSizeListArray> for FixedSizeBinaryArray {
.len(v.len())
.offset(v.offset())
.add_buffer(child_data.buffers()[0].slice(child_data.offset()))
- .null_bit_buffer(v.data_ref().null_buffer().cloned());
+ .nulls(v.data_ref().nulls().cloned());
let data = unsafe { builder.build_unchecked() };
Self::from(data)
diff --git a/arrow-array/src/array/null_array.rs b/arrow-array/src/array/null_array.rs
index 6b68aace706f..8eb8e64b0eda 100644
--- a/arrow-array/src/array/null_array.rs
+++ b/arrow-array/src/array/null_array.rs
@@ -99,7 +99,7 @@ impl From<ArrayData> for NullArray {
"NullArray data should contain 0 buffers"
);
assert!(
- data.null_buffer().is_none(),
+ data.nulls().is_none(),
"NullArray data should not contain a null buffer, as no buffers are required"
);
Self { data }
diff --git a/arrow-array/src/array/primitive_array.rs b/arrow-array/src/array/primitive_array.rs
index 53217a06f497..0e28060b25f8 100644
--- a/arrow-array/src/array/primitive_array.rs
+++ b/arrow-array/src/array/primitive_array.rs
@@ -443,7 +443,7 @@ impl<T: ArrowPrimitiveType> PrimitiveArray<T> {
let len = self.len();
let null_count = self.null_count();
- let null_buffer = data.null_buffer().map(|b| b.bit_slice(data.offset(), len));
+ let null_buffer = data.nulls().map(|b| b.inner().sliced());
let values = self.values().iter().map(|v| op(*v));
// JUSTIFICATION
// Benefit
@@ -500,7 +500,7 @@ impl<T: ArrowPrimitiveType> PrimitiveArray<T> {
let len = self.len();
let null_count = self.null_count();
- let null_buffer = data.null_buffer().map(|b| b.bit_slice(data.offset(), len));
+ let null_buffer = data.nulls().map(|b| b.inner().sliced());
let mut buffer = BufferBuilder::<O::Native>::new(len);
buffer.append_n_zeroed(len);
let slice = buffer.as_slice_mut();
@@ -567,9 +567,10 @@ impl<T: ArrowPrimitiveType> PrimitiveArray<T> {
{
let data = self.data();
let len = data.len();
- let offset = data.offset();
- let null_count = data.null_count();
- let nulls = data.null_buffer().map(|x| x.as_slice());
+ let (nulls, null_count, offset) = match data.nulls() {
+ Some(n) => (Some(n.validity()), n.null_count(), n.offset()),
+ None => (None, 0, 0),
+ };
let mut null_builder = BooleanBufferBuilder::new(len);
match nulls {
@@ -608,10 +609,7 @@ impl<T: ArrowPrimitiveType> PrimitiveArray<T> {
/// data buffer is not shared by others.
pub fn into_builder(self) -> Result<PrimitiveBuilder<T>, Self> {
let len = self.len();
- let null_bit_buffer = self
- .data
- .null_buffer()
- .map(|b| b.bit_slice(self.data.offset(), len));
+ let null_bit_buffer = self.data.nulls().map(|b| b.inner().sliced());
let element_len = std::mem::size_of::<T::Native>();
let buffer = self.data.buffers()[0]
@@ -1791,7 +1789,7 @@ mod tests {
let primitive_array = PrimitiveArray::<Int32Type>::from_iter(iter);
assert_eq!(primitive_array.len(), 10);
assert_eq!(primitive_array.null_count(), 0);
- assert_eq!(primitive_array.data().null_buffer(), None);
+ assert!(primitive_array.data().nulls().is_none());
assert_eq!(primitive_array.values(), &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
}
diff --git a/arrow-array/src/array/struct_array.rs b/arrow-array/src/array/struct_array.rs
index 9149895f6ec9..35d4444e0117 100644
--- a/arrow-array/src/array/struct_array.rs
+++ b/arrow-array/src/array/struct_array.rs
@@ -154,22 +154,20 @@ impl TryFrom<Vec<(&str, ArrayRef)>> for StructArray {
fields.push(Field::new(
field_name,
array.data_type().clone(),
- child_datum.null_buffer().is_some(),
+ child_datum.nulls().is_some(),
));
- if let Some(child_null_buffer) = child_datum.null_buffer() {
- let child_datum_offset = child_datum.offset();
-
+ if let Some(child_nulls) = child_datum.nulls() {
null = Some(if let Some(null_buffer) = &null {
buffer_bin_or(
null_buffer,
0,
- child_null_buffer,
- child_datum_offset,
+ child_nulls.buffer(),
+ child_nulls.offset(),
child_datum_len,
)
} else {
- child_null_buffer.bit_slice(child_datum_offset, child_datum_len)
+ child_nulls.inner().sliced()
});
} else if null.is_some() {
// when one of the fields has no nulls, then there is no null in the array
@@ -321,7 +319,6 @@ mod tests {
BooleanArray, Float32Array, Float64Array, Int32Array, Int64Array, StringArray,
};
use arrow_buffer::ToByteSlice;
- use arrow_data::Bitmap;
use std::sync::Arc;
#[test]
@@ -410,8 +407,8 @@ mod tests {
assert_eq!(1, struct_data.null_count());
assert_eq!(
// 00001011
- Some(&Bitmap::from(Buffer::from(&[11_u8]))),
- struct_data.null_bitmap()
+ &[11_u8],
+ struct_data.nulls().unwrap().validity()
);
let expected_string_data = ArrayData::builder(DataType::Utf8)
diff --git a/arrow-array/src/builder/boolean_builder.rs b/arrow-array/src/builder/boolean_builder.rs
index eeb39b802948..0862b35b07e0 100644
--- a/arrow-array/src/builder/boolean_builder.rs
+++ b/arrow-array/src/builder/boolean_builder.rs
@@ -289,7 +289,7 @@ mod tests {
let array = builder.finish();
assert_eq!(0, array.null_count());
- assert!(array.data().null_buffer().is_none());
+ assert!(array.data().nulls().is_none());
}
#[test]
@@ -311,7 +311,7 @@ mod tests {
assert_eq!(4, array.false_count());
assert_eq!(0, array.null_count());
- assert!(array.data().null_buffer().is_none());
+ assert!(array.data().nulls().is_none());
}
#[test]
diff --git a/arrow-array/src/builder/generic_bytes_builder.rs b/arrow-array/src/builder/generic_bytes_builder.rs
index 406e79c3169c..c723b3349930 100644
--- a/arrow-array/src/builder/generic_bytes_builder.rs
+++ b/arrow-array/src/builder/generic_bytes_builder.rs
@@ -425,7 +425,7 @@ mod tests {
builder.append_value("parquet");
let arr = builder.finish();
// array should not have null buffer because there is not `null` value.
- assert_eq!(None, arr.data().null_buffer());
+ assert!(arr.data().nulls().is_none());
assert_eq!(GenericStringArray::<O>::from(vec!["arrow", "parquet"]), arr,)
}
@@ -454,7 +454,7 @@ mod tests {
builder.append_value("parquet");
arr = builder.finish();
- assert!(arr.data().null_buffer().is_some());
+ assert!(arr.data().nulls().is_some());
assert_eq!(&[O::zero()], builder.offsets_slice());
assert_eq!(5, arr.len());
}
diff --git a/arrow-array/src/builder/struct_builder.rs b/arrow-array/src/builder/struct_builder.rs
index 72aa53e189dd..51b4c7cfcdc6 100644
--- a/arrow-array/src/builder/struct_builder.rs
+++ b/arrow-array/src/builder/struct_builder.rs
@@ -284,7 +284,6 @@ impl StructBuilder {
mod tests {
use super::*;
use arrow_buffer::Buffer;
- use arrow_data::Bitmap;
use crate::array::Array;
@@ -329,10 +328,7 @@ mod tests {
let struct_data = arr.data();
assert_eq!(4, struct_data.len());
assert_eq!(1, struct_data.null_count());
- assert_eq!(
- Some(&Bitmap::from(Buffer::from(&[11_u8]))),
- struct_data.null_bitmap()
- );
+ assert_eq!(&[11_u8], struct_data.nulls().unwrap().validity());
let expected_string_data = ArrayData::builder(DataType::Utf8)
.len(4)
diff --git a/arrow-array/src/lib.rs b/arrow-array/src/lib.rs
index 400b6e262faa..bfdc35c6ce5d 100644
--- a/arrow-array/src/lib.rs
+++ b/arrow-array/src/lib.rs
@@ -141,18 +141,18 @@
//!
//! For example, the type [`Int16Array`] represents an array of 16-bit integers and consists of:
//!
-//! * An optional [`Bitmap`] identifying any null values
+//! * An optional [`NullBuffer`] identifying any null values
//! * A contiguous [`Buffer`] of 16-bit integers
//!
//! Similarly, the type [`StringArray`] represents an array of UTF-8 strings and consists of:
//!
-//! * An optional [`Bitmap`] identifying any null values
+//! * An optional [`NullBuffer`] identifying any null values
//! * An offsets [`Buffer`] of 32-bit integers identifying valid UTF-8 sequences within the values buffer
//! * A values [`Buffer`] of UTF-8 encoded string data
//!
//! [Arrow specification]: https://arrow.apache.org/docs/format/Columnar.html
//! [`&dyn Array`]: Array
-//! [`Bitmap`]: arrow_data::Bitmap
+//! [`NullBuffer`]: arrow_buffer::buffer::NullBuffer
//! [`Buffer`]: arrow_buffer::Buffer
//! [`compute`]: https://docs.rs/arrow/latest/arrow/compute/index.html
//! [`json`]: https://docs.rs/arrow/latest/arrow/json/index.html
diff --git a/arrow-array/src/record_batch.rs b/arrow-array/src/record_batch.rs
index 04a559f21603..20e4e19bad39 100644
--- a/arrow-array/src/record_batch.rs
+++ b/arrow-array/src/record_batch.rs
@@ -603,7 +603,7 @@ mod tests {
let record_batch =
RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a), Arc::new(b)])
.unwrap();
- assert_eq!(record_batch.get_array_memory_size(), 640);
+ assert_eq!(record_batch.get_array_memory_size(), 672);
}
fn check_batch(record_batch: RecordBatch, num_rows: usize) {
diff --git a/arrow-buffer/src/buffer/boolean.rs b/arrow-buffer/src/buffer/boolean.rs
index 82755a2b0a27..0239111cbafe 100644
--- a/arrow-buffer/src/buffer/boolean.rs
+++ b/arrow-buffer/src/buffer/boolean.rs
@@ -15,16 +15,33 @@
// specific language governing permissions and limitations
// under the License.
+use crate::bit_chunk_iterator::BitChunks;
use crate::{bit_util, Buffer};
/// A slice-able [`Buffer`] containing bit-packed booleans
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, Eq)]
pub struct BooleanBuffer {
buffer: Buffer,
offset: usize,
len: usize,
}
+impl PartialEq for BooleanBuffer {
+ fn eq(&self, other: &Self) -> bool {
+ if self.len != other.len {
+ return false;
+ }
+
+ let lhs = self.bit_chunks();
+ let rhs = other.bit_chunks();
+
+ if lhs.iter().zip(rhs.iter()).any(|(a, b)| a != b) {
+ return false;
+ }
+ lhs.remainder_bits() == rhs.remainder_bits()
+ }
+}
+
impl BooleanBuffer {
/// Create a new [`BooleanBuffer`] from a [`Buffer`], an `offset` and `length` in bits
///
@@ -47,6 +64,12 @@ impl BooleanBuffer {
self.buffer.count_set_bits_offset(self.offset, self.len)
}
+ /// Returns a `BitChunks` instance which can be used to iterate over
+ /// this buffer's bits in `u64` chunks
+ pub fn bit_chunks(&self) -> BitChunks {
+ BitChunks::new(self.values(), self.offset, self.len)
+ }
+
/// Returns `true` if the bit at index `i` is set
///
/// # Panics
@@ -81,4 +104,39 @@ impl BooleanBuffer {
pub fn values(&self) -> &[u8] {
&self.buffer
}
+
+ /// Slices this [`BooleanBuffer`] by the provided `offset` and `length`
+ pub fn slice(&self, offset: usize, len: usize) -> Self {
+ assert!(
+ offset.saturating_add(len) <= self.len,
+ "the length + offset of the sliced BooleanBuffer cannot exceed the existing length"
+ );
+ Self {
+ buffer: self.buffer.clone(),
+ offset: self.offset + offset,
+ len,
+ }
+ }
+
+ /// Returns a [`Buffer`] containing the sliced contents of this [`BooleanBuffer`]
+ ///
+ /// Equivalent to `self.buffer.bit_slice(self.offset, self.len)`
+ pub fn sliced(&self) -> Buffer {
+ self.buffer.bit_slice(self.offset, self.len)
+ }
+
+ /// Returns true if this [`BooleanBuffer`] is equal to `other`, using pointer comparisons
+ /// to determine buffer equality. This is cheaper than `PartialEq::eq` but may
+ /// return false when the arrays are logically equal
+ pub fn ptr_eq(&self, other: &Self) -> bool {
+ self.buffer.as_ptr() == other.buffer.as_ptr()
+ && self.offset == other.offset
+ && self.len == other.len
+ }
+
+ /// Returns the inner [`Buffer`]
+ #[inline]
+ pub fn inner(&self) -> &Buffer {
+ &self.buffer
+ }
}
diff --git a/arrow-buffer/src/buffer/null.rs b/arrow-buffer/src/buffer/null.rs
index 2d52c9096dce..a4854f1adfed 100644
--- a/arrow-buffer/src/buffer/null.rs
+++ b/arrow-buffer/src/buffer/null.rs
@@ -16,8 +16,9 @@
// under the License.
use crate::buffer::BooleanBuffer;
+use crate::{Buffer, MutableBuffer};
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, Eq, PartialEq)]
pub struct NullBuffer {
buffer: BooleanBuffer,
null_count: usize,
@@ -30,6 +31,16 @@ impl NullBuffer {
Self { buffer, null_count }
}
+ /// Create a new [`NullBuffer`] of length `len` where all values are null
+ pub fn new_null(len: usize) -> Self {
+ let buffer = MutableBuffer::new_null(len).into_buffer();
+ let buffer = BooleanBuffer::new(buffer, 0, len);
+ Self {
+ buffer,
+ null_count: len,
+ }
+ }
+
/// Create a new [`NullBuffer`] with the provided `buffer` and `null_count`
///
/// # Safety
@@ -45,6 +56,12 @@ impl NullBuffer {
self.buffer.len()
}
+ /// Returns the offset of this [`NullBuffer`] in bits
+ #[inline]
+ pub fn offset(&self) -> usize {
+ self.buffer.offset()
+ }
+
/// Returns true if this [`NullBuffer`] is empty
#[inline]
pub fn is_empty(&self) -> bool {
@@ -69,11 +86,28 @@ impl NullBuffer {
!self.is_valid(idx)
}
- /// Returns the inner buffer
+ /// Returns the packed validity of this [`NullBuffer`] not including any offset
+ #[inline]
+ pub fn validity(&self) -> &[u8] {
+ self.buffer.values()
+ }
+
+ /// Slices this [`NullBuffer`] by the provided `offset` and `length`
+ pub fn slice(&self, offset: usize, len: usize) -> Self {
+ Self::new(self.buffer.slice(offset, len))
+ }
+
+ /// Returns the inner [`BooleanBuffer`]
#[inline]
pub fn inner(&self) -> &BooleanBuffer {
&self.buffer
}
+
+ /// Returns the underlying [`Buffer`]
+ #[inline]
+ pub fn buffer(&self) -> &Buffer {
+ self.buffer.inner()
+ }
}
#[cfg(test)]
diff --git a/arrow-cast/src/cast.rs b/arrow-cast/src/cast.rs
index d49775c98211..8e3bde990fcd 100644
--- a/arrow-cast/src/cast.rs
+++ b/arrow-cast/src/cast.rs
@@ -2942,22 +2942,15 @@ fn dictionary_cast<K: ArrowDictionaryKeyType>(
)));
}
- // keys are data, child_data is values (dictionary)
- let data = unsafe {
- ArrayData::new_unchecked(
- to_type.clone(),
- cast_keys.len(),
- Some(cast_keys.null_count()),
- cast_keys
- .data()
- .null_bitmap()
- .cloned()
- .map(|bitmap| bitmap.into_buffer()),
- cast_keys.data().offset(),
- cast_keys.data().buffers().to_vec(),
- vec![cast_values.into_data()],
- )
- };
+ let data = cast_keys.into_data();
+ let builder = data
+ .into_builder()
+ .data_type(to_type.clone())
+ .child_data(vec![cast_values.into_data()]);
+
+ // Safety
+ // Cast keys are still valid
+ let data = unsafe { builder.build_unchecked() };
// create the appropriate array type
let new_array: ArrayRef = match **to_index_type {
@@ -3184,11 +3177,7 @@ fn cast_primitive_to_list<OffsetSize: OffsetSizeTrait + NumCast>(
to_type.clone(),
array.len(),
Some(cast_array.null_count()),
- cast_array
- .data()
- .null_bitmap()
- .cloned()
- .map(|bitmap| bitmap.into_buffer()),
+ cast_array.data().nulls().map(|b| b.inner().sliced()),
0,
vec![offsets.into()],
vec![cast_array.into_data()],
@@ -3207,23 +3196,18 @@ fn cast_list_inner<OffsetSize: OffsetSizeTrait>(
to_type: &DataType,
cast_options: &CastOptions,
) -> Result<ArrayRef, ArrowError> {
- let data = array.data_ref();
+ let data = array.data().clone();
let underlying_array = make_array(data.child_data()[0].clone());
- let cast_array = cast_with_options(&underlying_array, to.data_type(), cast_options)?;
- let array_data = unsafe {
- ArrayData::new_unchecked(
- to_type.clone(),
- array.len(),
- Some(data.null_count()),
- data.null_bitmap()
- .cloned()
- .map(|bitmap| bitmap.into_buffer()),
- array.offset(),
- // reuse offset buffer
- data.buffers().to_vec(),
- vec![cast_array.into_data()],
- )
- };
+ let cast_array =
+ cast_with_options(underlying_array.as_ref(), to.data_type(), cast_options)?;
+ let builder = data
+ .into_builder()
+ .data_type(to_type.clone())
+ .child_data(vec![cast_array.into_data()]);
+
+ // Safety
+ // Data was valid before
+ let array_data = unsafe { builder.build_unchecked() };
let list = GenericListArray::<OffsetSize>::from(array_data);
Ok(Arc::new(list) as ArrayRef)
}
@@ -3302,7 +3286,7 @@ where
.len(array.len())
.add_buffer(offset_buffer)
.add_buffer(str_values_buf)
- .null_bit_buffer(data.null_buffer().cloned());
+ .nulls(data.nulls().cloned());
let array_data = unsafe { builder.build_unchecked() };
@@ -3377,7 +3361,7 @@ where
.len(array.len())
.add_buffer(offset_buffer)
.add_child_data(value_data)
- .null_bit_buffer(data.null_buffer().cloned());
+ .nulls(data.nulls().cloned());
let array_data = unsafe { builder.build_unchecked() };
Ok(make_array(array_data))
diff --git a/arrow-data/src/bit_mask.rs b/arrow-data/src/bit_mask.rs
index ed8e65257788..94ea57259ac8 100644
--- a/arrow-data/src/bit_mask.rs
+++ b/arrow-data/src/bit_mask.rs
@@ -74,7 +74,10 @@ pub fn combine_option_bitmap(
) -> Option<Buffer> {
let (buffer, offset) = arrays
.iter()
- .map(|array| (array.null_buffer().cloned(), array.offset()))
+ .map(|array| match array.nulls() {
+ Some(n) => (Some(n.buffer().clone()), n.offset()),
+ None => (None, 0),
+ })
.reduce(|acc, buffer_and_offset| match (acc, buffer_and_offset) {
((None, _), (None, _)) => (None, 0),
((Some(buffer), offset), (None, _)) | ((None, _), (Some(buffer), offset)) => {
diff --git a/arrow-data/src/bitmap.rs b/arrow-data/src/bitmap.rs
deleted file mode 100644
index a356b9ff7d38..000000000000
--- a/arrow-data/src/bitmap.rs
+++ /dev/null
@@ -1,189 +0,0 @@
-// 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.
-
-//! Defines [Bitmap] for tracking validity bitmaps
-
-use arrow_buffer::bit_util;
-use arrow_schema::ArrowError;
-use std::mem;
-
-use arrow_buffer::buffer::{buffer_bin_and, buffer_bin_or, Buffer};
-use std::ops::{BitAnd, BitOr};
-
-#[derive(Debug, Clone)]
-/// Defines a bitmap, which is used to track which values in an Arrow
-/// array are null.
-///
-/// This is called a "validity bitmap" in the Arrow documentation.
-pub struct Bitmap {
- pub(crate) bits: Buffer,
-}
-
-impl Bitmap {
- pub fn new(num_bits: usize) -> Self {
- let num_bytes = bit_util::ceil(num_bits, 8);
- let len = bit_util::round_upto_multiple_of_64(num_bytes);
- Bitmap {
- bits: Buffer::from(&vec![0xFF; len]),
- }
- }
-
- /// Return the length of this Bitmap in bits (not bytes)
- pub fn bit_len(&self) -> usize {
- self.bits.len() * 8
- }
-
- pub fn is_empty(&self) -> bool {
- self.bits.is_empty()
- }
-
- pub fn is_set(&self, i: usize) -> bool {
- assert!(i < (self.bits.len() << 3));
- unsafe { bit_util::get_bit_raw(self.bits.as_ptr(), i) }
- }
-
- pub fn buffer(&self) -> &Buffer {
- &self.bits
- }
-
- pub fn buffer_ref(&self) -> &Buffer {
- &self.bits
- }
-
- pub fn into_buffer(self) -> Buffer {
- self.bits
- }
-
- /// Returns the total number of bytes of memory occupied by the
- /// buffers owned by this [Bitmap].
- ///
- /// If multiple [`Bitmap`]s refer to the same underlying
- /// [`Buffer`] they will both report the same size.
- pub fn get_buffer_memory_size(&self) -> usize {
- self.bits.capacity()
- }
-
- /// Returns the total number of bytes of memory occupied
- /// physically by this [Bitmap] and its [`Buffer`]s.
- ///
- /// Equivalent to: `size_of_val(self)` + [`Self::get_buffer_memory_size`]
- pub fn get_array_memory_size(&self) -> usize {
- self.bits.capacity() + mem::size_of_val(self)
- }
-}
-
-impl<'a, 'b> BitAnd<&'b Bitmap> for &'a Bitmap {
- type Output = Result<Bitmap, ArrowError>;
-
- fn bitand(self, rhs: &'b Bitmap) -> Result<Bitmap, ArrowError> {
- if self.bits.len() != rhs.bits.len() {
- return Err(ArrowError::ComputeError(
- "Buffers must be the same size to apply Bitwise AND.".to_string(),
- ));
- }
- Ok(Bitmap::from(buffer_bin_and(
- &self.bits,
- 0,
- &rhs.bits,
- 0,
- self.bit_len(),
- )))
- }
-}
-
-impl<'a, 'b> BitOr<&'b Bitmap> for &'a Bitmap {
- type Output = Result<Bitmap, ArrowError>;
-
- fn bitor(self, rhs: &'b Bitmap) -> Result<Bitmap, ArrowError> {
- if self.bits.len() != rhs.bits.len() {
- return Err(ArrowError::ComputeError(
- "Buffers must be the same size to apply Bitwise OR.".to_string(),
- ));
- }
- Ok(Bitmap::from(buffer_bin_or(
- &self.bits,
- 0,
- &rhs.bits,
- 0,
- self.bit_len(),
- )))
- }
-}
-
-impl From<Buffer> for Bitmap {
- fn from(buf: Buffer) -> Self {
- Self { bits: buf }
- }
-}
-
-impl PartialEq for Bitmap {
- fn eq(&self, other: &Self) -> bool {
- // buffer equality considers capacity, but here we want to only compare
- // actual data contents
- let self_len = self.bits.len();
- let other_len = other.bits.len();
- if self_len != other_len {
- return false;
- }
- self.bits.as_slice()[..self_len] == other.bits.as_slice()[..self_len]
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn test_bitmap_length() {
- assert_eq!(512, Bitmap::new(63 * 8).bit_len());
- assert_eq!(512, Bitmap::new(64 * 8).bit_len());
- assert_eq!(1024, Bitmap::new(65 * 8).bit_len());
- }
-
- #[test]
- fn test_bitwise_and() {
- let bitmap1 = Bitmap::from(Buffer::from([0b01101010]));
- let bitmap2 = Bitmap::from(Buffer::from([0b01001110]));
- assert_eq!(
- Bitmap::from(Buffer::from([0b01001010])),
- (&bitmap1 & &bitmap2).unwrap()
- );
- }
-
- #[test]
- fn test_bitwise_or() {
- let bitmap1 = Bitmap::from(Buffer::from([0b01101010]));
- let bitmap2 = Bitmap::from(Buffer::from([0b01001110]));
- assert_eq!(
- Bitmap::from(Buffer::from([0b01101110])),
- (&bitmap1 | &bitmap2).unwrap()
- );
- }
-
- #[test]
- fn test_bitmap_is_set() {
- let bitmap = Bitmap::from(Buffer::from([0b01001010]));
- assert!(!bitmap.is_set(0));
- assert!(bitmap.is_set(1));
- assert!(!bitmap.is_set(2));
- assert!(bitmap.is_set(3));
- assert!(!bitmap.is_set(4));
- assert!(!bitmap.is_set(5));
- assert!(bitmap.is_set(6));
- assert!(!bitmap.is_set(7));
- }
-}
diff --git a/arrow-data/src/data/mod.rs b/arrow-data/src/data/mod.rs
index eb1fe2bcffa2..ab617b584b7d 100644
--- a/arrow-data/src/data/mod.rs
+++ b/arrow-data/src/data/mod.rs
@@ -18,8 +18,9 @@
//! Contains [`ArrayData`], a generic representation of Arrow array data which encapsulates
//! common attributes and operations for Arrow array.
-use crate::{bit_iterator::BitSliceIterator, bitmap::Bitmap};
+use crate::bit_iterator::BitSliceIterator;
use arrow_buffer::bit_chunk_iterator::BitChunks;
+use arrow_buffer::buffer::{BooleanBuffer, NullBuffer};
use arrow_buffer::{bit_util, ArrowNativeType, Buffer, MutableBuffer};
use arrow_schema::{ArrowError, DataType, UnionMode};
use std::convert::TryInto;
@@ -38,27 +39,32 @@ mod types;
#[inline]
pub(crate) fn contains_nulls(
- null_bit_buffer: Option<&Buffer>,
+ null_bit_buffer: Option<&NullBuffer>,
offset: usize,
len: usize,
) -> bool {
match null_bit_buffer {
- Some(buffer) => match BitSliceIterator::new(buffer, offset, len).next() {
- Some((start, end)) => start != 0 || end != len,
- None => len != 0, // No non-null values
- },
+ Some(buffer) => {
+ match BitSliceIterator::new(buffer.validity(), buffer.offset() + offset, len)
+ .next()
+ {
+ Some((start, end)) => start != 0 || end != len,
+ None => len != 0, // No non-null values
+ }
+ }
None => false, // No null buffer
}
}
#[inline]
pub(crate) fn count_nulls(
- null_bit_buffer: Option<&Buffer>,
+ null_bit_buffer: Option<&NullBuffer>,
offset: usize,
len: usize,
) -> usize {
if let Some(buf) = null_bit_buffer {
- len - buf.count_set_bits_offset(offset, len)
+ let buffer = buf.buffer();
+ len - buffer.count_set_bits_offset(offset + buf.offset(), len)
} else {
0
}
@@ -222,9 +228,6 @@ pub struct ArrayData {
/// The number of elements in this array data
len: usize,
- /// The number of null elements in this array data
- null_count: usize,
-
/// The offset into this array data, in number of items
offset: usize,
@@ -239,7 +242,7 @@ pub struct ArrayData {
/// The null bitmap. A `None` value for this indicates all values are non-null in
/// this array.
- null_bitmap: Option<Bitmap>,
+ nulls: Option<NullBuffer>,
}
pub type ArrayDataRef = Arc<ArrayData>;
@@ -271,19 +274,21 @@ impl ArrayData {
buffers: Vec<Buffer>,
child_data: Vec<ArrayData>,
) -> Self {
- let null_count = match null_count {
- None => count_nulls(null_bit_buffer.as_ref(), offset, len),
- Some(null_count) => null_count,
- };
- let null_bitmap = null_bit_buffer.filter(|_| null_count > 0).map(Bitmap::from);
+ let nulls = null_bit_buffer
+ .map(|b| BooleanBuffer::new(b, offset, len))
+ .map(|b| match null_count {
+ None => NullBuffer::new(b),
+ Some(null_count) => NullBuffer::new_unchecked(b, null_count),
+ })
+ .filter(|b| b.null_count() > 0);
+
let new_self = Self {
data_type,
len,
- null_count,
offset,
buffers,
child_data,
- null_bitmap,
+ nulls,
};
// Provide a force_validate mode
@@ -368,30 +373,26 @@ impl ArrayData {
}
/// Returns whether the element at index `i` is null
+ #[inline]
pub fn is_null(&self, i: usize) -> bool {
- if let Some(ref b) = self.null_bitmap {
- return !b.is_set(self.offset + i);
+ match &self.nulls {
+ Some(v) => v.is_null(i),
+ None => false,
}
- false
}
- /// Returns a reference to the null bitmap of this [`ArrayData`]
+ /// Returns a reference to the null buffer of this [`ArrayData`] if any
+ ///
+ /// Note: [`ArrayData::offset`] does NOT apply to the returned [`NullBuffer`]
#[inline]
- pub const fn null_bitmap(&self) -> Option<&Bitmap> {
- self.null_bitmap.as_ref()
- }
-
- /// Returns a reference to the null buffer of this [`ArrayData`].
- pub fn null_buffer(&self) -> Option<&Buffer> {
- self.null_bitmap().as_ref().map(|b| b.buffer_ref())
+ pub fn nulls(&self) -> Option<&NullBuffer> {
+ self.nulls.as_ref()
}
/// Returns whether the element at index `i` is not null
+ #[inline]
pub fn is_valid(&self, i: usize) -> bool {
- if let Some(ref b) = self.null_bitmap {
- return b.is_set(self.offset + i);
- }
- true
+ !self.is_null(i)
}
/// Returns the length (i.e., number of elements) of this [`ArrayData`].
@@ -414,8 +415,11 @@ impl ArrayData {
/// Returns the total number of nulls in this array
#[inline]
- pub const fn null_count(&self) -> usize {
- self.null_count
+ pub fn null_count(&self) -> usize {
+ self.nulls
+ .as_ref()
+ .map(|x| x.null_count())
+ .unwrap_or_default()
}
/// Returns the total number of bytes of memory occupied by the
@@ -434,8 +438,8 @@ impl ArrayData {
for buffer in &self.buffers {
size += buffer.capacity();
}
- if let Some(bitmap) = &self.null_bitmap {
- size += bitmap.get_buffer_memory_size()
+ if let Some(bitmap) = &self.nulls {
+ size += bitmap.buffer().capacity()
}
for child in &self.child_data {
size += child.get_buffer_memory_size();
@@ -500,7 +504,7 @@ impl ArrayData {
}
}
- if self.null_bitmap().is_some() {
+ if self.nulls().is_some() {
result += bit_util::ceil(self.len, 8);
}
@@ -526,11 +530,8 @@ impl ArrayData {
size += mem::size_of::<Buffer>();
size += buffer.capacity();
}
- if let Some(bitmap) = &self.null_bitmap {
- // this includes the size of the bitmap struct itself, since it is stored directly in
- // this struct we already counted those bytes in the size_of_val(self) above
- size += bitmap.get_array_memory_size();
- size -= mem::size_of::<Bitmap>();
+ if let Some(nulls) = &self.nulls {
+ size += nulls.buffer().capacity();
}
for child in &self.child_data {
size += child.get_array_memory_size();
@@ -555,7 +556,6 @@ impl ArrayData {
let new_data = ArrayData {
data_type: self.data_type().clone(),
len: length,
- null_count: count_nulls(self.null_buffer(), new_offset, length),
offset: new_offset,
buffers: self.buffers.clone(),
// Slice child data, to propagate offsets down to them
@@ -564,7 +564,7 @@ impl ArrayData {
.iter()
.map(|data| data.slice(offset, length))
.collect(),
- null_bitmap: self.null_bitmap().cloned(),
+ nulls: self.nulls.as_ref().map(|x| x.slice(offset, length)),
};
new_data
@@ -573,9 +573,7 @@ impl ArrayData {
new_data.len = length;
new_data.offset = offset + self.offset;
-
- new_data.null_count =
- count_nulls(new_data.null_buffer(), new_data.offset, new_data.len);
+ new_data.nulls = self.nulls.as_ref().map(|x| x.slice(offset, length));
new_data
}
@@ -704,7 +702,7 @@ impl ArrayData {
.child_data(child_data);
if has_nulls {
- builder = builder.null_count(len).null_bit_buffer(Some(zeroed(len)))
+ builder = builder.nulls(Some(NullBuffer::new_null(len)))
}
// SAFETY:
@@ -734,7 +732,7 @@ impl ArrayData {
// Check that the data layout conforms to the spec
let layout = layout(&self.data_type);
- if !layout.can_contain_null_mask && self.null_bitmap.is_some() {
+ if !layout.can_contain_null_mask && self.nulls.is_some() {
return Err(ArrowError::InvalidArgumentError(format!(
"Arrays of type {:?} cannot contain a null bitmask",
self.data_type,
@@ -786,29 +784,31 @@ impl ArrayData {
}
}
- if self.null_count > self.len {
- return Err(ArrowError::InvalidArgumentError(format!(
- "null_count {} for an array exceeds length of {} elements",
- self.null_count, self.len
- )));
- }
-
// check null bit buffer size
- if let Some(null_bit_map) = self.null_bitmap.as_ref() {
- let null_bit_buffer = null_bit_map.buffer_ref();
+ if let Some(nulls) = self.nulls() {
+ if nulls.null_count() > self.len {
+ return Err(ArrowError::InvalidArgumentError(format!(
+ "null_count {} for an array exceeds length of {} elements",
+ nulls.null_count(),
+ self.len
+ )));
+ }
+
+ let actual_len = nulls.validity().len();
let needed_len = bit_util::ceil(len_plus_offset, 8);
- if null_bit_buffer.len() < needed_len {
+ if actual_len < needed_len {
return Err(ArrowError::InvalidArgumentError(format!(
- "null_bit_buffer size too small. got {} needed {}",
- null_bit_buffer.len(),
- needed_len
+ "null_bit_buffer size too small. got {actual_len} needed {needed_len}",
+ )));
+ }
+
+ if nulls.len() != self.len {
+ return Err(ArrowError::InvalidArgumentError(format!(
+ "null buffer incorrect size. got {} expected {}",
+ nulls.len(),
+ self.len
)));
}
- } else if self.null_count > 0 {
- return Err(ArrowError::InvalidArgumentError(format!(
- "Array of type {} has {} nulls but no null bitmap",
- self.data_type, self.null_count
- )));
}
self.validate_child_data()?;
@@ -1145,14 +1145,14 @@ impl ArrayData {
/// Validates the the null count is correct and that any
/// nullability requirements of its children are correct
pub fn validate_nulls(&self) -> Result<(), ArrowError> {
- let nulls = self.null_buffer();
-
- let actual_null_count = count_nulls(nulls, self.offset, self.len);
- if actual_null_count != self.null_count {
- return Err(ArrowError::InvalidArgumentError(format!(
- "null_count value ({}) doesn't match actual number of nulls in array ({})",
- self.null_count, actual_null_count
- )));
+ if let Some(nulls) = &self.nulls {
+ let actual = nulls.len() - nulls.inner().count_set_bits();
+ if actual != nulls.null_count() {
+ return Err(ArrowError::InvalidArgumentError(format!(
+ "null_count value ({}) doesn't match actual number of nulls in array ({})",
+ nulls.null_count(), actual
+ )));
+ }
}
// In general non-nullable children should not contain nulls, however, for certain
@@ -1168,7 +1168,7 @@ impl ArrayData {
DataType::FixedSizeList(field, len) => {
let child = &self.child_data[0];
if !field.is_nullable() {
- match nulls {
+ match &self.nulls {
Some(nulls) => {
let element_len = *len as usize;
let mut buffer =
@@ -1177,7 +1177,7 @@ impl ArrayData {
// Expand each bit within `null_mask` into `element_len`
// bits, constructing the implicit mask of the child elements
for i in 0..self.len {
- if !bit_util::get_bit(nulls.as_ref(), self.offset + i) {
+ if nulls.is_null(i) {
continue;
}
for j in 0..element_len {
@@ -1197,7 +1197,14 @@ impl ArrayData {
DataType::Struct(fields) => {
for (field, child) in fields.iter().zip(&self.child_data) {
if !field.is_nullable() {
- self.validate_non_nullable(nulls, self.offset, child)?
+ match &self.nulls {
+ Some(n) => self.validate_non_nullable(
+ Some(n.buffer()),
+ n.offset(),
+ child,
+ )?,
+ None => self.validate_non_nullable(None, 0, child)?,
+ }
}
}
}
@@ -1216,7 +1223,7 @@ impl ArrayData {
) -> Result<(), ArrowError> {
let mask = match mask {
Some(mask) => mask.as_ref(),
- None => return match data.null_count {
+ None => return match data.null_count() {
0 => Ok(()),
_ => Err(ArrowError::InvalidArgumentError(format!(
"non-nullable child of type {} contains nulls not present in parent {}",
@@ -1226,10 +1233,10 @@ impl ArrayData {
},
};
- match data.null_buffer() {
+ match data.nulls() {
Some(nulls) => {
let mask = BitChunks::new(mask, offset, data.len);
- let nulls = BitChunks::new(nulls.as_ref(), data.offset, data.len);
+ let nulls = BitChunks::new(nulls.validity(), nulls.offset(), data.len);
mask
.iter()
.zip(nulls.iter())
@@ -1500,7 +1507,6 @@ impl ArrayData {
pub fn ptr_eq(&self, other: &Self) -> bool {
if self.offset != other.offset
|| self.len != other.len
- || self.null_count != other.null_count
|| self.data_type != other.data_type
|| self.buffers.len() != other.buffers.len()
|| self.child_data.len() != other.child_data.len()
@@ -1508,8 +1514,8 @@ impl ArrayData {
return false;
}
- match (&self.null_bitmap, &other.null_bitmap) {
- (Some(a), Some(b)) if a.bits.as_ptr() != b.bits.as_ptr() => return false,
+ match (&self.nulls, &other.nulls) {
+ (Some(a), Some(b)) if !a.inner().ptr_eq(b.inner()) => return false,
(Some(_), None) | (None, Some(_)) => return false,
_ => {}
};
@@ -1704,6 +1710,7 @@ pub struct ArrayDataBuilder {
len: usize,
null_count: Option<usize>,
null_bit_buffer: Option<Buffer>,
+ nulls: Option<NullBuffer>,
offset: usize,
buffers: Vec<Buffer>,
child_data: Vec<ArrayData>,
@@ -1717,6 +1724,7 @@ impl ArrayDataBuilder {
len: 0,
null_count: None,
null_bit_buffer: None,
+ nulls: None,
offset: 0,
buffers: vec![],
child_data: vec![],
@@ -1734,12 +1742,20 @@ impl ArrayDataBuilder {
self
}
+ pub fn nulls(mut self, nulls: Option<NullBuffer>) -> Self {
+ self.nulls = nulls;
+ self.null_count = None;
+ self.null_bit_buffer = None;
+ self
+ }
+
pub fn null_count(mut self, null_count: usize) -> Self {
self.null_count = Some(null_count);
self
}
pub fn null_bit_buffer(mut self, buf: Option<Buffer>) -> Self {
+ self.nulls = None;
self.null_bit_buffer = buf;
self
}
@@ -1776,43 +1792,53 @@ impl ArrayDataBuilder {
///
/// The same caveats as [`ArrayData::new_unchecked`]
/// apply.
+ #[allow(clippy::let_and_return)]
pub unsafe fn build_unchecked(self) -> ArrayData {
- ArrayData::new_unchecked(
- self.data_type,
- self.len,
- self.null_count,
- self.null_bit_buffer,
- self.offset,
- self.buffers,
- self.child_data,
- )
+ let nulls = self.nulls.or_else(|| {
+ let buffer = self.null_bit_buffer?;
+ let buffer = BooleanBuffer::new(buffer, self.offset, self.len);
+ Some(match self.null_count {
+ Some(n) => NullBuffer::new_unchecked(buffer, n),
+ None => NullBuffer::new(buffer),
+ })
+ });
+
+ let data = ArrayData {
+ data_type: self.data_type,
+ len: self.len,
+ offset: self.offset,
+ buffers: self.buffers,
+ child_data: self.child_data,
+ nulls,
+ };
+
+ // Provide a force_validate mode
+ #[cfg(feature = "force_validate")]
+ data.validate_data().unwrap();
+ data
}
/// Creates an array data, validating all inputs
+ #[allow(clippy::let_and_return)]
pub fn build(self) -> Result<ArrayData, ArrowError> {
- ArrayData::try_new(
- self.data_type,
- self.len,
- self.null_bit_buffer,
- self.offset,
- self.buffers,
- self.child_data,
- )
+ let data = unsafe { self.build_unchecked() };
+ #[cfg(not(feature = "force_validate"))]
+ data.validate_data()?;
+ Ok(data)
}
}
impl From<ArrayData> for ArrayDataBuilder {
fn from(d: ArrayData) -> Self {
- // TODO: Store Bitmap on ArrayData (#1799)
- let null_bit_buffer = d.null_buffer().cloned();
Self {
- null_bit_buffer,
data_type: d.data_type,
len: d.len,
- null_count: Some(d.null_count),
offset: d.offset,
buffers: d.buffers,
child_data: d.child_data,
+ nulls: d.nulls,
+ null_bit_buffer: None,
+ null_count: None,
}
}
}
@@ -1926,8 +1952,8 @@ mod tests {
.null_bit_buffer(Some(Buffer::from(bit_v)))
.build()
.unwrap();
- assert!(arr_data.null_buffer().is_some());
- assert_eq!(&bit_v, arr_data.null_buffer().unwrap().as_slice());
+ assert!(arr_data.nulls().is_some());
+ assert_eq!(&bit_v, arr_data.nulls().unwrap().validity());
}
#[test]
@@ -2045,11 +2071,12 @@ mod tests {
#[test]
fn test_count_nulls() {
- let null_buffer = Some(Buffer::from(vec![0b00010110, 0b10011111]));
- let count = count_nulls(null_buffer.as_ref(), 0, 16);
+ let buffer = Buffer::from(vec![0b00010110, 0b10011111]);
+ let buffer = NullBuffer::new(BooleanBuffer::new(buffer, 0, 16));
+ let count = count_nulls(Some(&buffer), 0, 16);
assert_eq!(count, 7);
- let count = count_nulls(null_buffer.as_ref(), 4, 8);
+ let count = count_nulls(Some(&buffer), 4, 8);
assert_eq!(count, 3);
}
@@ -2057,7 +2084,7 @@ mod tests {
fn test_contains_nulls() {
let buffer: Buffer =
MutableBuffer::from_iter([false, false, false, true, true, false]).into();
-
+ let buffer = NullBuffer::new(BooleanBuffer::new(buffer, 0, 6));
assert!(contains_nulls(Some(&buffer), 0, 6));
assert!(contains_nulls(Some(&buffer), 0, 3));
assert!(!contains_nulls(Some(&buffer), 3, 2));
diff --git a/arrow-data/src/equal/boolean.rs b/arrow-data/src/equal/boolean.rs
index 52e822f03f30..a20ca5ac0bd7 100644
--- a/arrow-data/src/equal/boolean.rs
+++ b/arrow-data/src/equal/boolean.rs
@@ -33,7 +33,7 @@ pub(super) fn boolean_equal(
let lhs_values = lhs.buffers()[0].as_slice();
let rhs_values = rhs.buffers()[0].as_slice();
- let contains_nulls = contains_nulls(lhs.null_buffer(), lhs_start + lhs.offset(), len);
+ let contains_nulls = contains_nulls(lhs.nulls(), lhs_start, len);
if !contains_nulls {
// Optimize performance for starting offset at u8 boundary.
@@ -76,15 +76,13 @@ pub(super) fn boolean_equal(
)
} else {
// get a ref of the null buffer bytes, to use in testing for nullness
- let lhs_null_bytes = lhs.null_buffer().as_ref().unwrap().as_slice();
+ let lhs_nulls = lhs.nulls().unwrap();
- let lhs_start = lhs.offset() + lhs_start;
- let rhs_start = rhs.offset() + rhs_start;
-
- BitIndexIterator::new(lhs_null_bytes, lhs_start, len).all(|i| {
- let lhs_pos = lhs_start + i;
- let rhs_pos = rhs_start + i;
- get_bit(lhs_values, lhs_pos) == get_bit(rhs_values, rhs_pos)
- })
+ BitIndexIterator::new(lhs_nulls.validity(), lhs_start + lhs_nulls.offset(), len)
+ .all(|i| {
+ let lhs_pos = lhs_start + lhs.offset() + i;
+ let rhs_pos = rhs_start + rhs.offset() + i;
+ get_bit(lhs_values, lhs_pos) == get_bit(rhs_values, rhs_pos)
+ })
}
}
diff --git a/arrow-data/src/equal/dictionary.rs b/arrow-data/src/equal/dictionary.rs
index 5638c5c91c5c..1d9c4b8d964f 100644
--- a/arrow-data/src/equal/dictionary.rs
+++ b/arrow-data/src/equal/dictionary.rs
@@ -16,7 +16,7 @@
// under the License.
use crate::data::{contains_nulls, ArrayData};
-use arrow_buffer::{bit_util::get_bit, ArrowNativeType};
+use arrow_buffer::ArrowNativeType;
use super::equal_range;
@@ -35,7 +35,7 @@ pub(super) fn dictionary_equal<T: ArrowNativeType>(
// Only checking one null mask here because by the time the control flow reaches
// this point, the equality of the two masks would have already been verified.
- if !contains_nulls(lhs.null_buffer(), lhs_start + lhs.offset(), len) {
+ if !contains_nulls(lhs.nulls(), lhs_start, len) {
(0..len).all(|i| {
let lhs_pos = lhs_start + i;
let rhs_pos = rhs_start + i;
@@ -50,14 +50,14 @@ pub(super) fn dictionary_equal<T: ArrowNativeType>(
})
} else {
// get a ref of the null buffer bytes, to use in testing for nullness
- let lhs_null_bytes = lhs.null_buffer().as_ref().unwrap().as_slice();
- let rhs_null_bytes = rhs.null_buffer().as_ref().unwrap().as_slice();
+ let lhs_nulls = lhs.nulls().unwrap();
+ let rhs_nulls = rhs.nulls().unwrap();
(0..len).all(|i| {
let lhs_pos = lhs_start + i;
let rhs_pos = rhs_start + i;
- let lhs_is_null = !get_bit(lhs_null_bytes, lhs_pos + lhs.offset());
- let rhs_is_null = !get_bit(rhs_null_bytes, rhs_pos + rhs.offset());
+ let lhs_is_null = lhs_nulls.is_null(lhs_pos);
+ let rhs_is_null = rhs_nulls.is_null(rhs_pos);
lhs_is_null
|| (lhs_is_null == rhs_is_null)
diff --git a/arrow-data/src/equal/fixed_binary.rs b/arrow-data/src/equal/fixed_binary.rs
index 17e470b5c47c..9e0e77ff7eca 100644
--- a/arrow-data/src/equal/fixed_binary.rs
+++ b/arrow-data/src/equal/fixed_binary.rs
@@ -19,7 +19,6 @@ use crate::bit_iterator::BitSliceIterator;
use crate::contains_nulls;
use crate::data::ArrayData;
use crate::equal::primitive::NULL_SLICES_SELECTIVITY_THRESHOLD;
-use arrow_buffer::bit_util::get_bit;
use arrow_schema::DataType;
use super::utils::equal_len;
@@ -41,7 +40,7 @@ pub(super) fn fixed_binary_equal(
// Only checking one null mask here because by the time the control flow reaches
// this point, the equality of the two masks would have already been verified.
- if !contains_nulls(lhs.null_buffer(), lhs_start + lhs.offset(), len) {
+ if !contains_nulls(lhs.nulls(), lhs_start, len) {
equal_len(
lhs_values,
rhs_values,
@@ -54,15 +53,15 @@ pub(super) fn fixed_binary_equal(
if selectivity_frac >= NULL_SLICES_SELECTIVITY_THRESHOLD {
// get a ref of the null buffer bytes, to use in testing for nullness
- let lhs_null_bytes = lhs.null_buffer().as_ref().unwrap().as_slice();
- let rhs_null_bytes = rhs.null_buffer().as_ref().unwrap().as_slice();
+ let lhs_nulls = lhs.nulls().unwrap();
+ let rhs_nulls = rhs.nulls().unwrap();
// with nulls, we need to compare item by item whenever it is not null
(0..len).all(|i| {
let lhs_pos = lhs_start + i;
let rhs_pos = rhs_start + i;
- let lhs_is_null = !get_bit(lhs_null_bytes, lhs_pos + lhs.offset());
- let rhs_is_null = !get_bit(rhs_null_bytes, rhs_pos + rhs.offset());
+ let lhs_is_null = lhs_nulls.is_null(lhs_pos);
+ let rhs_is_null = rhs_nulls.is_null(rhs_pos);
lhs_is_null
|| (lhs_is_null == rhs_is_null)
@@ -75,14 +74,16 @@ pub(super) fn fixed_binary_equal(
)
})
} else {
+ let lhs_nulls = lhs.nulls().unwrap();
let lhs_slices_iter = BitSliceIterator::new(
- lhs.null_buffer().as_ref().unwrap(),
- lhs_start + lhs.offset(),
+ lhs_nulls.validity(),
+ lhs_start + lhs_nulls.offset(),
len,
);
+ let rhs_nulls = lhs.nulls().unwrap();
let rhs_slices_iter = BitSliceIterator::new(
- rhs.null_buffer().as_ref().unwrap(),
- rhs_start + rhs.offset(),
+ rhs_nulls.validity(),
+ rhs_start + rhs_nulls.offset(),
len,
);
diff --git a/arrow-data/src/equal/fixed_list.rs b/arrow-data/src/equal/fixed_list.rs
index 204a8658e747..4b79e5c33fab 100644
--- a/arrow-data/src/equal/fixed_list.rs
+++ b/arrow-data/src/equal/fixed_list.rs
@@ -16,7 +16,6 @@
// under the License.
use crate::data::{contains_nulls, ArrayData};
-use arrow_buffer::bit_util::get_bit;
use arrow_schema::DataType;
use super::equal_range;
@@ -38,7 +37,7 @@ pub(super) fn fixed_list_equal(
// Only checking one null mask here because by the time the control flow reaches
// this point, the equality of the two masks would have already been verified.
- if !contains_nulls(lhs.null_buffer(), lhs_start + lhs.offset(), len) {
+ if !contains_nulls(lhs.nulls(), lhs_start, len) {
equal_range(
lhs_values,
rhs_values,
@@ -48,15 +47,15 @@ pub(super) fn fixed_list_equal(
)
} else {
// get a ref of the null buffer bytes, to use in testing for nullness
- let lhs_null_bytes = lhs.null_buffer().as_ref().unwrap().as_slice();
- let rhs_null_bytes = rhs.null_buffer().as_ref().unwrap().as_slice();
+ let lhs_nulls = lhs.nulls().unwrap();
+ let rhs_nulls = rhs.nulls().unwrap();
// with nulls, we need to compare item by item whenever it is not null
(0..len).all(|i| {
let lhs_pos = lhs_start + i;
let rhs_pos = rhs_start + i;
- let lhs_is_null = !get_bit(lhs_null_bytes, lhs_pos + lhs.offset());
- let rhs_is_null = !get_bit(rhs_null_bytes, rhs_pos + rhs.offset());
+ let lhs_is_null = lhs_nulls.is_null(lhs_pos);
+ let rhs_is_null = rhs_nulls.is_null(rhs_pos);
lhs_is_null
|| (lhs_is_null == rhs_is_null)
diff --git a/arrow-data/src/equal/list.rs b/arrow-data/src/equal/list.rs
index 25273f8bad63..cc4ba3cacf9f 100644
--- a/arrow-data/src/equal/list.rs
+++ b/arrow-data/src/equal/list.rs
@@ -16,7 +16,6 @@
// under the License.
use crate::data::{count_nulls, ArrayData};
-use arrow_buffer::bit_util::get_bit;
use arrow_buffer::ArrowNativeType;
use num::Integer;
@@ -90,8 +89,8 @@ pub(super) fn list_equal<T: ArrowNativeType + Integer>(
let lhs_values = &lhs.child_data()[0];
let rhs_values = &rhs.child_data()[0];
- let lhs_null_count = count_nulls(lhs.null_buffer(), lhs_start + lhs.offset(), len);
- let rhs_null_count = count_nulls(rhs.null_buffer(), rhs_start + rhs.offset(), len);
+ let lhs_null_count = count_nulls(lhs.nulls(), lhs_start, len);
+ let rhs_null_count = count_nulls(rhs.nulls(), rhs_start, len);
if lhs_null_count != rhs_null_count {
return false;
@@ -112,8 +111,8 @@ pub(super) fn list_equal<T: ArrowNativeType + Integer>(
)
} else {
// get a ref of the parent null buffer bytes, to use in testing for nullness
- let lhs_null_bytes = lhs.null_buffer().unwrap().as_slice();
- let rhs_null_bytes = rhs.null_buffer().unwrap().as_slice();
+ let lhs_nulls = lhs.nulls().unwrap();
+ let rhs_nulls = rhs.nulls().unwrap();
// with nulls, we need to compare item by item whenever it is not null
// TODO: Could potentially compare runs of not NULL values
@@ -121,8 +120,8 @@ pub(super) fn list_equal<T: ArrowNativeType + Integer>(
let lhs_pos = lhs_start + i;
let rhs_pos = rhs_start + i;
- let lhs_is_null = !get_bit(lhs_null_bytes, lhs_pos + lhs.offset());
- let rhs_is_null = !get_bit(rhs_null_bytes, rhs_pos + rhs.offset());
+ let lhs_is_null = lhs_nulls.is_null(lhs_pos);
+ let rhs_is_null = rhs_nulls.is_null(rhs_pos);
if lhs_is_null != rhs_is_null {
return false;
diff --git a/arrow-data/src/equal/primitive.rs b/arrow-data/src/equal/primitive.rs
index f52541e2861c..7b3cbc9eb949 100644
--- a/arrow-data/src/equal/primitive.rs
+++ b/arrow-data/src/equal/primitive.rs
@@ -17,7 +17,6 @@
use crate::bit_iterator::BitSliceIterator;
use crate::contains_nulls;
-use arrow_buffer::bit_util::get_bit;
use std::mem::size_of;
use crate::data::ArrayData;
@@ -39,7 +38,7 @@ pub(super) fn primitive_equal<T>(
// Only checking one null mask here because by the time the control flow reaches
// this point, the equality of the two masks would have already been verified.
- if !contains_nulls(lhs.null_buffer(), lhs_start + lhs.offset(), len) {
+ if !contains_nulls(lhs.nulls(), lhs_start, len) {
// without nulls, we just need to compare slices
equal_len(
lhs_values,
@@ -53,14 +52,14 @@ pub(super) fn primitive_equal<T>(
if selectivity_frac >= NULL_SLICES_SELECTIVITY_THRESHOLD {
// get a ref of the null buffer bytes, to use in testing for nullness
- let lhs_null_bytes = lhs.null_buffer().as_ref().unwrap().as_slice();
- let rhs_null_bytes = rhs.null_buffer().as_ref().unwrap().as_slice();
+ let lhs_nulls = lhs.nulls().unwrap();
+ let rhs_nulls = rhs.nulls().unwrap();
// with nulls, we need to compare item by item whenever it is not null
(0..len).all(|i| {
let lhs_pos = lhs_start + i;
let rhs_pos = rhs_start + i;
- let lhs_is_null = !get_bit(lhs_null_bytes, lhs_pos + lhs.offset());
- let rhs_is_null = !get_bit(rhs_null_bytes, rhs_pos + rhs.offset());
+ let lhs_is_null = lhs_nulls.is_null(lhs_pos);
+ let rhs_is_null = rhs_nulls.is_null(rhs_pos);
lhs_is_null
|| (lhs_is_null == rhs_is_null)
@@ -73,14 +72,16 @@ pub(super) fn primitive_equal<T>(
)
})
} else {
+ let lhs_nulls = lhs.nulls().unwrap();
let lhs_slices_iter = BitSliceIterator::new(
- lhs.null_buffer().as_ref().unwrap(),
- lhs_start + lhs.offset(),
+ lhs_nulls.validity(),
+ lhs_start + lhs_nulls.offset(),
len,
);
+ let rhs_nulls = rhs.nulls().unwrap();
let rhs_slices_iter = BitSliceIterator::new(
- rhs.null_buffer().as_ref().unwrap(),
- rhs_start + rhs.offset(),
+ rhs_nulls.validity(),
+ rhs_start + rhs_nulls.offset(),
len,
);
diff --git a/arrow-data/src/equal/structure.rs b/arrow-data/src/equal/structure.rs
index 25ab340cd3f8..e4751c26f489 100644
--- a/arrow-data/src/equal/structure.rs
+++ b/arrow-data/src/equal/structure.rs
@@ -16,7 +16,6 @@
// under the License.
use crate::data::{contains_nulls, ArrayData};
-use arrow_buffer::bit_util::get_bit;
use super::equal_range;
@@ -46,19 +45,19 @@ pub(super) fn struct_equal(
) -> bool {
// Only checking one null mask here because by the time the control flow reaches
// this point, the equality of the two masks would have already been verified.
- if !contains_nulls(lhs.null_buffer(), lhs_start + lhs.offset(), len) {
+ if !contains_nulls(lhs.nulls(), lhs_start, len) {
equal_child_values(lhs, rhs, lhs_start, rhs_start, len)
} else {
// get a ref of the null buffer bytes, to use in testing for nullness
- let lhs_null_bytes = lhs.null_buffer().as_ref().unwrap().as_slice();
- let rhs_null_bytes = rhs.null_buffer().as_ref().unwrap().as_slice();
+ let lhs_nulls = lhs.nulls().unwrap();
+ let rhs_nulls = rhs.nulls().unwrap();
// with nulls, we need to compare item by item whenever it is not null
(0..len).all(|i| {
let lhs_pos = lhs_start + i;
let rhs_pos = rhs_start + i;
// if both struct and child had no null buffers,
- let lhs_is_null = !get_bit(lhs_null_bytes, lhs_pos + lhs.offset());
- let rhs_is_null = !get_bit(rhs_null_bytes, rhs_pos + rhs.offset());
+ let lhs_is_null = lhs_nulls.is_null(lhs_pos);
+ let rhs_is_null = rhs_nulls.is_null(rhs_pos);
if lhs_is_null != rhs_is_null {
return false;
diff --git a/arrow-data/src/equal/utils.rs b/arrow-data/src/equal/utils.rs
index b3f7fc0b06ef..d1f0f392a195 100644
--- a/arrow-data/src/equal/utils.rs
+++ b/arrow-data/src/equal/utils.rs
@@ -49,15 +49,16 @@ pub(super) fn equal_nulls(
rhs_start: usize,
len: usize,
) -> bool {
- let lhs_offset = lhs_start + lhs.offset();
- let rhs_offset = rhs_start + rhs.offset();
-
- match (lhs.null_buffer(), rhs.null_buffer()) {
- (Some(lhs), Some(rhs)) => {
- equal_bits(lhs.as_slice(), rhs.as_slice(), lhs_offset, rhs_offset, len)
- }
- (Some(lhs), None) => !contains_nulls(Some(lhs), lhs_offset, len),
- (None, Some(rhs)) => !contains_nulls(Some(rhs), rhs_offset, len),
+ match (lhs.nulls(), rhs.nulls()) {
+ (Some(lhs), Some(rhs)) => equal_bits(
+ lhs.validity(),
+ rhs.validity(),
+ lhs.offset() + lhs_start,
+ rhs.offset() + rhs_start,
+ len,
+ ),
+ (Some(lhs), None) => !contains_nulls(Some(lhs), lhs_start, len),
+ (None, Some(rhs)) => !contains_nulls(Some(rhs), rhs_start, len),
(None, None) => true,
}
}
diff --git a/arrow-data/src/equal/variable_size.rs b/arrow-data/src/equal/variable_size.rs
index f661c614d301..ae880437450b 100644
--- a/arrow-data/src/equal/variable_size.rs
+++ b/arrow-data/src/equal/variable_size.rs
@@ -16,7 +16,6 @@
// under the License.
use crate::data::{count_nulls, ArrayData};
-use arrow_buffer::bit_util::get_bit;
use arrow_buffer::ArrowNativeType;
use num::Integer;
@@ -60,8 +59,8 @@ pub(super) fn variable_sized_equal<T: ArrowNativeType + Integer>(
let lhs_values = lhs.buffers()[1].as_slice();
let rhs_values = rhs.buffers()[1].as_slice();
- let lhs_null_count = count_nulls(lhs.null_buffer(), lhs_start + lhs.offset(), len);
- let rhs_null_count = count_nulls(rhs.null_buffer(), rhs_start + rhs.offset(), len);
+ let lhs_null_count = count_nulls(lhs.nulls(), lhs_start, len);
+ let rhs_null_count = count_nulls(rhs.nulls(), rhs_start, len);
if lhs_null_count == 0
&& rhs_null_count == 0
@@ -83,15 +82,8 @@ pub(super) fn variable_sized_equal<T: ArrowNativeType + Integer>(
let rhs_pos = rhs_start + i;
// the null bits can still be `None`, indicating that the value is valid.
- let lhs_is_null = !lhs
- .null_buffer()
- .map(|v| get_bit(v.as_slice(), lhs.offset() + lhs_pos))
- .unwrap_or(true);
-
- let rhs_is_null = !rhs
- .null_buffer()
- .map(|v| get_bit(v.as_slice(), rhs.offset() + rhs_pos))
- .unwrap_or(true);
+ let lhs_is_null = lhs.nulls().map(|v| v.is_null(lhs_pos)).unwrap_or_default();
+ let rhs_is_null = rhs.nulls().map(|v| v.is_null(rhs_pos)).unwrap_or_default();
lhs_is_null
|| (lhs_is_null == rhs_is_null)
diff --git a/arrow-data/src/ffi.rs b/arrow-data/src/ffi.rs
index e506653bb59b..b7d690fb9124 100644
--- a/arrow-data/src/ffi.rs
+++ b/arrow-data/src/ffi.rs
@@ -17,8 +17,10 @@
//! Contains declarations to bind to the [C Data Interface](https://arrow.apache.org/docs/format/CDataInterface.html).
+use crate::bit_mask::set_bits;
use crate::{layout, ArrayData};
-use arrow_buffer::Buffer;
+use arrow_buffer::buffer::NullBuffer;
+use arrow_buffer::{Buffer, MutableBuffer};
use arrow_schema::DataType;
use std::ffi::c_void;
@@ -83,6 +85,29 @@ unsafe extern "C" fn release_array(array: *mut FFI_ArrowArray) {
array.release = None;
}
+/// Aligns the provided `nulls` to the provided `data_offset`
+///
+/// This is a temporary measure until offset is removed from ArrayData (#1799)
+fn align_nulls(data_offset: usize, nulls: Option<&NullBuffer>) -> Option<Buffer> {
+ let nulls = nulls?;
+ if data_offset == nulls.offset() {
+ // Underlying buffer is already aligned
+ return Some(nulls.buffer().clone());
+ }
+ if data_offset == 0 {
+ return Some(nulls.inner().sliced());
+ }
+ let mut builder = MutableBuffer::new_null(data_offset + nulls.len());
+ set_bits(
+ builder.as_slice_mut(),
+ nulls.validity(),
+ data_offset,
+ nulls.offset(),
+ nulls.len(),
+ );
+ Some(builder.into())
+}
+
struct ArrayPrivateData {
#[allow(dead_code)]
buffers: Vec<Option<Buffer>>,
@@ -102,7 +127,7 @@ impl FFI_ArrowArray {
let buffers = if data_layout.can_contain_null_mask {
// * insert the null buffer at the start
// * make all others `Option<Buffer>`.
- std::iter::once(data.null_buffer().cloned())
+ std::iter::once(align_nulls(data.offset(), data.nulls()))
.chain(data.buffers().iter().map(|b| Some(b.clone())))
.collect::<Vec<_>>()
} else {
diff --git a/arrow-data/src/lib.rs b/arrow-data/src/lib.rs
index b37a8c5da72f..2b105f5bb040 100644
--- a/arrow-data/src/lib.rs
+++ b/arrow-data/src/lib.rs
@@ -17,8 +17,6 @@
//! Array data abstractions for [Apache Arrow](https://docs.rs/arrow)
-mod bitmap;
-pub use bitmap::Bitmap;
mod data;
pub use data::*;
diff --git a/arrow-data/src/transform/mod.rs b/arrow-data/src/transform/mod.rs
index fef6d4be4985..2719b96b6914 100644
--- a/arrow-data/src/transform/mod.rs
+++ b/arrow-data/src/transform/mod.rs
@@ -20,6 +20,7 @@ use super::{
ArrayData, ArrayDataBuilder,
};
use crate::bit_mask::set_bits;
+use arrow_buffer::buffer::{BooleanBuffer, NullBuffer};
use arrow_buffer::{bit_util, i256, ArrowNativeType, MutableBuffer};
use arrow_schema::{ArrowError, DataType, IntervalUnit, UnionMode};
use half::f16;
@@ -76,26 +77,30 @@ impl<'a> _MutableArrayData<'a> {
}
};
+ let nulls = (self.null_count > 0).then(|| {
+ let bools = BooleanBuffer::new(self.null_buffer.into(), 0, self.len);
+ unsafe { NullBuffer::new_unchecked(bools, self.null_count) }
+ });
+
ArrayDataBuilder::new(self.data_type)
.offset(0)
.len(self.len)
- .null_count(self.null_count)
+ .nulls(nulls)
.buffers(buffers)
.child_data(child_data)
- .null_bit_buffer((self.null_count > 0).then(|| self.null_buffer.into()))
}
}
fn build_extend_null_bits(array: &ArrayData, use_nulls: bool) -> ExtendNullBits {
- if let Some(bitmap) = array.null_bitmap() {
- let bytes = bitmap.buffer().as_slice();
+ if let Some(nulls) = array.nulls() {
+ let bytes = nulls.validity();
Box::new(move |mutable, start, len| {
utils::resize_for_bits(&mut mutable.null_buffer, mutable.len + len);
mutable.null_count += set_bits(
mutable.null_buffer.as_slice_mut(),
bytes,
mutable.len,
- array.offset() + start,
+ nulls.offset() + start,
len,
);
})
diff --git a/arrow-ipc/src/reader.rs b/arrow-ipc/src/reader.rs
index 6842474fb4e2..bb367f9447d5 100644
--- a/arrow-ipc/src/reader.rs
+++ b/arrow-ipc/src/reader.rs
@@ -227,10 +227,8 @@ fn create_array(
buffer_index = values_triple.2;
let run_array_length = run_node.length() as usize;
- let run_array_null_count = run_node.null_count() as usize;
let data = ArrayData::builder(data_type.clone())
.len(run_array_length)
- .null_count(run_array_null_count)
.offset(0)
.add_child_data(run_ends_triple.0.into_data())
.add_child_data(values_triple.0.into_data())
diff --git a/arrow-ipc/src/writer.rs b/arrow-ipc/src/writer.rs
index f019340154ac..75c48bebcf63 100644
--- a/arrow-ipc/src/writer.rs
+++ b/arrow-ipc/src/writer.rs
@@ -617,7 +617,6 @@ fn into_zero_offset_run_array<R: RunEndIndexType>(
// The function builds a valid run_ends array and hence need not be validated.
ArrayDataBuilder::new(run_array.run_ends().data_type().clone())
.len(physical_length)
- .null_count(0)
.add_buffer(builder.finish())
.build_unchecked()
};
@@ -1220,7 +1219,7 @@ fn write_array_data(
}
if has_validity_bitmap(array_data.data_type(), write_options) {
// write null buffer if exists
- let null_buffer = match array_data.null_buffer() {
+ let null_buffer = match array_data.nulls() {
None => {
// create a buffer and fill it with valid bits
let num_bytes = bit_util::ceil(num_rows, 8);
@@ -1228,7 +1227,7 @@ fn write_array_data(
let buffer = buffer.with_bitset(num_bytes, true);
buffer.into()
}
- Some(buffer) => buffer.bit_slice(array_data.offset(), array_data.len()),
+ Some(buffer) => buffer.inner().sliced(),
};
offset = write_buffer(
diff --git a/arrow-json/src/raw/list_array.rs b/arrow-json/src/raw/list_array.rs
index 91ca4b7275bf..a57f4273369b 100644
--- a/arrow-json/src/raw/list_array.rs
+++ b/arrow-json/src/raw/list_array.rs
@@ -19,6 +19,7 @@ use crate::raw::tape::{Tape, TapeElement};
use crate::raw::{make_decoder, tape_error, ArrayDecoder};
use arrow_array::builder::{BooleanBufferBuilder, BufferBuilder};
use arrow_array::OffsetSizeTrait;
+use arrow_buffer::buffer::{BooleanBuffer, NullBuffer};
use arrow_data::{ArrayData, ArrayDataBuilder};
use arrow_schema::{ArrowError, DataType};
use std::marker::PhantomData;
@@ -62,7 +63,6 @@ impl<O: OffsetSizeTrait> ArrayDecoder for ListArrayDecoder<O> {
let mut offsets = BufferBuilder::<O>::new(pos.len() + 1);
offsets.append(O::from_usize(0).unwrap());
- let mut null_count = 0;
let mut nulls = self
.is_nullable
.then(|| BooleanBufferBuilder::new(pos.len()));
@@ -76,7 +76,6 @@ impl<O: OffsetSizeTrait> ArrayDecoder for ListArrayDecoder<O> {
}
(TapeElement::Null, Some(nulls)) => {
nulls.append(false);
- null_count += 1;
*p + 1
}
(d, _) => return Err(tape_error(d, "[")),
@@ -102,11 +101,13 @@ impl<O: OffsetSizeTrait> ArrayDecoder for ListArrayDecoder<O> {
}
let child_data = self.decoder.decode(tape, &child_pos)?;
+ let nulls = nulls
+ .as_mut()
+ .map(|x| NullBuffer::new(BooleanBuffer::new(x.finish(), 0, pos.len())));
let data = ArrayDataBuilder::new(self.data_type.clone())
.len(pos.len())
- .null_bit_buffer(nulls.as_mut().map(|x| x.finish()))
- .null_count(null_count)
+ .nulls(nulls)
.add_buffer(offsets.finish())
.child_data(vec![child_data]);
diff --git a/arrow-json/src/raw/map_array.rs b/arrow-json/src/raw/map_array.rs
index ac48d8bce1e7..dee142bef6db 100644
--- a/arrow-json/src/raw/map_array.rs
+++ b/arrow-json/src/raw/map_array.rs
@@ -18,6 +18,7 @@
use crate::raw::tape::{Tape, TapeElement};
use crate::raw::{make_decoder, tape_error, ArrayDecoder};
use arrow_array::builder::{BooleanBufferBuilder, BufferBuilder};
+use arrow_buffer::buffer::{BooleanBuffer, NullBuffer};
use arrow_buffer::ArrowNativeType;
use arrow_data::{ArrayData, ArrayDataBuilder};
use arrow_schema::{ArrowError, DataType};
@@ -88,7 +89,6 @@ impl ArrayDecoder for MapArrayDecoder {
let mut key_pos = Vec::with_capacity(pos.len());
let mut value_pos = Vec::with_capacity(pos.len());
- let mut null_count = 0;
let mut nulls = self
.is_nullable
.then(|| BooleanBufferBuilder::new(pos.len()));
@@ -102,7 +102,6 @@ impl ArrayDecoder for MapArrayDecoder {
}
(TapeElement::Null, Some(nulls)) => {
nulls.append(false);
- null_count += 1;
p + 1
}
(d, _) => return Err(tape_error(d, "{")),
@@ -140,11 +139,14 @@ impl ArrayDecoder for MapArrayDecoder {
// Valid by construction
let struct_data = unsafe { struct_data.build_unchecked() };
+ let nulls = nulls
+ .as_mut()
+ .map(|x| NullBuffer::new(BooleanBuffer::new(x.finish(), 0, pos.len())));
+
let builder = ArrayDataBuilder::new(self.data_type.clone())
.len(pos.len())
.buffers(vec![offsets.finish()])
- .null_count(null_count)
- .null_bit_buffer(nulls.as_mut().map(|x| x.finish()))
+ .nulls(nulls)
.child_data(vec![struct_data]);
// Safety:
diff --git a/arrow-json/src/raw/mod.rs b/arrow-json/src/raw/mod.rs
index 595a54c10a9e..a0dbcbd53eaa 100644
--- a/arrow-json/src/raw/mod.rs
+++ b/arrow-json/src/raw/mod.rs
@@ -481,9 +481,10 @@ mod tests {
assert_eq!(batches.len(), 1);
let list = as_list_array(batches[0].column(0).as_ref());
+ assert_eq!(list.len(), 3);
assert_eq!(list.value_offsets(), &[0, 0, 2, 2]);
assert_eq!(list.null_count(), 1);
- assert!(list.is_null(4));
+ assert!(list.is_null(2));
let list_values = as_primitive_array::<Int32Type>(list.values().as_ref());
assert_eq!(list_values.values(), &[5, 6]);
@@ -501,10 +502,15 @@ mod tests {
assert!(b.is_null(2));
let nested_list = as_struct_array(batches[0].column(2).as_ref());
+ assert_eq!(nested_list.len(), 3);
+ assert_eq!(nested_list.null_count(), 1);
+ assert!(nested_list.is_null(2));
+
let list2 = as_list_array(nested_list.column(0).as_ref());
+ assert_eq!(list2.len(), 3);
assert_eq!(list2.null_count(), 1);
assert_eq!(list2.value_offsets(), &[0, 2, 2, 2]);
- assert!(list2.is_null(3));
+ assert!(list2.is_null(2));
let list2_values = as_struct_array(list2.values().as_ref());
diff --git a/arrow-json/src/raw/struct_array.rs b/arrow-json/src/raw/struct_array.rs
index 64ceff22429b..1d0019993426 100644
--- a/arrow-json/src/raw/struct_array.rs
+++ b/arrow-json/src/raw/struct_array.rs
@@ -18,6 +18,7 @@
use crate::raw::tape::{Tape, TapeElement};
use crate::raw::{make_decoder, tape_error, ArrayDecoder};
use arrow_array::builder::BooleanBufferBuilder;
+use arrow_buffer::buffer::{BooleanBuffer, NullBuffer};
use arrow_data::{ArrayData, ArrayDataBuilder};
use arrow_schema::{ArrowError, DataType, Field};
@@ -54,7 +55,6 @@ impl ArrayDecoder for StructArrayDecoder {
let mut child_pos: Vec<_> =
(0..fields.len()).map(|_| vec![0; pos.len()]).collect();
- let mut null_count = 0;
let mut nulls = self
.is_nullable
.then(|| BooleanBufferBuilder::new(pos.len()));
@@ -68,7 +68,6 @@ impl ArrayDecoder for StructArrayDecoder {
}
(TapeElement::Null, Some(nulls)) => {
nulls.append(false);
- null_count += 1;
continue;
}
(d, _) => return Err(tape_error(d, "{")),
@@ -108,10 +107,13 @@ impl ArrayDecoder for StructArrayDecoder {
.iter()
.for_each(|x| assert_eq!(x.len(), pos.len()));
+ let nulls = nulls
+ .as_mut()
+ .map(|x| NullBuffer::new(BooleanBuffer::new(x.finish(), 0, pos.len())));
+
let data = ArrayDataBuilder::new(self.data_type.clone())
.len(pos.len())
- .null_count(null_count)
- .null_bit_buffer(nulls.as_mut().map(|x| x.finish()))
+ .nulls(nulls)
.child_data(child_data);
// Safety
diff --git a/arrow-json/src/reader.rs b/arrow-json/src/reader.rs
index 7df63bf8d662..0ef438e36950 100644
--- a/arrow-json/src/reader.rs
+++ b/arrow-json/src/reader.rs
@@ -2378,7 +2378,7 @@ mod tests {
Buffer::from_slice_ref([0i32, 2, 3, 6, 6, 6, 7])
);
// compare list null buffers
- assert_eq!(read.data().null_buffer(), expected.data().null_buffer());
+ assert_eq!(read.data().nulls(), expected.data().nulls());
// build struct from list
let struct_array = as_struct_array(read.values());
let expected_struct_array = as_struct_array(expected.values());
@@ -2389,8 +2389,8 @@ mod tests {
assert_eq!(1, expected_struct_array.null_count());
// test struct's nulls
assert_eq!(
- struct_array.data().null_buffer(),
- expected_struct_array.data().null_buffer()
+ struct_array.data().nulls(),
+ expected_struct_array.data().nulls()
);
// test struct's fields
let read_b = struct_array.column(0);
diff --git a/arrow-ord/src/comparison.rs b/arrow-ord/src/comparison.rs
index a4f1fdb88091..2702514edc83 100644
--- a/arrow-ord/src/comparison.rs
+++ b/arrow-ord/src/comparison.rs
@@ -104,10 +104,7 @@ pub fn eq_utf8<OffsetSize: OffsetSizeTrait>(
fn utf8_empty<OffsetSize: OffsetSizeTrait, const EQ: bool>(
left: &GenericStringArray<OffsetSize>,
) -> Result<BooleanArray, ArrowError> {
- let null_bit_buffer = left
- .data()
- .null_buffer()
- .map(|b| b.bit_slice(left.offset(), left.len()));
+ let null_bit_buffer = left.data().nulls().map(|b| b.inner().sliced());
let buffer = unsafe {
MutableBuffer::from_trusted_len_iter_bool(left.value_offsets().windows(2).map(
@@ -213,10 +210,7 @@ pub fn eq_bool_scalar(
DataType::Boolean,
len,
None,
- left.data_ref()
- .null_bitmap()
- .as_ref()
- .map(|b| b.buffer().bit_slice(left_offset, len)),
+ left.data().nulls().map(|b| b.inner().sliced()),
0,
vec![values],
vec![],
@@ -1439,10 +1433,7 @@ where
result_remainder.copy_from_slice(remainder_mask_as_bytes);
}
- let null_bit_buffer = left
- .data_ref()
- .null_buffer()
- .map(|b| b.bit_slice(left.offset(), left.len()));
+ let null_bit_buffer = left.data().nulls().map(|b| b.inner().sliced());
// null count is the same as in the input since the right side of the scalar comparison cannot be null
let null_count = left.null_count();
diff --git a/arrow-ord/src/sort.rs b/arrow-ord/src/sort.rs
index c4baa2283885..230eb9390f2f 100644
--- a/arrow-ord/src/sort.rs
+++ b/arrow-ord/src/sort.rs
@@ -675,7 +675,6 @@ fn sort_run_downcasted<R: RunEndIndexType>(
// The function builds a valid run_ends array and hence need not be validated.
ArrayDataBuilder::new(run_array.run_ends().data_type().clone())
.len(new_physical_len)
- .null_count(0)
.add_buffer(new_run_ends_builder.finish())
.build_unchecked()
};
diff --git a/arrow-row/src/list.rs b/arrow-row/src/list.rs
index dcd247be1a7b..833baac7b655 100644
--- a/arrow-row/src/list.rs
+++ b/arrow-row/src/list.rs
@@ -168,8 +168,7 @@ pub unsafe fn decode<O: OffsetSizeTrait>(
let builder = ArrayDataBuilder::new(field.data_type.clone())
.len(rows.len())
- .null_count(canonical.null_count())
- .null_bit_buffer(canonical.data().null_buffer().cloned())
+ .nulls(canonical.data().nulls().cloned())
.add_buffer(offsets.finish())
.add_child_data(child_data);
diff --git a/arrow-select/src/filter.rs b/arrow-select/src/filter.rs
index fde4b41b04cf..d8ea9fceb856 100644
--- a/arrow-select/src/filter.rs
+++ b/arrow-select/src/filter.rs
@@ -153,11 +153,12 @@ pub fn build_filter(filter: &BooleanArray) -> Result<Filter, ArrowError> {
/// Remove null values by do a bitmask AND operation with null bits and the boolean bits.
pub fn prep_null_mask_filter(filter: &BooleanArray) -> BooleanArray {
let array_data = filter.data_ref();
- let null_bitmap = array_data.null_buffer().unwrap();
+ let nulls = array_data.nulls().unwrap();
let mask = filter.values();
let offset = filter.offset();
- let new_mask = buffer_bin_and(mask, offset, null_bitmap, offset, filter.len());
+ let new_mask =
+ buffer_bin_and(mask, offset, nulls.buffer(), nulls.offset(), filter.len());
let array_data = ArrayData::builder(DataType::Boolean)
.len(filter.len())
@@ -410,7 +411,8 @@ fn filter_null_mask(
return None;
}
- let nulls = filter_bits(data.null_buffer()?, data.offset(), predicate);
+ let nulls = data.nulls()?;
+ let nulls = filter_bits(nulls.buffer(), nulls.offset(), predicate);
// The filtered `nulls` has a length of `predicate.count` bits and
// therefore the null count is this minus the number of valid bits
let null_count = predicate.count - nulls.count_set_bits_offset(0, predicate.count);
diff --git a/arrow-select/src/nullif.rs b/arrow-select/src/nullif.rs
index 34876e948b9d..4b052ce004cc 100644
--- a/arrow-select/src/nullif.rs
+++ b/arrow-select/src/nullif.rs
@@ -53,13 +53,13 @@ pub fn nullif(left: &dyn Array, right: &BooleanArray) -> Result<ArrayRef, ArrowE
// OR left null bitmap & !(right_values & right_bitmap)
// Compute right_values & right_bitmap
- let (right, r_offset) = match right_data.null_buffer() {
- Some(buffer) => (
+ let (right, r_offset) = match right_data.nulls() {
+ Some(nulls) => (
buffer_bin_and(
&right_data.buffers()[0],
right_data.offset(),
- buffer,
- right_data.offset(),
+ nulls.buffer(),
+ nulls.offset(),
len,
),
0,
@@ -69,15 +69,21 @@ pub fn nullif(left: &dyn Array, right: &BooleanArray) -> Result<ArrayRef, ArrowE
// Compute left null bitmap & !right
- let (combined, null_count) = match left_data.null_buffer() {
+ let (combined, null_count) = match left_data.nulls() {
Some(left) => {
let mut valid_count = 0;
- let b =
- bitwise_bin_op_helper(left, l_offset, &right, r_offset, len, |l, r| {
+ let b = bitwise_bin_op_helper(
+ left.buffer(),
+ left.offset(),
+ &right,
+ r_offset,
+ len,
+ |l, r| {
let t = l & !r;
valid_count += t.count_ones() as usize;
t
- });
+ },
+ );
(b, len - valid_count)
}
None => {
diff --git a/arrow-select/src/take.rs b/arrow-select/src/take.rs
index 6436dc0d56e4..771a7eeb5c5a 100644
--- a/arrow-select/src/take.rs
+++ b/arrow-select/src/take.rs
@@ -340,12 +340,7 @@ where
// Soundness: `slice.map` is `TrustedLen`.
let buffer = unsafe { Buffer::try_from_trusted_len_iter(values)? };
- Ok((
- buffer,
- indices_data
- .null_buffer()
- .map(|b| b.bit_slice(indices_data.offset(), indices.len())),
- ))
+ Ok((buffer, indices_data.nulls().map(|b| b.inner().sliced())))
}
// take implementation when both values and indices contain nulls
@@ -530,14 +525,11 @@ where
IndexType::Native: ToPrimitive,
{
let val_buf = take_bits(values.values(), values.offset(), indices)?;
- let null_buf = match values.data().null_buffer() {
- Some(buf) if values.null_count() > 0 => {
- Some(take_bits(buf, values.offset(), indices)?)
+ let null_buf = match values.data().nulls() {
+ Some(nulls) if nulls.null_count() > 0 => {
+ Some(take_bits(nulls.buffer(), nulls.offset(), indices)?)
}
- _ => indices
- .data()
- .null_buffer()
- .map(|b| b.bit_slice(indices.offset(), indices.len())),
+ _ => indices.data().nulls().map(|b| b.inner().sliced()),
};
let data = unsafe {
@@ -626,7 +618,7 @@ where
}
*offset = length_so_far;
}
- nulls = indices.data_ref().null_buffer().cloned();
+ nulls = indices.data().nulls().map(|b| b.inner().sliced());
} else {
let num_bytes = bit_util::ceil(data_len, 8);
@@ -791,7 +783,7 @@ where
values.data_type().clone(),
new_keys.len(),
Some(new_keys_data.null_count()),
- new_keys_data.null_buffer().cloned(),
+ new_keys_data.nulls().map(|b| b.inner().sliced()),
0,
new_keys_data.buffers().to_vec(),
values.data().child_data().to_vec(),
@@ -1639,7 +1631,7 @@ mod tests {
let expected_list_data = ArrayData::builder(list_data_type)
.len(5)
// null buffer remains the same as only the indices have nulls
- .null_bit_buffer(index.data().null_buffer().cloned())
+ .nulls(index.data().nulls().cloned())
.add_buffer(expected_offsets)
.add_child_data(expected_data)
.build()
@@ -1713,7 +1705,7 @@ mod tests {
let expected_list_data = ArrayData::builder(list_data_type)
.len(5)
// null buffer remains the same as only the indices have nulls
- .null_bit_buffer(index.data().null_buffer().cloned())
+ .nulls(index.data().nulls().cloned())
.add_buffer(expected_offsets)
.add_child_data(expected_data)
.build()
diff --git a/arrow-string/src/length.rs b/arrow-string/src/length.rs
index 9651bef2771f..cd588fe01c6b 100644
--- a/arrow-string/src/length.rs
+++ b/arrow-string/src/length.rs
@@ -37,10 +37,7 @@ macro_rules! unary_offsets {
// `values` come from a slice iterator with a known size.
let buffer = unsafe { Buffer::from_trusted_len_iter(lengths) };
- let null_bit_buffer = $array
- .data_ref()
- .null_buffer()
- .map(|b| b.bit_slice($array.offset(), $array.len()));
+ let null_bit_buffer = $array.data().nulls().map(|b| b.inner().sliced());
let data = unsafe {
ArrayData::new_unchecked(
diff --git a/arrow-string/src/regexp.rs b/arrow-string/src/regexp.rs
index 4072d8ba07e5..bf6e60cfeaaa 100644
--- a/arrow-string/src/regexp.rs
+++ b/arrow-string/src/regexp.rs
@@ -122,7 +122,7 @@ pub fn regexp_is_match_utf8_scalar<OffsetSize: OffsetSizeTrait>(
regex: &str,
flag: Option<&str>,
) -> Result<BooleanArray, ArrowError> {
- let null_bit_buffer = array.data().null_buffer().cloned();
+ let null_bit_buffer = array.data().nulls().map(|x| x.inner().sliced());
let mut result = BooleanBufferBuilder::new(array.len());
let pattern = match flag {
diff --git a/arrow-string/src/substring.rs b/arrow-string/src/substring.rs
index 7d04304771a6..a59a54d7e6e4 100644
--- a/arrow-string/src/substring.rs
+++ b/arrow-string/src/substring.rs
@@ -210,10 +210,7 @@ pub fn substring_by_char<OffsetSize: OffsetSizeTrait>(
GenericStringArray::<OffsetSize>::DATA_TYPE,
array.len(),
None,
- array
- .data_ref()
- .null_buffer()
- .map(|b| b.bit_slice(array.offset(), array.len())),
+ array.data().nulls().map(|b| b.inner().sliced()),
0,
vec![new_offsets.finish(), vals.finish()],
vec![],
@@ -297,10 +294,7 @@ fn binary_substring<OffsetSize: OffsetSizeTrait>(
GenericBinaryArray::<OffsetSize>::DATA_TYPE,
array.len(),
None,
- array
- .data_ref()
- .null_buffer()
- .map(|b| b.bit_slice(array.offset(), array.len())),
+ array.data().nulls().map(|b| b.inner().sliced()),
0,
vec![Buffer::from_slice_ref(&new_offsets), new_values.into()],
vec![],
@@ -345,10 +339,7 @@ fn fixed_size_binary_substring(
DataType::FixedSizeBinary(new_len),
num_of_elements,
None,
- array
- .data_ref()
- .null_buffer()
- .map(|b| b.bit_slice(array.offset(), num_of_elements)),
+ array.data().nulls().map(|b| b.inner().sliced()),
0,
vec![new_values.into()],
vec![],
@@ -427,10 +418,7 @@ fn utf8_substring<OffsetSize: OffsetSizeTrait>(
GenericStringArray::<OffsetSize>::DATA_TYPE,
array.len(),
None,
- array
- .data_ref()
- .null_buffer()
- .map(|b| b.bit_slice(array.offset(), array.len())),
+ array.data().nulls().map(|b| b.inner().sliced()),
0,
vec![Buffer::from_slice_ref(&new_offsets), new_values.into()],
vec![],
diff --git a/arrow/src/lib.rs b/arrow/src/lib.rs
index f7ce24a97d2a..3d1bced298c9 100644
--- a/arrow/src/lib.rs
+++ b/arrow/src/lib.rs
@@ -306,10 +306,6 @@ pub use arrow_array::{downcast_dictionary_array, downcast_primitive_array};
pub use arrow_buffer::{alloc, buffer};
-pub mod bitmap {
- pub use arrow_data::Bitmap;
-}
-
pub mod array;
pub mod compute;
#[cfg(feature = "csv")]
diff --git a/parquet/src/arrow/arrow_writer/levels.rs b/parquet/src/arrow/arrow_writer/levels.rs
index 11ed35263e6a..de4cba4adb33 100644
--- a/parquet/src/arrow/arrow_writer/levels.rs
+++ b/parquet/src/arrow/arrow_writer/levels.rs
@@ -270,12 +270,12 @@ impl LevelInfoBuilder {
})
};
- match list_data.null_bitmap() {
+ match list_data.nulls() {
Some(nulls) => {
- let null_offset = list_data.offset() + range.start;
+ let null_offset = range.start;
// TODO: Faster bitmask iteration (#1757)
for (idx, w) in offsets.windows(2).enumerate() {
- let is_valid = nulls.is_set(idx + null_offset);
+ let is_valid = nulls.is_valid(idx + null_offset);
let start_idx = w[0].as_usize();
let end_idx = w[1].as_usize();
if !is_valid {
@@ -329,15 +329,14 @@ impl LevelInfoBuilder {
}
};
- match array.data().null_bitmap() {
+ match array.data().nulls() {
Some(validity) => {
- let null_offset = array.data().offset();
let mut last_non_null_idx = None;
let mut last_null_idx = None;
// TODO: Faster bitmask iteration (#1757)
for i in range.clone() {
- match validity.is_set(i + null_offset) {
+ match validity.is_valid(i) {
true => {
if let Some(last_idx) = last_null_idx.take() {
write_null(children, last_idx..i)
@@ -379,12 +378,11 @@ impl LevelInfoBuilder {
def_levels.reserve(len);
info.non_null_indices.reserve(len);
- match array.data().null_bitmap() {
+ match array.data().nulls() {
Some(nulls) => {
- let nulls_offset = array.data().offset();
// TODO: Faster bitmask iteration (#1757)
for i in range {
- match nulls.is_set(i + nulls_offset) {
+ match nulls.is_valid(i) {
true => {
def_levels.push(info.max_def_level);
info.non_null_indices.push(i)
diff --git a/parquet/src/arrow/record_reader/definition_levels.rs b/parquet/src/arrow/record_reader/definition_levels.rs
index 84b7ab94cebb..7c27a365fc28 100644
--- a/parquet/src/arrow/record_reader/definition_levels.rs
+++ b/parquet/src/arrow/record_reader/definition_levels.rs
@@ -20,7 +20,6 @@ use std::ops::Range;
use arrow_array::builder::BooleanBufferBuilder;
use arrow_buffer::bit_chunk_iterator::UnalignedBitChunk;
use arrow_buffer::Buffer;
-use arrow_data::Bitmap;
use crate::arrow::buffer::bit_util::count_set_bits;
use crate::arrow::record_reader::buffer::BufferQueue;
@@ -105,7 +104,7 @@ impl DefinitionLevelBuffer {
}
/// Split `len` levels out of `self`
- pub fn split_bitmask(&mut self, len: usize) -> Bitmap {
+ pub fn split_bitmask(&mut self, len: usize) -> Buffer {
let old_builder = match &mut self.inner {
BufferInner::Full { nulls, .. } => nulls,
BufferInner::Mask { nulls } => nulls,
@@ -124,7 +123,7 @@ impl DefinitionLevelBuffer {
// Swap into self
self.len = new_builder.len();
- Bitmap::from(std::mem::replace(old_builder, new_builder).finish())
+ std::mem::replace(old_builder, new_builder).finish()
}
pub fn nulls(&self) -> &BooleanBufferBuilder {
@@ -516,7 +515,7 @@ mod tests {
let bitmap = buffer.split_bitmask(19);
// Should have split off 19 records leaving, 81 behind
- assert_eq!(bitmap.bit_len(), 3 * 8); // Note: bitmask only tracks bytes not bits
+ assert_eq!(bitmap.len(), 3); // Note: bitmask only tracks bytes not bits
assert_eq!(buffer.nulls().len(), 81);
}
}
diff --git a/parquet/src/arrow/record_reader/mod.rs b/parquet/src/arrow/record_reader/mod.rs
index ef17b8d0e6f4..e47bdee1c38a 100644
--- a/parquet/src/arrow/record_reader/mod.rs
+++ b/parquet/src/arrow/record_reader/mod.rs
@@ -18,7 +18,6 @@
use std::cmp::{max, min};
use arrow_buffer::Buffer;
-use arrow_data::Bitmap;
use crate::arrow::record_reader::{
buffer::{BufferQueue, ScalarBuffer, ValuesBuffer},
@@ -271,7 +270,7 @@ where
/// Returns currently stored null bitmap data.
/// The side effect is similar to `consume_def_levels`.
pub fn consume_bitmap_buffer(&mut self) -> Option<Buffer> {
- self.consume_bitmap().map(|b| b.into_buffer())
+ self.consume_bitmap()
}
/// Reset state of record reader.
@@ -284,7 +283,7 @@ where
}
/// Returns bitmap data.
- pub fn consume_bitmap(&mut self) -> Option<Bitmap> {
+ pub fn consume_bitmap(&mut self) -> Option<Buffer> {
self.def_levels
.as_mut()
.map(|levels| levels.split_bitmask(self.num_values))
@@ -409,7 +408,6 @@ fn packed_null_mask(descr: &ColumnDescPtr) -> bool {
mod tests {
use std::sync::Arc;
- use arrow::bitmap::Bitmap;
use arrow::buffer::Buffer;
use arrow_array::builder::{Int16BufferBuilder, Int32BufferBuilder};
@@ -584,8 +582,7 @@ mod tests {
// Verify bitmap
let expected_valid = &[false, true, false, true, true, false, true];
let expected_buffer = Buffer::from_iter(expected_valid.iter().cloned());
- let expected_bitmap = Bitmap::from(expected_buffer);
- assert_eq!(Some(expected_bitmap), record_reader.consume_bitmap());
+ assert_eq!(Some(expected_buffer), record_reader.consume_bitmap());
// Verify result record data
let actual = record_reader.consume_record_data();
@@ -695,8 +692,7 @@ mod tests {
// Verify bitmap
let expected_valid = &[true, false, false, true, true, true, true, true, true];
let expected_buffer = Buffer::from_iter(expected_valid.iter().cloned());
- let expected_bitmap = Bitmap::from(expected_buffer);
- assert_eq!(Some(expected_bitmap), record_reader.consume_bitmap());
+ assert_eq!(Some(expected_buffer), record_reader.consume_bitmap());
// Verify result record data
let actual = record_reader.consume_record_data();
@@ -966,8 +962,7 @@ mod tests {
// Verify bitmap
let expected_valid = &[false, true, true];
let expected_buffer = Buffer::from_iter(expected_valid.iter().cloned());
- let expected_bitmap = Bitmap::from(expected_buffer);
- assert_eq!(Some(expected_bitmap), record_reader.consume_bitmap());
+ assert_eq!(Some(expected_buffer), record_reader.consume_bitmap());
// Verify result record data
let actual = record_reader.consume_record_data();
|
diff --git a/arrow/tests/array_validation.rs b/arrow/tests/array_validation.rs
index 3cdec46b59a0..7e45ee7afcda 100644
--- a/arrow/tests/array_validation.rs
+++ b/arrow/tests/array_validation.rs
@@ -943,17 +943,7 @@ fn test_try_new_sliced_struct() {
let struct_array_slice = struct_array.slice(1, 3);
let struct_array_data = struct_array_slice.data();
- let cloned_data = ArrayData::try_new(
- struct_array_slice.data_type().clone(),
- struct_array_slice.len(),
- struct_array_data.null_buffer().cloned(),
- struct_array_slice.offset(),
- struct_array_data.buffers().to_vec(),
- struct_array_data.child_data().to_vec(),
- )
- .unwrap();
- let cloned = make_array(cloned_data);
-
+ let cloned = make_array(struct_array_data.clone());
assert_eq!(&struct_array_slice, &cloned);
}
|
Use NullBuffer in ArrayData
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
<!--
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
(This section helps Arrow developers understand the context and *why* for this feature, in addition to the *what*)
-->
https://github.com/apache/arrow-rs/pull/3749 added a new `NullBuffer` abstraction, as part of #1176 it is necessary to switch `ArrayData` over to using it.
A complicating factor is that `ArrayData::offset` currently applies to both the values and the null buffer, this leads to two options:
1. Continue to provide `ArrayData::null_buffer` returning the underlying `Buffer` relying on clients to apply the offset
2. Change the return type of `ArrayData::null_buffer` to `NullBuffer` breaking downstreams
**Describe the solution you'd like**
<!--
A clear and concise description of what you want to happen.
-->
Option 2. puts us in a better place for #1176 as it leaves the offset as just applying to the array values, allowing for the null buffer to have a different offset. It also leads to a better API for users.
**Describe alternatives you've considered**
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
|
2023-02-28T19:13:58Z
|
34.0
|
495682aa72ffe92bbd0d6d8d93e0c00b5483ff7d
|
|
apache/arrow-rs
| 3,757
|
apache__arrow-rs-3757
|
[
"3755"
] |
9699e1df7c7e0b83c8ec8be6678ee17d77a17f47
|
diff --git a/CHANGELOG-old.md b/CHANGELOG-old.md
index 9ac8cb530456..9b9df494efb2 100644
--- a/CHANGELOG-old.md
+++ b/CHANGELOG-old.md
@@ -19,6 +19,79 @@
# Historical Changelog
+## [33.0.0](https://github.com/apache/arrow-rs/tree/33.0.0) (2023-02-10)
+
+[Full Changelog](https://github.com/apache/arrow-rs/compare/32.0.0...33.0.0)
+
+**Breaking changes:**
+
+- Use ArrayFormatter in Cast Kernel [\#3668](https://github.com/apache/arrow-rs/pull/3668) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Use dyn Array in cast kernels [\#3667](https://github.com/apache/arrow-rs/pull/3667) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Return references from FixedSizeListArray and MapArray [\#3652](https://github.com/apache/arrow-rs/pull/3652) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Lazy array display \(\#3638\) [\#3647](https://github.com/apache/arrow-rs/pull/3647) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Use array\_value\_to\_string in arrow-csv [\#3514](https://github.com/apache/arrow-rs/pull/3514) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([JayjeetAtGithub](https://github.com/JayjeetAtGithub))
+
+**Implemented enhancements:**
+
+- Support UTF8 cast to Timestamp with timezone [\#3664](https://github.com/apache/arrow-rs/issues/3664)
+- Add modulus\_dyn and modulus\_scalar\_dyn [\#3648](https://github.com/apache/arrow-rs/issues/3648) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- A trait for append\_value and append\_null on ArrayBuilders [\#3644](https://github.com/apache/arrow-rs/issues/3644)
+- Improve error messge "batches\[0\] schema is different with argument schema" [\#3628](https://github.com/apache/arrow-rs/issues/3628) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- Specified version of helper function to cast binary to string [\#3623](https://github.com/apache/arrow-rs/issues/3623) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- Casting generic binary to generic string [\#3606](https://github.com/apache/arrow-rs/issues/3606) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- Use `array_value_to_string` in `arrow-csv` [\#3483](https://github.com/apache/arrow-rs/issues/3483) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+
+**Fixed bugs:**
+
+- ArrowArray::try\_from\_raw Misleading Signature [\#3684](https://github.com/apache/arrow-rs/issues/3684) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- PyArrowConvert Leaks Memory [\#3683](https://github.com/apache/arrow-rs/issues/3683) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- Arrow-csv reader cannot produce RecordBatch even if the bytes are necessary [\#3674](https://github.com/apache/arrow-rs/issues/3674)
+- FFI Fails to Account For Offsets [\#3671](https://github.com/apache/arrow-rs/issues/3671) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- Regression in CSV reader error handling [\#3656](https://github.com/apache/arrow-rs/issues/3656) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- UnionArray Child and Value Fail to Account for non-contiguous Type IDs [\#3653](https://github.com/apache/arrow-rs/issues/3653) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- Panic when accessing RecordBatch from pyarrow [\#3646](https://github.com/apache/arrow-rs/issues/3646) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- Multiplication for decimals is incorrect [\#3645](https://github.com/apache/arrow-rs/issues/3645)
+- Inconsistent output between pretty print and CSV writer for Arrow [\#3513](https://github.com/apache/arrow-rs/issues/3513) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+
+**Closed issues:**
+
+- Release 33.0.0 of arrow/arrow-flight/parquet/parquet-derive \(next release after 32.0.0\) [\#3682](https://github.com/apache/arrow-rs/issues/3682)
+- Release `32.0.0` of `arrow`/`arrow-flight`/`parquet`/`parquet-derive` \(next release after `31.0.0`\) [\#3584](https://github.com/apache/arrow-rs/issues/3584) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)]
+
+**Merged pull requests:**
+
+- Move FFI to sub-crates [\#3687](https://github.com/apache/arrow-rs/pull/3687) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Update to 33.0.0 and update changelog [\#3686](https://github.com/apache/arrow-rs/pull/3686) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([iajoiner](https://github.com/iajoiner))
+- Cleanup FFI interface \(\#3684\) \(\#3683\) [\#3685](https://github.com/apache/arrow-rs/pull/3685) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- fix: take\_run benchmark parameter [\#3679](https://github.com/apache/arrow-rs/pull/3679) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([askoa](https://github.com/askoa))
+- Minor: Add some examples to Date\*Array and Time\*Array [\#3678](https://github.com/apache/arrow-rs/pull/3678) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([alamb](https://github.com/alamb))
+- Add CSV Decoder::capacity \(\#3674\) [\#3677](https://github.com/apache/arrow-rs/pull/3677) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Add ArrayData::new\_null and DataType::primitive\_width [\#3676](https://github.com/apache/arrow-rs/pull/3676) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Fix FFI which fails to account for offsets [\#3675](https://github.com/apache/arrow-rs/pull/3675) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([viirya](https://github.com/viirya))
+- Support UTF8 cast to Timestamp with timezone [\#3673](https://github.com/apache/arrow-rs/pull/3673) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([comphead](https://github.com/comphead))
+- Fix Date64Array docs [\#3670](https://github.com/apache/arrow-rs/pull/3670) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Update proc-macro2 requirement from =1.0.50 to =1.0.51 [\#3669](https://github.com/apache/arrow-rs/pull/3669) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([dependabot[bot]](https://github.com/apps/dependabot))
+- Add timezone accessor for Timestamp\*Array [\#3666](https://github.com/apache/arrow-rs/pull/3666) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Faster timezone cast [\#3665](https://github.com/apache/arrow-rs/pull/3665) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- feat + fix: IPC support for run encoded array. [\#3662](https://github.com/apache/arrow-rs/pull/3662) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([askoa](https://github.com/askoa))
+- Implement std::fmt::Write for StringBuilder \(\#3638\) [\#3659](https://github.com/apache/arrow-rs/pull/3659) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Include line and field number in CSV UTF-8 error \(\#3656\) [\#3657](https://github.com/apache/arrow-rs/pull/3657) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Handle non-contiguous type\_ids in UnionArray \(\#3653\) [\#3654](https://github.com/apache/arrow-rs/pull/3654) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Add modulus\_dyn and modulus\_scalar\_dyn [\#3649](https://github.com/apache/arrow-rs/pull/3649) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([viirya](https://github.com/viirya))
+- Improve error messge with detailed schema [\#3637](https://github.com/apache/arrow-rs/pull/3637) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([Veeupup](https://github.com/Veeupup))
+- Add limit to ArrowReaderBuilder to push limit down to parquet reader [\#3633](https://github.com/apache/arrow-rs/pull/3633) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([thinkharderdev](https://github.com/thinkharderdev))
+- chore: delete wrong comment and refactor set\_metadata in `Field` [\#3630](https://github.com/apache/arrow-rs/pull/3630) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([chunshao90](https://github.com/chunshao90))
+- Fix typo in comment [\#3627](https://github.com/apache/arrow-rs/pull/3627) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([kjschiroo](https://github.com/kjschiroo))
+- Minor: Update doc strings about Page Index / Column Index [\#3625](https://github.com/apache/arrow-rs/pull/3625) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([alamb](https://github.com/alamb))
+- Specified version of helper function to cast binary to string [\#3624](https://github.com/apache/arrow-rs/pull/3624) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([viirya](https://github.com/viirya))
+- feat: take kernel for RunArray [\#3622](https://github.com/apache/arrow-rs/pull/3622) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([askoa](https://github.com/askoa))
+- Remove BitSliceIterator specialization from try\_for\_each\_valid\_idx [\#3621](https://github.com/apache/arrow-rs/pull/3621) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Reduce PrimitiveArray::try\_unary codegen [\#3619](https://github.com/apache/arrow-rs/pull/3619) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Reduce Dictionary Builder Codegen [\#3616](https://github.com/apache/arrow-rs/pull/3616) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Minor: Add test for dictionary encoding of batches [\#3608](https://github.com/apache/arrow-rs/pull/3608) [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([alamb](https://github.com/alamb))
+- Casting generic binary to generic string [\#3607](https://github.com/apache/arrow-rs/pull/3607) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([viirya](https://github.com/viirya))
+- Add ArrayAccessor, Iterator, Extend and benchmarks for RunArray [\#3603](https://github.com/apache/arrow-rs/pull/3603) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([askoa](https://github.com/askoa))
+
## [32.0.0](https://github.com/apache/arrow-rs/tree/32.0.0) (2023-01-27)
[Full Changelog](https://github.com/apache/arrow-rs/compare/31.0.0...32.0.0)
@@ -94,6 +167,7 @@
- No panic on timestamp buffer overflow [\#3519](https://github.com/apache/arrow-rs/pull/3519) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([comphead](https://github.com/comphead))
- Support casting from binary to dictionary of binary [\#3482](https://github.com/apache/arrow-rs/pull/3482) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([viirya](https://github.com/viirya))
- Add Raw JSON Reader \(~2.5x faster\) [\#3479](https://github.com/apache/arrow-rs/pull/3479) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+
## [31.0.0](https://github.com/apache/arrow-rs/tree/31.0.0) (2023-01-13)
[Full Changelog](https://github.com/apache/arrow-rs/compare/30.0.1...31.0.0)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 66cc9104b0ee..0a25d8d8ff7e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,78 +19,63 @@
# Changelog
-## [33.0.0](https://github.com/apache/arrow-rs/tree/33.0.0) (2023-02-10)
+## [34.0.0](https://github.com/apache/arrow-rs/tree/34.0.0) (2023-02-23)
-[Full Changelog](https://github.com/apache/arrow-rs/compare/32.0.0...33.0.0)
+[Full Changelog](https://github.com/apache/arrow-rs/compare/33.0.0...34.0.0)
**Breaking changes:**
-- Use ArrayFormatter in Cast Kernel [\#3668](https://github.com/apache/arrow-rs/pull/3668) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Use dyn Array in cast kernels [\#3667](https://github.com/apache/arrow-rs/pull/3667) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Return references from FixedSizeListArray and MapArray [\#3652](https://github.com/apache/arrow-rs/pull/3652) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Lazy array display \(\#3638\) [\#3647](https://github.com/apache/arrow-rs/pull/3647) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Use array\_value\_to\_string in arrow-csv [\#3514](https://github.com/apache/arrow-rs/pull/3514) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([JayjeetAtGithub](https://github.com/JayjeetAtGithub))
+- Infer 2020-03-19 00:00:00 as timestamp not Date64 in CSV \(\#3744\) [\#3746](https://github.com/apache/arrow-rs/pull/3746) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Implement fallible streams for `FlightClient::do_put` [\#3464](https://github.com/apache/arrow-rs/pull/3464) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([alamb](https://github.com/alamb))
**Implemented enhancements:**
-- Support UTF8 cast to Timestamp with timezone [\#3664](https://github.com/apache/arrow-rs/issues/3664)
-- Add modulus\_dyn and modulus\_scalar\_dyn [\#3648](https://github.com/apache/arrow-rs/issues/3648) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
-- A trait for append\_value and append\_null on ArrayBuilders [\#3644](https://github.com/apache/arrow-rs/issues/3644)
-- Improve error messge "batches\[0\] schema is different with argument schema" [\#3628](https://github.com/apache/arrow-rs/issues/3628) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
-- Specified version of helper function to cast binary to string [\#3623](https://github.com/apache/arrow-rs/issues/3623) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
-- Casting generic binary to generic string [\#3606](https://github.com/apache/arrow-rs/issues/3606) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
-- Use `array_value_to_string` in `arrow-csv` [\#3483](https://github.com/apache/arrow-rs/issues/3483) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- Add datatime/interval/duration into comparison kernels [\#3729](https://github.com/apache/arrow-rs/issues/3729)
+- ! \(not\) operator overload for SortOptions [\#3726](https://github.com/apache/arrow-rs/issues/3726)
+- parquet: convert Bytes to ByteArray directly [\#3719](https://github.com/apache/arrow-rs/issues/3719)
+- Implement simple RecordBatchReader [\#3704](https://github.com/apache/arrow-rs/issues/3704)
+- Is possible to implement GenericListArray::from\_iter ? [\#3702](https://github.com/apache/arrow-rs/issues/3702)
+- `take_run` improvements [\#3701](https://github.com/apache/arrow-rs/issues/3701)
+- object\_store: support azure cli credential [\#3697](https://github.com/apache/arrow-rs/issues/3697)
+- Support `as_mut_any` in Array trait [\#3655](https://github.com/apache/arrow-rs/issues/3655)
+- `Array` --\> `Display` formatter that supports more options and is configurable [\#3638](https://github.com/apache/arrow-rs/issues/3638) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- arrow-csv: support decimal256 [\#3474](https://github.com/apache/arrow-rs/issues/3474)
+- Skip the wrong JSON line. [\#3392](https://github.com/apache/arrow-rs/issues/3392)
**Fixed bugs:**
-- ArrowArray::try\_from\_raw Misleading Signature [\#3684](https://github.com/apache/arrow-rs/issues/3684) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
-- PyArrowConvert Leaks Memory [\#3683](https://github.com/apache/arrow-rs/issues/3683) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
-- Arrow-csv reader cannot produce RecordBatch even if the bytes are necessary [\#3674](https://github.com/apache/arrow-rs/issues/3674)
-- FFI Fails to Account For Offsets [\#3671](https://github.com/apache/arrow-rs/issues/3671) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
-- Regression in CSV reader error handling [\#3656](https://github.com/apache/arrow-rs/issues/3656) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
-- UnionArray Child and Value Fail to Account for non-contiguous Type IDs [\#3653](https://github.com/apache/arrow-rs/issues/3653) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
-- Panic when accessing RecordBatch from pyarrow [\#3646](https://github.com/apache/arrow-rs/issues/3646) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
-- Multiplication for decimals is incorrect [\#3645](https://github.com/apache/arrow-rs/issues/3645)
-- Inconsistent output between pretty print and CSV writer for Arrow [\#3513](https://github.com/apache/arrow-rs/issues/3513) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- CSV reader infers Date64 type for fields like "2020-03-19 00:00:00" that it can't parse to Date64 [\#3744](https://github.com/apache/arrow-rs/issues/3744)
+- object\_store: bearer token is azure is used like access key [\#3696](https://github.com/apache/arrow-rs/issues/3696)
**Closed issues:**
-- Release 33.0.0 of arrow/arrow-flight/parquet/parquet-derive \(next release after 32.0.0\) [\#3682](https://github.com/apache/arrow-rs/issues/3682)
-- Release `32.0.0` of `arrow`/`arrow-flight`/`parquet`/`parquet-derive` \(next release after `31.0.0`\) [\#3584](https://github.com/apache/arrow-rs/issues/3584) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)]
+- Should we write a "arrow-rs" update blog post? [\#3565](https://github.com/apache/arrow-rs/issues/3565)
**Merged pull requests:**
-- Move FFI to sub-crates [\#3687](https://github.com/apache/arrow-rs/pull/3687) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Update to 33.0.0 and update changelog [\#3686](https://github.com/apache/arrow-rs/pull/3686) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([iajoiner](https://github.com/iajoiner))
-- Cleanup FFI interface \(\#3684\) \(\#3683\) [\#3685](https://github.com/apache/arrow-rs/pull/3685) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- fix: take\_run benchmark parameter [\#3679](https://github.com/apache/arrow-rs/pull/3679) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([askoa](https://github.com/askoa))
-- Minor: Add some examples to Date\*Array and Time\*Array [\#3678](https://github.com/apache/arrow-rs/pull/3678) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([alamb](https://github.com/alamb))
-- Add CSV Decoder::capacity \(\#3674\) [\#3677](https://github.com/apache/arrow-rs/pull/3677) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Add ArrayData::new\_null and DataType::primitive\_width [\#3676](https://github.com/apache/arrow-rs/pull/3676) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Fix FFI which fails to account for offsets [\#3675](https://github.com/apache/arrow-rs/pull/3675) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([viirya](https://github.com/viirya))
-- Support UTF8 cast to Timestamp with timezone [\#3673](https://github.com/apache/arrow-rs/pull/3673) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([comphead](https://github.com/comphead))
-- Fix Date64Array docs [\#3670](https://github.com/apache/arrow-rs/pull/3670) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Update proc-macro2 requirement from =1.0.50 to =1.0.51 [\#3669](https://github.com/apache/arrow-rs/pull/3669) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([dependabot[bot]](https://github.com/apps/dependabot))
-- Add timezone accessor for Timestamp\*Array [\#3666](https://github.com/apache/arrow-rs/pull/3666) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Faster timezone cast [\#3665](https://github.com/apache/arrow-rs/pull/3665) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- feat + fix: IPC support for run encoded array. [\#3662](https://github.com/apache/arrow-rs/pull/3662) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([askoa](https://github.com/askoa))
-- Implement std::fmt::Write for StringBuilder \(\#3638\) [\#3659](https://github.com/apache/arrow-rs/pull/3659) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Include line and field number in CSV UTF-8 error \(\#3656\) [\#3657](https://github.com/apache/arrow-rs/pull/3657) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Handle non-contiguous type\_ids in UnionArray \(\#3653\) [\#3654](https://github.com/apache/arrow-rs/pull/3654) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Add modulus\_dyn and modulus\_scalar\_dyn [\#3649](https://github.com/apache/arrow-rs/pull/3649) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([viirya](https://github.com/viirya))
-- Improve error messge with detailed schema [\#3637](https://github.com/apache/arrow-rs/pull/3637) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([Veeupup](https://github.com/Veeupup))
-- Add limit to ArrowReaderBuilder to push limit down to parquet reader [\#3633](https://github.com/apache/arrow-rs/pull/3633) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([thinkharderdev](https://github.com/thinkharderdev))
-- chore: delete wrong comment and refactor set\_metadata in `Field` [\#3630](https://github.com/apache/arrow-rs/pull/3630) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([chunshao90](https://github.com/chunshao90))
-- Fix typo in comment [\#3627](https://github.com/apache/arrow-rs/pull/3627) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([kjschiroo](https://github.com/kjschiroo))
-- Minor: Update doc strings about Page Index / Column Index [\#3625](https://github.com/apache/arrow-rs/pull/3625) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([alamb](https://github.com/alamb))
-- Specified version of helper function to cast binary to string [\#3624](https://github.com/apache/arrow-rs/pull/3624) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([viirya](https://github.com/viirya))
-- feat: take kernel for RunArray [\#3622](https://github.com/apache/arrow-rs/pull/3622) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([askoa](https://github.com/askoa))
-- Remove BitSliceIterator specialization from try\_for\_each\_valid\_idx [\#3621](https://github.com/apache/arrow-rs/pull/3621) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Reduce PrimitiveArray::try\_unary codegen [\#3619](https://github.com/apache/arrow-rs/pull/3619) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Reduce Dictionary Builder Codegen [\#3616](https://github.com/apache/arrow-rs/pull/3616) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Minor: Add test for dictionary encoding of batches [\#3608](https://github.com/apache/arrow-rs/pull/3608) [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([alamb](https://github.com/alamb))
-- Casting generic binary to generic string [\#3607](https://github.com/apache/arrow-rs/pull/3607) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([viirya](https://github.com/viirya))
-- Add ArrayAccessor, Iterator, Extend and benchmarks for RunArray [\#3603](https://github.com/apache/arrow-rs/pull/3603) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([askoa](https://github.com/askoa))
+- Update prost-build requirement from =0.11.6 to =0.11.7 [\#3753](https://github.com/apache/arrow-rs/pull/3753) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([dependabot[bot]](https://github.com/apps/dependabot))
+- Use Typed Buffers in Arrays \(\#1811\) \(\#1176\) [\#3743](https://github.com/apache/arrow-rs/pull/3743) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Cleanup arithmetic kernel type constraints [\#3739](https://github.com/apache/arrow-rs/pull/3739) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Make dictionary kernels optional for comparison benchmark [\#3738](https://github.com/apache/arrow-rs/pull/3738) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Support String Coercion in Raw JSON Reader [\#3736](https://github.com/apache/arrow-rs/pull/3736) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([rguerreiromsft](https://github.com/rguerreiromsft))
+- replace for loop by try\_for\_each [\#3734](https://github.com/apache/arrow-rs/pull/3734) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([suxiaogang223](https://github.com/suxiaogang223))
+- feat: implement generic record batch reader [\#3733](https://github.com/apache/arrow-rs/pull/3733) ([wjones127](https://github.com/wjones127))
+- \[minor\] fix doc test fail [\#3732](https://github.com/apache/arrow-rs/pull/3732) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([Ted-Jiang](https://github.com/Ted-Jiang))
+- Add datetime/interval/duration into dyn scalar comparison [\#3730](https://github.com/apache/arrow-rs/pull/3730) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([viirya](https://github.com/viirya))
+- Using Borrow\<Value\> on infer\_json\_schema\_from\_iterator [\#3728](https://github.com/apache/arrow-rs/pull/3728) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([rguerreiromsft](https://github.com/rguerreiromsft))
+- Not operator overload for SortOptions [\#3727](https://github.com/apache/arrow-rs/pull/3727) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([berkaysynnada](https://github.com/berkaysynnada))
+- fix: encoding batch with no columns [\#3724](https://github.com/apache/arrow-rs/pull/3724) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([wangrunji0408](https://github.com/wangrunji0408))
+- feat: impl `Ord`/`PartialOrd` for `SortOptions` [\#3723](https://github.com/apache/arrow-rs/pull/3723) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([crepererum](https://github.com/crepererum))
+- Add From\<Bytes\> for ByteArray [\#3720](https://github.com/apache/arrow-rs/pull/3720) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([tustvold](https://github.com/tustvold))
+- Deprecate old JSON reader \(\#3610\) [\#3718](https://github.com/apache/arrow-rs/pull/3718) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Add pretty format with options [\#3717](https://github.com/apache/arrow-rs/pull/3717) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Remove unreachable decimal take [\#3716](https://github.com/apache/arrow-rs/pull/3716) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Feat: arrow csv decimal256 [\#3711](https://github.com/apache/arrow-rs/pull/3711) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([suxiaogang223](https://github.com/suxiaogang223))
+- perf: `take_run` improvements [\#3705](https://github.com/apache/arrow-rs/pull/3705) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([askoa](https://github.com/askoa))
+- Add raw MapArrayReader [\#3703](https://github.com/apache/arrow-rs/pull/3703) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- feat: Sort kernel for `RunArray` [\#3695](https://github.com/apache/arrow-rs/pull/3695) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([askoa](https://github.com/askoa))
+- perf: Remove sorting to yield sorted\_rank [\#3693](https://github.com/apache/arrow-rs/pull/3693) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([askoa](https://github.com/askoa))
+- fix: Handle sliced array in run array iterator [\#3681](https://github.com/apache/arrow-rs/pull/3681) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([askoa](https://github.com/askoa))
diff --git a/arrow-arith/Cargo.toml b/arrow-arith/Cargo.toml
index 977590308e42..6b3d82c9c906 100644
--- a/arrow-arith/Cargo.toml
+++ b/arrow-arith/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-arith"
-version = "33.0.0"
+version = "34.0.0"
description = "Arrow arithmetic kernels"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,10 +38,10 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow-array = { version = "33.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "33.0.0", path = "../arrow-buffer" }
-arrow-data = { version = "33.0.0", path = "../arrow-data" }
-arrow-schema = { version = "33.0.0", path = "../arrow-schema" }
+arrow-array = { version = "34.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "34.0.0", path = "../arrow-buffer" }
+arrow-data = { version = "34.0.0", path = "../arrow-data" }
+arrow-schema = { version = "34.0.0", path = "../arrow-schema" }
chrono = { version = "0.4.23", default-features = false }
half = { version = "2.1", default-features = false }
num = { version = "0.4", default-features = false, features = ["std"] }
diff --git a/arrow-array/Cargo.toml b/arrow-array/Cargo.toml
index bc47672e2594..5f839426edba 100644
--- a/arrow-array/Cargo.toml
+++ b/arrow-array/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-array"
-version = "33.0.0"
+version = "34.0.0"
description = "Array abstractions for Apache Arrow"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -45,9 +45,9 @@ ahash = { version = "0.8", default-features = false, features = ["compile-time-r
ahash = { version = "0.8", default-features = false, features = ["runtime-rng"] }
[dependencies]
-arrow-buffer = { version = "33.0.0", path = "../arrow-buffer" }
-arrow-schema = { version = "33.0.0", path = "../arrow-schema" }
-arrow-data = { version = "33.0.0", path = "../arrow-data" }
+arrow-buffer = { version = "34.0.0", path = "../arrow-buffer" }
+arrow-schema = { version = "34.0.0", path = "../arrow-schema" }
+arrow-data = { version = "34.0.0", path = "../arrow-data" }
chrono = { version = "0.4.23", default-features = false, features = ["clock"] }
chrono-tz = { version = "0.8", optional = true }
num = { version = "0.4", default-features = false, features = ["std"] }
diff --git a/arrow-buffer/Cargo.toml b/arrow-buffer/Cargo.toml
index e84b11a2b596..63e5aaa4476d 100644
--- a/arrow-buffer/Cargo.toml
+++ b/arrow-buffer/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-buffer"
-version = "33.0.0"
+version = "34.0.0"
description = "Buffer abstractions for Apache Arrow"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
diff --git a/arrow-cast/Cargo.toml b/arrow-cast/Cargo.toml
index bb2d725b34f4..688e0001f973 100644
--- a/arrow-cast/Cargo.toml
+++ b/arrow-cast/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-cast"
-version = "33.0.0"
+version = "34.0.0"
description = "Cast kernel and utilities for Apache Arrow"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,11 +38,11 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow-array = { version = "33.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "33.0.0", path = "../arrow-buffer" }
-arrow-data = { version = "33.0.0", path = "../arrow-data" }
-arrow-schema = { version = "33.0.0", path = "../arrow-schema" }
-arrow-select = { version = "33.0.0", path = "../arrow-select" }
+arrow-array = { version = "34.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "34.0.0", path = "../arrow-buffer" }
+arrow-data = { version = "34.0.0", path = "../arrow-data" }
+arrow-schema = { version = "34.0.0", path = "../arrow-schema" }
+arrow-select = { version = "34.0.0", path = "../arrow-select" }
chrono = { version = "0.4.23", default-features = false, features = ["clock"] }
num = { version = "0.4", default-features = false, features = ["std"] }
lexical-core = { version = "^0.8", default-features = false, features = ["write-integers", "write-floats", "parse-integers", "parse-floats"] }
diff --git a/arrow-csv/Cargo.toml b/arrow-csv/Cargo.toml
index 9d1582b91c2f..62ca69bcaf9b 100644
--- a/arrow-csv/Cargo.toml
+++ b/arrow-csv/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-csv"
-version = "33.0.0"
+version = "34.0.0"
description = "Support for parsing CSV format into the Arrow format"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,11 +38,11 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow-array = { version = "33.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "33.0.0", path = "../arrow-buffer" }
-arrow-cast = { version = "33.0.0", path = "../arrow-cast" }
-arrow-data = { version = "33.0.0", path = "../arrow-data" }
-arrow-schema = { version = "33.0.0", path = "../arrow-schema" }
+arrow-array = { version = "34.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "34.0.0", path = "../arrow-buffer" }
+arrow-cast = { version = "34.0.0", path = "../arrow-cast" }
+arrow-data = { version = "34.0.0", path = "../arrow-data" }
+arrow-schema = { version = "34.0.0", path = "../arrow-schema" }
chrono = { version = "0.4.23", default-features = false, features = ["clock"] }
csv = { version = "1.1", default-features = false }
csv-core = { version = "0.1"}
diff --git a/arrow-data/Cargo.toml b/arrow-data/Cargo.toml
index a1938af4b194..33de17339131 100644
--- a/arrow-data/Cargo.toml
+++ b/arrow-data/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-data"
-version = "33.0.0"
+version = "34.0.0"
description = "Array data abstractions for Apache Arrow"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -50,8 +50,8 @@ features = ["ffi"]
[dependencies]
-arrow-buffer = { version = "33.0.0", path = "../arrow-buffer" }
-arrow-schema = { version = "33.0.0", path = "../arrow-schema" }
+arrow-buffer = { version = "34.0.0", path = "../arrow-buffer" }
+arrow-schema = { version = "34.0.0", path = "../arrow-schema" }
num = { version = "0.4", default-features = false, features = ["std"] }
half = { version = "2.1", default-features = false }
diff --git a/arrow-flight/Cargo.toml b/arrow-flight/Cargo.toml
index 1ed98c919d8e..0c820ed73ac9 100644
--- a/arrow-flight/Cargo.toml
+++ b/arrow-flight/Cargo.toml
@@ -18,7 +18,7 @@
[package]
name = "arrow-flight"
description = "Apache Arrow Flight"
-version = "33.0.0"
+version = "34.0.0"
edition = "2021"
rust-version = "1.62"
authors = ["Apache Arrow <dev@arrow.apache.org>"]
@@ -27,12 +27,12 @@ repository = "https://github.com/apache/arrow-rs"
license = "Apache-2.0"
[dependencies]
-arrow-array = { version = "33.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "33.0.0", path = "../arrow-buffer" }
+arrow-array = { version = "34.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "34.0.0", path = "../arrow-buffer" }
# Cast is needed to work around https://github.com/apache/arrow-rs/issues/3389
-arrow-cast = { version = "33.0.0", path = "../arrow-cast" }
-arrow-ipc = { version = "33.0.0", path = "../arrow-ipc" }
-arrow-schema = { version = "33.0.0", path = "../arrow-schema" }
+arrow-cast = { version = "34.0.0", path = "../arrow-cast" }
+arrow-ipc = { version = "34.0.0", path = "../arrow-ipc" }
+arrow-schema = { version = "34.0.0", path = "../arrow-schema" }
base64 = { version = "0.21", default-features = false, features = ["std"] }
tonic = { version = "0.8", default-features = false, features = ["transport", "codegen", "prost"] }
bytes = { version = "1", default-features = false }
@@ -50,7 +50,7 @@ flight-sql-experimental = []
tls = ["tonic/tls"]
[dev-dependencies]
-arrow = { version = "33.0.0", path = "../arrow", features = ["prettyprint"] }
+arrow = { version = "34.0.0", path = "../arrow", features = ["prettyprint"] }
tempfile = "3.3"
tokio-stream = { version = "0.1", features = ["net"] }
tower = "0.4.13"
diff --git a/arrow-flight/README.md b/arrow-flight/README.md
index 7992d93292ce..1f8026887485 100644
--- a/arrow-flight/README.md
+++ b/arrow-flight/README.md
@@ -27,7 +27,7 @@ Add this to your Cargo.toml:
```toml
[dependencies]
-arrow-flight = "33.0.0"
+arrow-flight = "34.0.0"
```
Apache Arrow Flight is a gRPC based protocol for exchanging Arrow data between processes. See the blog post [Introducing Apache Arrow Flight: A Framework for Fast Data Transport](https://arrow.apache.org/blog/2019/10/13/introducing-arrow-flight/) for more information.
diff --git a/arrow-ipc/Cargo.toml b/arrow-ipc/Cargo.toml
index 6661f35c0635..040d1c113a5c 100644
--- a/arrow-ipc/Cargo.toml
+++ b/arrow-ipc/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-ipc"
-version = "33.0.0"
+version = "34.0.0"
description = "Support for the Arrow IPC format"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,11 +38,11 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow-array = { version = "33.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "33.0.0", path = "../arrow-buffer" }
-arrow-cast = { version = "33.0.0", path = "../arrow-cast" }
-arrow-data = { version = "33.0.0", path = "../arrow-data" }
-arrow-schema = { version = "33.0.0", path = "../arrow-schema" }
+arrow-array = { version = "34.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "34.0.0", path = "../arrow-buffer" }
+arrow-cast = { version = "34.0.0", path = "../arrow-cast" }
+arrow-data = { version = "34.0.0", path = "../arrow-data" }
+arrow-schema = { version = "34.0.0", path = "../arrow-schema" }
flatbuffers = { version = "23.1.21", default-features = false }
lz4 = { version = "1.23", default-features = false, optional = true }
zstd = { version = "0.12.0", default-features = false, optional = true }
diff --git a/arrow-json/Cargo.toml b/arrow-json/Cargo.toml
index ab77c1843ec0..3869bfd90b19 100644
--- a/arrow-json/Cargo.toml
+++ b/arrow-json/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-json"
-version = "33.0.0"
+version = "34.0.0"
description = "Support for parsing JSON format into the Arrow format"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,11 +38,11 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow-array = { version = "33.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "33.0.0", path = "../arrow-buffer" }
-arrow-cast = { version = "33.0.0", path = "../arrow-cast" }
-arrow-data = { version = "33.0.0", path = "../arrow-data" }
-arrow-schema = { version = "33.0.0", path = "../arrow-schema" }
+arrow-array = { version = "34.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "34.0.0", path = "../arrow-buffer" }
+arrow-cast = { version = "34.0.0", path = "../arrow-cast" }
+arrow-data = { version = "34.0.0", path = "../arrow-data" }
+arrow-schema = { version = "34.0.0", path = "../arrow-schema" }
half = { version = "2.1", default-features = false }
indexmap = { version = "1.9", default-features = false, features = ["std"] }
num = { version = "0.4", default-features = false, features = ["std"] }
diff --git a/arrow-ord/Cargo.toml b/arrow-ord/Cargo.toml
index 682d68dac857..7e7ec7d4fedd 100644
--- a/arrow-ord/Cargo.toml
+++ b/arrow-ord/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-ord"
-version = "33.0.0"
+version = "34.0.0"
description = "Ordering kernels for arrow arrays"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,11 +38,11 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow-array = { version = "33.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "33.0.0", path = "../arrow-buffer" }
-arrow-data = { version = "33.0.0", path = "../arrow-data" }
-arrow-schema = { version = "33.0.0", path = "../arrow-schema" }
-arrow-select = { version = "33.0.0", path = "../arrow-select" }
+arrow-array = { version = "34.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "34.0.0", path = "../arrow-buffer" }
+arrow-data = { version = "34.0.0", path = "../arrow-data" }
+arrow-schema = { version = "34.0.0", path = "../arrow-schema" }
+arrow-select = { version = "34.0.0", path = "../arrow-select" }
num = { version = "0.4", default-features = false, features = ["std"] }
[dev-dependencies]
diff --git a/arrow-row/Cargo.toml b/arrow-row/Cargo.toml
index 94210a27a14b..3ddc195c39a0 100644
--- a/arrow-row/Cargo.toml
+++ b/arrow-row/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-row"
-version = "33.0.0"
+version = "34.0.0"
description = "Arrow row format"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -44,17 +44,17 @@ ahash = { version = "0.8", default-features = false, features = ["compile-time-r
ahash = { version = "0.8", default-features = false, features = ["runtime-rng"] }
[dependencies]
-arrow-array = { version = "33.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "33.0.0", path = "../arrow-buffer" }
-arrow-data = { version = "33.0.0", path = "../arrow-data" }
-arrow-schema = { version = "33.0.0", path = "../arrow-schema" }
+arrow-array = { version = "34.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "34.0.0", path = "../arrow-buffer" }
+arrow-data = { version = "34.0.0", path = "../arrow-data" }
+arrow-schema = { version = "34.0.0", path = "../arrow-schema" }
half = { version = "2.1", default-features = false }
hashbrown = { version = "0.13", default-features = false }
[dev-dependencies]
-arrow-cast = { version = "33.0.0", path = "../arrow-cast" }
-arrow-ord = { version = "33.0.0", path = "../arrow-ord" }
+arrow-cast = { version = "34.0.0", path = "../arrow-cast" }
+arrow-ord = { version = "34.0.0", path = "../arrow-ord" }
rand = { version = "0.8", default-features = false, features = ["std", "std_rng"] }
[features]
diff --git a/arrow-schema/Cargo.toml b/arrow-schema/Cargo.toml
index e4e7d0082eb8..acf6c43b8342 100644
--- a/arrow-schema/Cargo.toml
+++ b/arrow-schema/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-schema"
-version = "33.0.0"
+version = "34.0.0"
description = "Defines the logical types for arrow arrays"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
diff --git a/arrow-select/Cargo.toml b/arrow-select/Cargo.toml
index 789a23359a16..540d37cb5aa8 100644
--- a/arrow-select/Cargo.toml
+++ b/arrow-select/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-select"
-version = "33.0.0"
+version = "34.0.0"
description = "Selection kernels for arrow arrays"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,10 +38,10 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow-buffer = { version = "33.0.0", path = "../arrow-buffer" }
-arrow-data = { version = "33.0.0", path = "../arrow-data" }
-arrow-schema = { version = "33.0.0", path = "../arrow-schema" }
-arrow-array = { version = "33.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "34.0.0", path = "../arrow-buffer" }
+arrow-data = { version = "34.0.0", path = "../arrow-data" }
+arrow-schema = { version = "34.0.0", path = "../arrow-schema" }
+arrow-array = { version = "34.0.0", path = "../arrow-array" }
num = { version = "0.4", default-features = false, features = ["std"] }
[features]
diff --git a/arrow-string/Cargo.toml b/arrow-string/Cargo.toml
index 796024e873ef..2e8067051644 100644
--- a/arrow-string/Cargo.toml
+++ b/arrow-string/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-string"
-version = "33.0.0"
+version = "34.0.0"
description = "String kernels for arrow arrays"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,11 +38,11 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow-buffer = { version = "33.0.0", path = "../arrow-buffer" }
-arrow-data = { version = "33.0.0", path = "../arrow-data" }
-arrow-schema = { version = "33.0.0", path = "../arrow-schema" }
-arrow-array = { version = "33.0.0", path = "../arrow-array" }
-arrow-select = { version = "33.0.0", path = "../arrow-select" }
+arrow-buffer = { version = "34.0.0", path = "../arrow-buffer" }
+arrow-data = { version = "34.0.0", path = "../arrow-data" }
+arrow-schema = { version = "34.0.0", path = "../arrow-schema" }
+arrow-array = { version = "34.0.0", path = "../arrow-array" }
+arrow-select = { version = "34.0.0", path = "../arrow-select" }
regex = { version = "1.7.0", default-features = false, features = ["std", "unicode", "perf"] }
regex-syntax = { version = "0.6.27", default-features = false, features = ["unicode"] }
diff --git a/arrow/Cargo.toml b/arrow/Cargo.toml
index 2032d5048977..08fc5513d64f 100644
--- a/arrow/Cargo.toml
+++ b/arrow/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow"
-version = "33.0.0"
+version = "34.0.0"
description = "Rust implementation of Apache Arrow"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -45,19 +45,19 @@ ahash = { version = "0.8", default-features = false, features = ["compile-time-r
ahash = { version = "0.8", default-features = false, features = ["runtime-rng"] }
[dependencies]
-arrow-arith = { version = "33.0.0", path = "../arrow-arith" }
-arrow-array = { version = "33.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "33.0.0", path = "../arrow-buffer" }
-arrow-cast = { version = "33.0.0", path = "../arrow-cast" }
-arrow-csv = { version = "33.0.0", path = "../arrow-csv", optional = true }
-arrow-data = { version = "33.0.0", path = "../arrow-data" }
-arrow-ipc = { version = "33.0.0", path = "../arrow-ipc", optional = true }
-arrow-json = { version = "33.0.0", path = "../arrow-json", optional = true }
-arrow-ord = { version = "33.0.0", path = "../arrow-ord" }
-arrow-row = { version = "33.0.0", path = "../arrow-row" }
-arrow-schema = { version = "33.0.0", path = "../arrow-schema" }
-arrow-select = { version = "33.0.0", path = "../arrow-select" }
-arrow-string = { version = "33.0.0", path = "../arrow-string" }
+arrow-arith = { version = "34.0.0", path = "../arrow-arith" }
+arrow-array = { version = "34.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "34.0.0", path = "../arrow-buffer" }
+arrow-cast = { version = "34.0.0", path = "../arrow-cast" }
+arrow-csv = { version = "34.0.0", path = "../arrow-csv", optional = true }
+arrow-data = { version = "34.0.0", path = "../arrow-data" }
+arrow-ipc = { version = "34.0.0", path = "../arrow-ipc", optional = true }
+arrow-json = { version = "34.0.0", path = "../arrow-json", optional = true }
+arrow-ord = { version = "34.0.0", path = "../arrow-ord" }
+arrow-row = { version = "34.0.0", path = "../arrow-row" }
+arrow-schema = { version = "34.0.0", path = "../arrow-schema" }
+arrow-select = { version = "34.0.0", path = "../arrow-select" }
+arrow-string = { version = "34.0.0", path = "../arrow-string" }
rand = { version = "0.8", default-features = false, features = ["std", "std_rng"], optional = true }
comfy-table = { version = "6.0", optional = true, default-features = false }
diff --git a/arrow/README.md b/arrow/README.md
index 0714285011fa..6d0772e2d956 100644
--- a/arrow/README.md
+++ b/arrow/README.md
@@ -35,7 +35,7 @@ This crate is tested with the latest stable version of Rust. We do not currently
The arrow crate follows the [SemVer standard](https://doc.rust-lang.org/cargo/reference/semver.html) defined by Cargo and works well within the Rust crate ecosystem.
-However, for historical reasons, this crate uses versions with major numbers greater than `0.x` (e.g. `33.0.0`), unlike many other crates in the Rust ecosystem which spend extended time releasing versions `0.x` to signal planned ongoing API changes. Minor arrow releases contain only compatible changes, while major releases may contain breaking API changes.
+However, for historical reasons, this crate uses versions with major numbers greater than `0.x` (e.g. `34.0.0`), unlike many other crates in the Rust ecosystem which spend extended time releasing versions `0.x` to signal planned ongoing API changes. Minor arrow releases contain only compatible changes, while major releases may contain breaking API changes.
## Feature Flags
diff --git a/dev/release/README.md b/dev/release/README.md
index b8018bfaf7b4..70921dd024da 100644
--- a/dev/release/README.md
+++ b/dev/release/README.md
@@ -70,7 +70,7 @@ git pull
git checkout -b <RELEASE_BRANCH>
# Update versions. Make sure to run it before the next step since we do not want CHANGELOG-old.md affected.
-sed -i '' -e 's/14.0.0/33.0.0/g' `find . -name 'Cargo.toml' -or -name '*.md' | grep -v CHANGELOG.md`
+sed -i '' -e 's/14.0.0/34.0.0/g' `find . -name 'Cargo.toml' -or -name '*.md' | grep -v CHANGELOG.md`
git commit -a -m 'Update version'
# Copy the content of CHANGELOG.md to the beginning of CHANGELOG-old.md
diff --git a/dev/release/update_change_log.sh b/dev/release/update_change_log.sh
index 7b773fd05c61..920498905ccd 100755
--- a/dev/release/update_change_log.sh
+++ b/dev/release/update_change_log.sh
@@ -29,8 +29,8 @@
set -e
-SINCE_TAG="32.0.0"
-FUTURE_RELEASE="33.0.0"
+SINCE_TAG="33.0.0"
+FUTURE_RELEASE="34.0.0"
SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SOURCE_TOP_DIR="$(cd "${SOURCE_DIR}/../../" && pwd)"
diff --git a/parquet/Cargo.toml b/parquet/Cargo.toml
index d59f481f362f..87f552fbd36a 100644
--- a/parquet/Cargo.toml
+++ b/parquet/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "parquet"
-version = "33.0.0"
+version = "34.0.0"
license = "Apache-2.0"
description = "Apache Parquet implementation in Rust"
homepage = "https://github.com/apache/arrow-rs"
@@ -35,14 +35,14 @@ ahash = { version = "0.8", default-features = false, features = ["compile-time-r
ahash = { version = "0.8", default-features = false, features = ["runtime-rng"] }
[dependencies]
-arrow-array = { version = "33.0.0", path = "../arrow-array", default-features = false, optional = true }
-arrow-buffer = { version = "33.0.0", path = "../arrow-buffer", default-features = false, optional = true }
-arrow-cast = { version = "33.0.0", path = "../arrow-cast", default-features = false, optional = true }
-arrow-csv = { version = "33.0.0", path = "../arrow-csv", default-features = false, optional = true }
-arrow-data = { version = "33.0.0", path = "../arrow-data", default-features = false, optional = true }
-arrow-schema = { version = "33.0.0", path = "../arrow-schema", default-features = false, optional = true }
-arrow-select = { version = "33.0.0", path = "../arrow-select", default-features = false, optional = true }
-arrow-ipc = { version = "33.0.0", path = "../arrow-ipc", default-features = false, optional = true }
+arrow-array = { version = "34.0.0", path = "../arrow-array", default-features = false, optional = true }
+arrow-buffer = { version = "34.0.0", path = "../arrow-buffer", default-features = false, optional = true }
+arrow-cast = { version = "34.0.0", path = "../arrow-cast", default-features = false, optional = true }
+arrow-csv = { version = "34.0.0", path = "../arrow-csv", default-features = false, optional = true }
+arrow-data = { version = "34.0.0", path = "../arrow-data", default-features = false, optional = true }
+arrow-schema = { version = "34.0.0", path = "../arrow-schema", default-features = false, optional = true }
+arrow-select = { version = "34.0.0", path = "../arrow-select", default-features = false, optional = true }
+arrow-ipc = { version = "34.0.0", path = "../arrow-ipc", default-features = false, optional = true }
object_store = { version = "0.5", path = "../object_store", default-features = false, optional = true }
bytes = { version = "1.1", default-features = false, features = ["std"] }
@@ -76,7 +76,7 @@ flate2 = { version = "1.0", default-features = false, features = ["rust_backend"
lz4 = { version = "1.23", default-features = false }
zstd = { version = "0.12", default-features = false }
serde_json = { version = "1.0", features = ["std"], default-features = false }
-arrow = { path = "../arrow", version = "33.0.0", default-features = false, features = ["ipc", "test_utils", "prettyprint", "json"] }
+arrow = { path = "../arrow", version = "34.0.0", default-features = false, features = ["ipc", "test_utils", "prettyprint", "json"] }
tokio = { version = "1.0", default-features = false, features = ["macros", "rt", "io-util", "fs"] }
rand = { version = "0.8", default-features = false, features = ["std", "std_rng"] }
diff --git a/parquet_derive/Cargo.toml b/parquet_derive/Cargo.toml
index f648aafbf2fb..cb16846b0fb1 100644
--- a/parquet_derive/Cargo.toml
+++ b/parquet_derive/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "parquet_derive"
-version = "33.0.0"
+version = "34.0.0"
license = "Apache-2.0"
description = "Derive macros for the Rust implementation of Apache Parquet"
homepage = "https://github.com/apache/arrow-rs"
@@ -35,4 +35,4 @@ proc-macro = true
proc-macro2 = { version = "1.0", default-features = false }
quote = { version = "1.0", default-features = false }
syn = { version = "1.0", features = ["extra-traits"] }
-parquet = { path = "../parquet", version = "33.0.0", default-features = false }
+parquet = { path = "../parquet", version = "34.0.0", default-features = false }
diff --git a/parquet_derive/README.md b/parquet_derive/README.md
index c8ee7ea81101..f3f66c45bc98 100644
--- a/parquet_derive/README.md
+++ b/parquet_derive/README.md
@@ -32,8 +32,8 @@ Add this to your Cargo.toml:
```toml
[dependencies]
-parquet = "33.0.0"
-parquet_derive = "33.0.0"
+parquet = "34.0.0"
+parquet_derive = "34.0.0"
```
and this to your crate root:
|
diff --git a/arrow-integration-test/Cargo.toml b/arrow-integration-test/Cargo.toml
index f9ca4297e6e7..2d92e6292ded 100644
--- a/arrow-integration-test/Cargo.toml
+++ b/arrow-integration-test/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-integration-test"
-version = "33.0.0"
+version = "34.0.0"
description = "Support for the Apache Arrow JSON test data format"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,8 +38,8 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow = { version = "33.0.0", path = "../arrow", default-features = false }
-arrow-buffer = { version = "33.0.0", path = "../arrow-buffer" }
+arrow = { version = "34.0.0", path = "../arrow", default-features = false }
+arrow-buffer = { version = "34.0.0", path = "../arrow-buffer" }
hex = { version = "0.4", default-features = false, features = ["std"] }
serde = { version = "1.0", default-features = false, features = ["rc", "derive"] }
serde_json = { version = "1.0", default-features = false, features = ["std"] }
diff --git a/arrow-integration-testing/Cargo.toml b/arrow-integration-testing/Cargo.toml
index e22a15f52ddc..67d5b7d2745a 100644
--- a/arrow-integration-testing/Cargo.toml
+++ b/arrow-integration-testing/Cargo.toml
@@ -18,7 +18,7 @@
[package]
name = "arrow-integration-testing"
description = "Binaries used in the Arrow integration tests (NOT PUBLISHED TO crates.io)"
-version = "33.0.0"
+version = "34.0.0"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
authors = ["Apache Arrow <dev@arrow.apache.org>"]
diff --git a/arrow-pyarrow-integration-testing/Cargo.toml b/arrow-pyarrow-integration-testing/Cargo.toml
index 3ab256e541b3..cbf2e9cf29d9 100644
--- a/arrow-pyarrow-integration-testing/Cargo.toml
+++ b/arrow-pyarrow-integration-testing/Cargo.toml
@@ -18,7 +18,7 @@
[package]
name = "arrow-pyarrow-integration-testing"
description = ""
-version = "33.0.0"
+version = "34.0.0"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
authors = ["Apache Arrow <dev@arrow.apache.org>"]
@@ -32,5 +32,5 @@ name = "arrow_pyarrow_integration_testing"
crate-type = ["cdylib"]
[dependencies]
-arrow = { path = "../arrow", version = "33.0.0", features = ["pyarrow"] }
+arrow = { path = "../arrow", version = "34.0.0", features = ["pyarrow"] }
pyo3 = { version = "0.18", features = ["extension-module"] }
diff --git a/parquet_derive_test/Cargo.toml b/parquet_derive_test/Cargo.toml
index df8fa3aef65a..33f7675a30ef 100644
--- a/parquet_derive_test/Cargo.toml
+++ b/parquet_derive_test/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "parquet_derive_test"
-version = "33.0.0"
+version = "34.0.0"
license = "Apache-2.0"
description = "Integration test package for parquet-derive"
homepage = "https://github.com/apache/arrow-rs"
@@ -29,6 +29,6 @@ publish = false
rust-version = "1.62"
[dependencies]
-parquet = { path = "../parquet", version = "33.0.0", default-features = false }
-parquet_derive = { path = "../parquet_derive", version = "33.0.0", default-features = false }
+parquet = { path = "../parquet", version = "34.0.0", default-features = false }
+parquet_derive = { path = "../parquet_derive", version = "34.0.0", default-features = false }
chrono = { version="0.4.23", default-features = false, features = [ "clock" ] }
|
Release 34.0.0 of arrow/arrow-flight/parquet/parquet-derive (next release after 33.0.0)
Follow on from https://github.com/apache/arrow-rs/issues/3682
- Planned Release Candidate: 2023-02-24
- Planned Release and Publish to crates.io: 2023-02-27
Items (from [dev/release/README.md](https://github.com/apache/arrow-rs/blob/master/dev/release/README.md)):
- [x] PR to update version and CHANGELOG:
- [x] Release candidate created:
- [ ] Release candidate approved:
- [ ] Release to crates.io:
- [ ] Make ticket for next release
See full list here:
https://github.com/apache/arrow-rs/compare/33.0.0...master
cc @alamb @tustvold @viirya
|
2023-02-23T14:49:12Z
|
33.0
|
9699e1df7c7e0b83c8ec8be6678ee17d77a17f47
|
|
apache/arrow-rs
| 3,686
|
apache__arrow-rs-3686
|
[
"3682"
] |
bb4fc59009e7c5861a6b1967a53e9daa2554d5c6
|
diff --git a/CHANGELOG-old.md b/CHANGELOG-old.md
index 65a95579e9f8..9ac8cb530456 100644
--- a/CHANGELOG-old.md
+++ b/CHANGELOG-old.md
@@ -19,6 +19,81 @@
# Historical Changelog
+## [32.0.0](https://github.com/apache/arrow-rs/tree/32.0.0) (2023-01-27)
+
+[Full Changelog](https://github.com/apache/arrow-rs/compare/31.0.0...32.0.0)
+
+**Breaking changes:**
+
+- Allow `StringArray` construction with `Vec<Option<String>>` [\#3602](https://github.com/apache/arrow-rs/pull/3602) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([sinistersnare](https://github.com/sinistersnare))
+- Use native types in PageIndex \(\#3575\) [\#3578](https://github.com/apache/arrow-rs/pull/3578) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([tustvold](https://github.com/tustvold))
+- Add external variant to ParquetError \(\#3285\) [\#3574](https://github.com/apache/arrow-rs/pull/3574) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([tustvold](https://github.com/tustvold))
+- Return reference from ListArray::values [\#3561](https://github.com/apache/arrow-rs/pull/3561) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- feat: Add `RunEndEncodedArray` [\#3553](https://github.com/apache/arrow-rs/pull/3553) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([askoa](https://github.com/askoa))
+
+**Implemented enhancements:**
+
+- There should be a `From<Vec<Option<String>>>` impl for `GenericStringArray<OffsetSize>` [\#3599](https://github.com/apache/arrow-rs/issues/3599) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- FlightDataEncoder Optionally send Schema even when no record batches [\#3591](https://github.com/apache/arrow-rs/issues/3591) [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)]
+- Use Native Types in PageIndex [\#3575](https://github.com/apache/arrow-rs/issues/3575) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)]
+- Packing array into dictionary of generic byte array [\#3571](https://github.com/apache/arrow-rs/issues/3571) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- Implement `Error::Source` for ArrowError and FlightError [\#3566](https://github.com/apache/arrow-rs/issues/3566) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)]
+- \[FlightSQL\] Allow access to underlying FlightClient [\#3551](https://github.com/apache/arrow-rs/issues/3551) [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)]
+- Arrow CSV writer should not fail when cannot cast the value [\#3547](https://github.com/apache/arrow-rs/issues/3547) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- Write Deprecated Min Max Statistics When ColumnOrder Signed [\#3526](https://github.com/apache/arrow-rs/issues/3526) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)]
+- Improve Performance of JSON Reader [\#3441](https://github.com/apache/arrow-rs/issues/3441)
+- Support footer kv metadata for IPC file [\#3432](https://github.com/apache/arrow-rs/issues/3432)
+- Add `External` variant to ParquetError [\#3285](https://github.com/apache/arrow-rs/issues/3285) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)]
+
+**Fixed bugs:**
+
+- Nullif of NULL Predicate is not NULL [\#3589](https://github.com/apache/arrow-rs/issues/3589)
+- BooleanBufferBuilder Fails to Clear Set Bits On Truncate [\#3587](https://github.com/apache/arrow-rs/issues/3587) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- `nullif` incorrectly calculates `null_count`, sometimes panics with substraction overflow error [\#3579](https://github.com/apache/arrow-rs/issues/3579) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- Meet warning when use pyarrow [\#3543](https://github.com/apache/arrow-rs/issues/3543) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- Incorrect row group total\_byte\_size written to parquet file [\#3530](https://github.com/apache/arrow-rs/issues/3530) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)]
+- Overflow when casting timestamps prior to the epoch [\#3512](https://github.com/apache/arrow-rs/issues/3512) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+
+**Closed issues:**
+
+- Panic on Key Overflow in Dictionary Builders [\#3562](https://github.com/apache/arrow-rs/issues/3562) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- Bumping version gives compilation error \(arrow-array\) [\#3525](https://github.com/apache/arrow-rs/issues/3525)
+
+**Merged pull requests:**
+
+- Add Push-Based CSV Decoder [\#3604](https://github.com/apache/arrow-rs/pull/3604) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Update to flatbuffers 23.1.21 [\#3597](https://github.com/apache/arrow-rs/pull/3597) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Faster BooleanBufferBuilder::append\_n for true values [\#3596](https://github.com/apache/arrow-rs/pull/3596) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Support sending schemas for empty streams [\#3594](https://github.com/apache/arrow-rs/pull/3594) [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([alamb](https://github.com/alamb))
+- Faster ListArray to StringArray conversion [\#3593](https://github.com/apache/arrow-rs/pull/3593) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Add conversion from StringArray to BinaryArray [\#3592](https://github.com/apache/arrow-rs/pull/3592) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Fix nullif null count \(\#3579\) [\#3590](https://github.com/apache/arrow-rs/pull/3590) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Clear bits in BooleanBufferBuilder \(\#3587\) [\#3588](https://github.com/apache/arrow-rs/pull/3588) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Iterate all dictionary key types in cast test [\#3585](https://github.com/apache/arrow-rs/pull/3585) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([viirya](https://github.com/viirya))
+- Propagate EOF Error from AsyncRead [\#3576](https://github.com/apache/arrow-rs/pull/3576) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([Sach1nAgarwal](https://github.com/Sach1nAgarwal))
+- Show row\_counts also for \(FixedLen\)ByteArray [\#3573](https://github.com/apache/arrow-rs/pull/3573) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([bmmeijers](https://github.com/bmmeijers))
+- Packing array into dictionary of generic byte array [\#3572](https://github.com/apache/arrow-rs/pull/3572) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([viirya](https://github.com/viirya))
+- Remove unwrap on datetime cast for CSV writer [\#3570](https://github.com/apache/arrow-rs/pull/3570) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([comphead](https://github.com/comphead))
+- Implement `std::error::Error::source` for `ArrowError` and `FlightError` [\#3567](https://github.com/apache/arrow-rs/pull/3567) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([alamb](https://github.com/alamb))
+- Improve GenericBytesBuilder offset overflow panic message \(\#139\) [\#3564](https://github.com/apache/arrow-rs/pull/3564) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Implement Extend for ArrayBuilder \(\#1841\) [\#3563](https://github.com/apache/arrow-rs/pull/3563) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Update pyarrow method call with kwargs [\#3560](https://github.com/apache/arrow-rs/pull/3560) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([Frankonly](https://github.com/Frankonly))
+- Update pyo3 requirement from 0.17 to 0.18 [\#3557](https://github.com/apache/arrow-rs/pull/3557) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([viirya](https://github.com/viirya))
+- Expose Inner FlightServiceClient on FlightSqlServiceClient \(\#3551\) [\#3556](https://github.com/apache/arrow-rs/pull/3556) [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([tustvold](https://github.com/tustvold))
+- Fix final page row count in parquet-index binary [\#3554](https://github.com/apache/arrow-rs/pull/3554) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([tustvold](https://github.com/tustvold))
+- Parquet Avoid Reading 8 Byte Footer Twice from AsyncRead [\#3550](https://github.com/apache/arrow-rs/pull/3550) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([Sach1nAgarwal](https://github.com/Sach1nAgarwal))
+- Improve concat kernel capacity estimation [\#3546](https://github.com/apache/arrow-rs/pull/3546) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Update proc-macro2 requirement from =1.0.49 to =1.0.50 [\#3545](https://github.com/apache/arrow-rs/pull/3545) [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([dependabot[bot]](https://github.com/apps/dependabot))
+- Update pyarrow method call to avoid warning [\#3544](https://github.com/apache/arrow-rs/pull/3544) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([Frankonly](https://github.com/Frankonly))
+- Enable casting between Utf8/LargeUtf8 and Binary/LargeBinary [\#3542](https://github.com/apache/arrow-rs/pull/3542) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([viirya](https://github.com/viirya))
+- Use GHA concurrency groups \(\#3495\) [\#3538](https://github.com/apache/arrow-rs/pull/3538) ([tustvold](https://github.com/tustvold))
+- set sum of uncompressed column size as row group size for parquet files [\#3531](https://github.com/apache/arrow-rs/pull/3531) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([sidred](https://github.com/sidred))
+- Minor: Add documentation about memory use for ArrayData [\#3529](https://github.com/apache/arrow-rs/pull/3529) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([alamb](https://github.com/alamb))
+- Upgrade to clap 4.1 + fix test [\#3528](https://github.com/apache/arrow-rs/pull/3528) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([tustvold](https://github.com/tustvold))
+- Write backwards compatible row group statistics \(\#3526\) [\#3527](https://github.com/apache/arrow-rs/pull/3527) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([tustvold](https://github.com/tustvold))
+- No panic on timestamp buffer overflow [\#3519](https://github.com/apache/arrow-rs/pull/3519) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([comphead](https://github.com/comphead))
+- Support casting from binary to dictionary of binary [\#3482](https://github.com/apache/arrow-rs/pull/3482) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([viirya](https://github.com/viirya))
+- Add Raw JSON Reader \(~2.5x faster\) [\#3479](https://github.com/apache/arrow-rs/pull/3479) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
## [31.0.0](https://github.com/apache/arrow-rs/tree/31.0.0) (2023-01-13)
[Full Changelog](https://github.com/apache/arrow-rs/compare/30.0.1...31.0.0)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 656c86eaf524..4676edd3e0df 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,81 +19,71 @@
# Changelog
-## [32.0.0](https://github.com/apache/arrow-rs/tree/32.0.0) (2023-01-27)
+## [33.0.0](https://github.com/apache/arrow-rs/tree/33.0.0) (2023-02-09)
-[Full Changelog](https://github.com/apache/arrow-rs/compare/31.0.0...32.0.0)
+[Full Changelog](https://github.com/apache/arrow-rs/compare/32.0.0...33.0.0)
**Breaking changes:**
-- Allow `StringArray` construction with `Vec<Option<String>>` [\#3602](https://github.com/apache/arrow-rs/pull/3602) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([sinistersnare](https://github.com/sinistersnare))
-- Use native types in PageIndex \(\#3575\) [\#3578](https://github.com/apache/arrow-rs/pull/3578) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([tustvold](https://github.com/tustvold))
-- Add external variant to ParquetError \(\#3285\) [\#3574](https://github.com/apache/arrow-rs/pull/3574) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([tustvold](https://github.com/tustvold))
-- Return reference from ListArray::values [\#3561](https://github.com/apache/arrow-rs/pull/3561) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- feat: Add `RunEndEncodedArray` [\#3553](https://github.com/apache/arrow-rs/pull/3553) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([askoa](https://github.com/askoa))
+- Use ArrayFormatter in Cast Kernel [\#3668](https://github.com/apache/arrow-rs/pull/3668) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Use dyn Array in cast kernels [\#3667](https://github.com/apache/arrow-rs/pull/3667) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Return references from FixedSizeListArray and MapArray [\#3652](https://github.com/apache/arrow-rs/pull/3652) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Lazy array display \(\#3638\) [\#3647](https://github.com/apache/arrow-rs/pull/3647) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Use array\_value\_to\_string in arrow-csv [\#3514](https://github.com/apache/arrow-rs/pull/3514) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([JayjeetAtGithub](https://github.com/JayjeetAtGithub))
**Implemented enhancements:**
-- There should be a `From<Vec<Option<String>>>` impl for `GenericStringArray<OffsetSize>` [\#3599](https://github.com/apache/arrow-rs/issues/3599) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
-- FlightDataEncoder Optionally send Schema even when no record batches [\#3591](https://github.com/apache/arrow-rs/issues/3591) [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)]
-- Use Native Types in PageIndex [\#3575](https://github.com/apache/arrow-rs/issues/3575) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)]
-- Packing array into dictionary of generic byte array [\#3571](https://github.com/apache/arrow-rs/issues/3571) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
-- Implement `Error::Source` for ArrowError and FlightError [\#3566](https://github.com/apache/arrow-rs/issues/3566) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)]
-- \[FlightSQL\] Allow access to underlying FlightClient [\#3551](https://github.com/apache/arrow-rs/issues/3551) [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)]
-- Arrow CSV writer should not fail when cannot cast the value [\#3547](https://github.com/apache/arrow-rs/issues/3547) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
-- Write Deprecated Min Max Statistics When ColumnOrder Signed [\#3526](https://github.com/apache/arrow-rs/issues/3526) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)]
-- Improve Performance of JSON Reader [\#3441](https://github.com/apache/arrow-rs/issues/3441)
-- Support footer kv metadata for IPC file [\#3432](https://github.com/apache/arrow-rs/issues/3432)
-- Add `External` variant to ParquetError [\#3285](https://github.com/apache/arrow-rs/issues/3285) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)]
+- object\_store: support encoded path as input [\#3651](https://github.com/apache/arrow-rs/issues/3651)
+- Add modulus\_dyn and modulus\_scalar\_dyn [\#3648](https://github.com/apache/arrow-rs/issues/3648)
+- A trait for append\_value and append\_null on ArrayBuilders [\#3644](https://github.com/apache/arrow-rs/issues/3644)
+- Improve error messge "batches\[0\] schema is different with argument schema" [\#3628](https://github.com/apache/arrow-rs/issues/3628)
+- Specified version of helper function to cast binary to string [\#3623](https://github.com/apache/arrow-rs/issues/3623)
+- Casting generic binary to generic string [\#3606](https://github.com/apache/arrow-rs/issues/3606) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- Use `array_value_to_string` in `arrow-csv` [\#3483](https://github.com/apache/arrow-rs/issues/3483)
**Fixed bugs:**
-- Nullif of NULL Predicate is not NULL [\#3589](https://github.com/apache/arrow-rs/issues/3589)
-- BooleanBufferBuilder Fails to Clear Set Bits On Truncate [\#3587](https://github.com/apache/arrow-rs/issues/3587) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
-- `nullif` incorrectly calculates `null_count`, sometimes panics with substraction overflow error [\#3579](https://github.com/apache/arrow-rs/issues/3579) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
-- Meet warning when use pyarrow [\#3543](https://github.com/apache/arrow-rs/issues/3543) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
-- Incorrect row group total\_byte\_size written to parquet file [\#3530](https://github.com/apache/arrow-rs/issues/3530) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)]
-- Overflow when casting timestamps prior to the epoch [\#3512](https://github.com/apache/arrow-rs/issues/3512) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
+- ArrowArray::try\_from\_raw Misleading Signature [\#3684](https://github.com/apache/arrow-rs/issues/3684)
+- PyArrowConvert Leaks Memory [\#3683](https://github.com/apache/arrow-rs/issues/3683)
+- FFI Fails to Account For Offsets [\#3671](https://github.com/apache/arrow-rs/issues/3671)
+- Regression in CSV reader error handling [\#3656](https://github.com/apache/arrow-rs/issues/3656)
+- UnionArray Child and Value Fail to Account for non-contiguous Type IDs [\#3653](https://github.com/apache/arrow-rs/issues/3653)
+- Panic when accessing RecordBatch from pyarrow [\#3646](https://github.com/apache/arrow-rs/issues/3646)
+- Multiplication for decimals is incorrect [\#3645](https://github.com/apache/arrow-rs/issues/3645)
+- Inconsistent output between pretty print and CSV writer for Arrow [\#3513](https://github.com/apache/arrow-rs/issues/3513)
**Closed issues:**
-- Panic on Key Overflow in Dictionary Builders [\#3562](https://github.com/apache/arrow-rs/issues/3562) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] [[arrow](https://github.com/apache/arrow-rs/labels/arrow)]
-- Bumping version gives compilation error \(arrow-array\) [\#3525](https://github.com/apache/arrow-rs/issues/3525)
+- Release `32.0.0` of `arrow`/`arrow-flight`/`parquet`/`parquet-derive` \(next release after `31.0.0`\) [\#3584](https://github.com/apache/arrow-rs/issues/3584)
**Merged pull requests:**
-- Add Push-Based CSV Decoder [\#3604](https://github.com/apache/arrow-rs/pull/3604) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Update to flatbuffers 23.1.21 [\#3597](https://github.com/apache/arrow-rs/pull/3597) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Faster BooleanBufferBuilder::append\_n for true values [\#3596](https://github.com/apache/arrow-rs/pull/3596) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Support sending schemas for empty streams [\#3594](https://github.com/apache/arrow-rs/pull/3594) [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([alamb](https://github.com/alamb))
-- Faster ListArray to StringArray conversion [\#3593](https://github.com/apache/arrow-rs/pull/3593) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Add conversion from StringArray to BinaryArray [\#3592](https://github.com/apache/arrow-rs/pull/3592) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Fix nullif null count \(\#3579\) [\#3590](https://github.com/apache/arrow-rs/pull/3590) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Clear bits in BooleanBufferBuilder \(\#3587\) [\#3588](https://github.com/apache/arrow-rs/pull/3588) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Iterate all dictionary key types in cast test [\#3585](https://github.com/apache/arrow-rs/pull/3585) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([viirya](https://github.com/viirya))
-- Propagate EOF Error from AsyncRead [\#3576](https://github.com/apache/arrow-rs/pull/3576) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([Sach1nAgarwal](https://github.com/Sach1nAgarwal))
-- Show row\_counts also for \(FixedLen\)ByteArray [\#3573](https://github.com/apache/arrow-rs/pull/3573) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([bmmeijers](https://github.com/bmmeijers))
-- Packing array into dictionary of generic byte array [\#3572](https://github.com/apache/arrow-rs/pull/3572) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([viirya](https://github.com/viirya))
-- Remove unwrap on datetime cast for CSV writer [\#3570](https://github.com/apache/arrow-rs/pull/3570) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([comphead](https://github.com/comphead))
-- Implement `std::error::Error::source` for `ArrowError` and `FlightError` [\#3567](https://github.com/apache/arrow-rs/pull/3567) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([alamb](https://github.com/alamb))
-- Improve GenericBytesBuilder offset overflow panic message \(\#139\) [\#3564](https://github.com/apache/arrow-rs/pull/3564) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Implement Extend for ArrayBuilder \(\#1841\) [\#3563](https://github.com/apache/arrow-rs/pull/3563) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Update pyarrow method call with kwargs [\#3560](https://github.com/apache/arrow-rs/pull/3560) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([Frankonly](https://github.com/Frankonly))
-- Update pyo3 requirement from 0.17 to 0.18 [\#3557](https://github.com/apache/arrow-rs/pull/3557) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([viirya](https://github.com/viirya))
-- Expose Inner FlightServiceClient on FlightSqlServiceClient \(\#3551\) [\#3556](https://github.com/apache/arrow-rs/pull/3556) [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([tustvold](https://github.com/tustvold))
-- Fix final page row count in parquet-index binary [\#3554](https://github.com/apache/arrow-rs/pull/3554) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([tustvold](https://github.com/tustvold))
-- Parquet Avoid Reading 8 Byte Footer Twice from AsyncRead [\#3550](https://github.com/apache/arrow-rs/pull/3550) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([Sach1nAgarwal](https://github.com/Sach1nAgarwal))
-- Improve concat kernel capacity estimation [\#3546](https://github.com/apache/arrow-rs/pull/3546) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
-- Update proc-macro2 requirement from =1.0.49 to =1.0.50 [\#3545](https://github.com/apache/arrow-rs/pull/3545) [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([dependabot[bot]](https://github.com/apps/dependabot))
-- Update pyarrow method call to avoid warning [\#3544](https://github.com/apache/arrow-rs/pull/3544) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([Frankonly](https://github.com/Frankonly))
-- Enable casting between Utf8/LargeUtf8 and Binary/LargeBinary [\#3542](https://github.com/apache/arrow-rs/pull/3542) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([viirya](https://github.com/viirya))
-- Use GHA concurrency groups \(\#3495\) [\#3538](https://github.com/apache/arrow-rs/pull/3538) ([tustvold](https://github.com/tustvold))
-- set sum of uncompressed column size as row group size for parquet files [\#3531](https://github.com/apache/arrow-rs/pull/3531) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([sidred](https://github.com/sidred))
-- Minor: Add documentation about memory use for ArrayData [\#3529](https://github.com/apache/arrow-rs/pull/3529) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([alamb](https://github.com/alamb))
-- Upgrade to clap 4.1 + fix test [\#3528](https://github.com/apache/arrow-rs/pull/3528) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([tustvold](https://github.com/tustvold))
-- Write backwards compatible row group statistics \(\#3526\) [\#3527](https://github.com/apache/arrow-rs/pull/3527) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([tustvold](https://github.com/tustvold))
-- No panic on timestamp buffer overflow [\#3519](https://github.com/apache/arrow-rs/pull/3519) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([comphead](https://github.com/comphead))
-- Support casting from binary to dictionary of binary [\#3482](https://github.com/apache/arrow-rs/pull/3482) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([viirya](https://github.com/viirya))
-- Add Raw JSON Reader \(~2.5x faster\) [\#3479](https://github.com/apache/arrow-rs/pull/3479) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Cleanup FFI interface \(\#3684\) \(\#3683\) [\#3685](https://github.com/apache/arrow-rs/pull/3685) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- fix: take\_run benchmark parameter [\#3679](https://github.com/apache/arrow-rs/pull/3679) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([askoa](https://github.com/askoa))
+- Minor: Add some examples to Date\*Array and Time\*Array [\#3678](https://github.com/apache/arrow-rs/pull/3678) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([alamb](https://github.com/alamb))
+- Add ArrayData::new\_null and DataType::primitive\_width [\#3676](https://github.com/apache/arrow-rs/pull/3676) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Fix FFI which fails to account for offsets [\#3675](https://github.com/apache/arrow-rs/pull/3675) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([viirya](https://github.com/viirya))
+- Fix Date64Array docs [\#3670](https://github.com/apache/arrow-rs/pull/3670) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Update proc-macro2 requirement from =1.0.50 to =1.0.51 [\#3669](https://github.com/apache/arrow-rs/pull/3669) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([dependabot[bot]](https://github.com/apps/dependabot))
+- Add timezone accessor for Timestamp\*Array [\#3666](https://github.com/apache/arrow-rs/pull/3666) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Faster timezone cast [\#3665](https://github.com/apache/arrow-rs/pull/3665) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Implement std::fmt::Write for StringBuilder \(\#3638\) [\#3659](https://github.com/apache/arrow-rs/pull/3659) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Include line and field number in CSV UTF-8 error \(\#3656\) [\#3657](https://github.com/apache/arrow-rs/pull/3657) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Handle non-contiguous type\_ids in UnionArray \(\#3653\) [\#3654](https://github.com/apache/arrow-rs/pull/3654) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Add modulus\_dyn and modulus\_scalar\_dyn [\#3649](https://github.com/apache/arrow-rs/pull/3649) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([viirya](https://github.com/viirya))
+- Improve error messge with detailed schema [\#3637](https://github.com/apache/arrow-rs/pull/3637) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([Veeupup](https://github.com/Veeupup))
+- Add limit to ArrowReaderBuilder to push limit down to parquet reader [\#3633](https://github.com/apache/arrow-rs/pull/3633) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([thinkharderdev](https://github.com/thinkharderdev))
+- chore: delete wrong comment and refactor set\_metadata in `Field` [\#3630](https://github.com/apache/arrow-rs/pull/3630) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([chunshao90](https://github.com/chunshao90))
+- Fix typo in comment [\#3627](https://github.com/apache/arrow-rs/pull/3627) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([kjschiroo](https://github.com/kjschiroo))
+- Minor: Update doc strings about Page Index / Column Index [\#3625](https://github.com/apache/arrow-rs/pull/3625) [[parquet](https://github.com/apache/arrow-rs/labels/parquet)] ([alamb](https://github.com/alamb))
+- Specified version of helper function to cast binary to string [\#3624](https://github.com/apache/arrow-rs/pull/3624) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([viirya](https://github.com/viirya))
+- feat: take kernel for RunArray [\#3622](https://github.com/apache/arrow-rs/pull/3622) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([askoa](https://github.com/askoa))
+- Remove BitSliceIterator specialization from try\_for\_each\_valid\_idx [\#3621](https://github.com/apache/arrow-rs/pull/3621) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Reduce PrimitiveArray::try\_unary codegen [\#3619](https://github.com/apache/arrow-rs/pull/3619) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Reduce Dictionary Builder Codegen [\#3616](https://github.com/apache/arrow-rs/pull/3616) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([tustvold](https://github.com/tustvold))
+- Minor: Add test for dictionary encoding of batches [\#3608](https://github.com/apache/arrow-rs/pull/3608) [[arrow-flight](https://github.com/apache/arrow-rs/labels/arrow-flight)] ([alamb](https://github.com/alamb))
+- Casting generic binary to generic string [\#3607](https://github.com/apache/arrow-rs/pull/3607) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([viirya](https://github.com/viirya))
+- Add ArrayAccessor, Iterator, Extend and benchmarks for RunArray [\#3603](https://github.com/apache/arrow-rs/pull/3603) [[arrow](https://github.com/apache/arrow-rs/labels/arrow)] ([askoa](https://github.com/askoa))
diff --git a/arrow-arith/Cargo.toml b/arrow-arith/Cargo.toml
index 774bb11bb090..977590308e42 100644
--- a/arrow-arith/Cargo.toml
+++ b/arrow-arith/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-arith"
-version = "32.0.0"
+version = "33.0.0"
description = "Arrow arithmetic kernels"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,10 +38,10 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow-array = { version = "32.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "32.0.0", path = "../arrow-buffer" }
-arrow-data = { version = "32.0.0", path = "../arrow-data" }
-arrow-schema = { version = "32.0.0", path = "../arrow-schema" }
+arrow-array = { version = "33.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "33.0.0", path = "../arrow-buffer" }
+arrow-data = { version = "33.0.0", path = "../arrow-data" }
+arrow-schema = { version = "33.0.0", path = "../arrow-schema" }
chrono = { version = "0.4.23", default-features = false }
half = { version = "2.1", default-features = false }
num = { version = "0.4", default-features = false, features = ["std"] }
diff --git a/arrow-array/Cargo.toml b/arrow-array/Cargo.toml
index c109db36973d..bc47672e2594 100644
--- a/arrow-array/Cargo.toml
+++ b/arrow-array/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-array"
-version = "32.0.0"
+version = "33.0.0"
description = "Array abstractions for Apache Arrow"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -45,9 +45,9 @@ ahash = { version = "0.8", default-features = false, features = ["compile-time-r
ahash = { version = "0.8", default-features = false, features = ["runtime-rng"] }
[dependencies]
-arrow-buffer = { version = "32.0.0", path = "../arrow-buffer" }
-arrow-schema = { version = "32.0.0", path = "../arrow-schema" }
-arrow-data = { version = "32.0.0", path = "../arrow-data" }
+arrow-buffer = { version = "33.0.0", path = "../arrow-buffer" }
+arrow-schema = { version = "33.0.0", path = "../arrow-schema" }
+arrow-data = { version = "33.0.0", path = "../arrow-data" }
chrono = { version = "0.4.23", default-features = false, features = ["clock"] }
chrono-tz = { version = "0.8", optional = true }
num = { version = "0.4", default-features = false, features = ["std"] }
diff --git a/arrow-buffer/Cargo.toml b/arrow-buffer/Cargo.toml
index d46e2f11a1d3..e84b11a2b596 100644
--- a/arrow-buffer/Cargo.toml
+++ b/arrow-buffer/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-buffer"
-version = "32.0.0"
+version = "33.0.0"
description = "Buffer abstractions for Apache Arrow"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
diff --git a/arrow-cast/Cargo.toml b/arrow-cast/Cargo.toml
index 2ce83e856806..bb2d725b34f4 100644
--- a/arrow-cast/Cargo.toml
+++ b/arrow-cast/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-cast"
-version = "32.0.0"
+version = "33.0.0"
description = "Cast kernel and utilities for Apache Arrow"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,11 +38,11 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow-array = { version = "32.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "32.0.0", path = "../arrow-buffer" }
-arrow-data = { version = "32.0.0", path = "../arrow-data" }
-arrow-schema = { version = "32.0.0", path = "../arrow-schema" }
-arrow-select = { version = "32.0.0", path = "../arrow-select" }
+arrow-array = { version = "33.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "33.0.0", path = "../arrow-buffer" }
+arrow-data = { version = "33.0.0", path = "../arrow-data" }
+arrow-schema = { version = "33.0.0", path = "../arrow-schema" }
+arrow-select = { version = "33.0.0", path = "../arrow-select" }
chrono = { version = "0.4.23", default-features = false, features = ["clock"] }
num = { version = "0.4", default-features = false, features = ["std"] }
lexical-core = { version = "^0.8", default-features = false, features = ["write-integers", "write-floats", "parse-integers", "parse-floats"] }
diff --git a/arrow-csv/Cargo.toml b/arrow-csv/Cargo.toml
index 517ffa33f9f0..9d1582b91c2f 100644
--- a/arrow-csv/Cargo.toml
+++ b/arrow-csv/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-csv"
-version = "32.0.0"
+version = "33.0.0"
description = "Support for parsing CSV format into the Arrow format"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,11 +38,11 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow-array = { version = "32.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "32.0.0", path = "../arrow-buffer" }
-arrow-cast = { version = "32.0.0", path = "../arrow-cast" }
-arrow-data = { version = "32.0.0", path = "../arrow-data" }
-arrow-schema = { version = "32.0.0", path = "../arrow-schema" }
+arrow-array = { version = "33.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "33.0.0", path = "../arrow-buffer" }
+arrow-cast = { version = "33.0.0", path = "../arrow-cast" }
+arrow-data = { version = "33.0.0", path = "../arrow-data" }
+arrow-schema = { version = "33.0.0", path = "../arrow-schema" }
chrono = { version = "0.4.23", default-features = false, features = ["clock"] }
csv = { version = "1.1", default-features = false }
csv-core = { version = "0.1"}
diff --git a/arrow-data/Cargo.toml b/arrow-data/Cargo.toml
index 42e1f43bf30d..ca50d8a12aee 100644
--- a/arrow-data/Cargo.toml
+++ b/arrow-data/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-data"
-version = "32.0.0"
+version = "33.0.0"
description = "Array data abstractions for Apache Arrow"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -45,8 +45,8 @@ force_validate = []
[dependencies]
-arrow-buffer = { version = "32.0.0", path = "../arrow-buffer" }
-arrow-schema = { version = "32.0.0", path = "../arrow-schema" }
+arrow-buffer = { version = "33.0.0", path = "../arrow-buffer" }
+arrow-schema = { version = "33.0.0", path = "../arrow-schema" }
num = { version = "0.4", default-features = false, features = ["std"] }
half = { version = "2.1", default-features = false }
diff --git a/arrow-flight/Cargo.toml b/arrow-flight/Cargo.toml
index 1fe382935a1d..603d4a636623 100644
--- a/arrow-flight/Cargo.toml
+++ b/arrow-flight/Cargo.toml
@@ -18,7 +18,7 @@
[package]
name = "arrow-flight"
description = "Apache Arrow Flight"
-version = "32.0.0"
+version = "33.0.0"
edition = "2021"
rust-version = "1.62"
authors = ["Apache Arrow <dev@arrow.apache.org>"]
@@ -27,12 +27,12 @@ repository = "https://github.com/apache/arrow-rs"
license = "Apache-2.0"
[dependencies]
-arrow-array = { version = "32.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "32.0.0", path = "../arrow-buffer" }
+arrow-array = { version = "33.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "33.0.0", path = "../arrow-buffer" }
# Cast is needed to work around https://github.com/apache/arrow-rs/issues/3389
-arrow-cast = { version = "32.0.0", path = "../arrow-cast" }
-arrow-ipc = { version = "32.0.0", path = "../arrow-ipc" }
-arrow-schema = { version = "32.0.0", path = "../arrow-schema" }
+arrow-cast = { version = "33.0.0", path = "../arrow-cast" }
+arrow-ipc = { version = "33.0.0", path = "../arrow-ipc" }
+arrow-schema = { version = "33.0.0", path = "../arrow-schema" }
base64 = { version = "0.21", default-features = false, features = ["std"] }
tonic = { version = "0.8", default-features = false, features = ["transport", "codegen", "prost"] }
bytes = { version = "1", default-features = false }
@@ -50,7 +50,7 @@ flight-sql-experimental = []
tls = ["tonic/tls"]
[dev-dependencies]
-arrow = { version = "32.0.0", path = "../arrow", features = ["prettyprint"] }
+arrow = { version = "33.0.0", path = "../arrow", features = ["prettyprint"] }
tempfile = "3.3"
tokio-stream = { version = "0.1", features = ["net"] }
tower = "0.4.13"
diff --git a/arrow-flight/README.md b/arrow-flight/README.md
index cb543c956d72..7992d93292ce 100644
--- a/arrow-flight/README.md
+++ b/arrow-flight/README.md
@@ -27,7 +27,7 @@ Add this to your Cargo.toml:
```toml
[dependencies]
-arrow-flight = "32.0.0"
+arrow-flight = "33.0.0"
```
Apache Arrow Flight is a gRPC based protocol for exchanging Arrow data between processes. See the blog post [Introducing Apache Arrow Flight: A Framework for Fast Data Transport](https://arrow.apache.org/blog/2019/10/13/introducing-arrow-flight/) for more information.
diff --git a/arrow-ipc/Cargo.toml b/arrow-ipc/Cargo.toml
index 79b34a7b4601..6661f35c0635 100644
--- a/arrow-ipc/Cargo.toml
+++ b/arrow-ipc/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-ipc"
-version = "32.0.0"
+version = "33.0.0"
description = "Support for the Arrow IPC format"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,11 +38,11 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow-array = { version = "32.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "32.0.0", path = "../arrow-buffer" }
-arrow-cast = { version = "32.0.0", path = "../arrow-cast" }
-arrow-data = { version = "32.0.0", path = "../arrow-data" }
-arrow-schema = { version = "32.0.0", path = "../arrow-schema" }
+arrow-array = { version = "33.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "33.0.0", path = "../arrow-buffer" }
+arrow-cast = { version = "33.0.0", path = "../arrow-cast" }
+arrow-data = { version = "33.0.0", path = "../arrow-data" }
+arrow-schema = { version = "33.0.0", path = "../arrow-schema" }
flatbuffers = { version = "23.1.21", default-features = false }
lz4 = { version = "1.23", default-features = false, optional = true }
zstd = { version = "0.12.0", default-features = false, optional = true }
diff --git a/arrow-json/Cargo.toml b/arrow-json/Cargo.toml
index 2a3a7ec1731f..ab77c1843ec0 100644
--- a/arrow-json/Cargo.toml
+++ b/arrow-json/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-json"
-version = "32.0.0"
+version = "33.0.0"
description = "Support for parsing JSON format into the Arrow format"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,11 +38,11 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow-array = { version = "32.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "32.0.0", path = "../arrow-buffer" }
-arrow-cast = { version = "32.0.0", path = "../arrow-cast" }
-arrow-data = { version = "32.0.0", path = "../arrow-data" }
-arrow-schema = { version = "32.0.0", path = "../arrow-schema" }
+arrow-array = { version = "33.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "33.0.0", path = "../arrow-buffer" }
+arrow-cast = { version = "33.0.0", path = "../arrow-cast" }
+arrow-data = { version = "33.0.0", path = "../arrow-data" }
+arrow-schema = { version = "33.0.0", path = "../arrow-schema" }
half = { version = "2.1", default-features = false }
indexmap = { version = "1.9", default-features = false, features = ["std"] }
num = { version = "0.4", default-features = false, features = ["std"] }
diff --git a/arrow-ord/Cargo.toml b/arrow-ord/Cargo.toml
index b029c8b91303..682d68dac857 100644
--- a/arrow-ord/Cargo.toml
+++ b/arrow-ord/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-ord"
-version = "32.0.0"
+version = "33.0.0"
description = "Ordering kernels for arrow arrays"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,11 +38,11 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow-array = { version = "32.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "32.0.0", path = "../arrow-buffer" }
-arrow-data = { version = "32.0.0", path = "../arrow-data" }
-arrow-schema = { version = "32.0.0", path = "../arrow-schema" }
-arrow-select = { version = "32.0.0", path = "../arrow-select" }
+arrow-array = { version = "33.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "33.0.0", path = "../arrow-buffer" }
+arrow-data = { version = "33.0.0", path = "../arrow-data" }
+arrow-schema = { version = "33.0.0", path = "../arrow-schema" }
+arrow-select = { version = "33.0.0", path = "../arrow-select" }
num = { version = "0.4", default-features = false, features = ["std"] }
[dev-dependencies]
diff --git a/arrow-row/Cargo.toml b/arrow-row/Cargo.toml
index f82e499cc302..94210a27a14b 100644
--- a/arrow-row/Cargo.toml
+++ b/arrow-row/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-row"
-version = "32.0.0"
+version = "33.0.0"
description = "Arrow row format"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -44,17 +44,17 @@ ahash = { version = "0.8", default-features = false, features = ["compile-time-r
ahash = { version = "0.8", default-features = false, features = ["runtime-rng"] }
[dependencies]
-arrow-array = { version = "32.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "32.0.0", path = "../arrow-buffer" }
-arrow-data = { version = "32.0.0", path = "../arrow-data" }
-arrow-schema = { version = "32.0.0", path = "../arrow-schema" }
+arrow-array = { version = "33.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "33.0.0", path = "../arrow-buffer" }
+arrow-data = { version = "33.0.0", path = "../arrow-data" }
+arrow-schema = { version = "33.0.0", path = "../arrow-schema" }
half = { version = "2.1", default-features = false }
hashbrown = { version = "0.13", default-features = false }
[dev-dependencies]
-arrow-cast = { version = "32.0.0", path = "../arrow-cast" }
-arrow-ord = { version = "32.0.0", path = "../arrow-ord" }
+arrow-cast = { version = "33.0.0", path = "../arrow-cast" }
+arrow-ord = { version = "33.0.0", path = "../arrow-ord" }
rand = { version = "0.8", default-features = false, features = ["std", "std_rng"] }
[features]
diff --git a/arrow-schema/Cargo.toml b/arrow-schema/Cargo.toml
index c36305b0b283..1a25c1022195 100644
--- a/arrow-schema/Cargo.toml
+++ b/arrow-schema/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-schema"
-version = "32.0.0"
+version = "33.0.0"
description = "Defines the logical types for arrow arrays"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
diff --git a/arrow-select/Cargo.toml b/arrow-select/Cargo.toml
index 8a8af0dbb825..789a23359a16 100644
--- a/arrow-select/Cargo.toml
+++ b/arrow-select/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-select"
-version = "32.0.0"
+version = "33.0.0"
description = "Selection kernels for arrow arrays"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,10 +38,10 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow-buffer = { version = "32.0.0", path = "../arrow-buffer" }
-arrow-data = { version = "32.0.0", path = "../arrow-data" }
-arrow-schema = { version = "32.0.0", path = "../arrow-schema" }
-arrow-array = { version = "32.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "33.0.0", path = "../arrow-buffer" }
+arrow-data = { version = "33.0.0", path = "../arrow-data" }
+arrow-schema = { version = "33.0.0", path = "../arrow-schema" }
+arrow-array = { version = "33.0.0", path = "../arrow-array" }
num = { version = "0.4", default-features = false, features = ["std"] }
[features]
diff --git a/arrow-string/Cargo.toml b/arrow-string/Cargo.toml
index 47740275c0fd..796024e873ef 100644
--- a/arrow-string/Cargo.toml
+++ b/arrow-string/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-string"
-version = "32.0.0"
+version = "33.0.0"
description = "String kernels for arrow arrays"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,11 +38,11 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow-buffer = { version = "32.0.0", path = "../arrow-buffer" }
-arrow-data = { version = "32.0.0", path = "../arrow-data" }
-arrow-schema = { version = "32.0.0", path = "../arrow-schema" }
-arrow-array = { version = "32.0.0", path = "../arrow-array" }
-arrow-select = { version = "32.0.0", path = "../arrow-select" }
+arrow-buffer = { version = "33.0.0", path = "../arrow-buffer" }
+arrow-data = { version = "33.0.0", path = "../arrow-data" }
+arrow-schema = { version = "33.0.0", path = "../arrow-schema" }
+arrow-array = { version = "33.0.0", path = "../arrow-array" }
+arrow-select = { version = "33.0.0", path = "../arrow-select" }
regex = { version = "1.7.0", default-features = false, features = ["std", "unicode", "perf"] }
regex-syntax = { version = "0.6.27", default-features = false, features = ["unicode"] }
diff --git a/arrow/Cargo.toml b/arrow/Cargo.toml
index f86ec09a9ac3..814ca14c8058 100644
--- a/arrow/Cargo.toml
+++ b/arrow/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow"
-version = "32.0.0"
+version = "33.0.0"
description = "Rust implementation of Apache Arrow"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -45,19 +45,19 @@ ahash = { version = "0.8", default-features = false, features = ["compile-time-r
ahash = { version = "0.8", default-features = false, features = ["runtime-rng"] }
[dependencies]
-arrow-arith = { version = "32.0.0", path = "../arrow-arith" }
-arrow-array = { version = "32.0.0", path = "../arrow-array" }
-arrow-buffer = { version = "32.0.0", path = "../arrow-buffer" }
-arrow-cast = { version = "32.0.0", path = "../arrow-cast" }
-arrow-csv = { version = "32.0.0", path = "../arrow-csv", optional = true }
-arrow-data = { version = "32.0.0", path = "../arrow-data" }
-arrow-ipc = { version = "32.0.0", path = "../arrow-ipc", optional = true }
-arrow-json = { version = "32.0.0", path = "../arrow-json", optional = true }
-arrow-ord = { version = "32.0.0", path = "../arrow-ord" }
-arrow-row = { version = "32.0.0", path = "../arrow-row" }
-arrow-schema = { version = "32.0.0", path = "../arrow-schema" }
-arrow-select = { version = "32.0.0", path = "../arrow-select" }
-arrow-string = { version = "32.0.0", path = "../arrow-string" }
+arrow-arith = { version = "33.0.0", path = "../arrow-arith" }
+arrow-array = { version = "33.0.0", path = "../arrow-array" }
+arrow-buffer = { version = "33.0.0", path = "../arrow-buffer" }
+arrow-cast = { version = "33.0.0", path = "../arrow-cast" }
+arrow-csv = { version = "33.0.0", path = "../arrow-csv", optional = true }
+arrow-data = { version = "33.0.0", path = "../arrow-data" }
+arrow-ipc = { version = "33.0.0", path = "../arrow-ipc", optional = true }
+arrow-json = { version = "33.0.0", path = "../arrow-json", optional = true }
+arrow-ord = { version = "33.0.0", path = "../arrow-ord" }
+arrow-row = { version = "33.0.0", path = "../arrow-row" }
+arrow-schema = { version = "33.0.0", path = "../arrow-schema" }
+arrow-select = { version = "33.0.0", path = "../arrow-select" }
+arrow-string = { version = "33.0.0", path = "../arrow-string" }
rand = { version = "0.8", default-features = false, features = ["std", "std_rng"], optional = true }
comfy-table = { version = "6.0", optional = true, default-features = false }
diff --git a/arrow/README.md b/arrow/README.md
index 68598078cfd8..0714285011fa 100644
--- a/arrow/README.md
+++ b/arrow/README.md
@@ -35,7 +35,7 @@ This crate is tested with the latest stable version of Rust. We do not currently
The arrow crate follows the [SemVer standard](https://doc.rust-lang.org/cargo/reference/semver.html) defined by Cargo and works well within the Rust crate ecosystem.
-However, for historical reasons, this crate uses versions with major numbers greater than `0.x` (e.g. `32.0.0`), unlike many other crates in the Rust ecosystem which spend extended time releasing versions `0.x` to signal planned ongoing API changes. Minor arrow releases contain only compatible changes, while major releases may contain breaking API changes.
+However, for historical reasons, this crate uses versions with major numbers greater than `0.x` (e.g. `33.0.0`), unlike many other crates in the Rust ecosystem which spend extended time releasing versions `0.x` to signal planned ongoing API changes. Minor arrow releases contain only compatible changes, while major releases may contain breaking API changes.
## Feature Flags
diff --git a/dev/release/README.md b/dev/release/README.md
index f86513822762..b8018bfaf7b4 100644
--- a/dev/release/README.md
+++ b/dev/release/README.md
@@ -70,7 +70,7 @@ git pull
git checkout -b <RELEASE_BRANCH>
# Update versions. Make sure to run it before the next step since we do not want CHANGELOG-old.md affected.
-sed -i '' -e 's/14.0.0/32.0.0/g' `find . -name 'Cargo.toml' -or -name '*.md' | grep -v CHANGELOG.md`
+sed -i '' -e 's/14.0.0/33.0.0/g' `find . -name 'Cargo.toml' -or -name '*.md' | grep -v CHANGELOG.md`
git commit -a -m 'Update version'
# Copy the content of CHANGELOG.md to the beginning of CHANGELOG-old.md
diff --git a/dev/release/update_change_log.sh b/dev/release/update_change_log.sh
index 2b8396347355..7b773fd05c61 100755
--- a/dev/release/update_change_log.sh
+++ b/dev/release/update_change_log.sh
@@ -29,8 +29,8 @@
set -e
-SINCE_TAG="31.0.0"
-FUTURE_RELEASE="32.0.0"
+SINCE_TAG="32.0.0"
+FUTURE_RELEASE="33.0.0"
SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SOURCE_TOP_DIR="$(cd "${SOURCE_DIR}/../../" && pwd)"
diff --git a/parquet/Cargo.toml b/parquet/Cargo.toml
index a112ec354e8d..d59f481f362f 100644
--- a/parquet/Cargo.toml
+++ b/parquet/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "parquet"
-version = "32.0.0"
+version = "33.0.0"
license = "Apache-2.0"
description = "Apache Parquet implementation in Rust"
homepage = "https://github.com/apache/arrow-rs"
@@ -35,14 +35,14 @@ ahash = { version = "0.8", default-features = false, features = ["compile-time-r
ahash = { version = "0.8", default-features = false, features = ["runtime-rng"] }
[dependencies]
-arrow-array = { version = "32.0.0", path = "../arrow-array", default-features = false, optional = true }
-arrow-buffer = { version = "32.0.0", path = "../arrow-buffer", default-features = false, optional = true }
-arrow-cast = { version = "32.0.0", path = "../arrow-cast", default-features = false, optional = true }
-arrow-csv = { version = "32.0.0", path = "../arrow-csv", default-features = false, optional = true }
-arrow-data = { version = "32.0.0", path = "../arrow-data", default-features = false, optional = true }
-arrow-schema = { version = "32.0.0", path = "../arrow-schema", default-features = false, optional = true }
-arrow-select = { version = "32.0.0", path = "../arrow-select", default-features = false, optional = true }
-arrow-ipc = { version = "32.0.0", path = "../arrow-ipc", default-features = false, optional = true }
+arrow-array = { version = "33.0.0", path = "../arrow-array", default-features = false, optional = true }
+arrow-buffer = { version = "33.0.0", path = "../arrow-buffer", default-features = false, optional = true }
+arrow-cast = { version = "33.0.0", path = "../arrow-cast", default-features = false, optional = true }
+arrow-csv = { version = "33.0.0", path = "../arrow-csv", default-features = false, optional = true }
+arrow-data = { version = "33.0.0", path = "../arrow-data", default-features = false, optional = true }
+arrow-schema = { version = "33.0.0", path = "../arrow-schema", default-features = false, optional = true }
+arrow-select = { version = "33.0.0", path = "../arrow-select", default-features = false, optional = true }
+arrow-ipc = { version = "33.0.0", path = "../arrow-ipc", default-features = false, optional = true }
object_store = { version = "0.5", path = "../object_store", default-features = false, optional = true }
bytes = { version = "1.1", default-features = false, features = ["std"] }
@@ -76,7 +76,7 @@ flate2 = { version = "1.0", default-features = false, features = ["rust_backend"
lz4 = { version = "1.23", default-features = false }
zstd = { version = "0.12", default-features = false }
serde_json = { version = "1.0", features = ["std"], default-features = false }
-arrow = { path = "../arrow", version = "32.0.0", default-features = false, features = ["ipc", "test_utils", "prettyprint", "json"] }
+arrow = { path = "../arrow", version = "33.0.0", default-features = false, features = ["ipc", "test_utils", "prettyprint", "json"] }
tokio = { version = "1.0", default-features = false, features = ["macros", "rt", "io-util", "fs"] }
rand = { version = "0.8", default-features = false, features = ["std", "std_rng"] }
diff --git a/parquet_derive/Cargo.toml b/parquet_derive/Cargo.toml
index 3fdcd66f248c..f648aafbf2fb 100644
--- a/parquet_derive/Cargo.toml
+++ b/parquet_derive/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "parquet_derive"
-version = "32.0.0"
+version = "33.0.0"
license = "Apache-2.0"
description = "Derive macros for the Rust implementation of Apache Parquet"
homepage = "https://github.com/apache/arrow-rs"
@@ -35,4 +35,4 @@ proc-macro = true
proc-macro2 = { version = "1.0", default-features = false }
quote = { version = "1.0", default-features = false }
syn = { version = "1.0", features = ["extra-traits"] }
-parquet = { path = "../parquet", version = "32.0.0", default-features = false }
+parquet = { path = "../parquet", version = "33.0.0", default-features = false }
diff --git a/parquet_derive/README.md b/parquet_derive/README.md
index 14d3c066c7e9..c8ee7ea81101 100644
--- a/parquet_derive/README.md
+++ b/parquet_derive/README.md
@@ -32,8 +32,8 @@ Add this to your Cargo.toml:
```toml
[dependencies]
-parquet = "32.0.0"
-parquet_derive = "32.0.0"
+parquet = "33.0.0"
+parquet_derive = "33.0.0"
```
and this to your crate root:
|
diff --git a/arrow-integration-test/Cargo.toml b/arrow-integration-test/Cargo.toml
index 35b088b1636f..f9ca4297e6e7 100644
--- a/arrow-integration-test/Cargo.toml
+++ b/arrow-integration-test/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "arrow-integration-test"
-version = "32.0.0"
+version = "33.0.0"
description = "Support for the Apache Arrow JSON test data format"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
@@ -38,8 +38,8 @@ path = "src/lib.rs"
bench = false
[dependencies]
-arrow = { version = "32.0.0", path = "../arrow", default-features = false }
-arrow-buffer = { version = "32.0.0", path = "../arrow-buffer" }
+arrow = { version = "33.0.0", path = "../arrow", default-features = false }
+arrow-buffer = { version = "33.0.0", path = "../arrow-buffer" }
hex = { version = "0.4", default-features = false, features = ["std"] }
serde = { version = "1.0", default-features = false, features = ["rc", "derive"] }
serde_json = { version = "1.0", default-features = false, features = ["std"] }
diff --git a/arrow-integration-testing/Cargo.toml b/arrow-integration-testing/Cargo.toml
index 46b2bb3691eb..e22a15f52ddc 100644
--- a/arrow-integration-testing/Cargo.toml
+++ b/arrow-integration-testing/Cargo.toml
@@ -18,7 +18,7 @@
[package]
name = "arrow-integration-testing"
description = "Binaries used in the Arrow integration tests (NOT PUBLISHED TO crates.io)"
-version = "32.0.0"
+version = "33.0.0"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
authors = ["Apache Arrow <dev@arrow.apache.org>"]
diff --git a/arrow-pyarrow-integration-testing/Cargo.toml b/arrow-pyarrow-integration-testing/Cargo.toml
index 02a96cf68fd4..75990dc90279 100644
--- a/arrow-pyarrow-integration-testing/Cargo.toml
+++ b/arrow-pyarrow-integration-testing/Cargo.toml
@@ -18,7 +18,7 @@
[package]
name = "arrow-pyarrow-integration-testing"
description = ""
-version = "32.0.0"
+version = "33.0.0"
homepage = "https://github.com/apache/arrow-rs"
repository = "https://github.com/apache/arrow-rs"
authors = ["Apache Arrow <dev@arrow.apache.org>"]
@@ -32,7 +32,7 @@ name = "arrow_pyarrow_integration_testing"
crate-type = ["cdylib"]
[dependencies]
-arrow = { path = "../arrow", version = "32.0.0", features = ["pyarrow"] }
+arrow = { path = "../arrow", version = "33.0.0", features = ["pyarrow"] }
pyo3 = { version = "0.18", features = ["extension-module"] }
[package.metadata.maturin]
diff --git a/parquet_derive_test/Cargo.toml b/parquet_derive_test/Cargo.toml
index e3306e7c4659..df8fa3aef65a 100644
--- a/parquet_derive_test/Cargo.toml
+++ b/parquet_derive_test/Cargo.toml
@@ -17,7 +17,7 @@
[package]
name = "parquet_derive_test"
-version = "32.0.0"
+version = "33.0.0"
license = "Apache-2.0"
description = "Integration test package for parquet-derive"
homepage = "https://github.com/apache/arrow-rs"
@@ -29,6 +29,6 @@ publish = false
rust-version = "1.62"
[dependencies]
-parquet = { path = "../parquet", version = "32.0.0", default-features = false }
-parquet_derive = { path = "../parquet_derive", version = "32.0.0", default-features = false }
+parquet = { path = "../parquet", version = "33.0.0", default-features = false }
+parquet_derive = { path = "../parquet_derive", version = "33.0.0", default-features = false }
chrono = { version="0.4.23", default-features = false, features = [ "clock" ] }
|
Release 33.0.0 of arrow/arrow-flight/parquet/parquet-derive (next release after 32.0.0)
Follow on from https://github.com/apache/arrow-rs/issues/3584
- Planned Release Candidate: 2023-02-10
- Planned Release and Publish to crates.io: 2023-02-13
Items (from [dev/release/README.md](https://github.com/apache/arrow-rs/blob/master/dev/release/README.md)):
- [x] PR to update version and CHANGELOG: https://github.com/apache/arrow-rs/pull/3686
- [ ] Release candidate created:
- [ ] Release candidate approved:
- [ ] Release to crates.io:
- [ ] Make ticket for next release
See full list here:
https://github.com/apache/arrow-rs/compare/32.0.0...master
cc @alamb @tustvold @viirya
|
Hmm that's not a bug.
@alamb On it. :)
Thanks @iajoiner -- FYI @tustvold
@alamb You’re welcome! Will finish in an hour.
|
2023-02-09T23:31:50Z
|
32.0
|
bb4fc59009e7c5861a6b1967a53e9daa2554d5c6
|
apache/arrow-rs
| 3,673
|
apache__arrow-rs-3673
|
[
"3664"
] |
b79f27b512d46715e9881e34fe4bb525b88fef9d
|
diff --git a/arrow-cast/src/cast.rs b/arrow-cast/src/cast.rs
index 69e42a5485e6..010c77c22455 100644
--- a/arrow-cast/src/cast.rs
+++ b/arrow-cast/src/cast.rs
@@ -168,7 +168,7 @@ pub fn can_cast_types(from_type: &DataType, to_type: &DataType) -> bool {
| Time32(TimeUnit::Millisecond)
| Time64(TimeUnit::Microsecond)
| Time64(TimeUnit::Nanosecond)
- | Timestamp(TimeUnit::Nanosecond, None)
+ | Timestamp(TimeUnit::Nanosecond, _)
) => true,
(Utf8, _) => DataType::is_numeric(to_type) && to_type != &Float16,
(LargeUtf8,
@@ -180,7 +180,7 @@ pub fn can_cast_types(from_type: &DataType, to_type: &DataType) -> bool {
| Time32(TimeUnit::Millisecond)
| Time64(TimeUnit::Microsecond)
| Time64(TimeUnit::Nanosecond)
- | Timestamp(TimeUnit::Nanosecond, None)
+ | Timestamp(TimeUnit::Nanosecond, _)
) => true,
(LargeUtf8, _) => DataType::is_numeric(to_type) && to_type != &Float16,
(Timestamp(_, _), Utf8) | (Timestamp(_, _), LargeUtf8) => true,
@@ -1145,7 +1145,7 @@ pub fn cast_with_options(
Time64(TimeUnit::Nanosecond) => {
cast_string_to_time64nanosecond::<i32>(array, cast_options)
}
- Timestamp(TimeUnit::Nanosecond, None) => {
+ Timestamp(TimeUnit::Nanosecond, _) => {
cast_string_to_timestamp_ns::<i32>(array, cast_options)
}
_ => Err(ArrowError::CastError(format!(
@@ -1254,7 +1254,7 @@ pub fn cast_with_options(
Time64(TimeUnit::Nanosecond) => {
cast_string_to_time64nanosecond::<i64>(array, cast_options)
}
- Timestamp(TimeUnit::Nanosecond, None) => {
+ Timestamp(TimeUnit::Nanosecond, _) => {
cast_string_to_timestamp_ns::<i64>(array, cast_options)
}
_ => Err(ArrowError::CastError(format!(
@@ -7833,4 +7833,42 @@ mod tests {
assert_eq!(v.value(0), 946728000000);
assert_eq!(v.value(1), 1608035696000);
}
+
+ #[test]
+ fn test_cast_utf8_to_timestamp() {
+ fn test_tz(tz: String) {
+ let valid = StringArray::from(vec![
+ "2023-01-01 04:05:06.789000-08:00",
+ "2023-01-01 04:05:06.789000-07:00",
+ "2023-01-01 04:05:06.789 -0800",
+ "2023-01-01 04:05:06.789 -08:00",
+ "2023-01-01 040506 +0730",
+ "2023-01-01 040506 +07:30",
+ "2023-01-01 04:05:06.789",
+ "2023-01-01 04:05:06",
+ "2023-01-01",
+ ]);
+
+ let array = Arc::new(valid) as ArrayRef;
+ let b = cast(&array, &DataType::Timestamp(TimeUnit::Nanosecond, Some(tz)))
+ .unwrap();
+
+ let c = b
+ .as_any()
+ .downcast_ref::<TimestampNanosecondArray>()
+ .unwrap();
+ assert_eq!(1672574706789000000, c.value(0));
+ assert_eq!(1672571106789000000, c.value(1));
+ assert_eq!(1672574706789000000, c.value(2));
+ assert_eq!(1672574706789000000, c.value(3));
+ assert_eq!(1672518906000000000, c.value(4));
+ assert_eq!(1672518906000000000, c.value(5));
+ assert_eq!(1672545906789000000, c.value(6));
+ assert_eq!(1672545906000000000, c.value(7));
+ assert_eq!(1672531200000000000, c.value(8));
+ }
+
+ test_tz("+00:00".to_owned());
+ test_tz("+02:00".to_owned());
+ }
}
diff --git a/arrow-cast/src/parse.rs b/arrow-cast/src/parse.rs
index 459b94f37dc8..f23e65b22845 100644
--- a/arrow-cast/src/parse.rs
+++ b/arrow-cast/src/parse.rs
@@ -68,6 +68,14 @@ use chrono::prelude::*;
/// the system timezone is set to Americas/New_York (UTC-5) the
/// timestamp will be interpreted as though it were
/// `1997-01-31T09:26:56.123-05:00`
+///
+/// Some formats that supported by PostgresSql <https://www.postgresql.org/docs/current/datatype-datetime.html#DATATYPE-DATETIME-TIME-TABLE>
+/// still not supported by chrono, like
+/// "2023-01-01 040506 America/Los_Angeles",
+/// "2023-01-01 04:05:06.789 +07:30:00",
+/// "2023-01-01 040506 +07:30:00",
+/// "2023-01-01 04:05:06.789 PST",
+/// "2023-01-01 04:05:06.789 -08",
#[inline]
pub fn string_to_timestamp_nanos(s: &str) -> Result<i64, ArrowError> {
// Fast path: RFC3339 timestamp (with a T)
@@ -81,10 +89,15 @@ pub fn string_to_timestamp_nanos(s: &str) -> Result<i64, ArrowError> {
// separating the date and time with a space ' ' rather than 'T' to be
// (more) compatible with Apache Spark SQL
- // timezone offset, using ' ' as a separator
- // Example: 2020-09-08 13:42:29.190855-05:00
- if let Ok(ts) = DateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S%.f%:z") {
- return to_timestamp_nanos(ts.naive_utc());
+ let supported_formats = vec![
+ "%Y-%m-%d %H:%M:%S%.f%:z", // Example: 2020-09-08 13:42:29.190855-05:00
+ "%Y-%m-%d %H%M%S%.3f%:z", // Example: "2023-01-01 040506 +07:30"
+ ];
+
+ for f in supported_formats.iter() {
+ if let Ok(ts) = DateTime::parse_from_str(s, f) {
+ return to_timestamp_nanos(ts.naive_utc());
+ }
}
// with an explicit Z, using ' ' as a separator
|
diff --git a/arrow/tests/array_cast.rs b/arrow/tests/array_cast.rs
index ae73b1b4200b..55719a6c7187 100644
--- a/arrow/tests/array_cast.rs
+++ b/arrow/tests/array_cast.rs
@@ -97,7 +97,7 @@ fn test_can_cast_types() {
/// Create instances of arrays with varying types for cast tests
fn get_arrays_of_all_types() -> Vec<ArrayRef> {
- let tz_name = String::from("America/New_York");
+ let tz_name = String::from("+08:00");
let binary_data: Vec<&[u8]> = vec![b"foo", b"bar"];
vec![
Arc::new(BinaryArray::from(binary_data.clone())),
@@ -349,7 +349,7 @@ fn create_decimal_array(
// Get a selection of datatypes to try and cast to
fn get_all_types() -> Vec<DataType> {
use DataType::*;
- let tz_name = String::from("America/New_York");
+ let tz_name = String::from("+08:00");
let mut types = vec![
Null,
|
Support UTF8 cast to Timestamp with timezone
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
Support cast UTF8 to Timestamp with time zone
<!--
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
(This section helps Arrow developers understand the context and *why* for this feature, in addition to the *what*)
-->
**Describe the solution you'd like**
<!--
A clear and concise description of what you want to happen.
-->
Support UTF8 cast to TimestampTZ in formats like PG https://www.postgresql.org/docs/current/datatype-datetime.html#DATATYPE-DATETIME-TIME-TABLE
**Describe alternatives you've considered**
<!--
A clear and concise description of any alternative solutions or features you've considered.
-->
Not doing this
**Additional context**
<!--
Add any other context or screenshots about the feature request here.
-->
Original ticket https://github.com/apache/arrow-datafusion/issues/5164
|
@viirya @waitingkuo @alamb please assign this issue to me
```
let valid = StringArray::from(vec![
"2023-01-01 04:05:06.789-8",
"2023-01-01 04:05:06.789-7",
]);
let array = Arc::new(valid) as ArrayRef;
let b = cast(&array, &DataType::Timestamp(TimeUnit::Nanosecond,?????????)).unwrap();
```
As I mentioned https://github.com/apache/arrow-datafusion/issues/5164#issuecomment-1416887886 currently the `cast` function supports one target datatype which includes only 1 timezone info, however input array can have mixed timezones, like in example above
@viirya @waitingkuo please let me know your thoughts. Probably cast functions should accept array type `TimestampNanosecondArray` instead of primitive type `DataType::Timestamp`
> however input array can have mixed timezones,
My naive expectation in such a case is that it would cast the timestamps to the provided output timezone. So in your example
```
let valid = StringArray::from(vec![
"2023-01-01 04:05:06.789-8",
"2023-01-01 04:05:06.789-7",
]);
let array = Arc::new(valid) as ArrayRef;
let b = cast(&array, &DataType::Timestamp(TimeUnit::Nanosecond, Some("+02:00".to_string()))).unwrap();
```
Would result in
```
"2023-01-01 14:05:06.789+2"
"2023-01-01 13:05:06.789+2"
```
Or to put it differently, each row would be parsed with any FixedOffset specific to that row, and it would then be converted to the output timezone. This would preserve the notion of the same point in time, but represented in different timezones.
This is also consistent with how timezone casts for timezone casts work, where the conversion is a metadata only operation (as TimestampArray always stores time since UTC epoch)
> Probably cast functions should accept array type TimestampNanosecondArray instead of primitive type DataType::Timestamp
I don't follow what you mean by this
@tustvold sorry probably I have expressed not very clear. The entire idea is to cast user provided Utf8 value to Timestamp with timezone like
```
select "2023-01-01 04:05:06.789-8"::timestamptz union all
select "2023-01-01 04:05:06.789-7"::timestamptz
```
In Datafusion such transformation happens through arrow-rs `cast` function which has single target datatype , in this specific case I believe it would be `DataType::Timestamp(TimeUnit::Nanosecond, Something)` where is Something is not very clear for me. Presumably we can use `+00:00` or `None`, I'm struggling if we can lose precision in this case.
> we can use +00:00
I think using `+00:00` makes sense to me, DataFusion is already smart enough to then coerce this where necessary to a different timezone (which is a purely metadata operation).
> I'm struggling if we can lose precision in this case
I think this is fine, timestamps are always stored with respect to UTC Unix epoch, and so this should have no impact on overflow behaviour.
Thanks @tustvold
Should we support all supported PG formats https://www.postgresql.org/docs/current/datatype-datetime.html#DATATYPE-DATETIME-TIME-TABLE
I'm doing some test
```
let valid = StringArray::from(vec![
"2023-01-01 04:05:06.789000-08:00",
"2023-01-01 04:05:06.789000-07:00",
"2023-01-01 04:05:06.789 PST",
"2023-01-01 04:05:06.789-8",
"2023-01-01 04:05:06.789-800",
"2023-01-01 04:05:06.789-8:00",
"2023-01-01 04:05:06.789+07:30:00",
"2023-01-01 040506+07:30:00",
"2023-01-01 040506+0730",
"2023-01-01 040506 America/Los_Angeles",
"2023-01-01 04:05:06",
"2023-01-01",
]);
```
All those valid for PG, but there is potential performance problem as we need to iterate through multiple formats until we find the match
> @tustvold sorry probably I have expressed not very clear. The entire idea is to cast user provided Utf8 value to Timestamp with timezone like
>
> ```
> select "2023-01-01 04:05:06.789-8"::timestamptz union all
> select "2023-01-01 04:05:06.789-7"::timestamptz
> ```
>
> In Datafusion such transformation happens through arrow-rs `cast` function which has single target datatype , in this specific case I believe it would be `DataType::Timestamp(TimeUnit::Nanosecond, Something)` where is Something is not very clear for me. Presumably we can use `+00:00` or `None`, I'm struggling if we can lose precision in this case.
I think casting to timestamptz should return the same time zone (the one shown in `SHOW TIME ZONE`) in the same query.
i'm in UTC+8
in postgresql, `select '2023-01-01 04:05:06.789-8'::timestamptz` returns timestamptz in UTC+8
```bash
willy=# select '2023-01-01T04:05:06.789-8'::timestamptz;
timestamptz
----------------------------
2023-01-01 20:05:06.789+08
(1 row)
```
```bash
willy=# select '2023-01-01 04:05:06.789-7'::timestamptz;
timestamptz
----------------------------
2023-01-01 19:05:06.789+08
(1 row)
```
so in your query, the union return +8 time zone (my current time zone) for me in postgresql.
I think we could consider either fix it to +00:00 or current timezone
|
2023-02-07T19:06:14Z
|
32.0
|
bb4fc59009e7c5861a6b1967a53e9daa2554d5c6
|
apache/arrow-rs
| 3,602
|
apache__arrow-rs-3602
|
[
"3599"
] |
f0be9da82cbd76da3042b426daf6c424c9560d93
|
diff --git a/arrow-arith/src/aggregate.rs b/arrow-arith/src/aggregate.rs
index a1cf8d84954c..b578dbd4a94c 100644
--- a/arrow-arith/src/aggregate.rs
+++ b/arrow-arith/src/aggregate.rs
@@ -1072,7 +1072,8 @@ mod tests {
#[test]
fn test_string_min_max_all_nulls() {
- let a = StringArray::from(vec![None, None]);
+ let v: Vec<Option<&str>> = vec![None, None];
+ let a = StringArray::from(v);
assert_eq!(None, min_string(&a));
assert_eq!(None, max_string(&a));
}
diff --git a/arrow-array/src/array/string_array.rs b/arrow-array/src/array/string_array.rs
index 4a4152adc678..926bcc7bf3c1 100644
--- a/arrow-array/src/array/string_array.rs
+++ b/arrow-array/src/array/string_array.rs
@@ -249,6 +249,14 @@ impl<OffsetSize: OffsetSizeTrait> From<Vec<&str>> for GenericStringArray<OffsetS
}
}
+impl<OffsetSize: OffsetSizeTrait> From<Vec<Option<String>>>
+ for GenericStringArray<OffsetSize>
+{
+ fn from(v: Vec<Option<String>>) -> Self {
+ v.into_iter().collect()
+ }
+}
+
impl<OffsetSize: OffsetSizeTrait> From<Vec<String>> for GenericStringArray<OffsetSize> {
fn from(v: Vec<String>) -> Self {
Self::from_iter_values(v)
@@ -439,6 +447,13 @@ mod tests {
assert_eq!(array1.value(0), "hello");
assert_eq!(array1.value(1), "hello2");
+
+ // Also works with String types.
+ let data2: Vec<String> = vec!["goodbye".into(), "goodbye2".into()];
+ let array2 = StringArray::from_iter_values(data2.iter());
+
+ assert_eq!(array2.value(0), "goodbye");
+ assert_eq!(array2.value(1), "goodbye2");
}
#[test]
@@ -467,7 +482,7 @@ mod tests {
#[test]
fn test_string_array_all_null() {
- let data = vec![None];
+ let data: Vec<Option<&str>> = vec![None];
let array = StringArray::from(data);
array
.data()
@@ -477,7 +492,7 @@ mod tests {
#[test]
fn test_large_string_array_all_null() {
- let data = vec![None];
+ let data: Vec<Option<&str>> = vec![None];
let array = LargeStringArray::from(data);
array
.data()
diff --git a/arrow-array/src/builder/generic_bytes_dictionary_builder.rs b/arrow-array/src/builder/generic_bytes_dictionary_builder.rs
index 449100da1e0e..5af41a51948b 100644
--- a/arrow-array/src/builder/generic_bytes_dictionary_builder.rs
+++ b/arrow-array/src/builder/generic_bytes_dictionary_builder.rs
@@ -641,8 +641,9 @@ mod tests {
#[test]
fn test_string_dictionary_builder_with_reserved_null_value() {
+ let v: Vec<Option<&str>> = vec![None];
test_bytes_dictionary_builder_with_reserved_null_value::<GenericStringType<i32>>(
- StringArray::from(vec![None]),
+ StringArray::from(v),
vec!["abc", "def"],
);
}
diff --git a/arrow-ord/src/comparison.rs b/arrow-ord/src/comparison.rs
index 4754aeb1f75a..b8b510a2eb84 100644
--- a/arrow-ord/src/comparison.rs
+++ b/arrow-ord/src/comparison.rs
@@ -3712,7 +3712,8 @@ mod tests {
// value_offsets = [0, 3, 6, 6]
let list_array = builder.finish();
- let nulls = StringArray::from(vec![None, None, None, None]);
+ let v: Vec<Option<&str>> = vec![None, None, None, None];
+ let nulls = StringArray::from(v);
let nulls_result = contains_utf8(&nulls, &list_array).unwrap();
assert_eq!(
nulls_result
|
diff --git a/arrow/tests/array_transform.rs b/arrow/tests/array_transform.rs
index 3c08a592dd2c..34ef6cbae428 100644
--- a/arrow/tests/array_transform.rs
+++ b/arrow/tests/array_transform.rs
@@ -433,7 +433,8 @@ fn test_struct_nulls() {
let data = mutable.freeze();
let array = StructArray::from(data);
- let expected_string = Arc::new(StringArray::from(vec![None, None])) as ArrayRef;
+ let v: Vec<Option<&str>> = vec![None, None];
+ let expected_string = Arc::new(StringArray::from(v)) as ArrayRef;
let expected_int = Arc::new(Int32Array::from(vec![Some(2), None])) as ArrayRef;
let expected =
|
There should be a `From<Vec<Option<String>>>` impl for `GenericStringArray<OffsetSize>`
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
I have a `Vec<Option<String>>`, and I want it to be a `StringArray`. Right now the only relevant impls to do this are:
* `From<Vec<String>>`
* `From<Vec<&str>>`
* `From<Vec<Option<&str>>>`
[Relevant code here](https://github.com/apache/arrow-rs/blob/d938cd9bf621c9bf3c3bd9e33c4c0a5eb4060534/arrow-array/src/array/string_array.rs#L238)
So it seems reasonable for there to be an impl for `Option<String>`
**Describe the solution you'd like**
Adding this impl would allow me to do
```rs
let my_string: String = ...;
let stringarray: ArrayRef = Arc::new(StringArray::from(vec![Some(my_string), None]));
```
**Additional context**
I'm happy to add this if yall are interested. Just wanted to write this out to see if it could be considered.
|
Makes sense to me, would be happy to review a PR that implemented this.
FWIW from_iter should work I think
|
2023-01-25T14:09:57Z
|
31.0
|
f0be9da82cbd76da3042b426daf6c424c9560d93
|
apache/arrow-rs
| 3,557
|
apache__arrow-rs-3557
|
[
"3552"
] |
3ae1c728b266c1ba801409eb7f4b901285783e94
|
diff --git a/arrow/Cargo.toml b/arrow/Cargo.toml
index 8719cba0effe..ee926ee52868 100644
--- a/arrow/Cargo.toml
+++ b/arrow/Cargo.toml
@@ -61,7 +61,7 @@ arrow-string = { version = "31.0.0", path = "../arrow-string" }
rand = { version = "0.8", default-features = false, features = ["std", "std_rng"], optional = true }
comfy-table = { version = "6.0", optional = true, default-features = false }
-pyo3 = { version = "0.17", default-features = false, optional = true }
+pyo3 = { version = "0.18", default-features = false, optional = true }
bitflags = { version = "1.2.1", default-features = false, optional = true }
[package.metadata.docs.rs]
|
diff --git a/arrow-pyarrow-integration-testing/Cargo.toml b/arrow-pyarrow-integration-testing/Cargo.toml
index e1fa90836f61..7a2dc563a1ac 100644
--- a/arrow-pyarrow-integration-testing/Cargo.toml
+++ b/arrow-pyarrow-integration-testing/Cargo.toml
@@ -33,7 +33,7 @@ crate-type = ["cdylib"]
[dependencies]
arrow = { path = "../arrow", version = "31.0.0", features = ["pyarrow"] }
-pyo3 = { version = "0.17", features = ["extension-module"] }
+pyo3 = { version = "0.18", features = ["extension-module"] }
[package.metadata.maturin]
requires-dist = ["pyarrow>=1"]
|
Update pyo3 requirement from 0.17 to 0.18
Updates the requirements on [pyo3](https://github.com/pyo3/pyo3) to permit the latest version.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a href="https://github.com/pyo3/pyo3/releases">pyo3's releases</a>.</em></p>
<blockquote>
<h2>PyO3 0.18.0</h2>
<p>This release contains a number of new features for PyO3's macros which should make maintaining PyO3 projects easier.</p>
<p><code>#[pyfunction]</code> and <code>#[pymethods]</code> have a new <code>#[pyo3(signature = (...))]</code> option which allows specifying the Python signature. This replaces the <code>#[args]</code> option already present for <code>#[pymethods]</code>; the new option is better-validated and offers a syntax much more intuitive to users familiar with writing pure-Python functions.</p>
<p><code>#[pyclass]</code> has new <code>get_all</code> and <code>set_all</code> options for cases where <em>all</em> fields of a type should be readable or writable from Python.</p>
<p>The <code>#[pyo3(text_signature = "...")]</code> option is now autogenerated for all functions created with <code>#[pyfunction]</code> and <code>#[pymethods]</code>. It can still be applied manually when it is necessary to override the generated form.</p>
<p>As well as the macro API improvements, some other notable changes include:</p>
<ul>
<li><code>PySet::new</code> and <code>PyFrozenSet::new</code> now accept Rust iterators rather than requiring a slice.</li>
<li>Rust types have been added for all Python's built-in <code>Warning</code> types.</li>
<li>Non-zero integer types in <code>std::num</code> now have a conversion to/from Python <code>int</code>.</li>
<li>The deprecated <code>#[pyproto]</code> attribute is now removed.</li>
</ul>
<p>There have been numerous other smaller improvements, changes and fixes. For full details see the <a href="https://pyo3.rs/v0.18.0/changelog.html">CHANGELOG</a>.</p>
<p>Please consult the <a href="https://pyo3.rs/v0.18.0/migration.html">migration guide</a> for help upgrading.</p>
<p>Thank you to everyone who contributed code, documentation, design ideas, bug reports, and feedback. The following users' commits are included in this release:</p>
<p><a href="https://github.com/a1phyr"><code>@a1phyr</code></a>
<a href="https://github.com/adamreichold"><code>@adamreichold</code></a>
<a href="https://github.com/AdilZouitine"><code>@AdilZouitine</code></a>
<a href="https://github.com/alex"><code>@alex</code></a>
<a href="https://github.com/birkenfeld"><code>@birkenfeld</code></a>
<a href="https://github.com/CLOVIS-AI"><code>@CLOVIS-AI</code></a>
<a href="https://github.com/ctb"><code>@ctb</code></a>
<a href="https://github.com/dalcde"><code>@dalcde</code></a>
<a href="https://github.com/datapythonista"><code>@datapythonista</code></a>
<a href="https://github.com/davidhewitt"><code>@davidhewitt</code></a>
<a href="https://github.com/dylanbstorey"><code>@dylanbstorey</code></a>
<a href="https://github.com/flickpp"><code>@flickpp</code></a>
<a href="https://github.com/gnaaman-dn"><code>@gnaaman-dn</code></a>
<a href="https://github.com/haixuanTao"><code>@haixuanTao</code></a>
<a href="https://github.com/hauntsaninja"><code>@hauntsaninja</code></a>
<a href="https://github.com/ijl"><code>@ijl</code></a>
<a href="https://github.com/itamarst"><code>@itamarst</code></a>
<a href="https://github.com/jqnatividad"><code>@jqnatividad</code></a>
<a href="https://github.com/matthewlloyd"><code>@matthewlloyd</code></a>
<a href="https://github.com/mejrs"><code>@mejrs</code></a>
<a href="https://github.com/messense"><code>@messense</code></a>
<a href="https://github.com/mrob95"><code>@mrob95</code></a>
<a href="https://github.com/ongchi"><code>@ongchi</code></a>
<a href="https://github.com/Oppen"><code>@Oppen</code></a>
<a href="https://github.com/prehner"><code>@prehner</code></a>
<a href="https://github.com/Psykopear"><code>@Psykopear</code></a>
<a href="https://github.com/qbx2"><code>@qbx2</code></a>
<a href="https://github.com/ryanrussell"><code>@ryanrussell</code></a>
<a href="https://github.com/saethlin"><code>@saethlin</code></a></p>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a href="https://github.com/PyO3/pyo3/blob/main/CHANGELOG.md">pyo3's changelog</a>.</em></p>
<blockquote>
<h2>[0.18.0] - 2023-01-17</h2>
<h3>Packaging</h3>
<ul>
<li>Relax <code>indexmap</code> optional depecency to allow <code>>= 1.6, < 2</code>. [#2849](<a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2849">PyO3/pyo3#2849</a></li>
<li>Relax <code>hashbrown</code> optional dependency to allow <code>>= 0.9, < 0.14</code>. <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2875">#2875</a></li>
<li>Update <code>memoffset</code> dependency to 0.8. <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2875">#2875</a></li>
</ul>
<h3>Added</h3>
<ul>
<li>Add <code>GILOnceCell::get_or_try_init</code> for fallible <code>GILOnceCell</code> initialization. <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2398">#2398</a></li>
<li>Add experimental feature <code>experimental-inspect</code> with <code>type_input()</code> and <code>type_output()</code> helpers to get the Python type of any Python-compatible object. <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2490">#2490</a> <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2882">#2882</a></li>
<li>The <code>#[pyclass]</code> macro can now take <code>get_all</code> and <code>set_all</code> to create getters and setters for every field. <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2692">#2692</a></li>
<li>Add <code>#[pyo3(signature = (...))]</code> option for <code>#[pyfunction]</code> and <code>#[pymethods]</code>. <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2702">#2702</a></li>
<li><code>pyo3-build-config</code>: rebuild when <code>PYO3_ENVIRONMENT_SIGNATURE</code> environment variable value changes. <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2727">#2727</a></li>
<li>Add conversions between non-zero int types in <code>std::num</code> and Python <code>int</code>. <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2730">#2730</a></li>
<li>Add <code>Py::downcast()</code> as a companion to <code>PyAny::downcast()</code>, as well as <code>downcast_unchecked()</code> for both types. <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2734">#2734</a></li>
<li>Add types for all built-in <code>Warning</code> classes as well as <code>PyErr::warn_explicit</code>. <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2742">#2742</a></li>
<li>Add <code>abi3-py311</code> feature. <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2776">#2776</a></li>
<li>Add FFI definition <code>_PyErr_ChainExceptions()</code> for CPython. <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2788">#2788</a></li>
<li>Add FFI definitions <code>PyVectorcall_NARGS</code> and <code>PY_VECTORCALL_ARGUMENTS_OFFSET</code> for PyPy 3.8 and up. <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2811">#2811</a></li>
<li>Add <code>PyList::get_item_unchecked</code> for PyPy. <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2827">#2827</a></li>
</ul>
<h3>Changed</h3>
<ul>
<li>PyO3's macros now emit a much nicer error message if function return values don't implement the required trait(s). <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2664">#2664</a></li>
<li>Use a TypeError, rather than a ValueError, when refusing to treat a str as a Vec. <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2685">#2685</a></li>
<li>Change <code>PyCFunction::new_closure</code> to take <code>name</code> and <code>doc</code> arguments. <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2686">#2686</a></li>
<li><code>PyType::is_subclass</code>, <code>PyErr::is_instance</code> and <code>PyAny::is_instance</code> now take <code>&PyAny</code> instead of <code>&PyType</code> arguments, so that they work with objects that pretend to be types using <code>__subclasscheck__</code> and <code>__instancecheck__</code>. <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2695">#2695</a></li>
<li>Deprecate <code>#[args]</code> attribute and passing "args" specification directly to <code>#[pyfunction]</code> in favor of the new <code>#[pyo3(signature = (...))]</code> option. <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2702">#2702</a></li>
<li>Deprecate required arguments after <code>Option<T></code> arguments to <code>#[pyfunction]</code> and <code>#[pymethods]</code> without also using <code>#[pyo3(signature)]</code> to specify whether the arguments should be required or have defaults. <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2703">#2703</a></li>
<li>Change <code>#[pyfunction]</code> and <code>#[pymethods]</code> to use a common call "trampoline" to slightly reduce generated code size and compile times. <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2705">#2705</a></li>
<li><code>PyAny::cast_as()</code> and <code>Py::cast_as()</code> are now deprecated in favor of <code>PyAny::downcast()</code> and the new <code>Py::downcast()</code>. <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2734">#2734</a></li>
<li>Relax lifetime bounds on <code>PyAny::downcast()</code>. <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2734">#2734</a></li>
<li>Automatically generate <code>__text_signature__</code> for all Python functions created using <code>#[pyfunction]</code> and <code>#[pymethods]</code>. <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2784">#2784</a></li>
<li>Accept any iterator in <code>PySet::new</code> and <code>PyFrozenSet::new</code>. <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2795">#2795</a></li>
<li>Mixing <code>#[cfg(...)]</code> and <code>#[pyo3(...)]</code> attributes on <code>#[pyclass]</code> struct fields will now work. <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2796">#2796</a></li>
<li>Re-enable <code>PyFunction</code> on when building for abi3 or PyPy. <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2838">#2838</a></li>
<li>Improve <code>derive(FromPyObject)</code> to use <code>intern!</code> when applicable for <code>#[pyo3(item)]</code>. <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2838">#2838</a></li>
</ul>
<h3>Removed</h3>
<ul>
<li>Remove the deprecated <code>pyproto</code> feature, <code>#[pyproto]</code> macro, and all accompanying APIs. <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2587">#2587</a></li>
<li>Remove all functionality deprecated in PyO3 0.16. <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2843">#2843</a></li>
</ul>
<h3>Fixed</h3>
<ul>
<li>Disable <code>PyModule::filename</code> on PyPy. <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2715">#2715</a></li>
<li><code>PyCodeObject</code> is now once again defined with fields on Python 3.7. <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2726">#2726</a></li>
<li>Raise a <code>TypeError</code> if <code>#[new]</code> pymethods with no arguments receive arguments when called from Python. <a href="https://github-redirect.dependabot.com/PyO3/pyo3/pull/2749">#2749</a></li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a href="https://github.com/PyO3/pyo3/commit/224a4160b440a8f2577aa8eefa6a98886fc6b86f"><code>224a416</code></a> release: 0.18.0</li>
<li><a href="https://github.com/PyO3/pyo3/commit/ca1bbe3d39c3152924a55b23bb87189deb102190"><code>ca1bbe3</code></a> add migration notes for PyO3 0.18</li>
<li><a href="https://github.com/PyO3/pyo3/commit/72c561ce13240f6e35bfd9ae5c82d2628a1b50f1"><code>72c561c</code></a> Merge <a href="https://github-redirect.dependabot.com/pyo3/pyo3/issues/2882">#2882</a></li>
<li><a href="https://github.com/PyO3/pyo3/commit/713f51a7df235fbf25bfcce8079fd64ca2f3c3a9"><code>713f51a</code></a> Merge <a href="https://github-redirect.dependabot.com/pyo3/pyo3/issues/2879">#2879</a></li>
<li><a href="https://github.com/PyO3/pyo3/commit/8026f3521e6b1e9877f81283e5da4a7932565a4c"><code>8026f35</code></a> Improve derive(FromPyObject) to apply intern! when applicable</li>
<li><a href="https://github.com/PyO3/pyo3/commit/20ca3be659019deddca6c95833b9922d75d4cb87"><code>20ca3be</code></a> inspect: gate behind <code>experimental-inspect</code> feature</li>
<li><a href="https://github.com/PyO3/pyo3/commit/556b3cf48ac8b89a63e0378f48681273d074e151"><code>556b3cf</code></a> Merge <a href="https://github-redirect.dependabot.com/pyo3/pyo3/issues/2703">#2703</a></li>
<li><a href="https://github.com/PyO3/pyo3/commit/8f48d157d643f1bb17d763d9fe4b8951014ac3d9"><code>8f48d15</code></a> deprecate required arguments after option arguments without signature</li>
<li><a href="https://github.com/PyO3/pyo3/commit/ed0f3384d2db45a142eb04865dfb75a383840552"><code>ed0f338</code></a> Merge <a href="https://github-redirect.dependabot.com/pyo3/pyo3/issues/2875">#2875</a></li>
<li><a href="https://github.com/PyO3/pyo3/commit/a7a9daed24c761f271d0092bdb50f2ca79aa6004"><code>a7a9dae</code></a> Add a changelog entry for <code>[#2875](https://github.com/pyo3/pyo3/issues/2875)</code></li>
<li>Additional commits viewable in <a href="https://github.com/pyo3/pyo3/compare/v0.17.0...v0.18.0">compare view</a></li>
</ul>
</details>
<br />
Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.
[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)
---
<details>
<summary>Dependabot commands and options</summary>
<br />
You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
</details>
|
2023-01-18T18:37:59Z
|
31.0
|
f0be9da82cbd76da3042b426daf6c424c9560d93
|
|
apache/arrow-rs
| 3,542
|
apache__arrow-rs-3542
|
[
"1179"
] |
d938cd9bf621c9bf3c3bd9e33c4c0a5eb4060534
|
diff --git a/arrow-cast/src/cast.rs b/arrow-cast/src/cast.rs
index c54761840167..c60e660378aa 100644
--- a/arrow-cast/src/cast.rs
+++ b/arrow-cast/src/cast.rs
@@ -151,13 +151,16 @@ pub fn can_cast_types(from_type: &DataType, to_type: &DataType) -> bool {
(_, Decimal256(_, _)) => false,
(Struct(_), _) => false,
(_, Struct(_)) => false,
- (_, Boolean) => DataType::is_numeric(from_type) || from_type == &Utf8,
- (Boolean, _) => DataType::is_numeric(to_type) || to_type == &Utf8,
+ (_, Boolean) => DataType::is_numeric(from_type) || from_type == &Utf8 || from_type == &LargeUtf8,
+ (Boolean, _) => DataType::is_numeric(to_type) || to_type == &Utf8 || to_type == &LargeUtf8,
(Utf8, LargeUtf8) => true,
(LargeUtf8, Utf8) => true,
+ (Binary, LargeBinary) => true,
+ (LargeBinary, Binary) => true,
(Utf8,
Binary
+ | LargeBinary
| Date32
| Date64
| Time32(TimeUnit::Second)
@@ -168,7 +171,8 @@ pub fn can_cast_types(from_type: &DataType, to_type: &DataType) -> bool {
) => true,
(Utf8, _) => DataType::is_numeric(to_type) && to_type != &Float16,
(LargeUtf8,
- LargeBinary
+ Binary
+ | LargeBinary
| Date32
| Date64
| Time32(TimeUnit::Second)
@@ -1075,7 +1079,8 @@ pub fn cast_with_options(
Float16 => cast_numeric_to_bool::<Float16Type>(array),
Float32 => cast_numeric_to_bool::<Float32Type>(array),
Float64 => cast_numeric_to_bool::<Float64Type>(array),
- Utf8 => cast_utf8_to_boolean(array, cast_options),
+ Utf8 => cast_utf8_to_boolean::<i32>(array, cast_options),
+ LargeUtf8 => cast_utf8_to_boolean::<i64>(array, cast_options),
_ => Err(ArrowError::CastError(format!(
"Casting from {:?} to {:?} not supported",
from_type, to_type,
@@ -1102,13 +1107,22 @@ pub fn cast_with_options(
.collect::<StringArray>(),
))
}
+ LargeUtf8 => {
+ let array = array.as_any().downcast_ref::<BooleanArray>().unwrap();
+ Ok(Arc::new(
+ array
+ .iter()
+ .map(|value| value.map(|value| if value { "1" } else { "0" }))
+ .collect::<LargeStringArray>(),
+ ))
+ }
_ => Err(ArrowError::CastError(format!(
"Casting from {:?} to {:?} not supported",
from_type, to_type,
))),
},
(Utf8, _) => match to_type {
- LargeUtf8 => cast_str_container::<i32, i64>(&**array),
+ LargeUtf8 => cast_byte_container::<Utf8Type, LargeUtf8Type, str>(&**array),
UInt8 => cast_string_to_numeric::<UInt8Type, i32>(array, cast_options),
UInt16 => cast_string_to_numeric::<UInt16Type, i32>(array, cast_options),
UInt32 => cast_string_to_numeric::<UInt32Type, i32>(array, cast_options),
@@ -1121,7 +1135,11 @@ pub fn cast_with_options(
Float64 => cast_string_to_numeric::<Float64Type, i32>(array, cast_options),
Date32 => cast_string_to_date32::<i32>(&**array, cast_options),
Date64 => cast_string_to_date64::<i32>(&**array, cast_options),
- Binary => cast_string_to_binary(array),
+ Binary => Ok(Arc::new(BinaryArray::from(as_string_array(array).clone()))),
+ LargeBinary => {
+ let binary = BinaryArray::from(as_string_array(array).clone());
+ cast_byte_container::<BinaryType, LargeBinaryType, [u8]>(&binary)
+ }
Time32(TimeUnit::Second) => {
cast_string_to_time32second::<i32>(&**array, cast_options)
}
@@ -1143,7 +1161,7 @@ pub fn cast_with_options(
))),
},
(_, Utf8) => match from_type {
- LargeUtf8 => cast_str_container::<i64, i32>(&**array),
+ LargeUtf8 => cast_byte_container::<LargeUtf8Type, Utf8Type, str>(&**array),
UInt8 => cast_numeric_to_string::<UInt8Type, i32>(array),
UInt16 => cast_numeric_to_string::<UInt16Type, i32>(array),
UInt32 => cast_numeric_to_string::<UInt32Type, i32>(array),
@@ -1270,7 +1288,14 @@ pub fn cast_with_options(
Float64 => cast_string_to_numeric::<Float64Type, i64>(array, cast_options),
Date32 => cast_string_to_date32::<i64>(&**array, cast_options),
Date64 => cast_string_to_date64::<i64>(&**array, cast_options),
- LargeBinary => cast_string_to_binary(array),
+ Binary => {
+ let large_binary =
+ LargeBinaryArray::from(as_largestring_array(array).clone());
+ cast_byte_container::<LargeBinaryType, BinaryType, [u8]>(&large_binary)
+ }
+ LargeBinary => Ok(Arc::new(LargeBinaryArray::from(
+ as_largestring_array(array).clone(),
+ ))),
Time32(TimeUnit::Second) => {
cast_string_to_time32second::<i64>(&**array, cast_options)
}
@@ -1291,7 +1316,22 @@ pub fn cast_with_options(
from_type, to_type,
))),
},
-
+ (Binary, _) => match to_type {
+ LargeBinary => {
+ cast_byte_container::<BinaryType, LargeBinaryType, [u8]>(&**array)
+ }
+ _ => Err(ArrowError::CastError(format!(
+ "Casting from {:?} to {:?} not supported",
+ from_type, to_type,
+ ))),
+ },
+ (LargeBinary, _) => match to_type {
+ Binary => cast_byte_container::<LargeBinaryType, BinaryType, [u8]>(&**array),
+ _ => Err(ArrowError::CastError(format!(
+ "Casting from {:?} to {:?} not supported",
+ from_type, to_type,
+ ))),
+ },
// start numeric casts
(UInt8, UInt16) => {
cast_numeric_arrays::<UInt8Type, UInt16Type>(array, cast_options)
@@ -2007,41 +2047,6 @@ pub fn cast_with_options(
}
}
-/// Cast to string array to binary array
-fn cast_string_to_binary(array: &ArrayRef) -> Result<ArrayRef, ArrowError> {
- let from_type = array.data_type();
- match *from_type {
- DataType::Utf8 => {
- let data = unsafe {
- array
- .data()
- .clone()
- .into_builder()
- .data_type(DataType::Binary)
- .build_unchecked()
- };
-
- Ok(Arc::new(BinaryArray::from(data)) as ArrayRef)
- }
- DataType::LargeUtf8 => {
- let data = unsafe {
- array
- .data()
- .clone()
- .into_builder()
- .data_type(DataType::LargeBinary)
- .build_unchecked()
- };
-
- Ok(Arc::new(LargeBinaryArray::from(data)) as ArrayRef)
- }
- _ => Err(ArrowError::InvalidArgumentError(format!(
- "{:?} cannot be converted to binary array",
- from_type
- ))),
- }
-}
-
/// Get the time unit as a multiple of a second
const fn time_unit_multiple(unit: &TimeUnit) -> i64 {
match unit {
@@ -2843,11 +2848,17 @@ fn cast_string_to_timestamp_ns<Offset: OffsetSizeTrait>(
}
/// Casts Utf8 to Boolean
-fn cast_utf8_to_boolean(
+fn cast_utf8_to_boolean<OffsetSize>(
from: &ArrayRef,
cast_options: &CastOptions,
-) -> Result<ArrayRef, ArrowError> {
- let array = as_string_array(from);
+) -> Result<ArrayRef, ArrowError>
+where
+ OffsetSize: OffsetSizeTrait,
+{
+ let array = from
+ .as_any()
+ .downcast_ref::<GenericStringArray<OffsetSize>>()
+ .unwrap();
let output_array = array
.iter()
@@ -2861,7 +2872,7 @@ fn cast_utf8_to_boolean(
invalid_value => match cast_options.safe {
true => Ok(None),
false => Err(ArrowError::CastError(format!(
- "Cannot cast string '{}' to value of Boolean type",
+ "Cannot cast value '{}' to value of Boolean type",
invalid_value,
))),
},
@@ -3447,39 +3458,43 @@ fn cast_list_inner<OffsetSize: OffsetSizeTrait>(
Ok(Arc::new(list) as ArrayRef)
}
-/// Helper function to cast from `Utf8` to `LargeUtf8` and vice versa. If the `LargeUtf8` is too large for
-/// a `Utf8` array it will return an Error.
-fn cast_str_container<OffsetSizeFrom, OffsetSizeTo>(
+/// Helper function to cast from one `ByteArrayType` to another and vice versa.
+/// If the target one (e.g., `LargeUtf8`) is too large for the source array it will return an Error.
+fn cast_byte_container<FROM, TO, N: ?Sized>(
array: &dyn Array,
) -> Result<ArrayRef, ArrowError>
where
- OffsetSizeFrom: OffsetSizeTrait + ToPrimitive,
- OffsetSizeTo: OffsetSizeTrait + NumCast + ArrowNativeType,
+ FROM: ByteArrayType<Native = N>,
+ TO: ByteArrayType<Native = N>,
+ FROM::Offset: OffsetSizeTrait + ToPrimitive,
+ TO::Offset: OffsetSizeTrait + NumCast,
{
let data = array.data();
- assert_eq!(
- data.data_type(),
- &GenericStringArray::<OffsetSizeFrom>::DATA_TYPE
- );
+ assert_eq!(data.data_type(), &FROM::DATA_TYPE);
let str_values_buf = data.buffers()[1].clone();
- let offsets = data.buffers()[0].typed_data::<OffsetSizeFrom>();
+ let offsets = data.buffers()[0].typed_data::<FROM::Offset>();
- let mut offset_builder = BufferBuilder::<OffsetSizeTo>::new(offsets.len());
+ let mut offset_builder = BufferBuilder::<TO::Offset>::new(offsets.len());
offsets
.iter()
.try_for_each::<_, Result<_, ArrowError>>(|offset| {
- let offset = OffsetSizeTo::from(*offset).ok_or_else(|| {
- ArrowError::ComputeError(
- "large-utf8 array too large to cast to utf8-array".into(),
- )
- })?;
+ let offset = <<TO as ByteArrayType>::Offset as NumCast>::from(*offset)
+ .ok_or_else(|| {
+ ArrowError::ComputeError(format!(
+ "{}{} array too large to cast to {}{} array",
+ FROM::Offset::PREFIX,
+ FROM::PREFIX,
+ TO::Offset::PREFIX,
+ TO::PREFIX
+ ))
+ })?;
offset_builder.append(offset);
Ok(())
})?;
let offset_buffer = offset_builder.finish();
- let dtype = GenericStringArray::<OffsetSizeTo>::DATA_TYPE;
+ let dtype = TO::DATA_TYPE;
let builder = ArrayData::builder(dtype)
.offset(array.offset())
@@ -3490,9 +3505,7 @@ where
let array_data = unsafe { builder.build_unchecked() };
- Ok(Arc::new(GenericStringArray::<OffsetSizeTo>::from(
- array_data,
- )))
+ Ok(Arc::new(GenericByteArray::<TO>::from(array_data)))
}
/// Cast the container type of List/Largelist array but not the inner types.
@@ -4813,7 +4826,7 @@ mod tests {
Ok(_) => panic!("expected error"),
Err(e) => {
assert!(e.to_string().contains(
- "Cast error: Cannot cast string 'invalid' to value of Boolean type"
+ "Cast error: Cannot cast value 'invalid' to value of Boolean type"
))
}
}
|
diff --git a/arrow/tests/array_cast.rs b/arrow/tests/array_cast.rs
index ff6fbad099cb..ae73b1b4200b 100644
--- a/arrow/tests/array_cast.rs
+++ b/arrow/tests/array_cast.rs
@@ -421,7 +421,9 @@ fn get_all_types() -> Vec<DataType> {
vec![
Dictionary(Box::new(key_type.clone()), Box::new(Int32)),
Dictionary(Box::new(key_type.clone()), Box::new(Utf8)),
+ Dictionary(Box::new(key_type.clone()), Box::new(LargeUtf8)),
Dictionary(Box::new(key_type.clone()), Box::new(Binary)),
+ Dictionary(Box::new(key_type.clone()), Box::new(LargeBinary)),
Dictionary(Box::new(key_type.clone()), Box::new(Decimal128(38, 0))),
Dictionary(Box::new(key_type), Box::new(Decimal256(76, 0))),
]
|
Support casting to/from DictionaryArray <--> LargeUTF8, Binary and LargeBinary in Cast Kernels
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**
Currently if you try to cast a LargeStringArray, BinaryArray or LargeBinaryArray into a dictionary an error is returned
For example
```
CastError("Unsupported output type for dictionary packing: LargeUtf8")'
```
**Describe the solution you'd like**
Ideally this would work
|
Specifically, we would like to add support to the cast and cast_with_options kernels:
https://docs.rs/arrow/20.0.0/arrow/compute/kernels/cast/index.html
https://docs.rs/arrow/20.0.0/arrow/compute/kernels/cast/fn.cast_with_options.html
|
2023-01-17T08:40:14Z
|
31.0
|
f0be9da82cbd76da3042b426daf6c424c9560d93
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.