Skip to main content

perspective_python/client/
client_sync.rs

1// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
2// ┃ ██████ ██████ ██████       █      █      █      █      █ █▄  ▀███ █       ┃
3// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█  ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄  ▀█ █ ▀▀▀▀▀ ┃
4// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄   █ ▄▄▄▄▄ ┃
5// ┃ █      ██████ █  ▀█▄       █ ██████      █      ███▌▐███ ███████▄ █       ┃
6// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
7// ┃ Copyright (c) 2017, the Perspective Authors.                              ┃
8// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
9// ┃ This file is part of the Perspective library, distributed under the terms ┃
10// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃
11// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
12
13use std::collections::HashMap;
14use std::future::Future;
15use std::sync::Arc;
16
17use perspective_client::config::Scalar;
18use perspective_client::{JoinType, TableRef, assert_table_api, assert_view_api};
19#[cfg(doc)]
20use perspective_client::{TableInitOptions, UpdateOptions, config::ViewConfigUpdate};
21use pyo3::exceptions::PyTypeError;
22use pyo3::marker::Ungil;
23use pyo3::prelude::*;
24use pyo3::types::*;
25
26use super::client_async::*;
27use crate::py_err::ResultTClientErrorExt;
28use crate::server::Server;
29
30pub(crate) fn py_to_table_ref(val: &Bound<'_, PyAny>) -> PyResult<TableRef> {
31    if let Ok(t) = val.downcast::<Table>() {
32        let table_ref = t.borrow();
33        Ok(TableRef::from(&*table_ref.0.table))
34    } else if let Ok(name) = val.extract::<String>() {
35        Ok(TableRef::from(name))
36    } else {
37        Err(PyTypeError::new_err(
38            "Expected a Table or string table name",
39        ))
40    }
41}
42
43pub(crate) fn parse_join_type(join_type: Option<&str>) -> PyResult<JoinType> {
44    match join_type {
45        Some("left") => Ok(JoinType::Left),
46        Some("outer") => Ok(JoinType::Outer),
47        None | Some("inner") => Ok(JoinType::Inner),
48        Some(other) => Err(pyo3::exceptions::PyValueError::new_err(format!(
49            "Unknown join type: \"{}\"",
50            other
51        ))),
52    }
53}
54
55pub(crate) fn scalar_to_py(py: Python<'_>, scalar: &Scalar) -> PyObject {
56    match scalar {
57        Scalar::Float(x) => x.into_pyobject(py).unwrap().into_any().unbind(),
58        Scalar::String(x) => x.into_pyobject(py).unwrap().into_any().unbind(),
59        Scalar::Bool(x) => x.into_pyobject(py).unwrap().to_owned().into_any().unbind(),
60        Scalar::Null => py.None(),
61    }
62}
63
64pub(crate) trait PyFutureExt: Future {
65    fn py_block_on(self, py: Python<'_>) -> Self::Output
66    where
67        Self: Sized + Send,
68        Self::Output: Ungil,
69    {
70        use pollster::FutureExt;
71        py.allow_threads(move || self.block_on())
72    }
73}
74
75impl<F: Future> PyFutureExt for F {}
76
77/// An instance of a [`Client`] is a connection to a single [`Server`], whether
78/// locally in-memory or remote over some transport like a WebSocket.
79///
80/// [`Client`] and Perspective objects derived from it have _synchronous_ APIs,
81/// suitable for use in a repl or script context where this is the _only_
82/// [`Client`] connected to its [`Server`]. If you want to
83/// integrate with a Web framework or otherwise connect multiple clients,
84/// use [`AsyncClient`].
85#[pyclass(subclass, module = "perspective")]
86pub struct Client(pub(crate) AsyncClient);
87
88#[pymethods]
89impl Client {
90    #[new]
91    #[pyo3(signature = (handle_request, close_cb=None, name=None))]
92    pub fn new(
93        handle_request: Py<PyAny>,
94        close_cb: Option<Py<PyAny>>,
95        name: Option<String>,
96    ) -> PyResult<Self> {
97        let client = AsyncClient::new(handle_request, close_cb, name)?;
98        Ok(Client(client))
99    }
100
101    /// Create a new [`Client`] instance bound to a specific in-process
102    /// [`Server`] (e.g. generally _not_ the global [`Server`]).
103    #[staticmethod]
104    pub fn from_server(py: Python<'_>, server: Py<Server>) -> PyResult<Self> {
105        server.borrow(py).new_local_client()
106    }
107
108    /// Handle a message from the external message queue.
109    /// [`Client::handle_response`] is part of the low-level message-handling
110    /// API necessary to implement new transports for a [`Client`]
111    /// connection to a local-or-remote [`Server`], and
112    /// doesn't generally need to be called directly by "users" of a
113    /// [`Client`] once connected.
114    pub fn handle_response(&self, py: Python<'_>, response: Py<PyBytes>) -> PyResult<bool> {
115        self.0.handle_response(response).py_block_on(py)
116    }
117
118    /// Creates a new [`Table`] from either a _schema_ or _data_.
119    ///
120    /// The [`Client::table`] factory function can be initialized with either a
121    /// _schema_ (see [`Table::schema`]), or data in one of these formats:
122    ///
123    /// - Apache Arrow
124    /// - CSV
125    /// - JSON row-oriented
126    /// - JSON column-oriented
127    /// - NDJSON
128    ///
129    /// When instantiated with _data_, the schema is inferred from this data.
130    /// While this is convenient, inferrence is sometimes imperfect e.g.
131    /// when the input is empty, null or ambiguous. For these cases,
132    /// [`Client::table`] can first be instantiated with a explicit schema.
133    ///
134    /// When instantiated with a _schema_, the resulting [`Table`] is empty but
135    /// with known column names and column types. When subsqeuently
136    /// populated with [`Table::update`], these columns will be _coerced_ to
137    /// the schema's type. This behavior can be useful when
138    /// [`Client::table`]'s column type inferences doesn't work.
139    ///
140    /// The resulting [`Table`] is _virtual_, and invoking its methods
141    /// dispatches events to the `perspective_server::Server` this
142    /// [`Client`] connects to, where the data is stored and all calculation
143    /// occurs.
144    ///
145    /// # Arguments
146    ///
147    /// - `arg` - Either _schema_ or initialization _data_.
148    /// - `options` - Optional configuration which provides one of:
149    ///     - `limit` - The max number of rows the resulting [`Table`] can
150    ///       store.
151    ///     - `index` - The column name to use as an _index_ column. If this
152    ///       `Table` is being instantiated by _data_, this column name must be
153    ///       present in the data.
154    ///     - `name` - The name of the table. This will be generated if it is
155    ///       not provided.
156    ///     - `format` - The explicit format of the input data, can be one of
157    ///       `"json"`, `"columns"`, `"csv"` or `"arrow"`. This overrides
158    ///       language-specific type dispatch behavior, which allows stringified
159    ///       and byte array alternative inputs.
160    ///
161    /// # Python Examples
162    ///
163    /// Load a CSV from a `str`:
164    ///
165    /// ```python
166    /// table = client.table("x,y\n1,2\n3,4")
167    /// ```
168    #[allow(clippy::too_many_arguments)]
169    #[pyo3(signature = (input, limit=None, index=None, name=None, format=None, page_to_disk=None, list_flatten=None))]
170    pub fn table(
171        &self,
172        py: Python<'_>,
173        input: Py<PyAny>,
174        limit: Option<u32>,
175        index: Option<Py<PyString>>,
176        name: Option<Py<PyString>>,
177        format: Option<Py<PyString>>,
178        page_to_disk: Option<bool>,
179        list_flatten: Option<Py<PyString>>,
180    ) -> PyResult<Table> {
181        Ok(Table(
182            self.0
183                .table(
184                    input,
185                    limit,
186                    index,
187                    name,
188                    format,
189                    page_to_disk,
190                    list_flatten,
191                )
192                .py_block_on(py)?,
193        ))
194    }
195
196    /// Opens a [`Table`] that is hosted on the `perspective_server::Server`
197    /// that is connected to this [`Client`].
198    ///
199    /// The `name` property of [`TableInitOptions`] is used to identify each
200    /// [`Table`]. [`Table`] `name`s can be looked up for each [`Client`]
201    /// via [`Client::get_hosted_table_names`].
202    ///
203    /// # Python Examples
204    ///
205    /// ```python
206    /// table =  client.open_table("table_one");
207    /// ```
208    pub fn open_table(&self, py: Python<'_>, name: String) -> PyResult<Table> {
209        let client = self.0.clone();
210        let table = client.open_table(name).py_block_on(py)?;
211        Ok(Table(table))
212    }
213
214    /// Creates a new read-only [`Table`] by performing a JOIN on two
215    /// source tables. The resulting table is reactive: when either source
216    /// table is updated, the join is automatically recomputed.
217    ///
218    /// # Python Examples
219    ///
220    /// ```python
221    /// joined = client.join(orders_table, products_table, "Product ID", "left")
222    /// ```
223    #[pyo3(signature = (left, right, on, join_type=None, name=None, right_on=None))]
224    #[allow(clippy::too_many_arguments, reason = "This is a Python API")]
225    pub fn join(
226        &self,
227        py: Python<'_>,
228        left: &Bound<'_, PyAny>,
229        right: &Bound<'_, PyAny>,
230        on: String,
231        join_type: Option<String>,
232        name: Option<String>,
233        right_on: Option<String>,
234    ) -> PyResult<Table> {
235        let left_ref = py_to_table_ref(left)?;
236        let right_ref = py_to_table_ref(right)?;
237        let jt = parse_join_type(join_type.as_deref())?;
238        let options = perspective_client::JoinOptions {
239            join_type: Some(jt),
240            name,
241            right_on,
242        };
243        let table = self
244            .0
245            .client
246            .join(left_ref, right_ref, &on, options)
247            .py_block_on(py)
248            .into_pyerr()?;
249        Ok(Table(AsyncTable {
250            table: Arc::new(table),
251            client: self.0.clone(),
252        }))
253    }
254
255    /// Retrieves the names of all tables that this client has access to.
256    ///
257    /// `name` is a string identifier unique to the [`Table`] (per [`Client`]),
258    /// which can be used in conjunction with [`Client::open_table`] to get
259    /// a [`Table`] instance without the use of [`Client::table`]
260    /// constructor directly (e.g., one created by another [`Client`]).
261    ///
262    /// # Python Examples
263    ///
264    /// ```python
265    /// tables = client.get_hosted_table_names();
266    /// ```
267    pub fn get_hosted_table_names(&self, py: Python<'_>) -> PyResult<Vec<String>> {
268        self.0.get_hosted_table_names().py_block_on(py)
269    }
270
271    /// Register a callback which is invoked whenever [`Client::table`] (on this
272    /// [`Client`]) or [`Table::delete`] (on a [`Table`] belinging to this
273    /// [`Client`]) are called.
274    pub fn on_hosted_tables_update(&self, py: Python<'_>, callback: Py<PyAny>) -> PyResult<u32> {
275        self.0.on_hosted_tables_update(callback).py_block_on(py)
276    }
277
278    /// Remove a callback previously registered via
279    /// [`Client::on_hosted_tables_update`].
280    pub fn remove_hosted_tables_update(&self, py: Python<'_>, callback_id: u32) -> PyResult<()> {
281        self.0
282            .remove_hosted_tables_update(callback_id)
283            .py_block_on(py)
284    }
285
286    /// Provides the [`SystemInfo`] struct, implementation-specific metadata
287    /// about the [`perspective_server::Server`] runtime such as Memory and
288    /// CPU usage.
289    pub fn system_info(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
290        self.0.system_info().py_block_on(py)
291    }
292
293    /// Terminates this [`Client`], cleaning up any [`View`] handles the
294    /// [`Client`] has open as well as its callbacks.
295    pub fn terminate(&self, py: Python<'_>) -> PyResult<()> {
296        self.0.terminate(py)
297    }
298}
299
300/// [`Table`] is Perspective's columnar data frame, analogous to a Pandas/Polars
301/// `DataFrame` or Apache Arrow, supporting append & in-place updates, removal
302/// by index, and update notifications.
303///
304/// A [`Table`] contains columns, each of which have a unique name, are strongly
305/// and consistently typed, and contains rows of data conforming to the column's
306/// type. Each column in a [`Table`] must have the same number of rows, though
307/// not every row must contain data; null-values are used to indicate missing
308/// values in the dataset. The schema of a [`Table`] is _immutable after
309/// creation_, which means the column names and data types cannot be changed
310/// after the [`Table`] has been created. Columns cannot be added or deleted
311/// after creation either, but a [`View`] can be used to select an arbitrary set
312/// of columns from the [`Table`].
313#[pyclass(subclass, name = "Table", module = "perspective")]
314pub struct Table(AsyncTable);
315
316assert_table_api!(Table);
317
318#[pymethods]
319impl Table {
320    #[new]
321    fn new() -> PyResult<Self> {
322        Err(PyTypeError::new_err(
323            "Do not call Table's constructor directly, construct from a Client instance.",
324        ))
325    }
326
327    /// Returns the name of the index column for the table.
328    ///
329    /// # Python Examples
330    ///
331    /// ```python
332    /// table = perspective.table("x,y\n1,2\n3,4", index="x");
333    /// index = client.get_index()
334    /// ```
335    pub fn get_index(&self) -> Option<String> {
336        self.0.get_index()
337    }
338
339    /// Get a copy of the [`Client`] this [`Table`] came from.
340    pub fn get_client(&self, py: Python<'_>) -> Client {
341        Client(self.0.get_client().py_block_on(py))
342    }
343
344    /// Returns the user-specified row limit for this table.
345    pub fn get_limit(&self) -> Option<u32> {
346        self.0.get_limit()
347    }
348
349    /// Returns the user-specified name for this table, or the auto-generated
350    /// name if a name was not specified when the table was created.
351    pub fn get_name(&self) -> String {
352        self.0.get_name()
353    }
354
355    /// Removes all the rows in the [`Table`], but preserves everything else
356    /// including the schema, index, and any callbacks or registered
357    /// [`View`] instances.
358    ///
359    /// Calling [`Table::clear`], like [`Table::update`] and [`Table::remove`],
360    /// will trigger an update event to any registered listeners via
361    /// [`View::on_update`].
362    pub fn clear(&self, py: Python<'_>) -> PyResult<()> {
363        self.0.clear().py_block_on(py)
364    }
365
366    /// Returns the column names of this [`Table`] in "natural" order (the
367    /// ordering implied by the input format).
368    ///  
369    ///  # Python Examples
370    ///
371    /// ```python
372    /// columns = table.columns()
373    /// ```
374    pub fn columns(&self, py: Python<'_>) -> PyResult<Vec<String>> {
375        self.0.columns().py_block_on(py)
376    }
377
378    /// Delete this [`Table`] and cleans up associated resources.
379    ///
380    /// [`Table`]s do not stop consuming resources or processing updates when
381    /// they are garbage collected in their host language - you must call
382    /// this method to reclaim these.
383    ///
384    /// # Arguments
385    ///
386    /// - `options` An options dictionary.
387    ///     - `lazy` Whether to delete this [`Table`] _lazily_. When false (the
388    ///       default), the delete will occur immediately, assuming it has no
389    ///       [`View`] instances registered to it (which must be deleted first,
390    ///       otherwise this method will throw an error). When true, the
391    ///       [`Table`] will only be marked for deltion once its [`View`]
392    ///       dependency count reaches 0.
393    ///
394    /// # Python Examples
395    ///
396    /// ```python
397    /// table = client.table("x,y\n1,2\n3,4")
398    ///
399    /// # ...
400    ///
401    /// table.delete(lazy=True)
402    /// ```
403    #[pyo3(signature=(lazy=false))]
404    pub fn delete(&self, py: Python<'_>, lazy: bool) -> PyResult<()> {
405        self.0.delete(lazy).py_block_on(py)
406    }
407
408    /// Create a unique channel ID on this [`Table`], which allows
409    /// `View::on_update` callback calls to be associated with the
410    /// `Table::update` which caused them.
411    pub fn make_port(&self, py: Python<'_>) -> PyResult<i32> {
412        let table = self.0.clone();
413        table.make_port().py_block_on(py)
414    }
415
416    /// Register a callback which is called exactly once, when this [`Table`] is
417    /// deleted with the [`Table::delete`] method.
418    ///
419    /// [`Table::on_delete`] resolves when the subscription message is sent, not
420    /// when the _delete_ event occurs.
421    pub fn on_delete(&self, py: Python<'_>, callback: Py<PyAny>) -> PyResult<u32> {
422        let table = self.0.clone();
423        table.on_delete(callback).py_block_on(py)
424    }
425
426    #[pyo3(signature = (input, format=None))]
427    pub fn remove(&self, py: Python<'_>, input: Py<PyAny>, format: Option<String>) -> PyResult<()> {
428        let table = self.0.clone();
429        table.remove(input, format).py_block_on(py)
430    }
431
432    /// Removes a listener with a given ID, as returned by a previous call to
433    /// [`Table::on_delete`].
434    pub fn remove_delete(&self, py: Python<'_>, callback_id: u32) -> PyResult<()> {
435        let table = self.0.clone();
436        table.remove_delete(callback_id).py_block_on(py)
437    }
438
439    /// Returns a table's [`Schema`], a mapping of column names to column types.
440    ///
441    /// The mapping of a [`Table`]'s column names to data types is referred to
442    /// as a [`Schema`]. Each column has a unique name and a data type, one
443    /// of:
444    ///
445    /// - `"boolean"` - A boolean type
446    /// - `"date"` - A timesonze-agnostic date type (month/day/year)
447    /// - `"datetime"` - A millisecond-precision datetime type in the UTC
448    ///   timezone
449    /// - `"float"` - A 64 bit float
450    /// - `"integer"` - A signed 32 bit integer (the integer type supported by
451    ///   JavaScript)
452    /// - `"string"` - A `String` data type (encoded internally as a
453    ///   _dictionary_)
454    ///
455    /// Note that all [`Table`] columns are _nullable_, regardless of the data
456    /// type.
457    pub fn schema(&self, py: Python<'_>) -> PyResult<HashMap<String, String>> {
458        let table = self.0.clone();
459        table.schema().py_block_on(py)
460    }
461
462    /// Validates the given expressions.
463    pub fn validate_expressions(
464        &self,
465        py: Python<'_>,
466        expression: Py<PyAny>,
467    ) -> PyResult<Py<PyAny>> {
468        let table = self.0.clone();
469        table.validate_expressions(expression).py_block_on(py)
470    }
471
472    /// Create a new [`View`] from this table with a specified
473    /// [`ViewConfigUpdate`].
474    ///
475    /// See [`View`] struct.
476    ///
477    /// # Examples
478    ///
479    /// ```python
480    /// view view = table.view(
481    ///     columns=["Sales"],
482    ///     aggregates={"Sales": "sum"},
483    ///     group_by=["Region", "State"],
484    /// )
485    /// ```
486    #[pyo3(signature = (**config))]
487    pub fn view(&self, py: Python<'_>, config: Option<Py<PyDict>>) -> PyResult<View> {
488        Ok(View(self.0.view(config).py_block_on(py)?))
489    }
490
491    /// Returns the number of rows in a [`Table`].
492    pub fn size(&self, py: Python<'_>) -> PyResult<usize> {
493        self.0.size().py_block_on(py)
494    }
495
496    /// Removes all the rows in the [`Table`], but preserves everything else
497    /// including the schema, index, and any callbacks or registered
498    /// [`View`] instances.
499    ///
500    /// Calling [`Table::clear`], like [`Table::update`] and [`Table::remove`],
501    /// will trigger an update event to any registered listeners via
502    /// [`View::on_update`].
503    #[pyo3(signature = (input, format=None))]
504    pub fn replace(
505        &self,
506        py: Python<'_>,
507        input: Py<PyAny>,
508        format: Option<String>,
509    ) -> PyResult<()> {
510        self.0.replace(input, format).py_block_on(py)
511    }
512
513    /// Updates the rows of this table and any derived [`View`] instances.
514    ///
515    /// Calling [`Table::update`] will trigger the [`View::on_update`] callbacks
516    /// register to derived [`View`], and the call itself will not resolve until
517    /// _all_ derived [`View`]'s are notified.
518    ///
519    /// When updating a [`Table`] with an `index`, [`Table::update`] supports
520    /// partial updates, by omitting columns from the update data.
521    ///
522    /// # Arguments
523    ///
524    /// - `input` - The input data for this [`Table`]. The schema of a [`Table`]
525    ///   is immutable after creation, so this method cannot be called with a
526    ///   schema.
527    /// - `options` - Options for this update step - see
528    ///   [`perspective_client::UpdateOptions`].
529    /// ```  
530    #[pyo3(signature = (input, port_id=None, format=None))]
531    pub fn update(
532        &self,
533        py: Python<'_>,
534        input: Py<PyAny>,
535        port_id: Option<u32>,
536        format: Option<String>,
537    ) -> PyResult<()> {
538        self.0.update(input, port_id, format).py_block_on(py)
539    }
540}
541
542/// The [`View`] struct is Perspective's query and serialization interface. It
543/// represents a query on the `Table`'s dataset and is always created from an
544/// existing `Table` instance via the [`Table::view`] method.
545///
546/// [`View`]s are immutable with respect to the arguments provided to the
547/// [`Table::view`] method; to change these parameters, you must create a new
548/// [`View`] on the same [`Table`]. However, each [`View`] is _live_ with
549/// respect to the [`Table`]'s data, and will (within a conflation window)
550/// update with the latest state as its parent [`Table`] updates, including
551/// incrementally recalculating all aggregates, pivots, filters, etc. [`View`]
552/// query parameters are composable, in that each parameter works independently
553/// _and_ in conjunction with each other, and there is no limit to the number of
554/// pivots, filters, etc. which can be applied.
555///
556/// To construct a [`View`], call the [`Table::view`] factory method. A
557/// [`Table`] can have as many [`View`]s associated with it as you need -
558/// Perspective conserves memory by relying on a single [`Table`] to power
559/// multiple [`View`]s concurrently.
560#[pyclass(subclass, name = "View", module = "perspective")]
561pub struct View(pub(crate) AsyncView);
562
563assert_view_api!(View);
564
565#[pymethods]
566impl View {
567    #[new]
568    fn new() -> PyResult<Self> {
569        Err(PyTypeError::new_err(
570            "Do not call View's constructor directly, construct from a Table instance.",
571        ))
572    }
573
574    /// Returns an array of strings containing the column paths of the [`View`]
575    /// without any of the source columns.
576    ///
577    /// A column path shows the columns that a given cell belongs to after
578    /// pivots are applied.
579    #[pyo3(signature = (**window))]
580    pub fn column_paths(
581        &self,
582        py: Python<'_>,
583        window: Option<Py<PyDict>>,
584    ) -> PyResult<Vec<String>> {
585        self.0.column_paths(window).py_block_on(py)
586    }
587
588    /// Renders this [`View`] as a column-oriented JSON string. Useful if you
589    /// want to save additional round trip serialize/deserialize cycles.  
590    #[pyo3(signature = (**window))]
591    pub fn to_columns_string(
592        &self,
593        py: Python<'_>,
594        window: Option<Py<PyDict>>,
595    ) -> PyResult<String> {
596        self.0.to_columns_string(window).py_block_on(py)
597    }
598
599    /// Renders this `View` as a row-oriented JSON string.
600    #[pyo3(signature = (**window))]
601    pub fn to_json_string(&self, py: Python<'_>, window: Option<Py<PyDict>>) -> PyResult<String> {
602        self.0.to_json_string(window).py_block_on(py)
603    }
604
605    /// Renders this [`View`] as an [NDJSON](https://github.com/ndjson/ndjson-spec)
606    /// formatted `String`.
607    #[pyo3(signature = (**window))]
608    pub fn to_ndjson(&self, py: Python<'_>, window: Option<Py<PyDict>>) -> PyResult<String> {
609        self.0.to_ndjson(window).py_block_on(py)
610    }
611
612    /// Renders this [`View`] as a row-oriented Python `list`.
613    #[pyo3(signature = (**window))]
614    pub fn to_records<'a>(
615        &self,
616        py: Python<'a>,
617        window: Option<Py<PyDict>>,
618    ) -> PyResult<Bound<'a, PyAny>> {
619        let json = self.0.to_json_string(window).py_block_on(py)?;
620        let json_module = PyModule::import(py, "json")?;
621        json_module.call_method1("loads", (json,))
622    }
623
624    /// Renders this [`View`] as a row-oriented Python `list`.
625    #[pyo3(signature = (**window))]
626    pub fn to_json<'a>(
627        &self,
628        py: Python<'a>,
629        window: Option<Py<PyDict>>,
630    ) -> PyResult<Bound<'a, PyAny>> {
631        self.to_records(py, window)
632    }
633
634    /// Renders this [`View`] as a column-oriented Python `dict`.
635    #[pyo3(signature = (**window))]
636    pub fn to_columns<'a>(
637        &self,
638        py: Python<'a>,
639        window: Option<Py<PyDict>>,
640    ) -> PyResult<Bound<'a, PyAny>> {
641        let json = self.0.to_columns_string(window).py_block_on(py)?;
642        let json_module = PyModule::import(py, "json")?;
643        json_module.call_method1("loads", (json,))
644    }
645
646    /// Renders this [`View`] as a CSV `String` in a standard format.
647    #[pyo3(signature = (**window))]
648    pub fn to_csv(&self, py: Python<'_>, window: Option<Py<PyDict>>) -> PyResult<String> {
649        self.0.to_csv(window).py_block_on(py)
650    }
651
652    /// Renders this [`View`] as a `pandas.DataFrame`.
653    #[pyo3(signature = (**window))]
654    // #[deprecated(since="3.2.0", note="Please use `View::to_pandas`")]
655    pub fn to_dataframe(&self, py: Python<'_>, window: Option<Py<PyDict>>) -> PyResult<Py<PyAny>> {
656        self.0.to_dataframe(window).py_block_on(py)
657    }
658
659    /// Renders this [`View`] as a `pandas.DataFrame`.
660    #[pyo3(signature = (**window))]
661    pub fn to_pandas(&self, py: Python<'_>, window: Option<Py<PyDict>>) -> PyResult<Py<PyAny>> {
662        self.0.to_dataframe(window).py_block_on(py)
663    }
664
665    /// Renders this [`View`] as a `polars.DataFrame`.
666    #[pyo3(signature = (**window))]
667    pub fn to_polars(&self, py: Python<'_>, window: Option<Py<PyDict>>) -> PyResult<Py<PyAny>> {
668        self.0.to_polars(window).py_block_on(py)
669    }
670
671    /// Renders this [`View`] as the Apache Arrow data format.
672    ///
673    /// # Arguments
674    ///
675    /// - `window` - a [`ViewWindow`]
676    #[pyo3(signature = (**window))]
677    pub fn to_arrow(&self, py: Python<'_>, window: Option<Py<PyDict>>) -> PyResult<Py<PyBytes>> {
678        self.0.to_arrow(window).py_block_on(py)
679    }
680
681    /// Delete this [`View`] and clean up all resources associated with it.
682    /// [`View`] objects do not stop consuming resources or processing
683    /// updates when they are garbage collected - you must call this method
684    /// to reclaim these.
685    pub fn delete(&self, py: Python<'_>) -> PyResult<()> {
686        self.0.delete().py_block_on(py)
687    }
688
689    pub fn expand(&self, py: Python<'_>, index: u32) -> PyResult<u32> {
690        self.0.expand(index).py_block_on(py)
691    }
692
693    pub fn collapse(&self, py: Python<'_>, index: u32) -> PyResult<u32> {
694        self.0.collapse(index).py_block_on(py)
695    }
696
697    /// Returns this [`View`]'s _dimensions_, row and column count, as well as
698    /// those of the [`crate::Table`] from which it was derived.
699    ///
700    /// - `num_table_rows` - The number of rows in the underlying
701    ///   [`crate::Table`].
702    /// - `num_table_columns` - The number of columns in the underlying
703    ///   [`crate::Table`] (including the `index` column if this
704    ///   [`crate::Table`] was constructed with one).
705    /// - `num_view_rows` - The number of rows in this [`View`]. If this
706    ///   [`View`] has a `group_by` clause, `num_view_rows` will also include
707    ///   aggregated rows.
708    /// - `num_view_columns` - The number of columns in this [`View`]. If this
709    ///   [`View`] has a `split_by` clause, `num_view_columns` will include all
710    ///   _column paths_, e.g. the number of `columns` clause times the number
711    ///   of `split_by` groups.
712    pub fn dimensions(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
713        self.0.dimensions().py_block_on(py)
714    }
715
716    /// The expression schema of this [`View`], which contains only the
717    /// expressions created on this [`View`]. See [`View::schema`] for
718    /// details.
719    pub fn expression_schema(&self, py: Python<'_>) -> PyResult<HashMap<String, String>> {
720        self.0.expression_schema().py_block_on(py)
721    }
722
723    /// A copy of the [`ViewConfig`] object passed to the [`Table::view`] method
724    /// which created this [`View`].
725    pub fn get_config(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
726        self.0.get_config().py_block_on(py)
727    }
728
729    /// Calculates the [min, max] of the leaf nodes of a column `column_name`.
730    ///
731    /// # Returns
732    ///
733    /// A tuple of [min, max], whose types are column and aggregate dependent.
734    pub fn get_min_max(
735        &self,
736        py: Python<'_>,
737        column_name: String,
738    ) -> PyResult<(PyObject, PyObject)> {
739        self.0.get_min_max(column_name).py_block_on(py)
740    }
741
742    /// The number of aggregated rows in this [`View`]. This is affected by the
743    /// "group_by" configuration parameter supplied to this view's contructor.
744    ///
745    /// # Returns
746    ///
747    /// The number of aggregated rows.
748    pub fn num_rows(&self, py: Python<'_>) -> PyResult<u32> {
749        self.0.num_rows().py_block_on(py)
750    }
751
752    /// The number of aggregated columns in this [`View`]. This is affected by
753    /// the "split_by" configuration parameter supplied to this view's
754    /// contructor.
755    ///
756    /// # Returns
757    ///
758    /// The number of aggregated columns.
759    pub fn num_columns(&self, py: Python<'_>) -> PyResult<u32> {
760        self.0.num_columns().py_block_on(py)
761    }
762
763    /// The schema of this [`View`].
764    ///
765    /// The [`View`] schema differs from the `schema` returned by
766    /// [`Table::schema`]; it may have different column names due to
767    /// `expressions` or `columns` configs, or it maye have _different
768    /// column types_ due to the application og `group_by` and `aggregates`
769    /// config. You can think of [`Table::schema`] as the _input_ schema and
770    /// [`View::schema`] as the _output_ schema of a Perspective pipeline.
771    pub fn schema(&self, py: Python<'_>) -> PyResult<HashMap<String, String>> {
772        self.0.schema().py_block_on(py)
773    }
774
775    /// Register a callback with this [`View`]. Whenever the [`View`] is
776    /// deleted, this callback will be invoked.
777    pub fn on_delete(&self, py: Python<'_>, callback: Py<PyAny>) -> PyResult<u32> {
778        self.0.on_delete(callback).py_block_on(py)
779    }
780
781    /// Unregister a previously registered [`View::on_delete`] callback.
782    pub fn remove_delete(&self, py: Python<'_>, callback_id: u32) -> PyResult<()> {
783        self.0.remove_delete(callback_id).py_block_on(py)
784    }
785
786    /// Register a callback with this [`View`]. Whenever the view's underlying
787    /// table emits an update, this callback will be invoked with an object
788    /// containing `port_id`, indicating which port the update fired on, and
789    /// optionally `delta`, which is the new data that was updated for each
790    /// cell or each row.
791    ///
792    /// # Arguments
793    ///
794    /// - `on_update` - A callback function invoked on update, which receives an
795    ///   object with two keys: `port_id`, indicating which port the update was
796    ///   triggered on, and `delta`, whose value is dependent on the mode
797    ///   parameter.
798    /// - `options` - If this is provided as `OnUpdateOptions { mode:
799    ///   Some(OnUpdateMode::Row) }`, then `delta` is an Arrow of the updated
800    ///   rows. Otherwise `delta` will be [`Option::None`].
801    #[pyo3(signature = (callback, mode=None))]
802    pub fn on_update(
803        &self,
804        py: Python<'_>,
805        callback: Py<PyAny>,
806        mode: Option<String>,
807    ) -> PyResult<u32> {
808        self.0.on_update(callback, mode).py_block_on(py)
809    }
810
811    /// Unregister a previously registered update callback with this [`View`].
812    ///
813    /// # Arguments
814    ///
815    /// - `id` - A callback `id` as returned by a recipricol call to
816    ///   [`View::on_update`].
817    ///
818    /// # Examples
819    ///
820    /// ```rust
821    /// let callback = |_| async { print!("Updated!") };
822    /// let cid = view.on_update(callback, OnUpdateOptions::default()).await?;
823    /// view.remove_update(cid).await?;
824    /// ```
825    pub fn remove_update(&self, py: Python<'_>, callback_id: u32) -> PyResult<()> {
826        self.0.remove_update(callback_id).py_block_on(py)
827    }
828}