Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/build.collage.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ export async function collage(page, ids, theme, { out, port }) {
`<img src="http://localhost:${port}/projects/${theme}/${present[i % present.length]}.png" />`,
).join("");

await page.setViewport({ width: COLLAGE_WIDTH, height });
await page.setViewportSize({ width: COLLAGE_WIDTH, height });
await page.setContent(
`<!doctype html><html><head><style>
html, body { margin: 0; padding: 0; background: ${COLLAGE_BG[theme]}; }
Expand Down Expand Up @@ -150,6 +150,7 @@ export async function collage(page, ids, theme, { out, port }) {
[...document.querySelectorAll(".collage img")].every(
(x) => x.complete,
),
undefined,
{ timeout: SETTLE_TIMEOUT },
);

Expand Down
6 changes: 3 additions & 3 deletions docs/build.projects.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { execSync } from "node:child_process";
import * as fs from "node:fs";
import * as path from "node:path";
import { fileURLToPath } from "node:url";
import puppeteer from "puppeteer";
import { chromium } from "@playwright/test";
import { TextWriter, Uint8ArrayReader, ZipReader } from "@zip.js/zip.js";
import { COLLAGE, collage } from "./build.collage.mjs";
import { screenshotTheme } from "./build.screenshot.mjs";
Expand Down Expand Up @@ -245,10 +245,10 @@ async function run() {
],
});

const browser = await puppeteer.launch({ headless: true });
const browser = await chromium.launch({ channel: "chromium" });
const page = await browser.newPage();
await page.goto(`http://localhost:${PORT}/index.html`, {
waitUntil: "networkidle2",
waitUntil: "networkidle",
});

