-
Notifications
You must be signed in to change notification settings - Fork 199
Expand file tree
/
Copy pathfile.rs
More file actions
347 lines (309 loc) · 11.5 KB
/
Copy pathfile.rs
File metadata and controls
347 lines (309 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors
use std::sync::Arc;
use arrow_array::RecordBatchReader;
use arrow_schema::Schema;
use pyo3::exceptions::PyTypeError;
use pyo3::intern;
use pyo3::prelude::*;
use pyo3::types::PyList;
use vortex::array::ArrayRef;
use vortex::array::ExecutionCtx;
use vortex::array::VortexSessionExecute;
use vortex::array::arrays::PrimitiveArray;
use vortex::array::builtins::ArrayBuiltins;
use vortex::dtype::DType;
use vortex::dtype::FieldNames;
use vortex::dtype::Nullability::NonNullable;
use vortex::dtype::PType;
use vortex::error::VortexResult;
use vortex::expr::Expression;
use vortex::expr::root;
use vortex::expr::select;
use vortex::file::OpenOptionsSessionExt;
use vortex::file::VortexFile;
use vortex::io::runtime::BlockingRuntime;
use vortex::layout::scan::scan_builder::ScanBuilder;
use vortex::layout::scan::split_by::SplitBy;
use vortex::layout::segments::MokaSegmentCache;
use vortex::scan::strict_sorted_buffer::StrictSortedBuffer;
use vortex_arrow::ArrowSessionExt;
use crate::arrays::PyArrayRef;
use crate::arrow::FromPyArrow;
use crate::arrow::IntoPyArrow;
use crate::current_runtime;
use crate::dataset::PyVortexDataset;
use crate::dtype::PyDType;
use crate::error::PyVortexResult;
use crate::expr::PyExpr;
use crate::install_module;
use crate::io::AnyVortexStore;
use crate::iter::PyArrayIterator;
use crate::object_store::resolve::ResolvedStore;
use crate::object_store::resolve::resolve_store;
use crate::scan::PyRepeatedScan;
use crate::session::session;
pub(crate) fn init(py: Python, parent: &Bound<PyModule>) -> PyResult<()> {
let m = PyModule::new(py, "file")?;
parent.add_submodule(&m)?;
install_module("vortex._lib.file", &m)?;
m.add_function(wrap_pyfunction!(open, &m)?)?;
m.add_function(wrap_pyfunction!(_reopen, &m)?)?;
m.add_class::<PyVortexFile>()?;
Ok(())
}
/// Reopen a Vortex file by path. The unpickling half of [`PyVortexFile::__reduce__`].
#[pyfunction]
fn _reopen(py: Python, path: &str, without_segment_cache: bool) -> PyVortexResult<PyVortexFile> {
open(py, path, None, without_segment_cache)
}
/// Open a Vortex file for reading.
///
/// Callers can optionally configure an object store to build from using one of the definitions
/// in the `vortex.store` crate.
#[pyfunction]
#[pyo3(signature = (path, *, store = None, without_segment_cache = false))]
pub fn open(
py: Python,
path: &str,
store: Option<AnyVortexStore>,
without_segment_cache: bool,
) -> PyVortexResult<PyVortexFile> {
let had_store = store.is_some();
let owned_path = path.to_string();
let vxf = py.detach(move || {
current_runtime().block_on(async move {
let mut options = session().open_options();
if !without_segment_cache {
// TODO(ngates): use a globally shared segment cache for all files
options = options.with_segment_cache(Arc::new(MokaSegmentCache::new(256 << 20)));
}
match resolve_store(path, store.map(|x| x.into_inner()))? {
ResolvedStore::ObjectStore(store, path) => {
options.open_object_store(&store, path.as_ref()).await
}
ResolvedStore::Path(path) => options.open_path(path).await,
}
})
})?;
Ok(PyVortexFile {
vxf,
path: owned_path,
had_store,
without_segment_cache,
})
}
#[pyclass(name = "VortexFile", module = "vortex", frozen)]
pub struct PyVortexFile {
vxf: VortexFile,
/// The path this file was opened from, retained so that it can be reopened in another process.
path: String,
/// Whether an explicit object store was passed to [`open`]. Object stores are not picklable, so
/// such a file cannot be reopened by path alone.
had_store: bool,
without_segment_cache: bool,
}
#[pymethods]
impl PyVortexFile {
fn __len__(slf: PyRef<Self>) -> PyResult<usize> {
Ok(usize::try_from(slf.vxf.row_count())?)
}
/// The path or URL this file was opened from.
///
/// Returns
/// -------
/// :class:`.str`
#[getter]
fn path(slf: PyRef<Self>) -> String {
slf.path.clone()
}
/// Support for Python's pickle protocol: the file is reopened by path in the receiving process.
///
/// Only the path is transferred, never any read state or segment cache, so this is cheap enough
/// to send a file to every worker of a multiprocessing pool or Ray job.
///
/// Raises
/// ------
/// :class:`TypeError`
/// If the file was opened with an explicit ``store``, since object stores cannot be
/// pickled. Pass the URL to :func:`vortex.open` in the worker instead.
fn __reduce__<'py>(slf: PyRef<'py, Self>) -> PyResult<(Bound<'py, PyAny>, (String, bool))> {
if slf.had_store {
return Err(PyTypeError::new_err(
"cannot pickle a VortexFile opened with an explicit store, because object stores \
are not picklable; open it from its URL in the receiving process instead",
));
}
let py = slf.py();
let module = PyModule::import(py, "vortex._lib.file")?;
let reopen = module.getattr(intern!(py, "_reopen"))?;
Ok((reopen, (slf.path.clone(), slf.without_segment_cache)))
}
#[getter]
fn dtype(slf: Bound<Self>) -> PyResult<Bound<PyDType>> {
PyDType::init(slf.py(), slf.get().vxf.dtype().clone())
}
#[pyo3(signature = (projection = None, *, expr = None, limit = None, indices = None, batch_size = None))]
fn scan(
slf: Bound<Self>,
projection: Option<PyIntoProjection>,
expr: Option<PyExpr>,
limit: Option<u64>,
indices: Option<PyArrayRef>,
batch_size: Option<usize>,
) -> PyVortexResult<PyArrayIterator> {
let vxf = slf.get().vxf.clone();
let projection = projection.map(|p| p.0);
let expr = expr.map(|e| e.into_inner());
let indices = indices.map(|i| i.into_inner());
slf.py().detach(move || {
let session = session();
let mut ctx = session.create_execution_ctx();
let builder =
scan_builder(&vxf, projection, expr, limit, indices, batch_size, &mut ctx)?;
let runtime = current_runtime();
Ok(PyArrayIterator::new(Box::new(
builder.into_array_iter(&runtime)?,
)))
})
}
#[pyo3(signature = (projection = None, *, expr = None, limit = None, indices = None, batch_size = None))]
fn prepare(
slf: Bound<Self>,
projection: Option<PyIntoProjection>,
expr: Option<PyExpr>,
limit: Option<u64>,
indices: Option<PyArrayRef>,
batch_size: Option<usize>,
) -> PyVortexResult<PyRepeatedScan> {
let vxf = slf.get().vxf.clone();
let projection = projection.map(|p| p.0);
let expr = expr.map(|e| e.into_inner());
let indices = indices.map(|i| i.into_inner());
let scan = slf.py().detach(move || {
let session = session();
let mut ctx = session.create_execution_ctx();
scan_builder(&vxf, projection, expr, limit, indices, batch_size, &mut ctx)?.prepare()
})?;
Ok(PyRepeatedScan {
scan: Arc::new(scan),
row_count: slf.get().vxf.row_count(),
})
}
#[pyo3(signature = (projection = None, *, expr = None, limit = None, batch_size = None, schema = None))]
fn to_arrow(
slf: Bound<Self>,
projection: Option<PyIntoProjection>,
expr: Option<PyExpr>,
limit: Option<u64>,
batch_size: Option<usize>,
schema: Option<&Bound<PyAny>>,
) -> PyVortexResult<Py<PyAny>> {
let vxf = slf.get().vxf.clone();
let schema = schema
.map(|schema| Schema::from_pyarrow(&schema.as_borrowed()))
.transpose()?
.map(Arc::new);
let runtime = current_runtime();
let reader = slf.py().detach(|| {
let filter = expr
.map(|e| {
e.into_inner()
.optimize_recursive(vxf.dtype())?
.bind(vxf.dtype())
})
.transpose()?;
let projection = projection
.map(|p| p.0)
.unwrap_or_else(root)
.optimize_recursive(vxf.dtype())?
.bind(vxf.dtype())?;
let mut builder = vxf
.scan()?
.with_some_filter(filter)
.with_projection(projection);
if let Some(limit) = limit {
builder = builder.with_limit(limit);
}
if let Some(batch_size) = batch_size {
builder = builder.with_split_by(SplitBy::RowCount(batch_size));
}
let schema = match schema {
Some(schema) => schema,
None => Arc::new(session().arrow().to_arrow_schema(&builder.dtype()?)?),
};
builder.into_record_batch_reader(schema, &runtime)
})?;
let rbr: Box<dyn RecordBatchReader + Send> = Box::new(reader);
Ok(rbr.into_pyarrow(slf.py())?)
}
fn to_dataset(slf: Bound<Self>) -> PyVortexResult<PyVortexDataset> {
Ok(PyVortexDataset::try_new(slf.get().vxf.clone())?)
}
#[pyo3(signature = (*))]
pub fn splits(&self) -> PyVortexResult<Vec<(u64, u64)>> {
Ok(self
.vxf
.splits()?
.into_iter()
.map(|x| (x.start, x.end))
.collect())
}
}
fn scan_builder(
vxf: &VortexFile,
projection: Option<Expression>,
expr: Option<Expression>,
limit: Option<u64>,
indices: Option<ArrayRef>,
batch_size: Option<usize>,
ctx: &mut ExecutionCtx,
) -> VortexResult<ScanBuilder<ArrayRef>> {
let projection = projection
.unwrap_or_else(root)
.optimize_recursive(vxf.dtype())?
.bind(vxf.dtype())?;
let expr = expr
.map(|expr| expr.optimize_recursive(vxf.dtype())?.bind(vxf.dtype()))
.transpose()?;
let mut builder = vxf
.scan()?
.with_some_filter(expr)
.with_projection(projection);
if let Some(limit) = limit {
builder = builder.with_limit(limit);
}
if let Some(indices) = indices {
let casted = indices.cast(DType::Primitive(PType::U64, NonNullable))?;
let indices = casted.execute::<PrimitiveArray>(ctx)?.into_buffer::<u64>();
builder = builder.with_row_indices(StrictSortedBuffer::try_new(indices)?);
}
if let Some(batch_size) = batch_size {
builder = builder.with_split_by(SplitBy::RowCount(batch_size));
}
Ok(builder)
}
pub struct PyIntoProjection(Expression);
impl<'py> FromPyObject<'_, 'py> for PyIntoProjection {
type Error = PyErr;
fn extract(ob: Borrowed<'_, 'py, PyAny>) -> Result<Self, Self::Error> {
// If it's a list of strings, convert to a column selection.
if let Ok(py_list) = ob.cast::<PyList>() {
let cols = py_list
.iter()
.map(|item| item.extract::<String>())
.collect::<PyResult<Vec<String>>>()?;
return Ok(PyIntoProjection(select(
cols.into_iter().collect::<FieldNames>(),
root(),
)));
}
// If it's an expression, just return it.
if let Ok(py_expr) = ob.cast::<PyExpr>() {
return Ok(PyIntoProjection(py_expr.get().inner().clone()));
}
Err(PyTypeError::new_err(
"projection must be a list of strings or a vortex.Expr",
))
}
}