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

Expose Transforms to Python Binding #556

Merged
merged 19 commits into from
Aug 27, 2024
Merged
Show file tree
Hide file tree
Changes from 15 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
2 changes: 1 addition & 1 deletion .github/workflows/bindings_python_ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,4 @@ jobs:
set -e
pip install hatch==1.12.0
hatch run dev:pip install dist/pyiceberg_core-*.whl --force-reinstall
hatch run dev:test
hatch run dev:test
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,5 @@ dist/*
**/venv
*.so
*.pyc
*.whl
*.tar.gz
3 changes: 2 additions & 1 deletion bindings/python/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,5 @@ crate-type = ["cdylib"]

[dependencies]
iceberg = { path = "../../crates/iceberg" }
pyo3 = { version = "0.22", features = ["extension-module"] }
pyo3 = { version = "0.21.1", features = ["extension-module"] }
arrow = { version = "52.2.0", features = ["pyarrow"] }
1 change: 1 addition & 0 deletions bindings/python/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ ignore = ["F403", "F405"]
dependencies = [
"maturin>=1.0,<2.0",
"pytest>=8.3.2",
"pyarrow>=17.0.0",
]

[tool.hatch.envs.dev.scripts]
Expand Down
23 changes: 22 additions & 1 deletion bindings/python/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@

use iceberg::io::FileIOBuilder;
use pyo3::prelude::*;
use pyo3::wrap_pyfunction;

mod transform;

#[pyfunction]
fn hello_world() -> PyResult<String> {
Expand All @@ -25,7 +28,25 @@ fn hello_world() -> PyResult<String> {
}

#[pymodule]
fn pyiceberg_core_rust(m: &Bound<'_, PyModule>) -> PyResult<()> {
fn submodule(_py: Python, module: &Bound<'_, PyModule>) -> PyResult<()> {
use transform::bucket_transform;

module.add_wrapped(wrap_pyfunction!(bucket_transform))?;
Ok(())
}

#[pymodule]
fn pyiceberg_core_rust(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(hello_world, m)?)?;

// https://github.com/PyO3/pyo3/issues/759
Copy link
Member

Choose a reason for hiding this comment

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

I will explore better ways for this. Not a blocker of this PR.

// Submodules added through PyO3 cannot be imported in Python using
// the syntax: 'from parent.child import function'.
// We need to add the submodule in sys.modules manually so that
// Python can find it.
let child_module = PyModule::new_bound(py, "pyiceberg_core.transform")?;
submodule(py, &child_module)?;
m.add("transform", child_module.clone())?;
py.import_bound("sys")?.getattr("modules")?.set_item("pyiceberg_core.transform", child_module)?;
Ok(())
}
75 changes: 75 additions & 0 deletions bindings/python/src/transform.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
// 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::{error, fmt};
use iceberg::spec::Transform;
use iceberg::transform::create_transform_function;
use iceberg::Error;

use arrow::{
array::{make_array, Array, ArrayData},
};
use arrow::pyarrow::{FromPyArrow, ToPyArrow};
use pyo3::{exceptions::PyValueError, prelude::*};

#[derive(Debug)]
enum PyO3IcebergError {
Copy link
Member

Choose a reason for hiding this comment

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

How about implementing a simple fn to_py_err(err: iceberg::Error) -> PyError. So we can use:

let bucket = create_transform_function(&Transform::Bucket(num_buckets)).map_err(to_py_err)?;

But no need for implementing Display, From by hand.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

That worked like a charm! Thanks @Xuanwo

Error(Error),
}

impl fmt::Display for PyO3IcebergError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
PyO3IcebergError::Error(ref e) => e.fmt(f),
}
}
}

impl error::Error for PyO3IcebergError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match *self {
// The cause is the underlying implementation error type. Is implicitly
// cast to the trait object `&error::Error`. This works because the
// underlying type already implements the `Error` trait.
PyO3IcebergError::Error(ref e) => Some(e),
}
}
}

impl From<Error> for PyO3IcebergError {
fn from(err: Error) -> PyO3IcebergError {
PyO3IcebergError::Error(err)
}
}

impl From<PyO3IcebergError> for PyErr {
fn from(err: PyO3IcebergError) -> PyErr {
PyValueError::new_err(err.to_string())
}
}

#[pyfunction]
pub fn bucket_transform(array: PyObject, num_buckets: u32, py: Python) -> PyResult<PyObject> {
// import
let array = ArrayData::from_pyarrow_bound(array.bind(py))?;
let array = make_array(array);
let bucket = create_transform_function(&Transform::Bucket(num_buckets)).map_err(PyO3IcebergError::from)?;
let array = bucket.transform(array).map_err(PyO3IcebergError::from)?;
// export
let array = array.into_data();
array.to_pyarrow(py)
}
49 changes: 49 additions & 0 deletions bindings/python/tests/test_transform.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# 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.

from pyiceberg_core.transform import bucket_transform

import pytest
import pyarrow as pa


def test_bucket_pyarrow_array():
arr = pa.array([1, 2])
result = bucket_transform(arr, 10)
expected = pa.array([6, 2], type=pa.int32())
assert result == expected


def test_bucket_pyarrow_array_list_type_fails():
arr = pa.array([[1, 2], [3, 4]])
with pytest.raises(
ValueError,
match=r"FeatureUnsupported => Unsupported data type for bucket transform",
):
bucket_transform(arr, 10)


def test_bucket_chunked_array():
chunked = pa.chunked_array([pa.array([1, 2]), pa.array([3, 4])])
result_chunks = []
for arr in chunked.iterchunks():
result_chunks.append(bucket_transform(arr, 10))

expected = pa.chunked_array(
[pa.array([6, 2], type=pa.int32()), pa.array([5, 0], type=pa.int32())]
)
assert pa.chunked_array(result_chunks).equals(expected)
Loading