@malloy-publisher/sdk 0.10.1 → 0.10.3
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/dist/{RenderedResult-vf6tu8tf.es.js → RenderedResult-B_sW7neX.es.js} +329 -266
- package/dist/RenderedResult-BlYdT4lz.cjs.js +179 -0
- package/dist/{ServerProvider-B6RLAbgV.es.js → ServerProvider-BN399NH6.es.js} +4 -4
- package/dist/builder/index.cjs.js +1 -1
- package/dist/builder/index.es.js +3 -3
- package/dist/client/api.d.ts +6 -6
- package/dist/client/index.es.js +1 -1
- package/dist/components/Dashboard/DashboardView.d.ts +10 -3
- package/dist/components/Dashboard/DownloadRowsCsv.d.ts +10 -0
- package/dist/components/Dashboard/RowsDialog.d.ts +63 -21
- package/dist/components/Dashboard/index.d.ts +2 -0
- package/dist/components/Dashboard/rowsCsv.d.ts +26 -0
- package/dist/components/RenderedResult/ResultContainer.d.ts +2 -3
- package/dist/components/RenderedResult/resultSizing.d.ts +2 -0
- package/dist/components/Report/Report.d.ts +8 -1
- package/dist/components/drill/drillClauses.d.ts +34 -0
- package/dist/components/drill/drillClickRelay.d.ts +36 -0
- package/dist/components/drill/resolveDrill.d.ts +29 -0
- package/dist/components/drill/rowsTarget.d.ts +114 -0
- package/dist/components/drill/useDrill.d.ts +24 -12
- package/dist/index.cjs.js +13 -11
- package/dist/index.es.js +7331 -6886
- package/dist/{useCompiledDocument-C995sQ3j.cjs.js → useCompiledDocument-CyPOSStA.cjs.js} +31 -31
- package/dist/{useCompiledDocument-CLbTFtsJ.es.js → useCompiledDocument-xJRD5DRP.es.js} +1588 -1575
- package/dist/utils/malloyString.d.ts +2 -1
- package/package.json +1 -1
- package/src/components/Dashboard/DashboardView.tsx +54 -28
- package/src/components/Dashboard/DownloadRowsCsv.tsx +152 -0
- package/src/components/Dashboard/RowsDialog.actions.spec.tsx +250 -0
- package/src/components/Dashboard/RowsDialog.drill.compile.spec.ts +672 -0
- package/src/components/Dashboard/RowsDialog.spec.ts +38 -11
- package/src/components/Dashboard/RowsDialog.tsx +194 -40
- package/src/components/Dashboard/index.ts +2 -0
- package/src/components/Dashboard/rowsCsv.spec.ts +105 -0
- package/src/components/Dashboard/rowsCsv.ts +107 -0
- package/src/components/RenderedResult/RenderedResult.tsx +44 -7
- package/src/components/RenderedResult/ResultContainer.tsx +2 -2
- package/src/components/RenderedResult/resultSizing.ts +3 -0
- package/src/components/Report/Report.tsx +9 -0
- package/src/components/drill/drillClauses.ts +201 -0
- package/src/components/drill/drillClickRelay.spec.ts +122 -0
- package/src/components/drill/drillClickRelay.ts +106 -0
- package/src/components/drill/resolveDrill.ts +29 -0
- package/src/components/drill/rowsTarget.ts +245 -0
- package/src/components/drill/useDrill.spec.tsx +311 -15
- package/src/components/drill/useDrill.tsx +206 -67
- package/src/components/legacy/malloynb/NotebookCell.tsx +0 -7
- package/src/utils/malloyString.ts +21 -2
- package/dist/RenderedResult-B5f4qOjp.cjs.js +0 -171
|
@@ -5,26 +5,53 @@ import { describe, expect, it } from "bun:test";
|
|
|
5
5
|
import { rowsQuery, sourceOf, stepsOf } from "./RowsDialog";
|
|
6
6
|
|
|
7
7
|
describe("the rows query", () => {
|
|
8
|
-
it("
|
|
8
|
+
it("filters the source by the tile's filters and each dimension of the row", () => {
|
|
9
|
+
const target = {
|
|
10
|
+
source: "overview",
|
|
11
|
+
filters: ["region ~ $REGION", "is_online = true"],
|
|
12
|
+
};
|
|
9
13
|
expect(
|
|
10
14
|
rowsQuery({
|
|
11
|
-
|
|
12
|
-
view: "best_sellers",
|
|
15
|
+
target,
|
|
13
16
|
field: "name",
|
|
14
|
-
rawValue: "
|
|
15
|
-
label: "
|
|
17
|
+
rawValue: "x",
|
|
18
|
+
label: "x",
|
|
19
|
+
dimensions: [
|
|
20
|
+
{
|
|
21
|
+
code: "products.name",
|
|
22
|
+
value: { kind: "string_literal", string_value: "O'Brien" },
|
|
23
|
+
},
|
|
24
|
+
{ code: "region", value: { kind: "null_literal" } },
|
|
25
|
+
{
|
|
26
|
+
code: "sold_at.hour",
|
|
27
|
+
value: {
|
|
28
|
+
kind: "timestamp_literal",
|
|
29
|
+
timestamp_value: "2026-02-03T23:00:00Z",
|
|
30
|
+
},
|
|
31
|
+
},
|
|
32
|
+
],
|
|
33
|
+
timezone: "Asia/Tokyo",
|
|
16
34
|
}),
|
|
17
35
|
).toBe(
|
|
18
|
-
"run: overview -> {
|
|
36
|
+
"run: overview -> { timezone: 'Asia/Tokyo'; where: region ~ $REGION, is_online = true, products.name = 'O\\'Brien', region is null, sold_at.hour = @2026-02-04 08:00:00; select: *; limit: 200 }",
|
|
19
37
|
);
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
it("writes a click with no row by its own value, and nothing it cannot spell", () => {
|
|
41
|
+
const target = { source: "overview", filters: [] };
|
|
20
42
|
expect(
|
|
21
43
|
rowsQuery({
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
44
|
+
target,
|
|
45
|
+
field: "name",
|
|
46
|
+
rawValue: "Loft Insulated Jacket",
|
|
47
|
+
label: "Loft Insulated Jacket",
|
|
48
|
+
code: "products.name",
|
|
27
49
|
}),
|
|
50
|
+
).toBe(
|
|
51
|
+
"run: overview -> { where: products.name = 'Loft Insulated Jacket'; select: *; limit: 200 }",
|
|
52
|
+
);
|
|
53
|
+
expect(
|
|
54
|
+
rowsQuery({ target, field: "f", rawValue: {}, label: "", code: "f" }),
|
|
28
55
|
).toBeUndefined();
|
|
29
56
|
});
|
|
30
57
|
|
|
@@ -12,49 +12,160 @@ import {
|
|
|
12
12
|
IconButton,
|
|
13
13
|
Typography,
|
|
14
14
|
} from "@mui/material";
|
|
15
|
-
import { useEffect, useRef } from "react";
|
|
15
|
+
import { Fragment, useEffect, useRef, type ReactNode } from "react";
|
|
16
16
|
import { useQueryResult } from "../../hooks/useQueryResult";
|
|
17
|
+
import {
|
|
18
|
+
drillClauseLabels,
|
|
19
|
+
literalText,
|
|
20
|
+
type DrillClauseLabel,
|
|
21
|
+
} from "../drill/drillClauses";
|
|
22
|
+
import type { DrillRowsRequest } from "../drill/resolveDrill";
|
|
23
|
+
import { type RowsTarget } from "../drill/rowsTarget";
|
|
17
24
|
import { malloyLiteral } from "../../utils/malloyLiteral";
|
|
18
|
-
import {
|
|
25
|
+
import { escapeMalloyString } from "../../utils/malloyString";
|
|
26
|
+
import { isBareName, isIdentifier, tileSteps } from "../../utils/malloyText";
|
|
19
27
|
import { usePublisherTheme } from "../../theme/ThemeContext";
|
|
20
28
|
import { ResultPanel } from "../RenderedResult/ResultPanel";
|
|
29
|
+
import { withPreamble } from "./textSource";
|
|
21
30
|
import { now } from "../../utils/clock";
|
|
31
|
+
import { DownloadRowsCsv } from "./DownloadRowsCsv";
|
|
32
|
+
import { rowsFileName } from "./rowsCsv";
|
|
22
33
|
|
|
23
34
|
/**
|
|
24
35
|
* The rows behind a value: "show the rows" on a cell, as one query.
|
|
25
36
|
*
|
|
26
|
-
* A grouped value is an aggregate over rows of the tile's source, and
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
* `drill:` resolves it through the view, which is where the name lives.
|
|
37
|
+
* A grouped value is an aggregate over rows of the tile's source, and those
|
|
38
|
+
* rows are the source filtered by everything the value was filtered by: the
|
|
39
|
+
* tile's own `where:` (its control bindings included), every enclosing nest's,
|
|
40
|
+
* and each dimension of the clicked row at its value. All of that is read
|
|
41
|
+
* from the result's metadata (`rowsTarget.ts`), so a refined tile, a named
|
|
42
|
+
* query and a nest open their rows the same way a `source -> view` tile does.
|
|
33
43
|
*/
|
|
34
44
|
export const ROW_LIMIT = 200;
|
|
35
45
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
46
|
+
/** A click's rows request once its result has named everything a query needs. */
|
|
47
|
+
export type RowsRequest = DrillRowsRequest & { target: RowsTarget };
|
|
48
|
+
|
|
49
|
+
/** The dialog's request for a click, if its result named everything a query needs. */
|
|
50
|
+
export function rowsRequestFor(
|
|
51
|
+
request: DrillRowsRequest,
|
|
52
|
+
): RowsRequest | undefined {
|
|
53
|
+
const { target } = request;
|
|
54
|
+
if (target === undefined) return undefined;
|
|
55
|
+
if (request.dimensions === undefined && request.code === undefined)
|
|
56
|
+
return undefined;
|
|
57
|
+
return { ...request, target };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* What a host's rows actions get: everything needed to fetch the rows behind
|
|
62
|
+
* the value in full, not just the first {@link ROW_LIMIT} the dialog shows.
|
|
63
|
+
*/
|
|
64
|
+
export interface RowsActionsContext {
|
|
65
|
+
/**
|
|
66
|
+
* The rows query with no `limit:`, so the server's own row cap is the only
|
|
67
|
+
* bound. Without the preamble: in text-source mode send
|
|
68
|
+
* `withPreamble(preamble, query)`, as the dialog does.
|
|
69
|
+
*/
|
|
70
|
+
query: string;
|
|
71
|
+
/** Text-source mode: the document's definitions, sent ahead of `query`. */
|
|
72
|
+
preamble?: string;
|
|
73
|
+
environmentName: string;
|
|
74
|
+
packageName: string;
|
|
75
|
+
modelPath: string;
|
|
76
|
+
versionId?: string;
|
|
77
|
+
/** The givens the dialog's own query sends. */
|
|
78
|
+
givens: Record<string, unknown>;
|
|
79
|
+
/** A file name without an extension: the source and each value of the row. */
|
|
80
|
+
fileName: string;
|
|
44
81
|
}
|
|
45
82
|
|
|
46
|
-
/**
|
|
47
|
-
|
|
83
|
+
/**
|
|
84
|
+
* The host's actions for the rows behind a value (a download, an export),
|
|
85
|
+
* drawn in the rows dialog's title row. Return `null` to show none; omitted,
|
|
86
|
+
* the dialog offers its own Download CSV.
|
|
87
|
+
*/
|
|
88
|
+
export type RowsActions = (context: RowsActionsContext) => ReactNode;
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* The query the dialog runs, or undefined when a value cannot be spelled.
|
|
92
|
+
* `limit` caps the rows; `null` leaves the query unlimited, so only the
|
|
93
|
+
* server's own cap applies.
|
|
94
|
+
*/
|
|
95
|
+
export function rowsQuery(
|
|
96
|
+
request: RowsRequest,
|
|
97
|
+
limit: number | null = ROW_LIMIT,
|
|
98
|
+
): string | undefined {
|
|
99
|
+
const values = dimensionFilters(request);
|
|
100
|
+
if (values === undefined) return undefined;
|
|
101
|
+
const where = [...request.target.filters, ...values].join(", ");
|
|
102
|
+
// A timestamp is truncated in the query's zone, so a tile with its own
|
|
103
|
+
// `timezone:` is filtered in that zone or matches nothing.
|
|
104
|
+
const zone = request.timezone
|
|
105
|
+
? `timezone: '${escapeMalloyString(request.timezone)}'; `
|
|
106
|
+
: "";
|
|
107
|
+
const cap = limit === null ? "" : `; limit: ${limit}`;
|
|
108
|
+
const source = sourceName(request.target.source);
|
|
109
|
+
if (source === undefined) return undefined;
|
|
110
|
+
return `run: ${source} -> { ${zone}where: ${where}; select: *${cap} }`;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** A source name as `run:` reads it: back-quoted unless it stands bare. */
|
|
114
|
+
function sourceName(name: string): string | undefined {
|
|
115
|
+
if (isBareName(name)) return name;
|
|
116
|
+
return name.includes("`") ? undefined : `\`${name}\``;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* A dimension's code as an operand: parenthesized unless it is a plain name
|
|
121
|
+
* or dotted path, since `region = 'East' or region = 'West' = false` binds
|
|
122
|
+
* the `=` to the last disjunct only.
|
|
123
|
+
*/
|
|
124
|
+
function operand(code: string): string {
|
|
125
|
+
return /^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$/.test(code)
|
|
126
|
+
? code
|
|
127
|
+
: `(${code})`;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Each dimension at its value; undefined if any one cannot be written. */
|
|
131
|
+
function dimensionFilters(request: RowsRequest): string[] | undefined {
|
|
132
|
+
if (request.dimensions) {
|
|
133
|
+
const out: string[] = [];
|
|
134
|
+
for (const { code, value } of request.dimensions) {
|
|
135
|
+
// A row whose dimension is null is the rows where it is null.
|
|
136
|
+
if (value.kind === "null_literal") {
|
|
137
|
+
out.push(`${operand(code)} is null`);
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
const literal = literalText(value, request.timezone);
|
|
141
|
+
if (literal === undefined) return undefined;
|
|
142
|
+
out.push(`${operand(code)} = ${literal}`);
|
|
143
|
+
}
|
|
144
|
+
return out;
|
|
145
|
+
}
|
|
48
146
|
const literal = malloyLiteral(request.rawValue);
|
|
49
|
-
|
|
50
|
-
|
|
147
|
+
return request.code !== undefined && literal
|
|
148
|
+
? [`${operand(request.code)} = ${literal}`]
|
|
149
|
+
: undefined;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** What the dialog says when a request has no query. */
|
|
153
|
+
export const ROWS_REFUSAL =
|
|
154
|
+
"This value cannot be written as a filter, so its rows cannot be fetched.";
|
|
155
|
+
|
|
156
|
+
/** What the title names: every value of the row, or the clicked one alone. */
|
|
157
|
+
export function rowsTitleParts(request: RowsRequest): DrillClauseLabel[] {
|
|
158
|
+
const parts = request.drillClauses
|
|
159
|
+
? drillClauseLabels(request.drillClauses, request.timezone)
|
|
160
|
+
: [];
|
|
161
|
+
return parts.length > 0
|
|
162
|
+
? parts
|
|
163
|
+
: [{ field: request.field, label: request.label }];
|
|
51
164
|
}
|
|
52
165
|
|
|
53
166
|
/**
|
|
54
167
|
* `overview -> revenue_trend` → its source and view; undefined for anything
|
|
55
|
-
* else
|
|
56
|
-
* filters `drill:` would not, and a longer pipeline has no one view its value
|
|
57
|
-
* came from.
|
|
168
|
+
* else.
|
|
58
169
|
*/
|
|
59
170
|
export function stepsOf(
|
|
60
171
|
tileExpression: string | undefined,
|
|
@@ -80,23 +191,50 @@ export function RowsDialog({
|
|
|
80
191
|
packageName,
|
|
81
192
|
versionId,
|
|
82
193
|
modelPath,
|
|
194
|
+
preamble,
|
|
83
195
|
givens,
|
|
84
196
|
onClose,
|
|
85
197
|
onDone,
|
|
198
|
+
actions,
|
|
86
199
|
}: {
|
|
87
200
|
request: RowsRequest | undefined;
|
|
88
201
|
environmentName: string;
|
|
89
202
|
packageName: string;
|
|
90
203
|
versionId?: string;
|
|
91
204
|
modelPath: string;
|
|
205
|
+
/**
|
|
206
|
+
* Text-source mode: the document's definitions, sent ahead of the rows
|
|
207
|
+
* query exactly as they are ahead of each tile's, so the rows run as the
|
|
208
|
+
* viewer's own text on the same model.
|
|
209
|
+
*/
|
|
210
|
+
preamble?: string;
|
|
92
211
|
/** The applied control row, which the source's own `where:` may read. */
|
|
93
212
|
givens: Record<string, unknown>;
|
|
94
213
|
onClose: () => void;
|
|
95
214
|
/** The query's outcome and how long it took, once per request. */
|
|
96
215
|
onDone?: (ok: boolean, durationMs: number) => void;
|
|
216
|
+
/** The host's actions for these rows; omitted, the dialog's own Download CSV. */
|
|
217
|
+
actions?: RowsActions;
|
|
97
218
|
}) {
|
|
98
219
|
const { theme } = usePublisherTheme();
|
|
99
220
|
const query = request ? rowsQuery(request) : undefined;
|
|
221
|
+
const unlimited = request ? rowsQuery(request, null) : undefined;
|
|
222
|
+
const actionsContext: RowsActionsContext | undefined =
|
|
223
|
+
request && unlimited !== undefined
|
|
224
|
+
? {
|
|
225
|
+
query: unlimited,
|
|
226
|
+
...(preamble === undefined ? {} : { preamble }),
|
|
227
|
+
environmentName,
|
|
228
|
+
packageName,
|
|
229
|
+
modelPath,
|
|
230
|
+
...(versionId === undefined ? {} : { versionId }),
|
|
231
|
+
givens,
|
|
232
|
+
fileName: rowsFileName(
|
|
233
|
+
request.target.source,
|
|
234
|
+
rowsTitleParts(request).map((part) => part.label),
|
|
235
|
+
),
|
|
236
|
+
}
|
|
237
|
+
: undefined;
|
|
100
238
|
|
|
101
239
|
return (
|
|
102
240
|
<Dialog
|
|
@@ -117,10 +255,15 @@ export function RowsDialog({
|
|
|
117
255
|
{request ? (
|
|
118
256
|
<>
|
|
119
257
|
Rows where{" "}
|
|
120
|
-
|
|
121
|
-
{
|
|
122
|
-
|
|
123
|
-
|
|
258
|
+
{rowsTitleParts(request).map((part, index) => (
|
|
259
|
+
<Fragment key={index}>
|
|
260
|
+
{index > 0 && " and "}
|
|
261
|
+
<Box component="code" sx={{ fontSize: "0.9em" }}>
|
|
262
|
+
{part.field}
|
|
263
|
+
</Box>{" "}
|
|
264
|
+
is {part.label}
|
|
265
|
+
</Fragment>
|
|
266
|
+
))}
|
|
124
267
|
</>
|
|
125
268
|
) : (
|
|
126
269
|
"Rows"
|
|
@@ -131,29 +274,40 @@ export function RowsDialog({
|
|
|
131
274
|
sx={{ color: theme.tileTitle, mt: 0.25 }}
|
|
132
275
|
>
|
|
133
276
|
{request
|
|
134
|
-
? `The first ${ROW_LIMIT} rows of ${request.source} behind this value, with the tile's own filters and the controls applied.`
|
|
277
|
+
? `The first ${ROW_LIMIT} rows of ${request.target.source} behind this value, with the tile's own filters and the controls applied.`
|
|
135
278
|
: ""}
|
|
136
279
|
</Typography>
|
|
137
280
|
</Box>
|
|
138
|
-
<
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
281
|
+
<Box sx={{ display: "flex", alignItems: "center", gap: 1, ml: 1 }}>
|
|
282
|
+
{actionsContext &&
|
|
283
|
+
(actions ? (
|
|
284
|
+
actions(actionsContext)
|
|
285
|
+
) : (
|
|
286
|
+
<DownloadRowsCsv {...actionsContext} />
|
|
287
|
+
))}
|
|
288
|
+
<IconButton
|
|
289
|
+
onClick={onClose}
|
|
290
|
+
aria-label="Close"
|
|
291
|
+
size="small"
|
|
292
|
+
sx={{ color: "text.secondary" }}
|
|
293
|
+
>
|
|
294
|
+
<CloseIcon fontSize="small" />
|
|
295
|
+
</IconButton>
|
|
296
|
+
</Box>
|
|
146
297
|
</DialogTitle>
|
|
147
298
|
<DialogContent dividers sx={{ p: 0, minHeight: 240 }}>
|
|
148
299
|
{query === undefined && request && (
|
|
149
300
|
<Typography variant="body2" sx={{ p: 2 }}>
|
|
150
|
-
|
|
151
|
-
be fetched.
|
|
301
|
+
{ROWS_REFUSAL}
|
|
152
302
|
</Typography>
|
|
153
303
|
)}
|
|
154
304
|
{query !== undefined && (
|
|
155
305
|
<RowsResult
|
|
156
|
-
query={
|
|
306
|
+
query={
|
|
307
|
+
preamble === undefined
|
|
308
|
+
? query
|
|
309
|
+
: withPreamble(preamble, query)
|
|
310
|
+
}
|
|
157
311
|
environmentName={environmentName}
|
|
158
312
|
packageName={packageName}
|
|
159
313
|
{...(versionId === undefined ? {} : { versionId })}
|
|
@@ -15,4 +15,6 @@ export {
|
|
|
15
15
|
withPreamble,
|
|
16
16
|
} from "./textSource";
|
|
17
17
|
export { TILE_MIN_HEIGHT, TileCard, TileHeading } from "./TileCard";
|
|
18
|
+
export type { RowsActions, RowsActionsContext } from "./RowsDialog";
|
|
19
|
+
export { DownloadRowsCsv } from "./DownloadRowsCsv";
|
|
18
20
|
export type { TileHeadingSlots } from "./TileCard";
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// Copyright (c) Credible Data Inc.
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { describe, expect, it } from "bun:test";
|
|
5
|
+
import type * as Malloy from "@malloydata/malloy-interfaces";
|
|
6
|
+
import {
|
|
7
|
+
neutralizeFormula,
|
|
8
|
+
resultToCsv,
|
|
9
|
+
rowsFileName,
|
|
10
|
+
serverCappedAt,
|
|
11
|
+
} from "./rowsCsv";
|
|
12
|
+
|
|
13
|
+
const field = (name: string): Malloy.FieldInfo => ({
|
|
14
|
+
kind: "dimension",
|
|
15
|
+
name,
|
|
16
|
+
type: { kind: "string_type" },
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
const result = (names: string[], rows: Malloy.Cell[][]): Malloy.Result => ({
|
|
20
|
+
connection_name: "duckdb",
|
|
21
|
+
schema: { fields: names.map(field) },
|
|
22
|
+
data: {
|
|
23
|
+
kind: "array_cell",
|
|
24
|
+
array_value: rows.map((record_value) => ({
|
|
25
|
+
kind: "record_cell",
|
|
26
|
+
record_value,
|
|
27
|
+
})),
|
|
28
|
+
},
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
const str = (string_value: string): Malloy.Cell => ({
|
|
32
|
+
kind: "string_cell",
|
|
33
|
+
string_value,
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
describe("the rows as CSV", () => {
|
|
37
|
+
it("quotes a value holding a comma, a quote or a line break", () => {
|
|
38
|
+
const csv = resultToCsv(
|
|
39
|
+
result(
|
|
40
|
+
["owner"],
|
|
41
|
+
[
|
|
42
|
+
[str("Bob's team")],
|
|
43
|
+
[str('say "hi"')],
|
|
44
|
+
[str("a,b")],
|
|
45
|
+
[str("one\ntwo")],
|
|
46
|
+
],
|
|
47
|
+
),
|
|
48
|
+
);
|
|
49
|
+
expect(csv).toBe(
|
|
50
|
+
'\uFEFFowner\r\nBob\'s team\r\n"say ""hi"""\r\n"a,b"\r\n"one\ntwo"\r\n',
|
|
51
|
+
);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it("writes a null as an empty field, and a number, boolean, date and timestamp as they are", () => {
|
|
55
|
+
const csv = resultToCsv(
|
|
56
|
+
result(
|
|
57
|
+
["a", "b", "c", "d", "e"],
|
|
58
|
+
[
|
|
59
|
+
[
|
|
60
|
+
{ kind: "null_cell" },
|
|
61
|
+
{ kind: "number_cell", number_value: -12.5 },
|
|
62
|
+
{ kind: "boolean_cell", boolean_value: false },
|
|
63
|
+
{ kind: "date_cell", date_value: "2025-12-01" },
|
|
64
|
+
{
|
|
65
|
+
kind: "timestamp_cell",
|
|
66
|
+
timestamp_value: "2025-12-01T08:30:00.000Z",
|
|
67
|
+
},
|
|
68
|
+
],
|
|
69
|
+
],
|
|
70
|
+
),
|
|
71
|
+
);
|
|
72
|
+
expect(csv).toBe(
|
|
73
|
+
"\uFEFFa,b,c,d,e\r\n,-12.5,false,2025-12-01,2025-12-01T08:30:00.000Z\r\n",
|
|
74
|
+
);
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it("prefixes text a spreadsheet would run as a formula, but never a number", () => {
|
|
78
|
+
expect(neutralizeFormula('=HYPERLINK("http://x","x")')).toBe(
|
|
79
|
+
`'=HYPERLINK("http://x","x")`,
|
|
80
|
+
);
|
|
81
|
+
for (const lead of ["=", "+", "-", "@"])
|
|
82
|
+
expect(neutralizeFormula(`${lead}1`)).toBe(`'${lead}1`);
|
|
83
|
+
expect(neutralizeFormula("West")).toBe("West");
|
|
84
|
+
const csv = resultToCsv(
|
|
85
|
+
result(["=name"], [[str("@SUM(A1)")], [str("-2+3")]]),
|
|
86
|
+
);
|
|
87
|
+
expect(csv).toBe("\uFEFF'=name\r\n'@SUM(A1)\r\n'-2+3\r\n");
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it("names the file by the source and each value, in plain characters", () => {
|
|
91
|
+
expect(rowsFileName("orders", ["Complete", "2025-12"])).toBe(
|
|
92
|
+
"orders_rows_Complete_2025-12",
|
|
93
|
+
);
|
|
94
|
+
expect(rowsFileName("owners", ["West", "Bob's team"])).toBe(
|
|
95
|
+
"owners_rows_West_Bob_s_team",
|
|
96
|
+
);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it("says the server cut a result short only when its own default did", () => {
|
|
100
|
+
expect(serverCappedAt(1000, 1000, "server_default")).toBe(1000);
|
|
101
|
+
expect(serverCappedAt(999, 1000, "server_default")).toBeUndefined();
|
|
102
|
+
expect(serverCappedAt(1000, 1000, "query")).toBeUndefined();
|
|
103
|
+
expect(serverCappedAt(5, undefined, undefined)).toBeUndefined();
|
|
104
|
+
});
|
|
105
|
+
});
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// Copyright (c) Credible Data Inc.
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import type * as Malloy from "@malloydata/malloy-interfaces";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The rows behind a value as a CSV file: what the rows dialog's default
|
|
8
|
+
* download writes. A `select: *` result is one flat table, so each schema
|
|
9
|
+
* field is a column and each record a line.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** A text value a spreadsheet would run as a formula is written with a leading `'`. */
|
|
13
|
+
export function neutralizeFormula(value: string): string {
|
|
14
|
+
return /^[=+\-@\t\r]/.test(value) ? `'${value}` : value;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function quote(value: string): string {
|
|
18
|
+
return /[",\r\n]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* One cell as a CSV field. Text (strings, JSON, a database-native value, a
|
|
23
|
+
* nested record or array as JSON) is neutralized and quoted; a number, a
|
|
24
|
+
* boolean, a date and a timestamp are written as they are, so a negative
|
|
25
|
+
* number stays a number. A null is an empty field.
|
|
26
|
+
*/
|
|
27
|
+
function csvField(cell: Malloy.Cell | undefined): string {
|
|
28
|
+
if (cell === undefined) return "";
|
|
29
|
+
switch (cell.kind) {
|
|
30
|
+
case "null_cell":
|
|
31
|
+
return "";
|
|
32
|
+
case "number_cell":
|
|
33
|
+
return cell.string_value ?? String(cell.number_value);
|
|
34
|
+
case "boolean_cell":
|
|
35
|
+
return cell.boolean_value ? "true" : "false";
|
|
36
|
+
case "date_cell":
|
|
37
|
+
return cell.date_value;
|
|
38
|
+
case "timestamp_cell":
|
|
39
|
+
return cell.timestamp_value;
|
|
40
|
+
case "string_cell":
|
|
41
|
+
return quote(neutralizeFormula(cell.string_value));
|
|
42
|
+
case "json_cell":
|
|
43
|
+
return quote(neutralizeFormula(cell.json_value));
|
|
44
|
+
case "sql_native_cell":
|
|
45
|
+
return quote(neutralizeFormula(cell.sql_native_value));
|
|
46
|
+
default:
|
|
47
|
+
return quote(neutralizeFormula(JSON.stringify(cell)));
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The records of a result, in order. */
|
|
52
|
+
export function resultRecords(result: Malloy.Result): Malloy.Cell[][] {
|
|
53
|
+
const data = result.data;
|
|
54
|
+
if (data?.kind !== "array_cell") return [];
|
|
55
|
+
return data.array_value.flatMap((row) =>
|
|
56
|
+
row.kind === "record_cell" ? [row.record_value] : [],
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The result as CSV text: a header of the field names, then one line per
|
|
62
|
+
* record. Starts with a byte-order mark and ends lines with CRLF, so a
|
|
63
|
+
* spreadsheet opens non-ASCII text and line breaks inside a value correctly.
|
|
64
|
+
*/
|
|
65
|
+
export function resultToCsv(result: Malloy.Result): string {
|
|
66
|
+
const fields = result.schema.fields;
|
|
67
|
+
const lines = [
|
|
68
|
+
// A field name is text a spreadsheet would run too.
|
|
69
|
+
fields.map((f) => quote(neutralizeFormula(f.name))).join(","),
|
|
70
|
+
...resultRecords(result).map((record) =>
|
|
71
|
+
fields.map((_, i) => csvField(record[i])).join(","),
|
|
72
|
+
),
|
|
73
|
+
];
|
|
74
|
+
return `\uFEFF${lines.join("\r\n")}\r\n`;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* A file name for the rows behind a value, without an extension: the source
|
|
79
|
+
* and each value the rows are filtered on, as the dialog's title names them.
|
|
80
|
+
*/
|
|
81
|
+
export function rowsFileName(
|
|
82
|
+
source: string,
|
|
83
|
+
values: readonly string[],
|
|
84
|
+
): string {
|
|
85
|
+
const name = [source, "rows", ...values]
|
|
86
|
+
.join("_")
|
|
87
|
+
.replace(/[^A-Za-z0-9._-]+/g, "_")
|
|
88
|
+
.replace(/_+/g, "_")
|
|
89
|
+
.replace(/^[_.]+|[_.]+$/g, "");
|
|
90
|
+
return name.slice(0, 120) || "rows";
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* How many rows the server's own cap left in a result, when that cap (not
|
|
95
|
+
* the query) cut it short; undefined when the result is complete.
|
|
96
|
+
*/
|
|
97
|
+
export function serverCappedAt(
|
|
98
|
+
rowCount: number,
|
|
99
|
+
queryRowLimit: number | undefined,
|
|
100
|
+
queryRowLimitSource: string | undefined,
|
|
101
|
+
): number | undefined {
|
|
102
|
+
return queryRowLimitSource === "server_default" &&
|
|
103
|
+
queryRowLimit !== undefined &&
|
|
104
|
+
rowCount >= queryRowLimit
|
|
105
|
+
? queryRowLimit
|
|
106
|
+
: undefined;
|
|
107
|
+
}
|