// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors use std::num::NonZeroU64; use std::sync::Arc; use arrow::pyarrow::ToPyArrow; use lancedb::query::metadata_reader::QueryResultReader; use lancedb::query::{ExecutableQuery, MetadataRequest, TrackTotalHits}; use pyo3::{Bound, PyAny, PyResult, Python, exceptions::PyRuntimeError, pyclass, pymethods}; use crate::{error::PythonErrorExt, runtime::future_into_py}; #[pyclass] pub struct NativeQueryResult(Arc); pub fn execute_with_metadata( py: Python<'_>, query: Q, track: bool, cap: Option, ) -> PyResult> { let mode = match (track, cap) { (_, Some(cap)) => TrackTotalHits::UpTo(cap), (true, None) => TrackTotalHits::Exact, (false, None) => TrackTotalHits::Off, }; let request = MetadataRequest::new().track_total_hits(mode); future_into_py(py, async move { let result = query .execute_with_metadata(crate::query::query_execution_options(None, None), request) .await .infer_error()?; Ok(NativeQueryResult(Arc::new(QueryResultReader::new(result)))) }) } #[pymethods] impl NativeQueryResult { fn next_batch<'py>(&self, py: Python<'py>) -> PyResult> { let reader = self.0.clone(); future_into_py(py, async move { let batch = reader.next().await.infer_error()?; Python::attach(|py| { batch .map(|batch| batch.to_pyarrow(py).map(Bound::unbind)) .transpose() }) }) } fn total_hits(&self) -> PyResult> { let metadata = self .0 .metadata() .map_err(|e| PyRuntimeError::new_err(e.to_string()))?; Ok(metadata .total_hits .as_ref() .map(|hits| (hits.value, hits.relation.as_str()))) } fn close<'py>(&self, py: Python<'py>) -> PyResult> { let reader = self.0.clone(); future_into_py(py, async move { reader.close().await; Ok(()) }) } }