const ids = await page.evaluate(async () => {
Expand Down
9 changes: 3 additions & 6 deletions docs/build.screenshot.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ async function screenshot(page, id, theme, { out, port }) {
}

await page.goto(`http://localhost:${port}/index.html`, {
waitUntil: "networkidle2",
waitUntil: "networkidle",
});

await page.evaluate(async () => {
Expand Down Expand Up @@ -101,11 +101,8 @@ async function screenshot(page, id, theme, { out, port }) {

export async function screenshotTheme(page, ids, theme, { out, port }) {
fs.mkdirSync(path.join(out, theme), { recursive: true });
await page.emulateMediaFeatures([
{ name: "prefers-color-scheme", value: theme },
]);

await page.setViewport(VIEWPORT);
await page.emulateMedia({ colorScheme: theme });
await page.setViewportSize(VIEWPORT);
let wrote = 0;
let failed = 0;
for (const id of ids) {
Expand Down
1 change: 1 addition & 0 deletions docs/md/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
- [`index`, `limit` and `page_to_disk` options](./explanation/table/options.md)
- [`update()` and `remove()` streaming methods](./explanation/table/update_and_remove.md)
- [`clear()` and `replace()` start-over methods](./explanation/table/clear_and_replace.md)
- [Metadata](./explanation/table/metadata.md)
- [`View`](./explanation/view.md)
- [Querying data](./explanation/view/querying.md)
- [Grouping and Pivots](./explanation/view/config/grouping_and_pivots.md)
Expand Down
162 changes: 162 additions & 0 deletions docs/md/explanation/table/metadata.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
# Metadata

A `Table` can carry _metadata_: [Markdown](https://commonmark.org/help/)
descriptions of the `Table` itself and of its columns, written by the developer
who knows what the data means. `<perspective-viewer>` shows them to the user, so
a dashboard can answer "gross or net?" or "which timezone?" where the question
comes up.

Metadata is given once, when the `Table` is created, and never changes
afterwards.

<div class="javascript">

```javascript
const table = await client.table(data, {
name: "orders",
metadata: {
description: "One row per order line, refreshed nightly.",
columns: {
Sales: { description: "**Gross** sales in USD, before returns." },
Profit: { description: "`Sales` less cost of goods and shipping." },
},
},
});

const metadata = await table.metadata();
// { description: "...", columns: { Sales: {...}, Profit: {...} } }
```

</div>
<div class="python">

```python
table = client.table(
data,
name="orders",
metadata={
"description": "One row per order line, refreshed nightly.",
"columns": {
"Sales": {"description": "**Gross** sales in USD, before returns."},
"Profit": {"description": "`Sales` less cost of goods and shipping."},
},
},
)

metadata = table.metadata()
# {"description": "...", "columns": {"Sales": {...}, "Profit": {...}}}
```

</div>

Both `description` fields are optional, and an empty description is the same as
none: `Table::metadata` reports only what was described, and an empty object for
a `Table` with no metadata. Describing a column the `Table` does not have is an
error, and the `Table` is not created. `Table::clear` and `Table::replace` keep
metadata; it is dropped when the `Table` is deleted.

`Client::get_hosted_table_metadata` returns the metadata of every hosted `Table`
which has any, by name.

## Caching

Because metadata cannot change, a `Client` fetches it once per `Table` name and
caches it. It asks the server again only when the set of hosted `Table` names
changes, or when the `Client` itself creates or deletes a `Table`.

A subscription made with `on_hosted_tables_update(callback, { metadata: true })`
(`metadata=True` in Python) receives the hosted `Table`s with their metadata in
each notification, which keeps the cache current without further requests.
`<perspective-viewer>` subscribes this way.

The cache assumes that a `Table` name keeps its metadata for the life of the
`Client`. If another `Client` deletes a `Table` and creates a new one with the
same name but different metadata, a `Client` without a `metadata` subscription
can report the old metadata until the set of names next changes.

## In `<perspective-viewer>`

A `Table`'s description is shown in the workspace panel's _Tables_ tab: a
described `Table`'s row has a marker which expands the description below it.

A column with a description gets an _Info_ tab in its column settings, and the
settings button on that column's row is marked and enabled even when the column
is not in use.

## Derived and joined `Table`s

A [`Table` made from a `View`](../derived_table.md) with no `metadata` of its
own starts with the column descriptions of each column it shares, by name, with
the `View`'s own `Table`. A [joined `Table`](../join.md) starts with the column
descriptions of both sources, the left one winning for a column they share. The
`Table`'s own description is not inherited, since a derived `Table` is a
different dataset. Giving a `Table` made from a `View` its own `metadata`
replaces inheritance entirely.

## Virtual servers

A [virtual server](../virtual_servers.md) reports its data source's own
comments. Metadata cannot be given to a `Table` created through a virtual
server: `Client::table` with `metadata` is rejected unless the server's features
include `metadata`, so author comments with the database's own tools.

| Virtual server | `Table` description | Column descriptions |
| -------------- | ------------------------------------- | ---------------------- |
| DuckDB | `COMMENT ON TABLE`, `COMMENT ON VIEW` | `COMMENT ON COLUMN` |
| PostgreSQL | `COMMENT ON TABLE` (or view) | `COMMENT ON COLUMN` |
| ClickHouse | The table's `COMMENT` | The column's `COMMENT` |
| Polars | Nothing | Nothing |

A custom handler opts in by implementing `tableMetadata(names)`
(`table_metadata(names)` in Python), which returns the metadata of each of the
named `Table`s which has any, in the shape `Table::metadata` returns, and by
declaring `metadata: true` in its features. It is called only when a client asks
for metadata.

## `Client` and server metadata

A `Client` and a server can each be given a name and a Markdown description when
they are created.

<div class="javascript">

```javascript
const server = new PerspectiveServer({
name: "Analytics",
metadata: { description: "Nightly **ERP** extracts." },
});

const client = await perspective.websocket("wss://example.com/ws", {
name: "Production",
metadata: { description: "Live positions and trades." },
});

client.get_name(); // "Production"
client.get_metadata(); // { description: "Live positions and trades." }
await client.get_server_name(); // "Analytics"
await client.get_server_metadata(); // { description: "Nightly **ERP** extracts." }
```

</div>
<div class="python">

```python
server = Server(name="Analytics", metadata={"description": "Nightly extracts."})
client = server.new_local_client(name="Local", metadata={"description": "..."})
await client.get_server_name() # "Analytics", on the async client
```

</div>

A `Client`'s name and metadata stay on the client: they are never sent to the
server. Its name must be unique among the `Client`s alive in the same process
(or page); a duplicate is an error, and `terminate()` frees the name. Without a
`name`, a `Client` is named `client-1`, `client-2` and so on.

The server's name and metadata reach every connected `Client` in its handshake,
with the server's release. `worker()` and `make_client()` take the same options
as `websocket()`; `VirtualServer` and `createMessageHandler` take the server's.

In `<perspective-viewer>`'s workspace panel, each `Client`'s section is headed
by its name and its server's, and a marker next to them expands both
descriptions.
11 changes: 11 additions & 0 deletions docs/md/how_to/javascript/virtual_server/duckdb.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,17 @@ await conn.query(`CREATE SECRET (TYPE s3, KEY_ID '...', SECRET '...', REGION 'us
await conn.query(`CREATE TABLE trades AS SELECT * FROM read_parquet('s3://bucket/trades/*.parquet')`);
```

## Comments

DuckDB table, view and column comments are the
[metadata](../../../explanation/table/metadata.md) of the hosted `Table`s, which
`<perspective-viewer>` shows as Markdown:

```javascript
await conn.query(`COMMENT ON TABLE my_table IS 'Trades, one row per fill'`);
await conn.query(`COMMENT ON COLUMN my_table.price IS 'Last trade, in **USD**'`);
```

## Examples

- [Browser DuckDB example](https://github.com/perspective-dev/perspective/tree/master/examples/esbuild-duckdb-virtual)
1 change: 1 addition & 0 deletions docs/md/how_to/python/virtual_server/custom.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ class MyHandler(VirtualServerHandler):
| `get_features()` | `columns` only | Which UI controls to enable — see [Features declaration](../../../explanation/virtual_servers.md#features-declaration) |
| `view_schema(view_name, config)` | `table_schema` | Schema of a temporary table, when it differs from its source |
| `view_size(view_name)` | `table_size` | Row count of a temporary table, when it differs from its source |
| `table_metadata(names)` | none | Table and column descriptions as `{table: {"description": markdown, "columns": {column: {"description": markdown}}}}`, with `"metadata": True` in `get_features()` — see [Metadata](../../../explanation/table/metadata.md) |
| `view_get_min_max(view_name, column_name, config)` | unsupported | Column bounds as a `(min, max)` tuple — required for gradient and sparkbar column styles |
| `view_expand(view_name, config, row_index)` | unsupported | Expand a row tree node — required by `expand_collapse`, see [Expand and collapse](../../../explanation/virtual_servers.md#expand-and-collapse) |
| `view_collapse(view_name, config, row_index)` | unsupported | Collapse a row tree node — required by `expand_collapse` |
Expand Down
11 changes: 11 additions & 0 deletions docs/md/how_to/python/virtual_server/duckdb.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,17 @@ advertised name is emitted into the `OVER` clause verbatim.
| Ranking | `row_number` `rank` `dense_rank` `percent_rank` `cume_dist` `ntile` |
| Perspective's own | `diff` `rate` |

## Comments

DuckDB table, view and column comments are the
[metadata](../../../explanation/table/metadata.md) of the hosted `Table`s, which
`<perspective-viewer>` shows as Markdown:

```python
conn.execute("COMMENT ON TABLE my_table IS 'Trades, one row per fill'")
conn.execute("COMMENT ON COLUMN my_table.price IS 'Last trade, in **USD**'")
```

## Examples

- [Python DuckDB example](https://github.com/perspective-dev/perspective/tree/master/examples/python-duckdb-virtual)
8 changes: 5 additions & 3 deletions docs/md/versioning.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,11 @@ Use the same version of every Perspective package in an application. Within a
Perspective's `init()` functions throw when a release of another `major.minor`
has registered on the same page.
- **Client and server.** A client and a server of the same `major.minor`
interoperate over a WebSocket, whatever their patch versions. The protocol has
no version handshake, so a mismatch across minor releases is not detected up
front: it surfaces as a decode error or as missing fields.
interoperate over a WebSocket, whatever their patch versions. A `Client` asks
its server's release once per connection, ahead of its first request and
without waiting for the answer. A server of another `major.minor` (or one that
does not report its release) is still used, and the `Client` logs one warning.
If a request then fails, its error names both releases as the likely cause.
- **Python and Jupyter.** `PerspectiveWidget` loads the
`@perspective-dev/viewer` release matching the installed `perspective-python`,
and treats `version` stamps of the same `major.minor` as equal.
Expand Down
2 changes: 1 addition & 1 deletion docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@
"@perspective-dev/viewer": "workspace:^",
"@perspective-dev/client": "workspace:^",
"@perspective-dev/server": "workspace:^",
"puppeteer": "catalog:",
"superstore-arrow": "catalog:"
},
"devDependencies": {
"@playwright/test": "catalog:",
"@zip.js/zip.js": "catalog:",
"esbuild": "catalog:",
"lightningcss": "catalog:",
Expand Down
27 changes: 27 additions & 0 deletions examples/esbuild-duckdb-virtual/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,35 @@ async function loadSampleData(db: duckdb.AsyncDuckDBConnection) {
}
}

async function describeSampleData(db: duckdb.AsyncDuckDBConnection) {
await db.query(`
COMMENT ON TABLE data_source_one
IS 'The **Superstore** sample dataset, one row per order line.';
`);

await db.query(`
COMMENT ON COLUMN data_source_one."Sales"
IS '**Gross** sales in USD, before returns and discounts.';
`);

await db.query(`
COMMENT ON COLUMN data_source_one."Profit"
IS '\`Sales\` less cost of goods and shipping.';
`);

await db.query(`
COMMENT ON COLUMN data_source_one."Segment"
IS 'One of:

- Consumer
- Corporate
- Home Office';
`);
}

const db = await initializeDuckDB();
await loadSampleData(db);
await describeSampleData(db);
const server = perspective.createMessageHandler(new DuckDBHandler(db));
const client = await perspective.worker(server);

Expand Down
11 changes: 9 additions & 2 deletions examples/esbuild-example/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,15 @@ await perspective_viewer.init({
const req = fetch(arrow);
const viewer = document.createElement("perspective-viewer");
document.body.append(viewer);
const worker = await perspective.worker();
const worker2 = await perspective.worker();
const worker = await perspective.worker(undefined, {
name: "primary",
metadata: { description: "The first of this page's two Web Workers." },
});

const worker2 = await perspective.worker(undefined, {
name: "secondary",
metadata: { description: "The second of this page's two Web Workers." },
});
const resp = await req;
const buffer = await resp.arrayBuffer();
await worker.table(buffer, { name: "superstore1" });
Expand Down
Loading
Loading