Skip to main content

perspective_js/
table.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 js_sys::Function;
14use perspective_client::config::*;
15use perspective_client::{
16    DeleteOptions, DescribeVerdict, UpdateData, UpdateOptions, assert_table_api,
17};
18use wasm_bindgen::prelude::*;
19use wasm_bindgen_derive::TryFromJsValue;
20use wasm_bindgen_futures::spawn_local;
21
22use crate::Client;
23use crate::table_data::UpdateDataExt;
24use crate::utils::{ApiFuture, ApiResult, JsValueSerdeExt, LocalPollLoop};
25pub use crate::view::*;
26
27#[derive(TryFromJsValue, Clone, PartialEq)]
28#[wasm_bindgen]
29pub struct Table(pub(crate) perspective_client::Table);
30
31assert_table_api!(Table);
32
33impl From<perspective_client::Table> for Table {
34    fn from(value: perspective_client::Table) -> Self {
35        Table(value)
36    }
37}
38
39/// [`Table`] is Perspective's columnar data frame, analogous to a Pandas/Polars
40/// `DataFrame` or Apache Arrow, supporting append & in-place updates, removal
41/// by index, and update notifications.
42///
43/// A [`Table`] contains columns, each of which have a unique name, are strongly
44/// and consistently typed, and contains rows of data conforming to the column's
45/// type. Each column in a [`Table`] must have the same number of rows, though
46/// not every row must contain data; null-values are used to indicate missing
47/// values in the dataset. The schema of a [`Table`] is _immutable after
48/// creation_, which means the column names and data types cannot be changed
49/// after the [`Table`] has been created. Columns cannot be added or deleted
50/// after creation either, but a [`View`] can be used to select an arbitrary set
51/// of columns from the [`Table`].
52impl Table {
53    pub fn get_table(&self) -> &'_ perspective_client::Table {
54        &self.0
55    }
56}
57
58#[wasm_bindgen]
59extern "C" {
60    // TODO Fix me
61    #[wasm_bindgen(typescript_type = "\
62        string | ArrayBuffer | Record<string, unknown[]> | Record<string, unknown>[] | \
63                                      Record<string, ColumnType>")]
64    pub type JsTableInitData;
65
66    #[wasm_bindgen(typescript_type = "ViewConfigUpdate")]
67    pub type JsViewConfig;
68
69    #[wasm_bindgen(typescript_type = "UpdateOptions")]
70    pub type JsUpdateOptions;
71
72    #[wasm_bindgen(typescript_type = "DeleteOptions")]
73    pub type JsDeleteOptions;
74}
75
76#[wasm_bindgen]
77impl Table {
78    /// Returns the name of the index column for the table.
79    ///
80    /// # JavaScript Examples
81    ///
82    /// ```javascript
83    /// const table = await client.table("x,y\n1,2\n3,4", { index: "x" });
84    /// const index = table.get_index(); // "x"
85    /// ```
86    #[wasm_bindgen]
87    pub async fn get_index(&self) -> Option<String> {
88        self.0.get_index()
89    }
90
91    /// Get a copy of the [`Client`] this [`Table`] came from.
92    #[wasm_bindgen]
93    pub async fn get_client(&self) -> Client {
94        Client {
95            close: None,
96            client: self.0.get_client(),
97        }
98    }
99
100    /// Returns the user-specified name for this table, or the auto-generated
101    /// name if a name was not specified when the table was created.
102    #[wasm_bindgen]
103    pub async fn get_name(&self) -> String {
104        self.0.get_name().to_owned()
105    }
106
107    /// Returns the user-specified row limit for this table.
108    #[wasm_bindgen]
109    pub async fn get_limit(&self) -> Option<u32> {
110        self.0.get_limit()
111    }
112
113    /// Removes all the rows in the [`Table`], but preserves everything else
114    /// including the schema, index, and any callbacks or registered
115    /// [`View`] instances.
116    ///
117    /// Calling [`Table::clear`], like [`Table::update`] and [`Table::remove`],
118    /// will trigger an update event to any registered listeners via
119    /// [`View::on_update`].
120    #[wasm_bindgen]
121    pub async fn clear(&self) -> ApiResult<()> {
122        self.0.clear().await?;
123        Ok(())
124    }
125
126    /// Delete this [`Table`] and cleans up associated resources.
127    ///
128    /// [`Table`]s do not stop consuming resources or processing updates when
129    /// they are garbage collected in their host language - you must call
130    /// this method to reclaim these.
131    ///
132    /// # Arguments
133    ///
134    /// - `options` An options dictionary.
135    ///     - `lazy` Whether to delete this [`Table`] _lazily_. When false (the
136    ///       default), the delete will occur immediately, assuming it has no
137    ///       [`View`] instances registered to it (which must be deleted first,
138    ///       otherwise this method will throw an error). When true, the
139    ///       [`Table`] will only be marked for deltion once its [`View`]
140    ///       dependency count reaches 0.
141    ///
142    /// # JavaScript Examples
143    ///
144    /// ```javascript
145    /// const table = await client.table("x,y\n1,2\n3,4");
146    ///
147    /// // ...
148    ///
149    /// await table.delete({ lazy: true });
150    /// ```
151    #[wasm_bindgen]
152    pub async fn delete(self, options: Option<JsDeleteOptions>) -> ApiResult<()> {
153        let options = options
154            .into_serde_ext::<Option<DeleteOptions>>()?
155            .unwrap_or_default();
156
157        self.0.delete(options).await?;
158        Ok(())
159    }
160
161    /// Returns the number of rows in a [`Table`].
162    #[wasm_bindgen]
163    pub async fn size(&self) -> ApiResult<f64> {
164        Ok(self.0.size().await? as f64)
165    }
166
167    /// Returns a table's [`Schema`], a mapping of column names to column types.
168    ///
169    /// The mapping of a [`Table`]'s column names to data types is referred to
170    /// as a [`Schema`]. Each column has a unique name and a data type, one
171    /// of:
172    ///
173    /// - `"boolean"` - A boolean type
174    /// - `"date"` - A timesonze-agnostic date type (month/day/year)
175    /// - `"datetime"` - A millisecond-precision datetime type in the UTC
176    ///   timezone
177    /// - `"float"` - A 64 bit float
178    /// - `"integer"` - A signed 32 bit integer (the integer type supported by
179    ///   JavaScript)
180    /// - `"string"` - A [`String`] data type (encoded internally as a
181    ///   _dictionary_)
182    ///
183    /// Note that all [`Table`] columns are _nullable_, regardless of the data
184    /// type.
185    #[wasm_bindgen(unchecked_return_type = "Record<string, ColumnType>")]
186    pub async fn schema(&self) -> ApiResult<JsValue> {
187        let schema = self.0.schema().await?;
188        Ok(JsValue::from_serde_ext(&schema)?)
189    }
190
191    /// Returns the column names of this [`Table`] in "natural" order (the
192    /// ordering implied by the input format).
193    ///  
194    ///  # JavaScript Examples
195    ///
196    ///  ```javascript
197    ///  const columns = await table.columns();
198    ///  ```   
199    #[wasm_bindgen]
200    pub async fn columns(&self) -> ApiResult<JsValue> {
201        let columns = self.0.columns().await?;
202        Ok(JsValue::from_serde_ext(&columns)?)
203    }
204
205    /// Create a unique channel ID on this [`Table`], which allows
206    /// `View::on_update` callback calls to be associated with the
207    /// `Table::update` which caused them.
208    #[wasm_bindgen]
209    pub async fn make_port(&self) -> ApiResult<i32> {
210        Ok(self.0.make_port().await?)
211    }
212
213    /// Register a callback which is called exactly once, when this [`Table`] is
214    /// deleted with the [`Table::delete`] method.
215    ///
216    /// [`Table::on_delete`] resolves when the subscription message is sent, not
217    /// when the _delete_ event occurs.
218    #[wasm_bindgen]
219    pub fn on_delete(&self, on_delete: Function) -> ApiFuture<u32> {
220        let table = self.clone();
221        ApiFuture::new(async move {
222            let emit = LocalPollLoop::new(move |()| on_delete.call0(&JsValue::UNDEFINED));
223            let on_delete = Box::new(move || spawn_local(emit.poll(())));
224            Ok(table.0.on_delete(on_delete).await?)
225        })
226    }
227
228    /// Removes a listener with a given ID, as returned by a previous call to
229    /// [`Table::on_delete`].
230    #[wasm_bindgen]
231    pub fn remove_delete(&self, callback_id: u32) -> ApiFuture<()> {
232        let client = self.0.clone();
233        ApiFuture::new(async move {
234            client.remove_delete(callback_id).await?;
235            Ok(())
236        })
237    }
238
239    /// Removes rows from this [`Table`] with the `index` column values
240    /// supplied.
241    ///
242    /// # Arguments
243    ///
244    /// - `indices` - A list of `index` column values for rows that should be
245    ///   removed.
246    ///
247    /// # JavaScript Examples
248    ///
249    /// ```javascript
250    /// await table.remove([1, 2, 3]);
251    /// ```
252    #[wasm_bindgen]
253    pub async fn remove(&self, value: &JsValue, options: Option<JsUpdateOptions>) -> ApiResult<()> {
254        let options = options
255            .into_serde_ext::<Option<UpdateOptions>>()?
256            .unwrap_or_default();
257
258        let input = UpdateData::from_js_value(value, options.format)?;
259        self.0.remove(input).await?;
260        Ok(())
261    }
262
263    /// Replace all rows in this [`Table`] with the input data, coerced to this
264    /// [`Table`]'s existing [`perspective_client::Schema`], notifying any
265    /// derived [`View`] and [`View::on_update`] callbacks.
266    ///
267    /// Calling [`Table::replace`] is an easy way to replace _all_ the data in a
268    /// [`Table`] without losing any derived [`View`] instances or
269    /// [`View::on_update`] callbacks. [`Table::replace`] does _not_ infer
270    /// data types like [`Client::table`] does, rather it _coerces_ input
271    /// data to the `Schema` like [`Table::update`]. If you need a [`Table`]
272    /// with a different `Schema`, you must create a new one.
273    ///
274    /// # JavaScript Examples
275    ///
276    /// ```javascript
277    /// await table.replace("x,y\n1,2");
278    /// ```
279    #[wasm_bindgen]
280    pub async fn replace(
281        &self,
282        input: &JsValue,
283        options: Option<JsUpdateOptions>,
284    ) -> ApiResult<()> {
285        let options = options
286            .into_serde_ext::<Option<UpdateOptions>>()?
287            .unwrap_or_default();
288
289        let input = UpdateData::from_js_value(input, options.format)?;
290        self.0.replace(input).await?;
291        Ok(())
292    }
293
294    /// Updates the rows of this table and any derived [`View`] instances.
295    ///
296    /// Calling [`Table::update`] will trigger the [`View::on_update`] callbacks
297    /// register to derived [`View`], and the call itself will not resolve until
298    /// _all_ derived [`View`]'s are notified.
299    ///
300    /// When updating a [`Table`] with an `index`, [`Table::update`] supports
301    /// partial updates, by omitting columns from the update data.
302    ///
303    /// # Arguments
304    ///
305    /// - `input` - The input data for this [`Table`]. The schema of a [`Table`]
306    ///   is immutable after creation, so this method cannot be called with a
307    ///   schema.
308    /// - `options` - Options for this update step - see [`UpdateOptions`].
309    ///
310    /// # JavaScript Examples
311    ///
312    /// ```javascript
313    /// await table.update("x,y\n1,2");
314    /// ```
315    #[wasm_bindgen]
316    pub fn update(
317        &self,
318        input: JsTableInitData,
319        options: Option<JsUpdateOptions>,
320    ) -> ApiFuture<()> {
321        let table = self.clone();
322        ApiFuture::new(async move {
323            let options = options
324                .into_serde_ext::<Option<UpdateOptions>>()?
325                .unwrap_or_default();
326
327            let input = UpdateData::from_js_value(&input, options.format)?;
328            Ok(table.0.update(input, options).await?)
329        })
330    }
331
332    /// Create a new [`View`] from this table with a specified
333    /// [`ViewConfigUpdate`].
334    ///
335    /// See [`View`] struct.
336    ///
337    /// # JavaScript Examples
338    ///
339    /// ```javascript
340    /// const view = await table.view({
341    ///     columns: ["Sales"],
342    ///     aggregates: { Sales: "sum" },
343    ///     group_by: ["Region", "Country"],
344    ///     filter: [["Category", "in", ["Furniture", "Technology"]]],
345    /// });
346    /// ```
347    #[wasm_bindgen]
348    pub async fn view(&self, config: Option<JsViewConfig>) -> ApiResult<View> {
349        let config = config
350            .map(|config| js_sys::JSON::stringify(&config))
351            .transpose()?
352            .and_then(|x| x.as_string())
353            .map(|x| serde_json::from_str(x.as_str()))
354            .transpose()?;
355
356        let view = self.0.view(config).await?;
357        Ok(View(view))
358    }
359
360    /// Validate a complete view config against this table and report the
361    /// schema a [`View`] built from it would have, WITHOUT creating one.
362    ///
363    /// # JavaScript Examples
364    ///
365    /// ```javascript
366    /// const verdict = await table.describe({
367    ///     columns: ["Sales", "margin"],
368    ///     group_by: ["Region"],
369    ///     expressions: { margin: '"Profit" / "Sales"' },
370    /// });
371    ///
372    /// if ("view_schema" in verdict) {
373    ///     const view = await table.view(config);
374    /// }
375    /// ```
376    #[wasm_bindgen]
377    pub async fn describe(&self, config: Option<JsViewConfig>) -> ApiResult<JsValue> {
378        let config = config
379            .map(|config| js_sys::JSON::stringify(&config))
380            .transpose()?
381            .and_then(|x| x.as_string())
382            .map(|x| serde_json::from_str(x.as_str()))
383            .transpose()?
384            .unwrap_or_default();
385
386        let verdict: DescribeVerdict = self.0.describe(config).await?.into();
387        Ok(JsValue::from_serde_ext(&verdict)?)
388    }
389
390    /// Validates the given expressions.
391    #[wasm_bindgen]
392    pub async fn validate_expressions(&self, exprs: &JsValue) -> ApiResult<JsValue> {
393        let exprs = JsValue::into_serde_ext::<Expressions>(exprs.clone())?;
394        let columns = self.0.validate_expressions(exprs).await?;
395        Ok(JsValue::from_serde_ext(&columns)?)
396    }
397}