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;
15
16use macro_rules_attribute::apply;
17use perspective_client::{assert_table_api, assert_view_api, Session};
18#[cfg(doc)]
19use perspective_client::{config::ViewConfigUpdate, Schema, TableInitOptions, UpdateOptions};
20use pyo3::exceptions::PyTypeError;
21use pyo3::marker::Ungil;
22use pyo3::prelude::*;
23use pyo3::types::*;
24
25use super::client_async::*;
26use crate::inherit_doc;
27use crate::py_err::ResultTClientErrorExt;
28use crate::server::PySyncServer;
29
30#[pyclass(module = "perspective")]
31#[derive(Clone)]
32pub struct ProxySession(perspective_client::ProxySession);
33
34#[pymethods]
35impl ProxySession {
36    #[new]
37    pub fn new(py: Python<'_>, client: Py<Client>, handle_request: Py<PyAny>) -> PyResult<Self> {
38        let callback = {
39            move |msg: &[u8]| {
40                let msg = msg.to_vec();
41                Python::with_gil(|py| {
42                    let bytes = PyBytes::new(py, &msg);
43                    handle_request.call1(py, (bytes,))?;
44                    Ok(())
45                })
46            }
47        };
48
49        Ok(ProxySession(perspective_client::ProxySession::new(
50            client.borrow(py).0.client.clone(),
51            callback,
52        )))
53    }
54
55    pub fn handle_request(&self, py: Python<'_>, data: Vec<u8>) -> PyResult<()> {
56        self.0.handle_request(&data).py_block_on(py).into_pyerr()?;
57        Ok(())
58    }
59
60    pub fn poll(&self, py: Python<'_>) -> PyResult<()> {
61        self.0.poll().py_block_on(py).into_pyerr()?;
62        Ok(())
63    }
64
65    pub fn close(&self, py: Python<'_>) -> PyResult<()> {
66        self.0.clone().close().py_block_on(py);
67        Ok(())
68    }
69}
70
71trait PyFutureExt: Future {
72    fn py_block_on(self, py: Python<'_>) -> Self::Output
73    where
74        Self: Sized + Send,
75        Self::Output: Ungil,
76    {
77        use pollster::FutureExt;
78        py.allow_threads(move || self.block_on())
79    }
80}
81
82impl<F: Future> PyFutureExt for F {}
83
84#[apply(inherit_doc)]
85#[inherit_doc = "client.md"]
86#[pyclass(subclass, module = "perspective")]
87pub struct Client(pub(crate) AsyncClient);
88
89#[pymethods]
90impl Client {
91    #[new]
92    #[pyo3(signature = (handle_request, close_cb=None))]
93    pub fn new(handle_request: Py<PyAny>, close_cb: Option<Py<PyAny>>) -> PyResult<Self> {
94        let client = AsyncClient::new(handle_request, close_cb);
95        Ok(Client(client))
96    }
97
98    #[staticmethod]
99    #[pyo3(signature = (server, loop_callback=None))]
100    pub fn from_server(
101        py: Python<'_>,
102        server: Py<PySyncServer>,
103        loop_callback: Option<Py<PyAny>>,
104    ) -> PyResult<Self> {
105        server.borrow(py).new_local_client(py, loop_callback)
106    }
107
108    pub fn handle_response(&self, py: Python<'_>, response: Py<PyBytes>) -> PyResult<bool> {
109        self.0.handle_response(response).py_block_on(py)
110    }
111
112    #[apply(inherit_doc)]
113    #[inherit_doc = "client/table.md"]
114    #[pyo3(signature = (input, limit=None, index=None, name=None, format=None))]
115    pub fn table(
116        &self,
117        py: Python<'_>,
118        input: Py<PyAny>,
119        limit: Option<u32>,
120        index: Option<Py<PyString>>,
121        name: Option<Py<PyString>>,
122        format: Option<Py<PyString>>,
123    ) -> PyResult<Table> {
124        Ok(Table(
125            self.0
126                .table(input, limit, index, name, format)
127                .py_block_on(py)?,
128        ))
129    }
130
131    #[apply(inherit_doc)]
132    #[inherit_doc = "client/open_table.md"]
133    pub fn open_table(&self, py: Python<'_>, name: String) -> PyResult<Table> {
134        let client = self.0.clone();
135        let table = client.open_table(name).py_block_on(py)?;
136        Ok(Table(table))
137    }
138
139    #[apply(inherit_doc)]
140    #[inherit_doc = "client/get_hosted_table_names.md"]
141    pub fn get_hosted_table_names(&self, py: Python<'_>) -> PyResult<Vec<String>> {
142        self.0.get_hosted_table_names().py_block_on(py)
143    }
144
145    #[apply(inherit_doc)]
146    #[inherit_doc = "client/set_loop_callback.md"]
147    pub fn set_loop_callback(&self, py: Python<'_>, loop_cb: Py<PyAny>) -> PyResult<()> {
148        self.0.set_loop_callback(loop_cb).py_block_on(py)
149    }
150
151    #[apply(inherit_doc)]
152    #[inherit_doc = "client/terminate.md"]
153    pub fn terminate(&self, py: Python<'_>) -> PyResult<()> {
154        self.0.terminate(py)
155    }
156}
157
158#[pyclass(subclass, name = "Table", module = "perspective")]
159pub struct Table(AsyncTable);
160
161assert_table_api!(Table);
162
163#[pymethods]
164impl Table {
165    #[new]
166    fn new() -> PyResult<Self> {
167        Err(PyTypeError::new_err(
168            "Do not call Table's constructor directly, construct from a Client instance.",
169        ))
170    }
171
172    #[apply(inherit_doc)]
173    #[inherit_doc = "table/get_index.md"]
174    pub fn get_index(&self) -> Option<String> {
175        self.0.get_index()
176    }
177
178    #[apply(inherit_doc)]
179    #[inherit_doc = "table/get_client.md"]
180    pub fn get_client(&self, py: Python<'_>) -> Client {
181        Client(self.0.get_client().py_block_on(py))
182    }
183
184    #[apply(inherit_doc)]
185    #[inherit_doc = "table/get_client.md"]
186    pub fn get_limit(&self) -> Option<u32> {
187        self.0.get_limit()
188    }
189
190    pub fn get_name(&self) -> String {
191        self.0.get_name()
192    }
193
194    #[apply(inherit_doc)]
195    #[inherit_doc = "table/clear.md"]
196    pub fn clear(&self, py: Python<'_>) -> PyResult<()> {
197        self.0.clear().py_block_on(py)
198    }
199
200    #[apply(inherit_doc)]
201    #[inherit_doc = "table/columns.md"]
202    pub fn columns(&self, py: Python<'_>) -> PyResult<Vec<String>> {
203        self.0.columns().py_block_on(py)
204    }
205
206    #[apply(inherit_doc)]
207    #[inherit_doc = "table/delete.md"]
208    pub fn delete(&self, py: Python<'_>) -> PyResult<()> {
209        self.0.delete().py_block_on(py)
210    }
211
212    #[apply(inherit_doc)]
213    #[inherit_doc = "table/make_port.md"]
214    pub fn make_port(&self, py: Python<'_>) -> PyResult<i32> {
215        let table = self.0.clone();
216        table.make_port().py_block_on(py)
217    }
218
219    #[apply(inherit_doc)]
220    #[inherit_doc = "table/on_delete.md"]
221    pub fn on_delete(&self, py: Python<'_>, callback: Py<PyAny>) -> PyResult<u32> {
222        let table = self.0.clone();
223        table.on_delete(callback).py_block_on(py)
224    }
225
226    #[apply(inherit_doc)]
227    #[inherit_doc = "table/remove.md"]
228    #[pyo3(signature = (input, format=None))]
229    pub fn remove(&self, py: Python<'_>, input: Py<PyAny>, format: Option<String>) -> PyResult<()> {
230        let table = self.0.clone();
231        table.remove(input, format).py_block_on(py)
232    }
233
234    #[apply(inherit_doc)]
235    #[inherit_doc = "table/remove_delete.md"]
236    pub fn remove_delete(&self, py: Python<'_>, callback_id: u32) -> PyResult<()> {
237        let table = self.0.clone();
238        table.remove_delete(callback_id).py_block_on(py)
239    }
240
241    #[apply(inherit_doc)]
242    #[inherit_doc = "table/schema.md"]
243    pub fn schema(&self, py: Python<'_>) -> PyResult<HashMap<String, String>> {
244        let table = self.0.clone();
245        table.schema().py_block_on(py)
246    }
247
248    #[apply(inherit_doc)]
249    #[inherit_doc = "table/validate_expressions.md"]
250    pub fn validate_expressions(
251        &self,
252        py: Python<'_>,
253        expression: Py<PyAny>,
254    ) -> PyResult<Py<PyAny>> {
255        let table = self.0.clone();
256        table.validate_expressions(expression).py_block_on(py)
257    }
258
259    #[apply(inherit_doc)]
260    #[inherit_doc = "table/view.md"]
261    #[pyo3(signature = (**config))]
262    pub fn view(&self, py: Python<'_>, config: Option<Py<PyDict>>) -> PyResult<View> {
263        Ok(View(self.0.view(config).py_block_on(py)?))
264    }
265
266    #[apply(inherit_doc)]
267    #[inherit_doc = "table/size.md"]
268    pub fn size(&self, py: Python<'_>) -> PyResult<usize> {
269        self.0.size().py_block_on(py)
270    }
271
272    #[apply(inherit_doc)]
273    #[inherit_doc = "table/update.md"]
274    #[pyo3(signature = (input, format=None))]
275    pub fn replace(
276        &self,
277        py: Python<'_>,
278        input: Py<PyAny>,
279        format: Option<String>,
280    ) -> PyResult<()> {
281        self.0.replace(input, format).py_block_on(py)
282    }
283
284    #[apply(inherit_doc)]
285    #[inherit_doc = "table/update.md"]
286    #[pyo3(signature = (input, port_id=None, format=None))]
287    pub fn update(
288        &self,
289        py: Python<'_>,
290        input: Py<PyAny>,
291        port_id: Option<u32>,
292        format: Option<String>,
293    ) -> PyResult<()> {
294        self.0.update(input, port_id, format).py_block_on(py)
295    }
296}
297
298#[apply(inherit_doc)]
299#[inherit_doc = "view.md"]
300#[pyclass(subclass, name = "View", module = "perspective")]
301pub struct View(AsyncView);
302
303assert_view_api!(View);
304
305#[pymethods]
306impl View {
307    #[new]
308    fn new() -> PyResult<Self> {
309        Err(PyTypeError::new_err(
310            "Do not call View's constructor directly, construct from a Table instance.",
311        ))
312    }
313
314    #[apply(inherit_doc)]
315    #[inherit_doc = "view/column_paths.md"]
316    pub fn column_paths(&self, py: Python<'_>) -> PyResult<Vec<String>> {
317        self.0.column_paths().py_block_on(py)
318    }
319
320    #[apply(inherit_doc)]
321    #[inherit_doc = "view/to_columns_string.md"]
322    #[pyo3(signature = (**window))]
323    pub fn to_columns_string(
324        &self,
325        py: Python<'_>,
326        window: Option<Py<PyDict>>,
327    ) -> PyResult<String> {
328        self.0.to_columns_string(window).py_block_on(py)
329    }
330
331    #[apply(inherit_doc)]
332    #[inherit_doc = "view/to_json_string.md"]
333    #[pyo3(signature = (**window))]
334    pub fn to_json_string(&self, py: Python<'_>, window: Option<Py<PyDict>>) -> PyResult<String> {
335        self.0.to_json_string(window).py_block_on(py)
336    }
337
338    #[apply(inherit_doc)]
339    #[inherit_doc = "view/to_ndjson.md"]
340    #[pyo3(signature = (**window))]
341    pub fn to_ndjson(&self, py: Python<'_>, window: Option<Py<PyDict>>) -> PyResult<String> {
342        self.0.to_ndjson(window).py_block_on(py)
343    }
344
345    #[pyo3(signature = (**window))]
346    pub fn to_records<'a>(
347        &self,
348        py: Python<'a>,
349        window: Option<Py<PyDict>>,
350    ) -> PyResult<Bound<'a, PyAny>> {
351        let json = self.0.to_json_string(window).py_block_on(py)?;
352        let json_module = PyModule::import(py, "json")?;
353        json_module.call_method1("loads", (json,))
354    }
355
356    #[apply(inherit_doc)]
357    #[inherit_doc = "view/to_json.md"]
358    #[pyo3(signature = (**window))]
359    pub fn to_json<'a>(
360        &self,
361        py: Python<'a>,
362        window: Option<Py<PyDict>>,
363    ) -> PyResult<Bound<'a, PyAny>> {
364        self.to_records(py, window)
365    }
366
367    #[apply(inherit_doc)]
368    #[inherit_doc = "view/to_columns.md"]
369    #[pyo3(signature = (**window))]
370    pub fn to_columns<'a>(
371        &self,
372        py: Python<'a>,
373        window: Option<Py<PyDict>>,
374    ) -> PyResult<Bound<'a, PyAny>> {
375        let json = self.0.to_columns_string(window).py_block_on(py)?;
376        let json_module = PyModule::import(py, "json")?;
377        json_module.call_method1("loads", (json,))
378    }
379
380    #[apply(inherit_doc)]
381    #[inherit_doc = "view/to_csv.md"]
382    #[pyo3(signature = (**window))]
383    pub fn to_csv(&self, py: Python<'_>, window: Option<Py<PyDict>>) -> PyResult<String> {
384        self.0.to_csv(window).py_block_on(py)
385    }
386
387    #[doc = include_str!("../../docs/client/to_pandas.md")]
388    #[pyo3(signature = (**window))]
389    // #[deprecated(since="3.2.0", note="Please use `View::to_pandas`")]
390    pub fn to_dataframe(&self, py: Python<'_>, window: Option<Py<PyDict>>) -> PyResult<Py<PyAny>> {
391        self.0.to_dataframe(window).py_block_on(py)
392    }
393
394    #[doc = include_str!("../../docs/client/to_pandas.md")]
395    #[pyo3(signature = (**window))]
396    pub fn to_pandas(&self, py: Python<'_>, window: Option<Py<PyDict>>) -> PyResult<Py<PyAny>> {
397        self.0.to_dataframe(window).py_block_on(py)
398    }
399
400    #[doc = include_str!("../../docs/client/to_polars.md")]
401    #[pyo3(signature = (**window))]
402    pub fn to_polars(&self, py: Python<'_>, window: Option<Py<PyDict>>) -> PyResult<Py<PyAny>> {
403        self.0.to_polars(window).py_block_on(py)
404    }
405
406    #[apply(inherit_doc)]
407    #[inherit_doc = "view/to_arrow.md"]
408    #[pyo3(signature = (**window))]
409    pub fn to_arrow(&self, py: Python<'_>, window: Option<Py<PyDict>>) -> PyResult<Py<PyBytes>> {
410        self.0.to_arrow(window).py_block_on(py)
411    }
412
413    #[apply(inherit_doc)]
414    #[inherit_doc = "view/delete.md"]
415    pub fn delete(&self, py: Python<'_>) -> PyResult<()> {
416        self.0.delete().py_block_on(py)
417    }
418
419    #[apply(inherit_doc)]
420    #[inherit_doc = "view/expand.md"]
421    pub fn expand(&self, py: Python<'_>, index: u32) -> PyResult<u32> {
422        self.0.expand(index).py_block_on(py)
423    }
424
425    #[apply(inherit_doc)]
426    #[inherit_doc = "view/collapse.md"]
427    pub fn collapse(&self, py: Python<'_>, index: u32) -> PyResult<u32> {
428        self.0.collapse(index).py_block_on(py)
429    }
430
431    #[apply(inherit_doc)]
432    #[inherit_doc = "view/dimensions.md"]
433    pub fn dimensions(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
434        self.0.dimensions().py_block_on(py)
435    }
436
437    #[apply(inherit_doc)]
438    #[inherit_doc = "view/expression_schema.md"]
439    pub fn expression_schema(&self, py: Python<'_>) -> PyResult<HashMap<String, String>> {
440        self.0.expression_schema().py_block_on(py)
441    }
442
443    #[apply(inherit_doc)]
444    #[inherit_doc = "view/get_config.md"]
445    pub fn get_config(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
446        self.0.get_config().py_block_on(py)
447    }
448
449    #[apply(inherit_doc)]
450    #[inherit_doc = "view/get_min_max.md"]
451    pub fn get_min_max(&self, py: Python<'_>, column_name: String) -> PyResult<(String, String)> {
452        self.0.get_min_max(column_name).py_block_on(py)
453    }
454
455    #[apply(inherit_doc)]
456    #[inherit_doc = "view/num_rows.md"]
457    pub fn num_rows(&self, py: Python<'_>) -> PyResult<u32> {
458        self.0.num_rows().py_block_on(py)
459    }
460
461    #[apply(inherit_doc)]
462    #[inherit_doc = "view/schema.md"]
463    pub fn schema(&self, py: Python<'_>) -> PyResult<HashMap<String, String>> {
464        self.0.schema().py_block_on(py)
465    }
466
467    #[apply(inherit_doc)]
468    #[inherit_doc = "view/on_delete.md"]
469    pub fn on_delete(&self, py: Python<'_>, callback: Py<PyAny>) -> PyResult<u32> {
470        self.0.on_delete(callback).py_block_on(py)
471    }
472
473    #[apply(inherit_doc)]
474    #[inherit_doc = "view/remove_delete.md"]
475    pub fn remove_delete(&self, py: Python<'_>, callback_id: u32) -> PyResult<()> {
476        self.0.remove_delete(callback_id).py_block_on(py)
477    }
478
479    #[apply(inherit_doc)]
480    #[inherit_doc = "view/on_update.md"]
481    #[pyo3(signature = (callback, mode=None))]
482    pub fn on_update(
483        &self,
484        py: Python<'_>,
485        callback: Py<PyAny>,
486        mode: Option<String>,
487    ) -> PyResult<u32> {
488        self.0.on_update(callback, mode).py_block_on(py)
489    }
490
491    #[apply(inherit_doc)]
492    #[inherit_doc = "view/remove_update.md"]
493    pub fn remove_update(&self, py: Python<'_>, callback_id: u32) -> PyResult<()> {
494        self.0.remove_update(callback_id).py_block_on(py)
495    }
496}