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: dataset update accepts binary value #2579

Merged
merged 2 commits into from
Jul 9, 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
20 changes: 20 additions & 0 deletions python/python/tests/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -1339,6 +1339,26 @@ def test_update_dataset_all_types(tmp_path: Path):
assert dataset.to_table() == expected


def test_update_with_binary_field(tmp_path: Path):
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: can we have a rust test as well?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Sure.

# Create a lance dataset with binary fields
table = pa.Table.from_pydict(
{
"a": [f"str-{i}" for i in range(100)],
"b": [b"bin-{i}" for i in range(100)],
"c": list(range(100)),
}
)
dataset = lance.write_dataset(table, tmp_path)

# Update binary field
dataset.update({"b": "X'616263'"}, where="c < 2")

ds = lance.dataset(tmp_path)
assert ds.scanner(filter="c < 2").to_table().column(
"b"
).combine_chunks() == pa.array([b"abc", b"abc"])


def test_create_update_empty_dataset(tmp_path: Path, provide_pandas: bool):
base_dir = tmp_path / "dataset"

Expand Down
57 changes: 56 additions & 1 deletion rust/lance/src/io/exec/planner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,9 @@ impl Planner {
Value::DollarQuotedString(_) => todo!(),
Value::EscapedStringLiteral(_) => todo!(),
Value::NationalStringLiteral(_) => todo!(),
Value::HexStringLiteral(_) => todo!(),
Value::HexStringLiteral(hsl) => {
Expr::Literal(ScalarValue::Binary(Self::try_decode_hex_literal(hsl)))
}
Value::DoubleQuotedString(s) => Expr::Literal(ScalarValue::Utf8(Some(s.clone()))),
Value::Boolean(v) => Expr::Literal(ScalarValue::Boolean(Some(*v))),
Value::Null => Expr::Literal(ScalarValue::Null),
Expand Down Expand Up @@ -673,6 +675,42 @@ impl Planner {
Ok(resolved)
}

/// Try to decode bytes from hex literal string.
///
/// Copied from datafusion because this is not public.
///
/// TODO: use SqlToRel from Datafusion directly?
fn try_decode_hex_literal(s: &str) -> Option<Vec<u8>> {
let hex_bytes = s.as_bytes();
let mut decoded_bytes = Vec::with_capacity((hex_bytes.len() + 1) / 2);

let start_idx = hex_bytes.len() % 2;
if start_idx > 0 {
// The first byte is formed of only one char.
decoded_bytes.push(Self::try_decode_hex_char(hex_bytes[0])?);
}

for i in (start_idx..hex_bytes.len()).step_by(2) {
let high = Self::try_decode_hex_char(hex_bytes[i])?;
let low = Self::try_decode_hex_char(hex_bytes[i + 1])?;
decoded_bytes.push(high << 4 | low);
}

Some(decoded_bytes)
}

/// Try to decode a byte from a hex char.
///
/// None will be returned if the input char is hex-invalid.
const fn try_decode_hex_char(c: u8) -> Option<u8> {
match c {
b'A'..=b'F' => Some(c - b'A' + 10),
b'a'..=b'f' => Some(c - b'a' + 10),
b'0'..=b'9' => Some(c - b'0'),
_ => None,
}
}

/// Optimize the filter expression and coerce data types.
pub fn optimize_expr(&self, expr: Expr) -> Result<Expr> {
let df_schema = Arc::new(DFSchema::try_from(self.schema.as_ref().clone())?);
Expand Down Expand Up @@ -1384,4 +1422,21 @@ mod tests {
let columns = Planner::column_names_in_expr(&expr);
assert_eq!(columns, vec!["s0", "st.s1", "st.st.s2"]);
}

#[test]
fn test_parse_binary_expr() {
let bin_str = "x'616263'";

let schema = Arc::new(Schema::new(vec![Field::new(
"binary",
DataType::Binary,
true,
)]));
let planner = Planner::new(schema);
let expr = planner.parse_expr(bin_str).unwrap();
assert_eq!(
expr,
Expr::Literal(ScalarValue::Binary(Some(vec![b'a', b'b', b'c'])))
);
}
}
Loading