kszucs commented on a change in pull request #439: URL: https://github.com/apache/arrow-rs/pull/439#discussion_r655484390
########## File path: arrow-pyarrow-integration-testing/tests/test_sql.py ########## @@ -16,84 +16,195 @@ # specific language governing permissions and limitations # under the License. -import unittest - -import pyarrow -import arrow_pyarrow_integration_testing - - -class TestCase(unittest.TestCase): - def test_primitive_python(self): - """ - Python -> Rust -> Python - """ - old_allocated = pyarrow.total_allocated_bytes() - a = pyarrow.array([1, 2, 3]) - b = arrow_pyarrow_integration_testing.double(a) - self.assertEqual(b, pyarrow.array([2, 4, 6])) - del a - del b - # No leak of C++ memory - self.assertEqual(old_allocated, pyarrow.total_allocated_bytes()) - - def test_primitive_rust(self): - """ - Rust -> Python -> Rust - """ - old_allocated = pyarrow.total_allocated_bytes() - - def double(array): - array = array.to_pylist() - return pyarrow.array([x * 2 if x is not None else None for x in array]) - - is_correct = arrow_pyarrow_integration_testing.double_py(double) - self.assertTrue(is_correct) - # No leak of C++ memory - self.assertEqual(old_allocated, pyarrow.total_allocated_bytes()) - - def test_string_python(self): - """ - Python -> Rust -> Python - """ - old_allocated = pyarrow.total_allocated_bytes() - a = pyarrow.array(["a", None, "ccc"]) - b = arrow_pyarrow_integration_testing.substring(a, 1) - self.assertEqual(b, pyarrow.array(["", None, "cc"])) - del a - del b - # No leak of C++ memory - self.assertEqual(old_allocated, pyarrow.total_allocated_bytes()) - - def test_time32_python(self): - """ - Python -> Rust -> Python - """ - old_allocated = pyarrow.total_allocated_bytes() - a = pyarrow.array([None, 1, 2], pyarrow.time32('s')) - b = arrow_pyarrow_integration_testing.concatenate(a) - expected = pyarrow.array([None, 1, 2] + [None, 1, 2], pyarrow.time32('s')) - self.assertEqual(b, expected) - del a - del b - del expected - # No leak of C++ memory - self.assertEqual(old_allocated, pyarrow.total_allocated_bytes()) - - def test_list_array(self): - """ - Python -> Rust -> Python - """ - old_allocated = pyarrow.total_allocated_bytes() - a = pyarrow.array([[], None, [1, 2], [4, 5, 6]], pyarrow.list_(pyarrow.int64())) - b = arrow_pyarrow_integration_testing.round_trip(a) - - b.validate(full=True) - assert a.to_pylist() == b.to_pylist() - assert a.type == b.type - del a - del b - # No leak of C++ memory - self.assertEqual(old_allocated, pyarrow.total_allocated_bytes()) +import contextlib +import string +import pytest +import pyarrow as pa +from arrow_pyarrow_integration_testing import PyDataType, PyField, PySchema +import arrow_pyarrow_integration_testing as rust + +@contextlib.contextmanager +def no_pyarrow_leak(): + # No leak of C++ memory + old_allocation = pa.total_allocated_bytes() + try: + yield + finally: + assert pa.total_allocated_bytes() == old_allocation + + +@pytest.fixture(autouse=True) +def assert_pyarrow_leak(): + # automatically applied to all test cases + with no_pyarrow_leak(): + yield + + +_supported_pyarrow_types = [ + pa.null(), + pa.bool_(), + pa.int32(), + pa.time32("s"), + pa.time64("us"), + pa.date32(), + pa.float16(), + pa.float32(), + pa.float64(), + pa.string(), + pa.binary(), + pa.large_string(), + pa.large_binary(), + pa.list_(pa.int32()), + pa.large_list(pa.uint16()), + pa.struct( + [ + pa.field("a", pa.int32()), + pa.field("b", pa.int8()), + pa.field("c", pa.string()), + ] + ), + pa.struct( + [ + pa.field("a", pa.int32(), nullable=False), + pa.field("b", pa.int8(), nullable=False), + pa.field("c", pa.string()), + ] + ), +] + +_unsupported_pyarrow_types = [ Review comment: https://github.com/apache/arrow-rs/issues/477 ########## File path: arrow/src/datatypes/ffi.rs ########## @@ -0,0 +1,287 @@ +// 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::convert::TryFrom; + +use crate::{ + datatypes::{DataType, Field, Schema, TimeUnit}, + error::{ArrowError, Result}, + ffi::{FFI_ArrowSchema, Flags}, +}; + +impl TryFrom<&FFI_ArrowSchema> for DataType { + type Error = ArrowError; + + /// See https://arrow.apache.org/docs/format/CDataInterface.html#data-type-description-format-strings + fn try_from(c_schema: &FFI_ArrowSchema) -> Result<Self> { + let dtype = match c_schema.format() { + "n" => DataType::Null, + "b" => DataType::Boolean, + "c" => DataType::Int8, + "C" => DataType::UInt8, + "s" => DataType::Int16, + "S" => DataType::UInt16, + "i" => DataType::Int32, + "I" => DataType::UInt32, + "l" => DataType::Int64, + "L" => DataType::UInt64, + "e" => DataType::Float16, + "f" => DataType::Float32, + "g" => DataType::Float64, + "z" => DataType::Binary, + "Z" => DataType::LargeBinary, + "u" => DataType::Utf8, + "U" => DataType::LargeUtf8, + "tdD" => DataType::Date32, + "tdm" => DataType::Date64, + "tts" => DataType::Time32(TimeUnit::Second), + "ttm" => DataType::Time32(TimeUnit::Millisecond), + "ttu" => DataType::Time64(TimeUnit::Microsecond), + "ttn" => DataType::Time64(TimeUnit::Nanosecond), + "+l" => { + let c_child = c_schema.child(0); + DataType::List(Box::new(Field::try_from(c_child)?)) + } + "+L" => { + let c_child = c_schema.child(0); + DataType::LargeList(Box::new(Field::try_from(c_child)?)) + } + "+s" => { + let fields = c_schema.children().map(Field::try_from); + DataType::Struct(fields.collect::<Result<Vec<_>>>()?) + } + other => { + return Err(ArrowError::CDataInterface(format!( + "The datatype \"{:?}\" is still not supported in Rust implementation", + other + ))) + } + }; + Ok(dtype) + } +} + +impl TryFrom<&FFI_ArrowSchema> for Field { + type Error = ArrowError; + + fn try_from(c_schema: &FFI_ArrowSchema) -> Result<Self> { + let dtype = DataType::try_from(c_schema)?; + let field = Field::new(c_schema.name(), dtype, c_schema.nullable()); + Ok(field) Review comment: https://github.com/apache/arrow-rs/issues/478 ########## File path: arrow/src/ffi.rs ########## @@ -122,66 +132,61 @@ unsafe extern "C" fn release_schema(schema: *mut FFI_ArrowSchema) { let schema = &mut *schema; // take ownership back to release it. - CString::from_raw(schema.format as *mut std::os::raw::c_char); - CString::from_raw(schema.name as *mut std::os::raw::c_char); - let private = Box::from_raw(schema.private_data as *mut SchemaPrivateData); - for child in private.children_ptr.iter() { - let _ = Box::from_raw(*child); + CString::from_raw(schema.format as *mut c_char); + if !schema.name.is_null() { + CString::from_raw(schema.name as *mut c_char); + } + if !schema.private_data.is_null() { + let private_data = Box::from_raw(schema.private_data as *mut SchemaPrivateData); + for child in private_data.children.iter() { + drop(Box::from_raw(*child)) + } + drop(private_data); } schema.release = None; } impl FFI_ArrowSchema { /// create a new [`Ffi_ArrowSchema`]. This fails if the fields' [`DataType`] is not supported. - fn try_new(field: Field) -> Result<FFI_ArrowSchema> { - let format = to_format(field.data_type())?; - let name = field.name().clone(); - - // allocate (and hold) the children - let children_vec = match field.data_type() { - DataType::List(field) => { - vec![Box::new(FFI_ArrowSchema::try_new(field.as_ref().clone())?)] - } - DataType::LargeList(field) => { - vec![Box::new(FFI_ArrowSchema::try_new(field.as_ref().clone())?)] - } - DataType::Struct(fields) => fields - .iter() - .map(|field| Ok(Box::new(FFI_ArrowSchema::try_new(field.clone())?))) - .collect::<Result<Vec<_>>>()?, - _ => vec![], - }; - // note: this cannot be done along with the above because the above is fallible and this op leaks. - let children_ptr = children_vec + pub fn try_new(format: &str, children: Vec<FFI_ArrowSchema>) -> Result<Self> { + let mut this = Self::empty(); + + // note: this op leaks. + let mut children_ptr = children .into_iter() + .map(Box::new) .map(Box::into_raw) .collect::<Box<_>>(); - let n_children = children_ptr.len() as i64; - let flags = field.is_nullable() as i64 * 2; + this.format = CString::new(format).unwrap().into_raw(); + this.release = Some(release_schema); + this.n_children = children_ptr.len() as i64; + this.children = children_ptr.as_mut_ptr(); - let mut private = Box::new(SchemaPrivateData { - field, - children_ptr, + let private_data = Box::new(SchemaPrivateData { + children: children_ptr, }); + this.private_data = Box::into_raw(private_data) as *mut c_void; - // <https://arrow.apache.org/docs/format/CDataInterface.html#c.ArrowSchema> - Ok(FFI_ArrowSchema { - format: CString::new(format).unwrap().into_raw(), - name: CString::new(name).unwrap().into_raw(), - metadata: std::ptr::null_mut(), - flags, - n_children, - children: private.children_ptr.as_mut_ptr(), - dictionary: std::ptr::null_mut(), - release: Some(release_schema), - private_data: Box::into_raw(private) as *mut ::std::os::raw::c_void, - }) + Ok(this) + } + + pub fn with_name(mut self, name: &str) -> Result<Self> { + self.name = CString::new(name).unwrap().into_raw(); + Ok(self) + } + + pub fn with_flags(mut self, flags: Flags) -> Result<Self> { + self.flags = flags.bits(); + Ok(self) } + // pub fn with_dictionary() {} + // pub fn with_metadata() {} Review comment: https://github.com/apache/arrow-rs/issues/478 ########## File path: arrow/src/ffi.rs ########## @@ -122,66 +132,61 @@ unsafe extern "C" fn release_schema(schema: *mut FFI_ArrowSchema) { let schema = &mut *schema; // take ownership back to release it. - CString::from_raw(schema.format as *mut std::os::raw::c_char); - CString::from_raw(schema.name as *mut std::os::raw::c_char); - let private = Box::from_raw(schema.private_data as *mut SchemaPrivateData); - for child in private.children_ptr.iter() { - let _ = Box::from_raw(*child); + CString::from_raw(schema.format as *mut c_char); + if !schema.name.is_null() { + CString::from_raw(schema.name as *mut c_char); + } + if !schema.private_data.is_null() { + let private_data = Box::from_raw(schema.private_data as *mut SchemaPrivateData); + for child in private_data.children.iter() { + drop(Box::from_raw(*child)) Review comment: That's my understanding as well. ########## File path: arrow/src/ffi.rs ########## @@ -122,66 +132,61 @@ unsafe extern "C" fn release_schema(schema: *mut FFI_ArrowSchema) { let schema = &mut *schema; // take ownership back to release it. - CString::from_raw(schema.format as *mut std::os::raw::c_char); - CString::from_raw(schema.name as *mut std::os::raw::c_char); - let private = Box::from_raw(schema.private_data as *mut SchemaPrivateData); - for child in private.children_ptr.iter() { - let _ = Box::from_raw(*child); + CString::from_raw(schema.format as *mut c_char); + if !schema.name.is_null() { + CString::from_raw(schema.name as *mut c_char); + } + if !schema.private_data.is_null() { + let private_data = Box::from_raw(schema.private_data as *mut SchemaPrivateData); + for child in private_data.children.iter() { + drop(Box::from_raw(*child)) + } + drop(private_data); } schema.release = None; } impl FFI_ArrowSchema { /// create a new [`Ffi_ArrowSchema`]. This fails if the fields' [`DataType`] is not supported. - fn try_new(field: Field) -> Result<FFI_ArrowSchema> { - let format = to_format(field.data_type())?; - let name = field.name().clone(); - - // allocate (and hold) the children - let children_vec = match field.data_type() { - DataType::List(field) => { - vec![Box::new(FFI_ArrowSchema::try_new(field.as_ref().clone())?)] - } - DataType::LargeList(field) => { - vec![Box::new(FFI_ArrowSchema::try_new(field.as_ref().clone())?)] - } - DataType::Struct(fields) => fields - .iter() - .map(|field| Ok(Box::new(FFI_ArrowSchema::try_new(field.clone())?))) - .collect::<Result<Vec<_>>>()?, - _ => vec![], - }; - // note: this cannot be done along with the above because the above is fallible and this op leaks. - let children_ptr = children_vec + pub fn try_new(format: &str, children: Vec<FFI_ArrowSchema>) -> Result<Self> { + let mut this = Self::empty(); + + // note: this op leaks. Review comment: I just kept the original comment from below, going to remove it. ########## File path: arrow/src/ffi.rs ########## @@ -122,66 +132,61 @@ unsafe extern "C" fn release_schema(schema: *mut FFI_ArrowSchema) { let schema = &mut *schema; // take ownership back to release it. - CString::from_raw(schema.format as *mut std::os::raw::c_char); - CString::from_raw(schema.name as *mut std::os::raw::c_char); - let private = Box::from_raw(schema.private_data as *mut SchemaPrivateData); - for child in private.children_ptr.iter() { - let _ = Box::from_raw(*child); + CString::from_raw(schema.format as *mut c_char); + if !schema.name.is_null() { + CString::from_raw(schema.name as *mut c_char); + } + if !schema.private_data.is_null() { + let private_data = Box::from_raw(schema.private_data as *mut SchemaPrivateData); + for child in private_data.children.iter() { + drop(Box::from_raw(*child)) + } + drop(private_data); } schema.release = None; } impl FFI_ArrowSchema { /// create a new [`Ffi_ArrowSchema`]. This fails if the fields' [`DataType`] is not supported. - fn try_new(field: Field) -> Result<FFI_ArrowSchema> { - let format = to_format(field.data_type())?; - let name = field.name().clone(); - - // allocate (and hold) the children - let children_vec = match field.data_type() { - DataType::List(field) => { - vec![Box::new(FFI_ArrowSchema::try_new(field.as_ref().clone())?)] - } - DataType::LargeList(field) => { - vec![Box::new(FFI_ArrowSchema::try_new(field.as_ref().clone())?)] - } - DataType::Struct(fields) => fields - .iter() - .map(|field| Ok(Box::new(FFI_ArrowSchema::try_new(field.clone())?))) - .collect::<Result<Vec<_>>>()?, - _ => vec![], - }; - // note: this cannot be done along with the above because the above is fallible and this op leaks. - let children_ptr = children_vec + pub fn try_new(format: &str, children: Vec<FFI_ArrowSchema>) -> Result<Self> { + let mut this = Self::empty(); + + // note: this op leaks. + let mut children_ptr = children .into_iter() + .map(Box::new) .map(Box::into_raw) .collect::<Box<_>>(); - let n_children = children_ptr.len() as i64; - let flags = field.is_nullable() as i64 * 2; + this.format = CString::new(format).unwrap().into_raw(); + this.release = Some(release_schema); + this.n_children = children_ptr.len() as i64; + this.children = children_ptr.as_mut_ptr(); - let mut private = Box::new(SchemaPrivateData { - field, - children_ptr, + let private_data = Box::new(SchemaPrivateData { + children: children_ptr, }); + this.private_data = Box::into_raw(private_data) as *mut c_void; - // <https://arrow.apache.org/docs/format/CDataInterface.html#c.ArrowSchema> - Ok(FFI_ArrowSchema { - format: CString::new(format).unwrap().into_raw(), - name: CString::new(name).unwrap().into_raw(), - metadata: std::ptr::null_mut(), - flags, - n_children, - children: private.children_ptr.as_mut_ptr(), - dictionary: std::ptr::null_mut(), - release: Some(release_schema), - private_data: Box::into_raw(private) as *mut ::std::os::raw::c_void, - }) + Ok(this) + } + + pub fn with_name(mut self, name: &str) -> Result<Self> { + self.name = CString::new(name).unwrap().into_raw(); + Ok(self) + } + + pub fn with_flags(mut self, flags: Flags) -> Result<Self> { + self.flags = flags.bits(); + Ok(self) } + // pub fn with_dictionary() {} + // pub fn with_metadata() {} Review comment: Metadata: https://github.com/apache/arrow-rs/issues/478 Dictionary: https://github.com/apache/arrow-rs/issues/479 -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: us...@infra.apache.org