Skip to content
Open
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
107 changes: 105 additions & 2 deletions pyiceberg/table/inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,18 @@
import itertools
from collections.abc import Iterator
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING, Any, cast

from pyiceberg.conversions import from_bytes
from pyiceberg.expressions import AlwaysTrue, BooleanExpression
from pyiceberg.manifest import DataFile, DataFileContent, ManifestContent, ManifestFile, PartitionFieldSummary
from pyiceberg.manifest import (
DataFile,
DataFileContent,
ManifestContent,
ManifestEntryStatus,
ManifestFile,
PartitionFieldSummary,
)
from pyiceberg.partitioning import PartitionSpec
from pyiceberg.table.snapshots import Snapshot, ancestors_of
from pyiceberg.types import PrimitiveType
Expand Down Expand Up @@ -1014,3 +1021,99 @@ def all_delete_files(self) -> pa.Table:
See ``_get_files_schema`` for the full column list.
"""
return self._all_files({DataFileContent.POSITION_DELETES, DataFileContent.EQUALITY_DELETES})

def _get_position_deletes_schema(self) -> pa.Schema:
"""Build the PyArrow schema for the position deletes metadata table.

Returns:
pa.Schema: The position deletes schema.
"""
import pyarrow as pa

from pyiceberg.io.pyarrow import schema_to_pyarrow

return pa.schema(
[
pa.field("file_path", pa.string(), nullable=False),
pa.field("pos", pa.int64(), nullable=False),
pa.field("row", cast(pa.DataType, schema_to_pyarrow(self.tbl.metadata.schema().as_struct())), nullable=True),
pa.field("partition", cast(pa.DataType, schema_to_pyarrow(self.tbl.metadata.specs_struct())), nullable=False),
pa.field("spec_id", pa.int32(), nullable=False),
pa.field("delete_file_path", pa.string(), nullable=False),
]
)

def _position_deletes_from_manifest(self, manifest: ManifestFile) -> pa.Table:
"""Read the position delete records from a single manifest.

Args:
manifest: The manifest to read.

Returns:
pa.Table: Position delete rows conforming to the position deletes schema.
"""
import pyarrow as pa

from pyiceberg.io.pyarrow import _read_deletes

schema = self._get_position_deletes_schema()
if manifest.content != ManifestContent.DELETES:
return schema.empty_table()

spec = self.tbl.metadata.specs()[manifest.partition_spec_id]
records = []
for entry in manifest.fetch_manifest_entry(io=self.tbl.io, discard_deleted=False):
if entry.status == ManifestEntryStatus.DELETED:
continue

data_file = entry.data_file
if data_file.content != DataFileContent.POSITION_DELETES:
continue

partition = {field.name: data_file.partition[pos] for pos, field in enumerate(spec.fields)}
for file_path, positions in _read_deletes(self.tbl.io, data_file).items():
for pos in positions.to_pylist():
records.append(
{
"file_path": file_path,
"pos": pos,
"row": None,
"partition": partition,
"spec_id": manifest.partition_spec_id,
"delete_file_path": data_file.file_path,
}
)

return pa.Table.from_pylist(records, schema=schema)

def position_deletes(self, snapshot_id: int | None = None) -> pa.Table:
"""Return position delete records for a snapshot as a PyArrow Table.

Each row names a data file and the row position deleted from it. The
optional ``row`` column is null because position delete files are not
required to store the deleted row.

Args:
snapshot_id: The snapshot to inspect. Defaults to the current snapshot.

Returns:
pa.Table: A table with columns: ``file_path`` (string), ``pos``
(int64), ``row`` (struct, nullable), ``partition`` (struct),
``spec_id`` (int32), and ``delete_file_path`` (string). Returns
an empty table when the table has no snapshots.
"""
import pyarrow as pa

if snapshot_id is None and not self.tbl.metadata.current_snapshot():
return self._get_position_deletes_schema().empty_table()

snapshot = self._get_snapshot(snapshot_id)
results = list(
ExecutorFactory.get_or_create().map(
self._position_deletes_from_manifest,
snapshot.manifests(self.tbl.io, self.tbl.encryption_manager),
)
)
if not results:
return self._get_position_deletes_schema().empty_table()
return pa.concat_tables(results)
59 changes: 58 additions & 1 deletion tests/table/test_inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,15 @@
# under the License.

from pathlib import PosixPath
from types import SimpleNamespace
from typing import Any

import pyarrow as pa
import pyarrow.parquet as pq
import pytest

from pyiceberg.conversions import to_bytes
from pyiceberg.manifest import DataFile, DataFileContent, FileFormat
from pyiceberg.manifest import DataFile, DataFileContent, FileFormat, ManifestContent, ManifestEntryStatus
from pyiceberg.partitioning import PartitionField, PartitionSpec
from pyiceberg.schema import Schema
from pyiceberg.table.inspect import InspectTable, _readable_bound
Expand Down Expand Up @@ -166,3 +168,58 @@ def test_inspect_bounds_after_type_promotion(catalog: InMemoryCatalog) -> None:
partition_summaries = tbl.inspect.manifests().to_pydict()["partition_summaries"][0]
assert partition_summaries[0]["lower_bound"] == str(values[0]), name
assert partition_summaries[0]["upper_bound"] == str(values[-1]), name


def test_position_deletes_empty_table(catalog: InMemoryCatalog) -> None:
schema = Schema(NestedField(1, "x", LongType(), required=False))
tbl = catalog.create_table("default.position_deletes_empty", schema)

result = tbl.inspect.position_deletes()

assert result.num_rows == 0
assert result.column_names == ["file_path", "pos", "row", "partition", "spec_id", "delete_file_path"]


def test_position_deletes_reads_live_delete_files(catalog: InMemoryCatalog) -> None:
schema = Schema(NestedField(1, "x", LongType(), required=False))
tbl = catalog.create_table("default.position_deletes", schema)
delete_path = f"{tbl.location().rstrip('/')}/data/deletes.parquet"
delete_records = pa.table(
{
"file_path": ["s3://bucket/data/a.parquet", "s3://bucket/data/b.parquet"],
"pos": pa.array([1, 4], type=pa.int64()),
}
)
with tbl.io.new_output(delete_path).create() as output:
pq.write_table(delete_records, output)

data_file = DataFile.from_args(
content=DataFileContent.POSITION_DELETES,
file_path=delete_path,
file_format=FileFormat.PARQUET,
partition=Record(),
record_count=2,
file_size_in_bytes=0,
spec_id=tbl.metadata.default_spec_id,
)
manifest: Any = SimpleNamespace(
content=ManifestContent.DELETES,
partition_spec_id=tbl.metadata.default_spec_id,
fetch_manifest_entry=lambda io, discard_deleted=True: [
SimpleNamespace(status=ManifestEntryStatus.ADDED, data_file=data_file),
SimpleNamespace(status=ManifestEntryStatus.DELETED, data_file=data_file),
],
)

rows = sorted(
tbl.inspect._position_deletes_from_manifest(manifest).to_pylist(),
key=lambda row: (row["file_path"], row["pos"]),
)

assert [(row["file_path"], row["pos"]) for row in rows] == [
("s3://bucket/data/a.parquet", 1),
("s3://bucket/data/b.parquet", 4),
]
assert all(row["row"] is None for row in rows)
assert {row["delete_file_path"] for row in rows} == {delete_path}
assert {row["spec_id"] for row in rows} == {tbl.metadata.default_spec_id}
Loading