Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: nested bson constructs (array and document) should always be structures #3102

Merged
merged 3 commits into from
Jul 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
116 changes: 88 additions & 28 deletions crates/datasources/src/bson/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::sync::Arc;

use bitvec::order::Lsb0;
use bitvec::vec::BitVec;
use bson::{RawBsonRef, RawDocumentBuf};
use bson::{Bson, RawBsonRef, RawDocumentBuf};
use datafusion::arrow::array::{
Array,
ArrayBuilder,
Expand Down Expand Up @@ -121,7 +121,7 @@ impl RecordStructBuilder {
Ok(())
}

pub fn project_and_append(&mut self, doc: &RawDocumentBuf) -> Result<()> {
pub fn append_value(&mut self, doc: &RawDocumentBuf) -> Result<()> {
let mut cols_set: BitVec<u8, Lsb0> = BitVec::repeat(false, self.fields.len());

for iter_result in doc.iter_elements() {
Expand Down Expand Up @@ -245,6 +245,11 @@ fn append_value(val: RawBsonRef, typ: &DataType, col: &mut dyn ArrayBuilder) ->

// Boolean
(RawBsonRef::Boolean(v), DataType::Boolean) => append_scalar!(BooleanBuilder, col, v),
(RawBsonRef::Boolean(v), DataType::Int32) => append_scalar!(Int32Builder, col, v.into()),
(RawBsonRef::Boolean(v), DataType::Int64) => append_scalar!(Int64Builder, col, v.into()),
(RawBsonRef::Boolean(v), DataType::Float64) => {
append_scalar!(Float64Builder, col, v.into())
}
(RawBsonRef::Boolean(v), DataType::Utf8) => {
append_scalar!(StringBuilder, col, v.to_string())
}
Expand Down Expand Up @@ -289,13 +294,7 @@ fn append_value(val: RawBsonRef, typ: &DataType, col: &mut dyn ArrayBuilder) ->
append_scalar!(Float64Builder, col, v.parse().unwrap_or_default())
}

// Binary
(RawBsonRef::Binary(v), DataType::Binary) => append_scalar!(BinaryBuilder, col, v.bytes),
(RawBsonRef::Binary(v), DataType::LargeBinary) => {
append_scalar!(LargeBinaryBuilder, col, v.bytes)
}

// Object id
// ObjectId
(RawBsonRef::ObjectId(v), DataType::Binary) => {
append_scalar!(BinaryBuilder, col, v.bytes())
}
Expand Down Expand Up @@ -357,34 +356,95 @@ fn append_value(val: RawBsonRef, typ: &DataType, col: &mut dyn ArrayBuilder) ->
append_scalar!(Date32Builder, col, (v.timestamp_millis() / 1000) as i32)
}

// Document
(RawBsonRef::Document(nested), DataType::Struct(_)) => {
let builder = col
.as_any_mut()
.downcast_mut::<RecordStructBuilder>()
.unwrap();
builder.project_and_append(&nested.to_raw_document_buf())?;
// Array
(RawBsonRef::Document(doc), DataType::Struct(_)) => {
append_scalar!(RecordStructBuilder, col, &doc.to_raw_document_buf())?
}
(RawBsonRef::Document(doc), DataType::Binary) => {
append_scalar!(BinaryBuilder, col, doc.as_bytes())
}
(RawBsonRef::Document(doc), DataType::LargeBinary) => {
append_scalar!(BinaryBuilder, col, doc.as_bytes())
}
(RawBsonRef::Document(doc), DataType::Utf8) => {
append_scalar!(
StringBuilder,
col,
Bson::Document(bson::Document::from_reader(doc.as_bytes())?)
.into_relaxed_extjson()
.to_string()
)
}
(RawBsonRef::Document(doc), DataType::LargeUtf8) => {
append_scalar!(
LargeStringBuilder,
col,
Bson::Document(bson::Document::from_reader(doc.as_bytes())?)
.into_relaxed_extjson()
.to_string()
)
}

// Array
(RawBsonRef::Array(doc), DataType::Struct(_)) => append_scalar!(
RecordStructBuilder,
col,
&RawDocumentBuf::from_bytes(doc.as_bytes().into())?
)?,
(RawBsonRef::Array(arr), DataType::Binary) => {
append_scalar!(BinaryBuilder, col, arr.as_bytes())
}
(RawBsonRef::Array(arr), DataType::LargeBinary) => {
append_scalar!(BinaryBuilder, col, arr.as_bytes())
}
(RawBsonRef::Array(arr), DataType::Utf8) => {
append_scalar!(
StringBuilder,
col,
serde_json::Value::from(
bson::Array::try_from(arr)
.map_err(|_| BsonError::FailedToReadRawBsonDocument)?
)
.to_string()
Bson::Array(bson::Array::try_from(arr)?)
.into_relaxed_extjson()
.to_string()
)
}
(RawBsonRef::Array(arr), DataType::LargeUtf8) => {
append_scalar!(
LargeStringBuilder,
col,
Bson::Array(bson::Array::try_from(arr)?)
.into_relaxed_extjson()
.to_string()
)
}

// Decimal128
(RawBsonRef::Decimal128(v), DataType::Decimal128(_, _)) => col
.as_any_mut()
.downcast_mut::<Decimal128Builder>()
.unwrap()
.append_value(i128::from_le_bytes(v.bytes())),
(RawBsonRef::Decimal128(v), DataType::Decimal128(_, _)) => {
append_scalar!(Decimal128Builder, col, i128::from_le_bytes(v.bytes()))
}

// Binary
(RawBsonRef::Binary(v), DataType::Binary) => append_scalar!(BinaryBuilder, col, v.bytes),
(RawBsonRef::Binary(v), DataType::LargeBinary) => {
append_scalar!(LargeBinaryBuilder, col, v.bytes)
}

(_, DataType::Binary) => append_scalar!(BinaryBuilder, col, bson::ser::to_vec(&val)?),
(_, DataType::LargeBinary) => {
append_scalar!(LargeBinaryBuilder, col, bson::ser::to_vec(&val)?)
}
(_, DataType::Utf8) => append_scalar!(
StringBuilder,
col,
bson::Bson::try_from(val)?
.into_relaxed_extjson()
.to_string()
),
(_, DataType::LargeUtf8) => append_scalar!(
LargeStringBuilder,
col,
bson::Bson::try_from(val)?
.into_relaxed_extjson()
.to_string()
),

(bson_ref, dt) => {
return Err(BsonError::UnhandledElementType(
Expand Down Expand Up @@ -601,7 +661,7 @@ mod test {
rsb.append_record(&buf.clone())
.expect_err("for append_record schema changes are an error");
assert_eq!(rsb.len(), 1);
rsb.project_and_append(&buf.clone())
rsb.append_value(&buf.clone())
.expect("project and append should filter out unrequired fields");
assert_eq!(rsb.len(), 2);

Expand All @@ -616,7 +676,7 @@ mod test {
// the first value was added successfully to another buffer to the rsb grew
assert_eq!(rsb.len(), 3);

rsb.project_and_append(&buf.clone())
rsb.append_value(&buf.clone())
.expect("project and append should filter out unrequired fields");
assert_eq!(rsb.len(), 4);
}
Expand Down
5 changes: 4 additions & 1 deletion crates/datasources/src/bson/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@ pub enum BsonError {
Raw(#[from] bson::raw::Error),

#[error(transparent)]
Serialization(#[from] bson::de::Error),
Serialization(#[from] bson::ser::Error),

#[error(transparent)]
Deserialization(#[from] bson::de::Error),

#[error(transparent)]
ObjectStore(#[from] ObjectStoreSourceError),
Expand Down
31 changes: 14 additions & 17 deletions crates/datasources/src/bson/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,21 +37,15 @@ fn fields_from_document(depth: usize, doc: &RawDocumentBuf) -> Result<Vec<Field>

fn bson_to_arrow_type(depth: usize, bson: RawBsonRef) -> Result<DataType> {
Ok(match bson {
RawBsonRef::Array(array_doc) => DataType::new_list(
// TODO this should become a struct with numeric keys to
// allow for heterogeneous types
bson_to_arrow_type(
0,
array_doc
.into_iter()
.next()
.map(|v| v.unwrap_or(RawBsonRef::Null))
.unwrap(),
)?,
true,
RawBsonRef::Array(doc) => DataType::Struct(
fields_from_document(
depth + 1,
&RawDocumentBuf::from_bytes(doc.as_bytes().into())?,
)?
.into(),
),
RawBsonRef::Document(nested) => {
DataType::Struct(fields_from_document(depth + 1, &nested.to_raw_document_buf())?.into())
RawBsonRef::Document(doc) => {
DataType::Struct(fields_from_document(depth + 1, &doc.to_raw_document_buf())?.into())
}
RawBsonRef::String(_) => DataType::Utf8,
RawBsonRef::Double(_) => DataType::Float64,
Expand Down Expand Up @@ -133,9 +127,12 @@ pub fn merge_schemas(schemas: impl IntoIterator<Item = Result<Schema>>) -> Resul
fn merge_field(left: &mut Field, right: &Field) -> Result<()> {
let dt = match (left.data_type(), right.data_type()) {
(&DataType::Null, right) => right.clone(),
(&DataType::Int32 | &DataType::Int64 | &DataType::Float64, &DataType::Float64) => {
DataType::Float64
}
(
&DataType::Boolean,
&DataType::Int32 | &DataType::Int64 | &DataType::Float64 | &DataType::Utf8,
) => right.data_type().clone(),
(&DataType::Int32, &DataType::Int64) => DataType::Int64,
(&DataType::Int32 | &DataType::Int64, &DataType::Float64) => DataType::Float64,
(_, &DataType::Utf8) => DataType::Utf8,
_ => return Ok(()),
};
Expand Down
2 changes: 1 addition & 1 deletion crates/datasources/src/bson/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ impl BsonStream {
let mut builder = RecordStructBuilder::new_with_capacity(schema.fields().clone(), 100)?;

for result in results {
builder.project_and_append(&result?)?;
builder.append_value(&result?)?;
}

let mut builders = builder.into_builders();
Expand Down
Loading