@casoon/opengrid 0.17.0 → 0.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -19,6 +19,151 @@ Two things belong in every release entry and are easy to leave out:
19
19
 
20
20
  ## [Unreleased]
21
21
 
22
+ ## [0.18.1] - 2026-11-18
23
+
24
+ Not yet verified by a screen reader: no pass with assistive technology has been recorded for this
25
+ release ([#5](https://github.com/casoon/opengrid/issues/5)). The keyboard and `axe-core` checks run on
26
+ every change.
27
+
28
+ ### Fixed
29
+
30
+ - **Grouping:** the focus ring of a group row goes round the row, not round the narrow first cell the
31
+ label runs out of. A label clipped to a pinned column keeps the ring on its cell.
32
+
33
+ ## [0.18.0] - 2026-11-17
34
+
35
+ Not yet verified by a screen reader: no pass with assistive technology has been recorded for this
36
+ release ([#5](https://github.com/casoon/opengrid/issues/5)). The keyboard and `axe-core` checks run on
37
+ every change.
38
+
39
+ **What breaks:** the Rust API of `opengrid-columns` (`SortKeys`, `Values::Decimal`, `Values::Utf8`
40
+ and `Values::Int64` changed their shape, see *Changed*). The npm package's API is unchanged.
41
+
42
+ ### Fixed
43
+
44
+ - **Grouping:** a group row's label stays on one line when its cell has the focus. It was
45
+ unfolded like any focused cell and wrapped over three lines inside the narrow first column.
46
+ - **Package:** a page that serves the package's files itself and leaves out `collation.js` no
47
+ longer breaks. Since 0.17.0 `loader.js` and `worker.js` imported it statically, so the loader
48
+ failed to load or the worker died without a word and the grid never showed a row. Both import
49
+ it on the first query that names a locale now; without the file only that sort is refused,
50
+ with an error that names it. `installation.mdx` lists what a page that copies the files must
51
+ copy ([#415](https://github.com/casoon/opengrid/issues/415)).
52
+ - **Pages:** the demo on the project page did not start since 0.17.0 (`loader.js` imports
53
+ `collation.js`, which the site did not copy).
54
+ - **Docs:** the API reference linked the protocol page as `protocol.md`, which is a 404 on the site.
55
+
56
+ ### Added
57
+
58
+ - **Docs:** the performance guide compares opengrid with AG Grid Community, RevoGrid, SlickGrid, Tabulator and w2ui (all MIT) on 100,000 and 1,000,000 rows, says why it is faster where it is and where it is behind, and says how far to trust the adapters ([#421](https://github.com/casoon/opengrid/issues/421)).
59
+ - **Docs, tools:** the performance guide has a section "In the browser, as a visitor sees it" with
60
+ opengrid's own page-level figures (first rows, sort, filter, group, scrolling, bytes fetched, page
61
+ memory; in the tab and in server mode), and `bench/baselines/` keeps them in the tool's format, also with the CPU four and six times slower;
62
+ `just bench-local` measures this checkout against them, `--baseline` marks what got worse
63
+ ([#421](https://github.com/casoon/opengrid/issues/421)).
64
+ - **Package, engine:** `provider.unload(name)` on the local and the worker provider, and `unload` on the engine module, free one source; a load after it takes the room the table had, so a page that reloads stays at one table instead of two ([Loading again](https://casoon.github.io/opengrid/docs/guides/performance/#loading-again), [#459](https://github.com/casoon/opengrid/issues/459)).
65
+ - **Docs:** the performance guide measures loading again: what the engine and the browser hold after ten loads of a million rows under one name and under ten, and what `terminate()` hands back, with `scripts/measure-reload.mjs` to repeat it ([Loading again](https://casoon.github.io/opengrid/docs/guides/performance/#loading-again), [#459](https://github.com/casoon/opengrid/issues/459)).
66
+ - **Docs:** the performance guide measures server mode: a window of 40 rows, a filter, a text search and a grouping from PostgreSQL and SQLite at one and ten million rows, with the server's memory and `cargo run --example server_bench` to repeat it ([In server mode](https://casoon.github.io/opengrid/docs/guides/performance/#in-server-mode), [#452](https://github.com/casoon/opengrid/issues/452)).
67
+ - **Pages:** the start page explains where the data lives — in the tab, on the server, or split — side by side, with when to start where, the query the browser sends instead of SQL, a diagram of one window fetched from the server, the sources a server reads and measured figures ([#453](https://github.com/casoon/opengrid/issues/453)).
68
+ - **Engine:** the WebAssembly engine reads rows as packs of typed columns: `begin_columns`,
69
+ `push_columns`, `end_columns` and `abort_columns`, as it reads CSV in pieces. An engine module
70
+ without them still loads rows, as JSON text
71
+ ([#445](https://github.com/casoon/opengrid/issues/445)).
72
+ - **Package, engine:** a CSV file can be read piece by piece: `provider.loadStream(name, source, schema, { chunkSize? })` on the worker and the local provider takes a `File`/`Blob`, a `ReadableStream` of bytes or an async iterable, and the engine module has `begin_csv`, `push_csv`, `end_csv` and `abort_csv` (Rust: `ingest::CsvLoader`). Only a piece and the columns are in memory, not the whole file as well: a 43 MB file loaded from a `fetch` stream takes about 30 MiB less in the browser than `load` of its bytes (the engine's module 118 MiB instead of 78–90 MiB). The pieces may end anywhere; the table, the errors and their line numbers are those of the whole file (#427). [Data you already have](docs/guides/data-you-have.md) has a section on it.
73
+ - **Columns:** `ColumnBuilder` has typed pushes, `push_bool`, `push_i64`, `push_f64`,
74
+ `push_decimal`, `push_date` and `push_timestamp`, for a cell that has just been read as that type.
75
+ A column of another type, or a decimal of another scale, is refused with an error
76
+ ([#442](https://github.com/casoon/opengrid/issues/442)).
77
+ - **Columns:** `ColumnBuilder::push_str` appends text to a text column without a `Value` in between. The CSV reader uses it, so a text cell is copied into its column once instead of being made a `String`, copied and freed (#429).
78
+ - **Docs:** *What the engine costs* — the engine on 100,000 and 1,000,000 rows (load, filter, sort,
79
+ group, pivot, memory), measured on an Apple M4 Pro, what a page pays for the WebAssembly modules,
80
+ what the figures are not, and `scripts/measure-queries.mjs` to repeat them.
81
+
82
+ ### Changed
83
+
84
+ - **Package:** `loadRows` of an array of objects starts the worker while the rows are made into columns, and makes the next pack while the engine takes the one before: the first rows of a million-row table show after 190 ms instead of 300 ms (100,000 rows: 86 instead of 112 ms). A pack the engine refuses stops the rest, as before.
85
+ - **Server:** the count of a query is remembered for 5 seconds, so the next window of it (only
86
+ `offset` changes) does not count again: on ten million rows in PostgreSQL the first window takes
87
+ 0.5 ms instead of 146 ms, a filtered one 246 instead of 461 ms. The key is the filter (the token's
88
+ row filter included), grouping and aggregates; `notify_changed` drops it, `count_cache_ttl` sets
89
+ the time, zero switches it off. A count can be stale for that time when a database changes without
90
+ the server being told. `Connector::execute_counted` is new and defaults to `execute`; PostgreSQL
91
+ and SQLite skip their count statement with it
92
+ ([#457](https://github.com/casoon/opengrid/issues/457)).
93
+ - **Engine, columns:** a sort by a locale makes one sort key per distinct text of a column with few
94
+ of them, and the rows share the keys, instead of one per row: a million rows by `customer` take 17 ms
95
+ for the first 100 rows with `de` instead of 501 ms, by `country` 16 ms instead of 208. The order is
96
+ the same. **What breaks:** `opengrid_columns::sort::SortKeys` has a second form (`by_codes`); `len`
97
+ and `get` read the same
98
+ ([#467](https://github.com/casoon/opengrid/issues/467)).
99
+ - **Engine:** grouping by text columns with few distinct texts finds a row's group by the codes of
100
+ its texts instead of building and hashing a key from each text: a million rows grouped by country
101
+ take 55 ms instead of 101, by customer (500 groups) 41 instead of 107, and the pivot of country
102
+ and customer 190 instead of 316. Groups come in the same order as before and nothing else
103
+ changes; columns of other types, flat texts and more than 262,144 combinations of codes group
104
+ as before
105
+ ([#465](https://github.com/casoon/opengrid/issues/465)).
106
+ - **Engine, columns:** an exact decimal of up to 18 digits of precision — an amount, a rate, a
107
+ price: `decimal(12, 2)` — keeps its coefficient in eight bytes instead of sixteen; the type
108
+ decides, wider decimals stay as they were. The ten columns of the benchmark table take 43 bytes a
109
+ row instead of 51, and the module's memory after loading a million of them 121 MiB instead of
110
+ 128. No answer changes (an exact sum stays exact), and no query gets slower. A coefficient that
111
+ does not fit the storage is refused when it is pushed, not cut. **What breaks:**
112
+ `opengrid_columns::Values::Decimal` holds a `Decimals` and not a `Vec<i128>`; read it with
113
+ `Decimals::get` or `iter`
114
+ ([#450](https://github.com/casoon/opengrid/issues/450)).
115
+ - **Engine, columns:** a text column with few distinct texts — a country, a status, a customer of a few
116
+ hundred — keeps each text once and a code of one or two bytes a row; a column of distinct texts
117
+ is stored as before. The ten columns of the benchmark table take 51 bytes a row instead of 73,
118
+ and the module's memory after loading a million of them 128 MiB instead of 173, and 68 instead
119
+ of 112 when the file is read in pieces. A search or a filter on such a column tests each distinct
120
+ text once: a text search over a million rows takes 21 ms instead of 47. Loading takes about a
121
+ tenth longer. No answer changes. **What breaks:** `opengrid_columns::Values::Utf8` holds a
122
+ `Strs`, a dictionary or a flat column, and not `offsets` and `text`; read it with `Column::str`
123
+ or `Strs::get`
124
+ ([#451](https://github.com/casoon/opengrid/issues/451)).
125
+ - **Engine, columns:** an `int64` column stores its values in as few bytes as they need — one for a
126
+ count, four for an id, eight at most — instead of eight each, and so do the columns derived
127
+ from a date. The ten columns of the benchmark table take 73 bytes a row instead of 103, the
128
+ module's memory after loading a million of them 173 MiB instead of 199, and 112 instead of 140
129
+ when the file is read in pieces. No answer changes, and no query gets slower. **What breaks:**
130
+ `opengrid_columns::Values::Int64` holds an `Ints` and not a `Vec<i64>`; read it with
131
+ `Ints::get`, `iter` or `to_vec`
132
+ ([#447](https://github.com/casoon/opengrid/issues/447)).
133
+ - **Package, engine:** `loadRows` of an array of objects hands them over as typed columns, in packs of
134
+ 65,536 rows, instead of as one JSON text. A million rows reach the first rows in 0.27 s instead
135
+ of 1.2 s, and the page holds 386 MiB instead of 847; 100,000 rows in 0.1 s instead of 0.17 s and
136
+ 128 MiB instead of 158. The table and every refusal are the same, and anything that is not
137
+ plain still goes as JSON text. See [Data you already have](docs/guides/data-you-have.md)
138
+ ([#445](https://github.com/casoon/opengrid/issues/445)).
139
+ - **Engine:** a CSV file loads in less than half the time: a million rows of ten columns in
140
+ 0.44 s instead of 1.0 s, 100,000 in 59 ms instead of 118, and a file read piece by piece
141
+ (`loadStream`) in 0.5 s instead of 1.1 s. The tables and the errors are the same
142
+ ([#440](https://github.com/casoon/opengrid/issues/440),
143
+ [#442](https://github.com/casoon/opengrid/issues/442)).
144
+ - **Docs:** *What the engine costs* says what using the grid adds to the page's memory: about
145
+ 55 MiB once, the browser's painting, and none of it in the engine
146
+ ([#428](https://github.com/casoon/opengrid/issues/428)).
147
+ - **Pages:** the start page and *What the engine costs* carry the loading times since the CSV reader's faster passes (a million rows in 0.44 s, 100,000 in 59 ms) and the module sizes as they are now (the engine about 172 KiB, the collation about 325 KiB).
148
+ - **Pages:** the figures of *What the engine costs* and of the start page are measured again after the optimisations (#426–#429, #428): a million rows load in 1.1 s instead of 1.3 s, a sort of the first 100 takes 26 ms instead of 52, the module holds 199 MiB instead of 213, and the whole page, with a fetched CSV and no rows of its own, about 175 MiB (145 read in pieces) instead of the 658 MiB the earlier test page showed, which included a million JavaScript objects it kept itself.
149
+ - **Engine:** a sort that asks for a page of a big table (the first 100 of a million rows) keeps the best rows as it reads them instead of building and sorting a pair for every row: sorting a million rows by one key takes 25 ms instead of 51 ms, and the module no longer grows by 51 MiB for it (the memory after the usual queries on a streamed load: 191 MiB before, 149 MiB after). The order is the same, ties by position (#428).
150
+ - **Engine:** loading a CSV file or a JSON array sizes the columns by the number of lines or objects in the text, so each is allocated once instead of grown by doubling. The module's memory, which never shrinks, holds 199 MiB instead of 215 MiB after a million CSV rows (the columns themselves take 98 MiB, the copy of the file 71 MiB) (#427).
151
+ - **Engine:** loading a CSV file is about 18 % faster (1,000,000 rows of the benchmark's ten columns: 1.41 s to 1.16 s in WebAssembly; native 0.86 s to 0.68 s before the text change). A timestamp in the usual spelling and a decimal of up to 18 digits are read by position and in 64 bits, a row no longer allocates two vectors, and text cells go straight into their column. Anything else is read as before; results and error messages are unchanged (#429).
152
+ - **Engine:** loading a JSON array of objects reads the text in one pass into the column builders instead of building a tree and a vector per row first: 1.7 times faster at 100,000 rows and 3 times at 1,000,000 (191 ms to 110 ms, 3.3 s to 1.1 s, WebAssembly in Node). Anything the fast path does not read the same way — escapes in keys, unknown or repeated keys, nested values, malformed text — goes to the general reader, so results and error messages are unchanged (#426).
153
+ - **Pages:** the start page no longer says *Light on memory*. It says *Compact, not free*: the columns
154
+ take 98 MiB for a million rows, and the whole page holds about 660 MiB with the engine beside the
155
+ page's data (loaded from CSV; 1.1 GiB when the page hands over JavaScript objects). *What the engine
156
+ costs* has the table, measured with `bench/`.
157
+ - **Pages:** the start page has two more cards, *Text in your language* (the collation of a
158
+ locale) and *Next to an AI assistant* (MCP), and *What sets it apart* says what the collation
159
+ is and promises.
160
+ - **Pages:** the project site uses the current shared theme (0.12.14): a wider header, a smaller
161
+ CASOON badge, and a block right after the hero no longer sits flush against it.
162
+ - **Pages:** the start page leads with *Why WebAssembly* — what the engine buys and what it costs,
163
+ with figures measured on an Apple M4 Pro — and then four points on what sets opengrid apart,
164
+ in blocks of four so no card stands alone. Its other figures (conformance cases, axe specs,
165
+ module sizes) are counted and measured when the site is built.
166
+
22
167
  ## [0.17.0] - 2026-11-13
23
168
 
24
169
  Not yet verified by a screen reader: no pass with assistive technology has been recorded for this
@@ -1664,7 +1809,9 @@ tested.
1664
1809
  tested: React 18 rendering on the server, SvelteKit, Nuxt, Next.js and Astro
1665
1810
  as real applications. A Vite production build needs `loadOpengrid({ moduleUrl })`.
1666
1811
 
1667
- [Unreleased]: https://github.com/casoon/opengrid/compare/v0.17.0...HEAD
1812
+ [Unreleased]: https://github.com/casoon/opengrid/compare/v0.18.1...HEAD
1813
+ [0.18.1]: https://github.com/casoon/opengrid/compare/v0.18.0...v0.18.1
1814
+ [0.18.0]: https://github.com/casoon/opengrid/compare/v0.17.0...v0.18.0
1668
1815
  [0.17.0]: https://github.com/casoon/opengrid/compare/v0.16.0...v0.17.0
1669
1816
  [0.16.0]: https://github.com/casoon/opengrid/compare/v0.15.0...v0.16.0
1670
1817
  [0.15.0]: https://github.com/casoon/opengrid/compare/v0.14.0...v0.15.0
package/README.md CHANGED
@@ -57,9 +57,9 @@ as the npm package, so give every `opengrid-*` crate the same one:
57
57
 
58
58
  ```toml
59
59
  [dependencies]
60
- opengrid-server = "0.17" # the gateway, as a library
61
- opengrid-connector-sqlite = "0.17" # or opengrid-datasource-postgres
62
- opengrid-engine = "0.17" # the engine alone, native
60
+ opengrid-server = "0.18" # the gateway, as a library
61
+ opengrid-connector-sqlite = "0.18" # or opengrid-datasource-postgres
62
+ opengrid-engine = "0.18" # the engine alone, native
63
63
  ```
64
64
 
65
65
  While the version is 0.x, a minor bump may break the Rust API
package/collation.js CHANGED
@@ -6,29 +6,17 @@
6
6
  * the engine then needs the collation's tables, some hundred kilobytes it does
7
7
  * not carry. They are a module of their own (`collation/`, built by
8
8
  * `just wasm-build-collation`); a page that never sorts by a locale does not
9
- * fetch it. The providers of the package call `withCollator` before the engine
10
- * runs a query.
9
+ * fetch it. `loader.js` and `worker.js` import **this file lazily**, on the first
10
+ * query that names a locale, so a page that serves the package's files itself and
11
+ * leaves this one out breaks locale sorts only (issue #415).
11
12
  */
12
13
 
13
- /** A sort key's collation that is not `binary`, in a query or a plan as JSON. */
14
- const NAMES_A_LOCALE = /"collation"\s*:\s*"(?!binary")/;
15
-
16
14
  /** The engines and planners that have their collator. */
17
15
  const given = new WeakSet();
18
16
 
19
17
  /** The collation module, loaded once; a failed load is not kept. */
20
18
  let module;
21
19
 
22
- /**
23
- * Whether `json` — a query, or the client half of a plan — sorts by a locale.
24
- *
25
- * @param {string} json
26
- * @returns {boolean}
27
- */
28
- export function sortsByLocale(json) {
29
- return NAMES_A_LOCALE.test(json);
30
- }
31
-
32
20
  /**
33
21
  * Loads the collation module and gives `engine` its collator. Once per engine;
34
22
  * later calls answer at once.
@@ -58,21 +46,3 @@ export async function giveCollator(engine) {
58
46
  engine.set_collator(glue.sort_keys);
59
47
  given.add(engine);
60
48
  }
61
-
62
- /**
63
- * Runs `run` once `engine` can answer `json`: at once when the query sorts by
64
- * no locale or the engine has its collator — the answer is then `run`'s own,
65
- * not a promise — and after the module has loaded otherwise.
66
- *
67
- * @template T
68
- * @param {{set_collator: Function}} engine an `Engine` or a `Planner`.
69
- * @param {string} json the query, or the client half of a plan.
70
- * @param {() => T} run
71
- * @returns {T | Promise<T>}
72
- */
73
- export function withCollator(engine, json, run) {
74
- if (given.has(engine) || !sortsByLocale(json)) {
75
- return run();
76
- }
77
- return giveCollator(engine).then(run);
78
- }
@@ -11,6 +11,39 @@
11
11
  export class Engine {
12
12
  free(): void;
13
13
  [Symbol.dispose](): void;
14
+ /**
15
+ * Drops the rows `begin_columns` started, nothing registered. Nothing to drop is not an
16
+ * error.
17
+ */
18
+ abort_columns(): void;
19
+ /**
20
+ * Drops the file `begin_csv` started, nothing registered: for a page whose reading of the
21
+ * file failed. Nothing to drop is not an error.
22
+ */
23
+ abort_csv(): void;
24
+ /**
25
+ * Starts reading the rows a page holds as packs of typed columns (issue #445): `push_columns`
26
+ * for each pack, then `end_columns`. `rows` is the number of rows of the whole table; the
27
+ * columns are sized by it. The format of a pack is in `opengrid_engine::ingest`. Rows begun
28
+ * before and not ended are dropped. An error here or later sends the page to `load_rows`,
29
+ * which owns every message.
30
+ */
31
+ begin_columns(name: string, schema_json: string, rows: number): void;
32
+ /**
33
+ * Starts reading a CSV file in pieces (issue #427): `push_csv` for each piece, then
34
+ * `end_csv`. Only a piece and the columns are in memory, not the whole file as well. The
35
+ * pieces may end anywhere. `size_hint` is the file's size in bytes, 0 when unknown; it only
36
+ * sizes the columns. A file begun before and not ended is dropped.
37
+ */
38
+ begin_csv(name: string, schema_json: string, size_hint: number): void;
39
+ /**
40
+ * The end of the rows: registers the source, replacing one of that name.
41
+ */
42
+ end_columns(): void;
43
+ /**
44
+ * The end of the file: registers the source, replacing one of that name.
45
+ */
46
+ end_csv(): void;
14
47
  /**
15
48
  * Runs a query JSON and answers with the result JSON.
16
49
  *
@@ -56,6 +89,16 @@ export class Engine {
56
89
  * hand the element.
57
90
  */
58
91
  pivot_columns(pivot_json: string): Uint8Array;
92
+ /**
93
+ * The next pack of the rows `begin_columns` started. A pack that does not hold ends the
94
+ * reading: nothing is registered.
95
+ */
96
+ push_columns(pack: Uint8Array): void;
97
+ /**
98
+ * The next piece of the file `begin_csv` started. A piece that cannot be read ends the
99
+ * file: nothing is registered, and the error names the line.
100
+ */
101
+ push_csv(bytes: Uint8Array): void;
59
102
  /**
60
103
  * Gives the engine its collator (rule S4a, issue #391): `sort_keys` of
61
104
  * the collation module, which a page loads when a query first sorts by a
@@ -77,6 +120,13 @@ export class Engine {
77
120
  * it. Sources by name.
78
121
  */
79
122
  stats(): string;
123
+ /**
124
+ * Frees the source `name` (issue #459); `true` when there was one. The
125
+ * module's memory does not shrink — WebAssembly memory only grows — but
126
+ * the next load takes the room the table had, so a page that unloads
127
+ * before it loads again needs one table's room, not two.
128
+ */
129
+ unload(name: string): boolean;
80
130
  /**
81
131
  * The query of a view (issue #144): what `get_query()` answers on an
82
132
  * `<opengrid-grid datasource=source columns=…>` once `view_json` is
@@ -154,6 +204,12 @@ export interface InitOutput {
154
204
  readonly memory: WebAssembly.Memory;
155
205
  readonly __wbg_engine_free: (a: number, b: number) => void;
156
206
  readonly __wbg_planner_free: (a: number, b: number) => void;
207
+ readonly engine_abort_columns: (a: number) => void;
208
+ readonly engine_abort_csv: (a: number) => void;
209
+ readonly engine_begin_columns: (a: number, b: number, c: number, d: number, e: number, f: number) => [number, number];
210
+ readonly engine_begin_csv: (a: number, b: number, c: number, d: number, e: number, f: number) => [number, number];
211
+ readonly engine_end_columns: (a: number) => [number, number];
212
+ readonly engine_end_csv: (a: number) => [number, number];
157
213
  readonly engine_execute: (a: number, b: number, c: number) => [number, number, number, number];
158
214
  readonly engine_execute_columns: (a: number, b: number, c: number) => [number, number, number, number];
159
215
  readonly engine_load_csv: (a: number, b: number, c: number, d: number, e: number, f: number, g: number) => [number, number];
@@ -161,9 +217,12 @@ export interface InitOutput {
161
217
  readonly engine_new: () => number;
162
218
  readonly engine_pivot: (a: number, b: number, c: number) => [number, number, number, number];
163
219
  readonly engine_pivot_columns: (a: number, b: number, c: number) => [number, number, number, number];
220
+ readonly engine_push_columns: (a: number, b: number, c: number) => [number, number];
221
+ readonly engine_push_csv: (a: number, b: number, c: number) => [number, number];
164
222
  readonly engine_set_collator: (a: number, b: any) => void;
165
223
  readonly engine_source_names: (a: number) => [number, number];
166
224
  readonly engine_stats: (a: number) => [number, number];
225
+ readonly engine_unload: (a: number, b: number, c: number) => number;
167
226
  readonly engine_view_query: (a: number, b: number, c: number, d: number, e: number, f: number, g: number) => [number, number, number, number];
168
227
  readonly planner_finish: (a: number, b: number, c: number, d: number, e: number) => [number, number, number, number];
169
228
  readonly planner_finish_columns: (a: number, b: number, c: number, d: number, e: number) => [number, number, number, number];
@@ -18,6 +18,77 @@ export class Engine {
18
18
  const ptr = this.__destroy_into_raw();
19
19
  wasm.__wbg_engine_free(ptr, 0);
20
20
  }
21
+ /**
22
+ * Drops the rows `begin_columns` started, nothing registered. Nothing to drop is not an
23
+ * error.
24
+ */
25
+ abort_columns() {
26
+ wasm.engine_abort_columns(this.__wbg_ptr);
27
+ }
28
+ /**
29
+ * Drops the file `begin_csv` started, nothing registered: for a page whose reading of the
30
+ * file failed. Nothing to drop is not an error.
31
+ */
32
+ abort_csv() {
33
+ wasm.engine_abort_csv(this.__wbg_ptr);
34
+ }
35
+ /**
36
+ * Starts reading the rows a page holds as packs of typed columns (issue #445): `push_columns`
37
+ * for each pack, then `end_columns`. `rows` is the number of rows of the whole table; the
38
+ * columns are sized by it. The format of a pack is in `opengrid_engine::ingest`. Rows begun
39
+ * before and not ended are dropped. An error here or later sends the page to `load_rows`,
40
+ * which owns every message.
41
+ * @param {string} name
42
+ * @param {string} schema_json
43
+ * @param {number} rows
44
+ */
45
+ begin_columns(name, schema_json, rows) {
46
+ const ptr0 = passStringToWasm0(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
47
+ const len0 = WASM_VECTOR_LEN;
48
+ const ptr1 = passStringToWasm0(schema_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
49
+ const len1 = WASM_VECTOR_LEN;
50
+ const ret = wasm.engine_begin_columns(this.__wbg_ptr, ptr0, len0, ptr1, len1, rows);
51
+ if (ret[1]) {
52
+ throw takeFromExternrefTable0(ret[0]);
53
+ }
54
+ }
55
+ /**
56
+ * Starts reading a CSV file in pieces (issue #427): `push_csv` for each piece, then
57
+ * `end_csv`. Only a piece and the columns are in memory, not the whole file as well. The
58
+ * pieces may end anywhere. `size_hint` is the file's size in bytes, 0 when unknown; it only
59
+ * sizes the columns. A file begun before and not ended is dropped.
60
+ * @param {string} name
61
+ * @param {string} schema_json
62
+ * @param {number} size_hint
63
+ */
64
+ begin_csv(name, schema_json, size_hint) {
65
+ const ptr0 = passStringToWasm0(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
66
+ const len0 = WASM_VECTOR_LEN;
67
+ const ptr1 = passStringToWasm0(schema_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
68
+ const len1 = WASM_VECTOR_LEN;
69
+ const ret = wasm.engine_begin_csv(this.__wbg_ptr, ptr0, len0, ptr1, len1, size_hint);
70
+ if (ret[1]) {
71
+ throw takeFromExternrefTable0(ret[0]);
72
+ }
73
+ }
74
+ /**
75
+ * The end of the rows: registers the source, replacing one of that name.
76
+ */
77
+ end_columns() {
78
+ const ret = wasm.engine_end_columns(this.__wbg_ptr);
79
+ if (ret[1]) {
80
+ throw takeFromExternrefTable0(ret[0]);
81
+ }
82
+ }
83
+ /**
84
+ * The end of the file: registers the source, replacing one of that name.
85
+ */
86
+ end_csv() {
87
+ const ret = wasm.engine_end_csv(this.__wbg_ptr);
88
+ if (ret[1]) {
89
+ throw takeFromExternrefTable0(ret[0]);
90
+ }
91
+ }
21
92
  /**
22
93
  * Runs a query JSON and answers with the result JSON.
23
94
  *
@@ -162,6 +233,32 @@ export class Engine {
162
233
  wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
163
234
  return v2;
164
235
  }
236
+ /**
237
+ * The next pack of the rows `begin_columns` started. A pack that does not hold ends the
238
+ * reading: nothing is registered.
239
+ * @param {Uint8Array} pack
240
+ */
241
+ push_columns(pack) {
242
+ const ptr0 = passArray8ToWasm0(pack, wasm.__wbindgen_malloc);
243
+ const len0 = WASM_VECTOR_LEN;
244
+ const ret = wasm.engine_push_columns(this.__wbg_ptr, ptr0, len0);
245
+ if (ret[1]) {
246
+ throw takeFromExternrefTable0(ret[0]);
247
+ }
248
+ }
249
+ /**
250
+ * The next piece of the file `begin_csv` started. A piece that cannot be read ends the
251
+ * file: nothing is registered, and the error names the line.
252
+ * @param {Uint8Array} bytes
253
+ */
254
+ push_csv(bytes) {
255
+ const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc);
256
+ const len0 = WASM_VECTOR_LEN;
257
+ const ret = wasm.engine_push_csv(this.__wbg_ptr, ptr0, len0);
258
+ if (ret[1]) {
259
+ throw takeFromExternrefTable0(ret[0]);
260
+ }
261
+ }
165
262
  /**
166
263
  * Gives the engine its collator (rule S4a, issue #391): `sort_keys` of
167
264
  * the collation module, which a page loads when a query first sorts by a
@@ -204,6 +301,20 @@ export class Engine {
204
301
  wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);
205
302
  }
206
303
  }
304
+ /**
305
+ * Frees the source `name` (issue #459); `true` when there was one. The
306
+ * module's memory does not shrink — WebAssembly memory only grows — but
307
+ * the next load takes the room the table had, so a page that unloads
308
+ * before it loads again needs one table's room, not two.
309
+ * @param {string} name
310
+ * @returns {boolean}
311
+ */
312
+ unload(name) {
313
+ const ptr0 = passStringToWasm0(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
314
+ const len0 = WASM_VECTOR_LEN;
315
+ const ret = wasm.engine_unload(this.__wbg_ptr, ptr0, len0);
316
+ return ret !== 0;
317
+ }
207
318
  /**
208
319
  * The query of a view (issue #144): what `get_query()` answers on an
209
320
  * `<opengrid-grid datasource=source columns=…>` once `view_json` is
@@ -417,14 +528,14 @@ function __wbg_get_imports() {
417
528
  __wbg___wbindgen_throw_344f42d3211c4765: function(arg0, arg1) {
418
529
  throw new Error(getStringFromWasm0(arg0, arg1));
419
530
  },
420
- __wbg_call_aa4db02d48413721: function() { return handleError(function (arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) {
531
+ __wbg_call_71757ee501b52574: function() { return handleError(function (arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) {
421
532
  const ret = arg1.call(arg2, getStringFromWasm0(arg3, arg4), getArrayU8FromWasm0(arg5, arg6), getArrayU32FromWasm0(arg7, arg8));
422
533
  const ptr1 = passArray8ToWasm0(ret, wasm.__wbindgen_malloc);
423
534
  const len1 = WASM_VECTOR_LEN;
424
535
  getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
425
536
  getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
426
537
  }, arguments); },
427
- __wbg_message_5539b0c90e0851ee: function(arg0) {
538
+ __wbg_message_571436f75b8ef765: function(arg0) {
428
539
  const ret = arg0.message;
429
540
  return ret;
430
541
  },
Binary file
@@ -3,6 +3,12 @@
3
3
  export const memory: WebAssembly.Memory;
4
4
  export const __wbg_engine_free: (a: number, b: number) => void;
5
5
  export const __wbg_planner_free: (a: number, b: number) => void;
6
+ export const engine_abort_columns: (a: number) => void;
7
+ export const engine_abort_csv: (a: number) => void;
8
+ export const engine_begin_columns: (a: number, b: number, c: number, d: number, e: number, f: number) => [number, number];
9
+ export const engine_begin_csv: (a: number, b: number, c: number, d: number, e: number, f: number) => [number, number];
10
+ export const engine_end_columns: (a: number) => [number, number];
11
+ export const engine_end_csv: (a: number) => [number, number];
6
12
  export const engine_execute: (a: number, b: number, c: number) => [number, number, number, number];
7
13
  export const engine_execute_columns: (a: number, b: number, c: number) => [number, number, number, number];
8
14
  export const engine_load_csv: (a: number, b: number, c: number, d: number, e: number, f: number, g: number) => [number, number];
@@ -10,9 +16,12 @@ export const engine_load_rows: (a: number, b: number, c: number, d: number, e: n
10
16
  export const engine_new: () => number;
11
17
  export const engine_pivot: (a: number, b: number, c: number) => [number, number, number, number];
12
18
  export const engine_pivot_columns: (a: number, b: number, c: number) => [number, number, number, number];
19
+ export const engine_push_columns: (a: number, b: number, c: number) => [number, number];
20
+ export const engine_push_csv: (a: number, b: number, c: number) => [number, number];
13
21
  export const engine_set_collator: (a: number, b: any) => void;
14
22
  export const engine_source_names: (a: number) => [number, number];
15
23
  export const engine_stats: (a: number) => [number, number];
24
+ export const engine_unload: (a: number, b: number, c: number) => number;
16
25
  export const engine_view_query: (a: number, b: number, c: number, d: number, e: number, f: number, g: number) => [number, number, number, number];
17
26
  export const planner_finish: (a: number, b: number, c: number, d: number, e: number) => [number, number, number, number];
18
27
  export const planner_finish_columns: (a: number, b: number, c: number, d: number, e: number) => [number, number, number, number];
package/loader.d.ts CHANGED
@@ -311,6 +311,20 @@ export interface ExecuteOptions {
311
311
  export interface EngineProvider extends Provider {
312
312
  /** Loads CSV bytes as the source `name`, against a schema (JSON). */
313
313
  load(name: string, bytes: ArrayBuffer | Uint8Array, schema: string): Promise<void>;
314
+ /**
315
+ * Loads a CSV file piece by piece as the source `name` (issue #427): a `File` or
316
+ * `Blob` (read a slice at a time), a `ReadableStream` of bytes or an async
317
+ * iterable of them. Only a piece and the columns are in the engine's memory, not
318
+ * the whole file as well. The pieces may end anywhere. A name that is already
319
+ * loaded is replaced, all or nothing; a piece that cannot be read rejects with
320
+ * the line, and the old source stays.
321
+ */
322
+ loadStream(
323
+ name: string,
324
+ source: Blob | ReadableStream<Uint8Array> | AsyncIterable<Uint8Array>,
325
+ schema: string,
326
+ options?: { chunkSize?: number },
327
+ ): Promise<void>;
314
328
  /**
315
329
  * Loads rows the page already holds as the source `name` (issue #182): an
316
330
  * array of objects keyed by field name — or that array as JSON text — with
@@ -322,6 +336,14 @@ export interface EngineProvider extends Provider {
322
336
  loadRows(name: string, rows: readonly Record<string, unknown>[] | string, schema: string): Promise<void>;
323
337
  /** Called by `set_provider`; the grid is told when a source it shows is replaced. */
324
338
  watch(host: HTMLElement): void;
339
+ /**
340
+ * Frees the source `name` (issue #459) and resolves with whether there was one.
341
+ * The engine's memory does not shrink — WebAssembly memory only grows — but the
342
+ * next load takes the room the table had: unloading before loading again needs
343
+ * one table's room instead of two, at the price of no data while the load runs.
344
+ * A grid on the name answers its next query with an unknown source.
345
+ */
346
+ unload(name: string): Promise<boolean>;
325
347
  /** What the engine holds: its memory and each source's size (issue #70). */
326
348
  stats(): Promise<EngineStats>;
327
349
  /** Stops a worker; a no-op in the tab. */
@@ -340,6 +362,12 @@ export interface EngineStats {
340
362
  /** The engine of the engine module, as `createLocalProvider` uses it. */
341
363
  export interface Engine {
342
364
  load_csv(name: string, bytes: Uint8Array, schema: string): void;
365
+ /** Reads a CSV file in pieces (issue #427): `begin_csv`, `push_csv` for each piece, `end_csv`. */
366
+ begin_csv(name: string, schema: string, sizeHint: number): void;
367
+ push_csv(bytes: Uint8Array): void;
368
+ end_csv(): void;
369
+ /** Drops a file `begin_csv` started. */
370
+ abort_csv(): void;
343
371
  /** Rows as JSON text (an array of objects); replaces a source of that name (issue #182). */
344
372
  load_rows(name: string, rowsJson: string, schema: string): void;
345
373
  /** The result as JSON. */
@@ -353,6 +381,8 @@ export interface Engine {
353
381
  * query first sorts by one.
354
382
  */
355
383
  set_collator(sortKeys: (locale: string, texts: Uint8Array, ends: Uint32Array) => Uint8Array): void;
384
+ /** Frees the source `name`; whether there was one (issue #459). */
385
+ unload(name: string): boolean;
356
386
  /** What it holds, as JSON (see `EngineStats`). */
357
387
  stats(): string;
358
388
  /** A pivot over the engine's sources, as JSON (issue #28). */
package/loader.js CHANGED
@@ -40,8 +40,6 @@
40
40
  // follows the import, and the `new URL("…_bg.wasm", import.meta.url)` inside the
41
41
  // glue, so the `.wasm` ends up in its output. `moduleUrl` replaces it.
42
42
  import * as packaged from "./pkg/opengrid_web_components.js";
43
- // The engine's collator, for a query that sorts by a locale (rule S4a).
44
- import { withCollator } from "./collation.js";
45
43
 
46
44
  /** Set once the first `loadOpengrid` call has run. */
47
45
  let loading;
@@ -195,6 +193,25 @@ export function createWorkerProvider({
195
193
 
196
194
  const watchers = createWatchers();
197
195
 
196
+ // Rows as packs of columns (issue #445): to the worker, which owns the engine.
197
+ let started = Promise.resolve();
198
+ const loadRowsAsColumns = columnLoader({
199
+ all: async (name, schema, rows, pack) => {
200
+ await started;
201
+ return request({ type: "columns", name, schema, rows, pack }, [pack]);
202
+ },
203
+ begin: async (name, schema, rows) => {
204
+ await started;
205
+ return request({ type: "columns_begin", name, schema, rows });
206
+ },
207
+ push: (pack) => request({ type: "columns_chunk", pack }, [pack]),
208
+ end: () => request({ type: "columns_end" }),
209
+ abort: async () => {
210
+ await started;
211
+ return request({ type: "columns_abort" });
212
+ },
213
+ });
214
+
198
215
  function start() {
199
216
  if (!worker) {
200
217
  // Written out in full: the `new Worker(new URL(…, import.meta.url), …)` form
@@ -219,14 +236,40 @@ export function createWorkerProvider({
219
236
  watchers.loaded(name);
220
237
  },
221
238
 
239
+ /**
240
+ * Loads a CSV file piece by piece (issue #427): a `File`/`Blob`, a
241
+ * `ReadableStream` of bytes or an async iterable of them. Only a piece and
242
+ * the columns are in the engine's memory, not the whole file as well. A
243
+ * name already loaded is replaced, all or nothing; a file that cannot be
244
+ * read leaves the old source and rejects with the line.
245
+ */
246
+ async loadStream(name, source, schema, options = {}) {
247
+ await start();
248
+ await request({ type: "load_begin", name, schema, size: sizeOf(source) });
249
+ try {
250
+ for await (const buffer of piecesOf(source, options.chunkSize)) {
251
+ await request({ type: "load_chunk", bytes: buffer }, [buffer]);
252
+ }
253
+ await request({ type: "load_end" });
254
+ } catch (error) {
255
+ await request({ type: "load_abort" });
256
+ throw error;
257
+ }
258
+ watchers.loaded(name);
259
+ },
260
+
222
261
  /**
223
262
  * Loads rows the page already holds — an array of objects keyed by field
224
263
  * name (or that array as JSON text) — against a schema (issue #182). A
225
264
  * name already loaded is replaced, all or nothing.
226
265
  */
227
266
  async loadRows(name, rows, schema) {
228
- await start();
229
- await request({ type: "rows", name, rows: rowsJson(rows), schema });
267
+ // The worker starts while the rows are made into columns, which is most of the wait.
268
+ started = start();
269
+ if (!(await loadRowsAsColumns(name, rows, schema))) {
270
+ await started;
271
+ await request({ type: "rows", name, rows: rowsJson(rows), schema });
272
+ }
230
273
  watchers.loaded(name);
231
274
  },
232
275
 
@@ -241,6 +284,17 @@ export function createWorkerProvider({
241
284
  return request({ type: "query", query: queryJson });
242
285
  },
243
286
 
287
+ /**
288
+ * Frees the source `name` (issue #459); resolves with whether there was
289
+ * one. The worker's memory does not shrink, but the next load takes the
290
+ * room the table had. A grid on the name answers its next query with an
291
+ * unknown source.
292
+ */
293
+ async unload(name) {
294
+ await start();
295
+ return request({ type: "unload", name });
296
+ },
297
+
244
298
  /**
245
299
  * What the engine in the worker holds (issue #70): its WASM memory and,
246
300
  * per source, rows, columns and bytes.
@@ -425,6 +479,280 @@ function rowsJson(rows) {
425
479
  return typeof rows === "string" ? rows : JSON.stringify(rows);
426
480
  }
427
481
 
482
+ // ---------------------------------------------------------------------------------------------
483
+ // Rows as columns (issue #445)
484
+ //
485
+ // An array of objects is handed to the engine as packs of typed columns, not as one JSON text:
486
+ // no text of the whole table on the main thread, in the worker and in the module, and no second
487
+ // reading of it. The format of a pack is in `crates/opengrid-engine/src/ingest/columns.rs`.
488
+ //
489
+ // The table has to be the table the JSON route makes of the same rows, so only what is plain is
490
+ // sent this way. A value that is not, an unknown key, a column the engine does not read from
491
+ // columns, or any error of the engine ends it, the engine drops what it had, and `loadRows` runs
492
+ // the JSON route, which owns every message.
493
+ // ---------------------------------------------------------------------------------------------
494
+
495
+ /** Rows per pack: a bound on what is in flight at once, as the pieces of `loadStream` are. */
496
+ const PACK_ROWS = 65536;
497
+ const textEncoder = new TextEncoder();
498
+
499
+ /** What the columns of `schema` are, or `null` when this way is not for these rows. */
500
+ function columnPlan(rows, schema) {
501
+ // A text that is not well formed is not what `JSON.stringify` and the JSON reader would make of
502
+ // it; a browser that cannot say takes the JSON route.
503
+ if (!Array.isArray(rows) || rows.length === 0 || typeof "".isWellFormed !== "function") {
504
+ return null;
505
+ }
506
+ let fields;
507
+ try {
508
+ fields = JSON.parse(schema)?.fields;
509
+ } catch {
510
+ return null;
511
+ }
512
+ if (!Array.isArray(fields)) {
513
+ return null;
514
+ }
515
+ const kinds = { bool: "bool", int64: "int", float64: "float", utf8: "utf8", date: "date", timestamp: "timestamp" };
516
+ const stored = [];
517
+ for (const field of fields) {
518
+ if (field?.from !== undefined && field?.from !== null) {
519
+ continue; // derived: computed by the engine, never sent
520
+ }
521
+ const kind = field?.type?.decimal ? "decimal" : kinds[field?.type];
522
+ if (typeof field?.name !== "string" || kind === undefined) {
523
+ return null; // a list column, or a schema the engine will explain
524
+ }
525
+ stored.push({ name: field.name, kind });
526
+ }
527
+ return stored.length > 0 ? stored : null;
528
+ }
529
+
530
+ /**
531
+ * One pack: rows `from` to `to` as typed columns, or `null` when a value is not plain.
532
+ * Plain is what the JSON route reads the same way: a boolean in a bool column, a safe integer
533
+ * in an int64, a finite number in a float64, a string in a text, date or timestamp column, a
534
+ * string or an integer in a decimal; `null` and a missing key are NULL.
535
+ */
536
+ function packOf(rows, from, to, stored) {
537
+ const n = to - from;
538
+ const pad = (size) => (size + 7) & ~7;
539
+ const bitsLength = Math.ceil(n / 8);
540
+ const sections = [];
541
+ // The keys of a row against the keys the schema has: a row with a key it does not know is the
542
+ // JSON route's, which names the key. `present` counts the keys of the schema a row has.
543
+ const present = new Uint16Array(n);
544
+ const plain = Object.prototype;
545
+ for (let i = 0; i < n; i += 1) {
546
+ const row = rows[from + i];
547
+ if (row === null || typeof row !== "object" || Object.getPrototypeOf(row) !== plain) {
548
+ return null;
549
+ }
550
+ }
551
+ for (const { name, kind } of stored) {
552
+ let bits = null; // the validity bitmap, made at the first NULL
553
+ const missing = (i) => {
554
+ bits ??= new Uint8Array(bitsLength).fill(255);
555
+ bits[i >> 3] &= ~(1 << (i & 7));
556
+ };
557
+ if (kind === "bool") {
558
+ const values = new Uint8Array(n);
559
+ for (let i = 0; i < n; i += 1) {
560
+ const value = rows[from + i][name];
561
+ if (value === undefined) {
562
+ missing(i);
563
+ continue;
564
+ }
565
+ present[i] += 1;
566
+ if (value === null) {
567
+ missing(i);
568
+ } else if (typeof value === "boolean") {
569
+ values[i] = value ? 1 : 0;
570
+ } else {
571
+ return null;
572
+ }
573
+ }
574
+ sections.push({ bits, payload: values, text: null });
575
+ } else if (kind === "int" || kind === "float") {
576
+ const values = new Float64Array(n);
577
+ for (let i = 0; i < n; i += 1) {
578
+ const value = rows[from + i][name];
579
+ if (value === undefined) {
580
+ missing(i);
581
+ continue;
582
+ }
583
+ present[i] += 1;
584
+ if (value === null) {
585
+ missing(i);
586
+ } else if (
587
+ typeof value === "number" &&
588
+ (kind === "int" ? Number.isSafeInteger(value) : Number.isFinite(value))
589
+ ) {
590
+ // JSON writes -0 as 0.
591
+ values[i] = value === 0 ? 0 : value;
592
+ } else {
593
+ return null;
594
+ }
595
+ }
596
+ sections.push({ bits, payload: new Uint8Array(values.buffer), text: null });
597
+ } else {
598
+ // Text, and what the engine reads from text: a decimal, a date, a timestamp.
599
+ const offsets = new Uint32Array(n + 1);
600
+ let bytes = new Uint8Array(Math.max(256, n * 12));
601
+ let at = 0;
602
+ for (let i = 0; i < n; i += 1) {
603
+ let value = rows[from + i][name];
604
+ if (value === undefined) {
605
+ missing(i);
606
+ offsets[i + 1] = at;
607
+ continue;
608
+ }
609
+ present[i] += 1;
610
+ if (value === null) {
611
+ missing(i);
612
+ offsets[i + 1] = at;
613
+ continue;
614
+ }
615
+ if (kind === "decimal" && typeof value === "number" && Number.isSafeInteger(value)) {
616
+ value = String(value);
617
+ }
618
+ if (typeof value !== "string") {
619
+ return null;
620
+ }
621
+ const length = value.length;
622
+ if (at + length * 3 > bytes.length) {
623
+ const grown = new Uint8Array(Math.max(bytes.length * 2, at + length * 3));
624
+ grown.set(bytes.subarray(0, at));
625
+ bytes = grown;
626
+ }
627
+ // ASCII, which most text is, is copied as it is; the rest is encoded, if it is well formed.
628
+ let ascii = true;
629
+ for (let j = 0; j < length; j += 1) {
630
+ const code = value.charCodeAt(j);
631
+ if (code > 127) {
632
+ ascii = false;
633
+ break;
634
+ }
635
+ bytes[at + j] = code;
636
+ }
637
+ if (ascii) {
638
+ at += length;
639
+ } else if (value.isWellFormed()) {
640
+ at += textEncoder.encodeInto(value, bytes.subarray(at)).written;
641
+ } else {
642
+ return null;
643
+ }
644
+ offsets[i + 1] = at;
645
+ }
646
+ sections.push({ bits, payload: new Uint8Array(offsets.buffer), text: bytes.subarray(0, at) });
647
+ }
648
+ }
649
+ for (let i = 0; i < n; i += 1) {
650
+ let keys = 0;
651
+ for (const _key in rows[from + i]) {
652
+ keys += 1;
653
+ }
654
+ if (keys !== present[i]) {
655
+ return null;
656
+ }
657
+ }
658
+ // The pack: the header, then each column's section from a multiple of 8.
659
+ let total = pad(4 + 8 * stored.length);
660
+ const starts = sections.map((section) => {
661
+ const start = total;
662
+ total += pad((section.bits ? pad(bitsLength) : 0) + section.payload.length + (section.text?.length ?? 0));
663
+ return start;
664
+ });
665
+ const pack = new ArrayBuffer(total);
666
+ const view = new DataView(pack);
667
+ const all = new Uint8Array(pack);
668
+ view.setUint32(0, n, true);
669
+ sections.forEach((section, index) => {
670
+ view.setUint32(4 + 8 * index, section.bits ? 1 : 0, true);
671
+ view.setUint32(8 + 8 * index, section.text?.length ?? 0, true);
672
+ let at = starts[index];
673
+ if (section.bits) {
674
+ all.set(section.bits, at);
675
+ at += pad(bitsLength);
676
+ }
677
+ all.set(section.payload, at);
678
+ if (section.text) {
679
+ all.set(section.text, at + section.payload.length);
680
+ }
681
+ });
682
+ return pack;
683
+ }
684
+
685
+ /**
686
+ * Loads `rows` as packs of columns through `io`, or says that it did not (`false`): the rows are
687
+ * not plain, or the engine refused them or does not know the calls. The engine holds nothing of
688
+ * them then, and the caller takes the JSON route.
689
+ */
690
+ async function loadColumns(name, rows, schema, io) {
691
+ const stored = columnPlan(rows, schema);
692
+ if (!stored) {
693
+ return false;
694
+ }
695
+ try {
696
+ if (rows.length <= PACK_ROWS) {
697
+ const pack = packOf(rows, 0, rows.length, stored);
698
+ if (!pack) {
699
+ return false;
700
+ }
701
+ await io.all(name, schema, rows.length, pack);
702
+ return true;
703
+ }
704
+ // The next pack is made while the engine takes the one before: a pack waits for the one two
705
+ // before it, not for the one before (which would leave the engine idle while a pack is made),
706
+ // and the page gets the thread back between packs. The first is made before `begin` is asked,
707
+ // so that a worker still starting does its start while that is done.
708
+ let pack = packOf(rows, 0, PACK_ROWS, stored);
709
+ if (!pack) {
710
+ return false;
711
+ }
712
+ await io.begin(name, schema, rows.length);
713
+ const sent = [];
714
+ let refused = null;
715
+ for (let from = 0; from < rows.length && !refused; from += PACK_ROWS) {
716
+ pack ??= packOf(rows, from, Math.min(rows.length, from + PACK_ROWS), stored);
717
+ if (!pack) {
718
+ refused = new Error("rows that are not plain");
719
+ break;
720
+ }
721
+ sent.push(io.push(pack).catch((error) => (refused ??= error)));
722
+ pack = null;
723
+ if (sent.length >= 2) {
724
+ await sent[sent.length - 2];
725
+ }
726
+ }
727
+ await Promise.all(sent);
728
+ if (refused) {
729
+ throw refused;
730
+ }
731
+ await io.end();
732
+ return true;
733
+ } catch {
734
+ try {
735
+ await io.abort();
736
+ } catch {
737
+ // Nothing to drop, or no engine to ask: the JSON route is next either way.
738
+ }
739
+ return false;
740
+ }
741
+ }
742
+
743
+ /**
744
+ * [`loadColumns`] one at a time: the engine keeps one set of rows in the making, so two loads
745
+ * must not interleave their packs.
746
+ */
747
+ function columnLoader(io) {
748
+ let queue = Promise.resolve();
749
+ return (name, rows, schema) => {
750
+ const run = queue.then(() => loadColumns(name, rows, schema, io));
751
+ queue = run.catch(() => {});
752
+ return run;
753
+ };
754
+ }
755
+
428
756
  /**
429
757
  * A provider over an engine that is already initialised on the main thread.
430
758
  *
@@ -436,6 +764,18 @@ function rowsJson(rows) {
436
764
  */
437
765
  export function createLocalProvider(engine) {
438
766
  const watchers = createWatchers();
767
+ // Rows as packs of columns (issue #445); an engine module without the calls takes the JSON route.
768
+ const loadRowsAsColumns = columnLoader({
769
+ all: async (name, schema, rows, pack) => {
770
+ engine.begin_columns(name, schema, rows);
771
+ engine.push_columns(new Uint8Array(pack));
772
+ engine.end_columns();
773
+ },
774
+ begin: async (name, schema, rows) => engine.begin_columns(name, schema, rows),
775
+ push: async (pack) => engine.push_columns(new Uint8Array(pack)),
776
+ end: async () => engine.end_columns(),
777
+ abort: async () => engine.abort_columns(),
778
+ });
439
779
  return {
440
780
  /** Where the queries run; the grid names it in its footer (issue #33). */
441
781
  kind: "local",
@@ -447,8 +787,23 @@ export function createLocalProvider(engine) {
447
787
  );
448
788
  watchers.loaded(name);
449
789
  },
790
+ async loadStream(name, source, schema, options = {}) {
791
+ engine.begin_csv(name, schema, sizeOf(source));
792
+ try {
793
+ for await (const buffer of piecesOf(source, options.chunkSize)) {
794
+ engine.push_csv(new Uint8Array(buffer));
795
+ }
796
+ engine.end_csv();
797
+ } catch (error) {
798
+ engine.abort_csv();
799
+ throw error;
800
+ }
801
+ watchers.loaded(name);
802
+ },
450
803
  async loadRows(name, rows, schema) {
451
- engine.load_rows(name, rowsJson(rows), schema);
804
+ if (!(await loadRowsAsColumns(name, rows, schema))) {
805
+ engine.load_rows(name, rowsJson(rows), schema);
806
+ }
452
807
  watchers.loaded(name);
453
808
  },
454
809
  watch(host) {
@@ -458,6 +813,10 @@ export function createLocalProvider(engine) {
458
813
  execute(queryJson) {
459
814
  return withCollator(engine, queryJson, () => engine.execute_columns(queryJson));
460
815
  },
816
+ /** Frees the source `name` (issue #459), as the worker provider does. */
817
+ async unload(name) {
818
+ return engine.unload(name);
819
+ },
461
820
  /** What the engine holds (issue #70), as the worker provider says it. */
462
821
  async stats() {
463
822
  return { kind: "local", ...JSON.parse(engine.stats()) };
@@ -771,6 +1130,39 @@ function coded(code, message) {
771
1130
  return error;
772
1131
  }
773
1132
 
1133
+ // The collator of the engine (rule S4a): `collation.js` and the module behind it are fetched
1134
+ // by the first query that names a locale, and never otherwise — so a page that serves the
1135
+ // package's files itself and leaves them out loses locale sorts, not the grid. The same test
1136
+ // is in `worker.js`; the two must agree.
1137
+ const NAMES_A_LOCALE = /"collation"\s*:\s*"(?!binary")/;
1138
+ /** The engines and planners that were given their collator. */
1139
+ const withCollation = new WeakSet();
1140
+
1141
+ async function giveCollation(engine) {
1142
+ let collation;
1143
+ try {
1144
+ collation = await import("./collation.js");
1145
+ } catch (error) {
1146
+ throw coded(
1147
+ "module_not_loaded",
1148
+ `a sort by a locale needs collation.js, and it did not load (${error?.message ?? error})`,
1149
+ );
1150
+ }
1151
+ await collation.giveCollator(engine);
1152
+ withCollation.add(engine);
1153
+ }
1154
+
1155
+ /**
1156
+ * Runs `run`, the answer itself — or, for a query that names a locale and an engine that has
1157
+ * no collator yet, a promise of it once the collation module is loaded.
1158
+ */
1159
+ function withCollator(engine, json, run) {
1160
+ if (withCollation.has(engine) || !NAMES_A_LOCALE.test(json)) {
1161
+ return run();
1162
+ }
1163
+ return giveCollation(engine).then(run);
1164
+ }
1165
+
774
1166
  /**
775
1167
  * A provider that asks an `opengrid-server` for a whole **pivot**.
776
1168
  *
@@ -1628,6 +2020,51 @@ function identityKey(value) {
1628
2020
  });
1629
2021
  }
1630
2022
 
2023
+ /** The bytes of a stream source when it says how many there are, else 0 (a hint, not a promise). */
2024
+ function sizeOf(source) {
2025
+ return typeof source?.size === "number" ? source.size : 0;
2026
+ }
2027
+
2028
+ /**
2029
+ * The pieces of a CSV source: a `Blob` is read a slice at a time, a stream or an
2030
+ * async iterable as it delivers. Each piece is an `ArrayBuffer` the caller may transfer.
2031
+ */
2032
+ async function* piecesOf(source, chunkSize = 4 * 1024 * 1024) {
2033
+ for await (const [piece, owned] of piecesAndOwners(source, chunkSize)) {
2034
+ // A piece the loader made, or a stream's chunk, is the loader's to hand on; the bytes an async
2035
+ // iterable yields may be reused by it, so they are copied.
2036
+ yield owned && piece.byteOffset === 0 && piece.byteLength === piece.buffer.byteLength
2037
+ ? piece.buffer
2038
+ : toTransferable(piece);
2039
+ }
2040
+ }
2041
+
2042
+ async function* piecesAndOwners(source, chunkSize) {
2043
+ if (typeof Blob !== "undefined" && source instanceof Blob) {
2044
+ for (let at = 0; at < source.size; at += chunkSize) {
2045
+ yield [new Uint8Array(await source.slice(at, at + chunkSize).arrayBuffer()), true];
2046
+ }
2047
+ return;
2048
+ }
2049
+ if (typeof source?.getReader === "function") {
2050
+ const reader = source.getReader();
2051
+ try {
2052
+ for (;;) {
2053
+ const { done, value } = await reader.read();
2054
+ if (done) return;
2055
+ yield [value, true];
2056
+ }
2057
+ } finally {
2058
+ reader.releaseLock();
2059
+ }
2060
+ }
2061
+ if (typeof source?.[Symbol.asyncIterator] === "function") {
2062
+ for await (const piece of source) yield [piece, false];
2063
+ return;
2064
+ }
2065
+ throw new TypeError("a CSV source must be a Blob, a ReadableStream or an async iterable of bytes");
2066
+ }
2067
+
1631
2068
  /**
1632
2069
  * The CSV bytes as a transferable `ArrayBuffer`.
1633
2070
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@casoon/opengrid",
3
- "version": "0.17.0",
3
+ "version": "0.18.1",
4
4
  "type": "module",
5
5
  "description": "Accessible data grid, table and pivot as web components, driven by a portable Rust/WASM query engine — with React, Vue and Svelte components.",
6
6
  "keywords": [
@@ -1,12 +1,12 @@
1
1
  /* @ts-self-types="./opengrid_web_components.d.ts" */
2
- import { __opengrid_numbers } from './snippets/opengrid-web-components-ae047af7b34e4f04/inline0.js';
3
- import { __opengrid_intl_formatter, __opengrid_page_lang } from './snippets/opengrid-web-components-ae047af7b34e4f04/inline1.js';
4
- import { __opengrid_define_element } from './snippets/opengrid-web-core-b158b7dd980e3998/inline1.js';
5
- import { __opengrid_apply_frame, __opengrid_remove_attribute, __opengrid_set_attribute, __opengrid_set_text } from './snippets/opengrid-web-core-b158b7dd980e3998/inline2.js';
6
- import * as import1 from "./snippets/opengrid-web-components-ae047af7b34e4f04/inline1.js"
7
- import * as import2 from "./snippets/opengrid-web-core-b158b7dd980e3998/inline0.js"
8
- import * as import3 from "./snippets/opengrid-web-core-b158b7dd980e3998/inline0.js"
9
- import * as import4 from "./snippets/opengrid-web-core-b158b7dd980e3998/inline0.js"
2
+ import { __opengrid_numbers } from './snippets/opengrid-web-components-79b23e2f3cc5fec9/inline0.js';
3
+ import { __opengrid_intl_formatter, __opengrid_page_lang } from './snippets/opengrid-web-components-79b23e2f3cc5fec9/inline1.js';
4
+ import { __opengrid_define_element } from './snippets/opengrid-web-core-b4bccfdabe05c2b9/inline1.js';
5
+ import { __opengrid_apply_frame, __opengrid_remove_attribute, __opengrid_set_attribute, __opengrid_set_text } from './snippets/opengrid-web-core-b4bccfdabe05c2b9/inline2.js';
6
+ import * as import1 from "./snippets/opengrid-web-components-79b23e2f3cc5fec9/inline1.js"
7
+ import * as import2 from "./snippets/opengrid-web-core-b4bccfdabe05c2b9/inline0.js"
8
+ import * as import3 from "./snippets/opengrid-web-core-b4bccfdabe05c2b9/inline0.js"
9
+ import * as import4 from "./snippets/opengrid-web-core-b4bccfdabe05c2b9/inline0.js"
10
10
 
11
11
 
12
12
  /**
@@ -454,34 +454,34 @@ function __wbg_get_imports() {
454
454
  const ret = Error(getStringFromWasm0(arg0, arg1));
455
455
  return ret;
456
456
  },
457
- __wbg___opengrid_apply_frame_d29f0faa02b21c54: function(arg0, arg1, arg2, arg3, arg4, arg5) {
457
+ __wbg___opengrid_apply_frame_0ef566ead1cfa14e: function(arg0, arg1, arg2, arg3, arg4, arg5) {
458
458
  __opengrid_apply_frame(arg0, arg1, getArrayU32FromWasm0(arg2, arg3), getStringFromWasm0(arg4, arg5));
459
459
  },
460
- __wbg___opengrid_define_element_e2f5e6af2c89bb08: function(arg0, arg1, arg2, arg3, arg4, arg5) {
460
+ __wbg___opengrid_define_element_4c39151754c9732f: function(arg0, arg1, arg2, arg3, arg4, arg5) {
461
461
  __opengrid_define_element(getStringFromWasm0(arg0, arg1), arg2, arg3, arg4, arg5);
462
462
  },
463
- __wbg___opengrid_intl_formatter_0fcf0cbef860d75a: function() { return handleError(function (arg0, arg1, arg2, arg3, arg4) {
463
+ __wbg___opengrid_intl_formatter_678848ff971df548: function() { return handleError(function (arg0, arg1, arg2, arg3, arg4) {
464
464
  const ret = __opengrid_intl_formatter(getStringFromWasm0(arg0, arg1), getStringFromWasm0(arg2, arg3), arg4);
465
465
  return ret;
466
466
  }, arguments); },
467
- __wbg___opengrid_numbers_c1ec0026a630b13a: function(arg0, arg1) {
467
+ __wbg___opengrid_numbers_21ad989927ada671: function(arg0, arg1) {
468
468
  const ret = __opengrid_numbers(getArrayF64FromWasm0(arg0, arg1));
469
469
  return ret;
470
470
  },
471
- __wbg___opengrid_page_lang_447464cff74da710: function(arg0, arg1) {
471
+ __wbg___opengrid_page_lang_4577ee188df2e39d: function(arg0, arg1) {
472
472
  const ret = __opengrid_page_lang(arg1);
473
473
  const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
474
474
  const len1 = WASM_VECTOR_LEN;
475
475
  getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
476
476
  getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
477
477
  },
478
- __wbg___opengrid_remove_attribute_dc5663ae33dab39e: function(arg0, arg1, arg2) {
478
+ __wbg___opengrid_remove_attribute_4b9c5e73ea9e4ec0: function(arg0, arg1, arg2) {
479
479
  __opengrid_remove_attribute(arg0, getStringFromWasm0(arg1, arg2));
480
480
  },
481
- __wbg___opengrid_set_attribute_8ae482e70d39630b: function(arg0, arg1, arg2, arg3, arg4) {
481
+ __wbg___opengrid_set_attribute_f3581b2125f143ec: function(arg0, arg1, arg2, arg3, arg4) {
482
482
  __opengrid_set_attribute(arg0, getStringFromWasm0(arg1, arg2), getStringFromWasm0(arg3, arg4));
483
483
  },
484
- __wbg___opengrid_set_text_40dda64a15f431aa: function(arg0, arg1, arg2) {
484
+ __wbg___opengrid_set_text_ea069a76256aff8a: function(arg0, arg1, arg2) {
485
485
  __opengrid_set_text(arg0, getStringFromWasm0(arg1, arg2));
486
486
  },
487
487
  __wbg___wbindgen_boolean_get_fa956cfa2d1bd751: function(arg0) {
@@ -1508,10 +1508,10 @@ function __wbg_get_imports() {
1508
1508
  return {
1509
1509
  __proto__: null,
1510
1510
  "./opengrid_web_components_bg.js": import0,
1511
- "./snippets/opengrid-web-components-ae047af7b34e4f04/inline1.js": import1,
1512
- "./snippets/opengrid-web-core-b158b7dd980e3998/inline0.js": import2,
1513
- "./snippets/opengrid-web-core-b158b7dd980e3998/inline0.js": import3,
1514
- "./snippets/opengrid-web-core-b158b7dd980e3998/inline0.js": import4,
1511
+ "./snippets/opengrid-web-components-79b23e2f3cc5fec9/inline1.js": import1,
1512
+ "./snippets/opengrid-web-core-b4bccfdabe05c2b9/inline0.js": import2,
1513
+ "./snippets/opengrid-web-core-b4bccfdabe05c2b9/inline0.js": import3,
1514
+ "./snippets/opengrid-web-core-b4bccfdabe05c2b9/inline0.js": import4,
1515
1515
  };
1516
1516
  }
1517
1517
 
Binary file
package/worker.js CHANGED
@@ -12,8 +12,12 @@
12
12
  * load { type:"load", id, name, bytes, schema }
13
13
  * -> { type:"loaded", id }
14
14
  * rows { type:"rows", id, name, rows, schema } -> { type:"loaded", id } (issue #182)
15
+ * columns { type:"columns", id, name, schema, rows, pack } -> { type:"loaded", id } (issue #445)
16
+ * columns_begin / columns_chunk / columns_end / columns_abort: the same rows in packs, as
17
+ * load_begin / load_chunk / load_end / load_abort are for CSV
15
18
  * query { type:"query", id, query } -> { id, result }
16
19
  * stats { type:"stats", id } -> { id, result } (issue #70)
20
+ * unload { type:"unload", id, name } -> { id, result } (issue #459): whether there was one
17
21
  * pivot { type:"pivot", id, pivot } -> { id, result } (issue #28)
18
22
  *
19
23
  * Any request that throws answers `{ id, type:"error", message }`. The `bytes`
@@ -25,9 +29,30 @@
25
29
  // The packaged engine glue, imported statically so that a bundler follows it and
26
30
  // the `.wasm` beside it; `init` names another one with `moduleUrl`.
27
31
  import * as packaged from "./engine/opengrid_wasm.js";
28
- // The collator, for a query that sorts by a locale (rule S4a): a module of its
29
- // own, fetched by the first such query.
30
- import { withCollator } from "./collation.js";
32
+
33
+ // The collator, for a query that sorts by a locale (rule S4a): `collation.js` and the module
34
+ // behind it are fetched by the first such query, and never otherwise — so a page that serves
35
+ // the package's files itself and leaves them out loses locale sorts, not the worker. The same
36
+ // test is in `loader.js`; the two must agree.
37
+ const NAMES_A_LOCALE = /"collation"\s*:\s*"(?!binary")/;
38
+ let collatorGiven = false;
39
+
40
+ async function withCollator(engine, json, run) {
41
+ if (!collatorGiven && NAMES_A_LOCALE.test(json)) {
42
+ let collation;
43
+ try {
44
+ collation = await import("./collation.js");
45
+ } catch (error) {
46
+ throw Object.assign(
47
+ new Error(`a sort by a locale needs collation.js, and it did not load (${error?.message ?? error})`),
48
+ { code: "module_not_loaded" },
49
+ );
50
+ }
51
+ await collation.giveCollator(engine);
52
+ collatorGiven = true;
53
+ }
54
+ return run();
55
+ }
31
56
 
32
57
  /** The single engine instance, created on `init` and reused for every query. */
33
58
  let engine;
@@ -49,11 +74,64 @@ self.onmessage = async ({ data }) => {
49
74
  self.postMessage({ type: "loaded", id: data.id });
50
75
  break;
51
76
  }
77
+ case "load_begin": {
78
+ engine.begin_csv(data.name, data.schema, data.size);
79
+ self.postMessage({ type: "loaded", id: data.id });
80
+ break;
81
+ }
82
+ case "load_chunk": {
83
+ engine.push_csv(new Uint8Array(data.bytes));
84
+ self.postMessage({ type: "loaded", id: data.id });
85
+ break;
86
+ }
87
+ case "load_end": {
88
+ engine.end_csv();
89
+ self.postMessage({ type: "loaded", id: data.id });
90
+ break;
91
+ }
92
+ case "load_abort": {
93
+ engine.abort_csv();
94
+ self.postMessage({ type: "loaded", id: data.id });
95
+ break;
96
+ }
97
+ case "columns": {
98
+ // The rows of a page as one pack of columns (issue #445); a pack that does not hold, or an
99
+ // engine module without the calls, answers with an error, and the page takes the JSON route.
100
+ engine.begin_columns(data.name, data.schema, data.rows);
101
+ engine.push_columns(new Uint8Array(data.pack));
102
+ engine.end_columns();
103
+ self.postMessage({ type: "loaded", id: data.id });
104
+ break;
105
+ }
106
+ case "columns_begin": {
107
+ engine.begin_columns(data.name, data.schema, data.rows);
108
+ self.postMessage({ type: "loaded", id: data.id });
109
+ break;
110
+ }
111
+ case "columns_chunk": {
112
+ engine.push_columns(new Uint8Array(data.pack));
113
+ self.postMessage({ type: "loaded", id: data.id });
114
+ break;
115
+ }
116
+ case "columns_end": {
117
+ engine.end_columns();
118
+ self.postMessage({ type: "loaded", id: data.id });
119
+ break;
120
+ }
121
+ case "columns_abort": {
122
+ engine.abort_columns();
123
+ self.postMessage({ type: "loaded", id: data.id });
124
+ break;
125
+ }
52
126
  case "rows": {
53
127
  engine.load_rows(data.name, data.rows, data.schema);
54
128
  self.postMessage({ type: "loaded", id: data.id });
55
129
  break;
56
130
  }
131
+ case "unload": {
132
+ self.postMessage({ id: data.id, result: engine.unload(data.name) });
133
+ break;
134
+ }
57
135
  case "stats": {
58
136
  // What the engine holds: its memory and each source's size, as JSON.
59
137
  self.postMessage({ id: data.id, result: engine.stats() });
Binary file