@nongt/visql 0.8.0 → 0.10.0

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.
Files changed (48) hide show
  1. package/README.md +23 -360
  2. package/dist/{MuiTimePicker-BjywwrRm.js → MuiTimePicker-DRqT6ByZ.js} +1 -1
  3. package/dist/PipelineEditor-Ch_i6OAc.js +10537 -0
  4. package/dist/core.js +339 -78
  5. package/dist/explain.js +356 -0
  6. package/dist/index.js +119 -100
  7. package/dist/issueLocation-Y1iaP_Cs.js +1108 -0
  8. package/dist/mui-date-pickers-host.js +1 -1
  9. package/dist/mui-date-pickers.js +1 -1
  10. package/dist/mui.js +95 -84
  11. package/dist/params-kc6eNrpu.js +2223 -0
  12. package/dist/{schema-DFC26AhZ.js → schema-KDJ1rpG5.js} +334 -271
  13. package/dist/sql-import.js +1 -1
  14. package/dist/sqlGen-Crgheqys.js +903 -0
  15. package/dist/style.css +1 -1
  16. package/dist/tokens-DV5rTGMj.js +171 -0
  17. package/dist/types/core/components/flow/NodeActionFrame.d.ts +20 -0
  18. package/dist/types/core/components/flow/useNodeActions.d.ts +18 -0
  19. package/dist/types/core/existsMenu.d.ts +4 -3
  20. package/dist/types/core/i18n/defaultMessages.d.ts +15 -0
  21. package/dist/types/core/i18n/messages.d.ts +11 -0
  22. package/dist/types/core/pipelineFlow.d.ts +1 -1
  23. package/dist/types/core/planFindings.d.ts +27 -0
  24. package/dist/types/core/queryHelpers.d.ts +1 -1
  25. package/dist/types/core/schema.d.ts +68 -24
  26. package/dist/types/core/scopeQuery.d.ts +2 -2
  27. package/dist/types/core/theme/appearance.d.ts +27 -0
  28. package/dist/types/core/theme/looks.d.ts +14 -0
  29. package/dist/types/core/theme/tokens.d.ts +9 -1
  30. package/dist/types/core-api.d.ts +2 -1
  31. package/dist/types/explain/explainQuery.d.ts +59 -0
  32. package/dist/types/explain/mySqlPlan.d.ts +4 -0
  33. package/dist/types/explain/planPlaces.d.ts +27 -0
  34. package/dist/types/explain/postgresPlan.d.ts +4 -0
  35. package/dist/types/explain/sqlServerPlan.d.ts +4 -0
  36. package/dist/types/explain/xml.d.ts +7 -0
  37. package/dist/types/explain.d.ts +2 -0
  38. package/dist/types/features/queryEditor/CanvasBackground.d.ts +2 -0
  39. package/dist/types/features/queryEditor/ExplainButton.d.ts +13 -0
  40. package/dist/types/features/queryEditor/IssuesButton.d.ts +14 -6
  41. package/dist/types/features/queryEditor/PipelineEditor.d.ts +15 -0
  42. package/dist/types/features/queryEditor/planText.d.ts +8 -0
  43. package/dist/types/index.d.ts +2 -0
  44. package/package.json +14 -1
  45. package/dist/PipelineEditor-DtT1TPgd.js +0 -10214
  46. package/dist/core-api-jaQDPXVK.js +0 -1171
  47. package/dist/issueLocation-DEIwB1DW.js +0 -3290
  48. package/dist/tokens-BTaVMSOx.js +0 -95
package/README.md CHANGED
@@ -80,366 +80,29 @@ export function ReportEditor() {
80
80
  }
81
81
  ```
82
82
 
83
- The editor fills its container, so give the container a height.
84
-
85
- ## Describing your database
86
-
87
- The editor only knows the tables you tell it about. Tables and columns fill
88
- its pickers, and relations (your foreign keys) are how it suggests joins.
89
-
90
- ```ts
91
- import type { DatabaseSchema } from '@nongt/visql';
92
-
93
- export const schema: DatabaseSchema = {
94
- tables: [
95
- {
96
- name: 'orders',
97
- label: 'Orders',
98
- columns: [
99
- { name: 'id', label: 'ID', type: 'integer' },
100
- { name: 'customer_id', label: 'Customer', type: 'integer' },
101
- { name: 'placed_at', label: 'Placed At', type: 'dateTime' },
102
- {
103
- name: 'status',
104
- label: 'Status',
105
- type: 'varchar',
106
- // Values compared with this column are picked from a list.
107
- options: [
108
- { value: 'open', label: 'Open' },
109
- { value: 'shipped', label: 'Shipped' },
110
- ],
111
- },
112
- ],
113
- },
114
- {
115
- name: 'customers',
116
- label: 'Customers',
117
- columns: [
118
- { name: 'id', label: 'ID', type: 'integer' },
119
- { name: 'name', label: 'Name', type: 'varchar' },
120
- ],
121
- },
122
- ],
123
- relations: [
124
- // orders.customer_id points at customers.id. Declare each key once,
125
- // from the table that holds it.
126
- { fromTable: 'orders', fromColumn: 'customer_id', toTable: 'customers', toColumn: 'id' },
127
- ],
128
- };
129
- ```
130
-
131
- Column types are `varchar`, `integer`, `decimal`, `date`, `dateTime`,
132
- `time` and `boolean`, and each gets the matching input. If the schema has a
133
- mistake in it, the editor reports it through `onSchemaIssues`, or
134
- `console.warn` if you don't pass that.
135
-
136
- If your database keeps dates as text (`'20261003'`, `'09:30'`), declare the
137
- column as a date or time anyway and give its `format`, such as
138
- `format: 'YYYYMMDD'`. Users still get a date picker, and the SQL compares in
139
- your format when you pass the schema to the SQL functions.
140
-
141
- Key columns are usually there only so tables can be joined. Mark one
142
- `joinOnly: true` and the editor still uses it to join tables, but leaves it
143
- out of every column picker, so nobody ends up grouping by an employee key or
144
- filtering on a surrogate id:
145
-
146
- ```ts
147
- { name: 'employee_key', label: 'Employee key', type: 'integer', joinOnly: true }
148
- ```
149
-
150
- A sub query can still select a key and group by it, so it can be joined
151
- back by that key, and outside the sub query that column is join-only too.
152
- `validateQuery` reports a key used anywhere else as `joinOnlyColumn`, an
153
- error, so your server refuses what the editor wouldn't offer.
154
-
155
- A large catalog is easier to pick from in groups. Give a table a `group`
156
- (its business area, say) and a `description`, and the table pickers list
157
- the tables under a heading per group, with the description under each
158
- label. You can also draw the options yourself, add your own button beside
159
- each picker, or replace the picker with your own.
160
- [Helping users find a table](docs/table-pickers.md) has the details.
161
-
162
- Relations also tell the editor which side of a join has many rows. Joining
163
- `orders` to `order_items` repeats each order once per item, so a SUM of the
164
- order totals comes out too high without any error. The editor warns about
165
- that on the canvas, and `validateQuery` reports it as `fanOut`.
166
-
167
- ## The query value
168
-
169
- `onChange` gives you a `QueryValue`. It's plain JSON, apart from date and
170
- `bigint` values:
171
-
172
- ```ts
173
- interface QueryPipeline {
174
- id: string; // stays the same through every edit
175
- from: { table: string; alias?: string };
176
- joins: { id: string; table: string; joinType: 'inner' | 'left' | 'right' | 'full'; on?: ExpressionNode }[];
177
- where?: ExpressionNode;
178
- groupBy?: { id: string; expression: ExpressionNode; fromSelect?: string }[];
179
- having?: ExpressionNode;
180
- select: { id: string; expression: ExpressionNode; alias?: string }[];
181
- distinct?: boolean;
182
- orderBy?: { id: string; expression: ExpressionNode; direction: 'asc' | 'desc' }[];
183
- limit?: number;
184
- offset?: number;
185
- }
186
- type QueryValue = QueryPipeline | { id: string }; // { id } while no table is picked yet
187
- ```
188
-
189
- Use it the way you'd use an `<input>`: pass `value` and `onChange` and hand
190
- back what you're given, or pass `defaultValue` and let the editor keep its
191
- own state. `value={null}` starts an empty query. A query with a different
192
- `id` starts a new undo history.
193
-
194
- A date in a query is a calendar day or a wall-clock time, not a moment in
195
- time. 3 October 2026 is stored as `2026-10-03T00:00:00Z` and written to SQL
196
- as `'2026-10-03'`, the same day whether the browser is in Bangkok or the
197
- server runs in UTC. If you build one in code, `new Date('2026-10-03')` is
198
- that day, but `new Date(2026, 9, 3)` is local midnight, which is the day
199
- before east of UTC.
200
-
201
- ### Storing it
202
-
203
- ```ts
204
- import { loadQuery, saveQuery } from '@nongt/visql/core';
205
-
206
- db.save(report.id, JSON.stringify(saveQuery(query)));
207
- const query = loadQuery(JSON.parse(db.load(report.id)));
208
- ```
209
-
210
- `saveQuery` adds a format version. `loadQuery` upgrades a query saved by an
211
- older version as it reads it, and refuses one saved by a newer version
212
- (a `QueryFormatError` of kind `'newerVersion'`) rather than guessing. That
213
- can happen after a rolled-back deploy. It doesn't check the query against
214
- your schema, because a table may have been dropped since the query was
215
- saved, so run `validateQuery` after loading.
216
-
217
- ## Getting SQL out
218
-
219
- To run a query, generate it with parameters. The values go to the driver
220
- separately from the SQL text:
221
-
222
- ```ts
223
- import { astToParameterizedSql } from '@nongt/visql';
224
-
225
- const { sql, params } = astToParameterizedSql(query, 'postgres');
226
- // SELECT * FROM "orders" WHERE "orders"."status" = $1 AND "orders"."total" > $2
227
- // ['open', 100]
228
- await pg.query(sql, params);
229
- ```
230
-
231
- Every value becomes a parameter, wherever it is: `?` in MySQL, `$1` in
232
- PostgreSQL, `@p1` in SQL Server. Names are quoted. Function names and other
233
- parts that can't be parameters are checked against plain patterns, and an
234
- operator the library doesn't know throws an error instead of being written. Dates
235
- are sent as text, because drivers would otherwise shift a `Date` into the
236
- server's time zone.
237
-
238
- To show a query to someone, `astToSql(query, 'mysql')` writes the values
239
- inline.
240
-
241
- If the names in your schema aren't the database's real ones (handy when you
242
- want saved queries to survive a rename), pass `resolveName`:
243
-
244
- ```ts
245
- const physical: Record<string, string> = {
246
- timecard: 'fact_timecard',
247
- 'timecard.minutes': 'worked_minutes',
248
- };
249
- astToParameterizedSql(query, 'mysql', {
250
- resolveName: (table, column) => physical[column ? `${table}.${column}` : table] ?? column ?? table,
251
- });
252
- // FROM fact_timecard AS timecard ... timecard.worked_minutes
253
- ```
254
-
255
- ## On the server
256
-
257
- Treat a query that arrives from a browser, or comes out of your database,
258
- as untrusted. The editor's `tableFilter` and `columnFilter` only hide things
259
- on screen. The check that actually enforces them is `validateQuery` on the
260
- server.
261
-
262
- ```ts
263
- import { astToParameterizedSql, hasBaseTable, validateQuery } from '@nongt/visql-core';
264
-
265
- app.get('/reports/:id/rows', async (req, res) => {
266
- const query = await reports.load(req.params.id);
267
- const issues = validateQuery(schema, query, {
268
- tableFilter: (t) => req.user.canSee(t.name),
269
- });
270
- // Errors mean don't run it. Warnings (no LIMIT, rows a join repeats) can run.
271
- if (issues.some((i) => i.severity === 'error')) return res.status(400).json({ issues });
272
- if (!hasBaseTable(query)) return res.json([]);
273
-
274
- const { sql, params } = astToParameterizedSql(query, 'postgres');
275
- res.json(await db.query(sql, params));
276
- });
277
- ```
278
-
279
- To limit every report to a tenant, use `scopeQuery`, not `addCondition`.
280
- A report can read the same table in several places: a sub query, an
281
- EXISTS, a second copy of the table in a self join. Each of those has to be
282
- limited, or the report can still use other tenants' rows. `scopeQuery`
283
- reaches all of them, and throws a `ScopeError` when it can't.
284
-
285
- [`docs/backend-integration.md`](docs/backend-integration.md) walks through
286
- the whole server side in order: loading, checking, scoping, parameters,
287
- writing the SQL, and the contract fixtures to run in CI.
288
-
289
- ## Props
290
-
291
- | Prop | Type | |
292
- |---|---|---|
293
- | `schema` | `DatabaseSchema` | **Required.** Tables, columns and relations. |
294
- | `value` / `defaultValue` | `QueryValue \| null` | The query, controlled or uncontrolled. |
295
- | `onChange` | `(query: QueryValue) => void` | Called on every edit, undo and redo. |
296
- | `ref` | `Ref<QueryBuilderHandle>` | `resetHistory()`, `goToIssue(issue)` to take the user to a problem, `run()`, and `addTable(name, { as })` to add a table from your own page. |
297
- | `readOnly` | `boolean` | Look around the query without changing it. |
298
- | `tableFilter` | `(table) => boolean` | Tables this user may see. They're never added automatically either. |
299
- | `columnFilter` | `(table, column) => boolean` | Columns this user may see. |
300
- | `functions` | `FunctionRegistry` | The SQL functions on offer. Defaults to `DEFAULT_FUNCTIONS`. |
301
- | `renderValueInput` | `RenderValueInput` | Your own input for some columns' values. |
302
- | `messages` | `Partial<Messages>` | Interface text, for translations. See `DEFAULT_MESSAGES`. |
303
- | `theme` | `Partial<QueryBuilderTheme>` | Colors. See `DEFAULT_THEME`. |
304
- | `fontFamily` | `string` | The editor's font. Defaults to the page's. |
305
- | `components` | `Partial<UIComponents>` | Swap single UI pieces, or bring a whole kit. |
306
- | `onSchemaIssues` | `(issues: SchemaIssue[]) => void` | Problems found in the schema. |
307
- | `onIssues` | `(issues: QueryIssue[]) => void` | The query's problems, whenever they change. The query is ready to run or save when none of them is an error. |
308
- | `showIssues` | `boolean` | The problem count above the canvas, with a list that takes the user to each one. On by default. |
309
- | `typeMismatch` | `'warning' \| 'error'` | How to report values whose types don't go together. Use the same setting as your server. |
310
- | `dialect` | `'mysql' \| 'mssql' \| 'postgres'` | Only offer what this database supports. Anything already in the query stays and is reported. |
311
- | `betweenOnText` | `'never' \| 'withoutOptions' \| 'always'` | Whether to offer BETWEEN on text. Off by default, because text ranges follow the collation: `'A'` to `'M'` leaves out "Mary". |
312
- | `hideWarnings` | `QueryWarningKind[]` | Warnings not to show, such as `['crossJoin']`. |
313
- | `onRun` | `(query) => RunResult \| void \| Promise<…>` | Adds a Run button. See below. |
314
- | `direction` | `'ltr' \| 'rtl'` | Which way the canvas grows. |
315
- | `orientation` | `'horizontal' \| 'vertical'` | Lay the main sections out side by side, or stacked for a narrow space. |
316
- | `subqueries` | `{ in?, union?, shared? }` | Turn on sub queries after IN, UNION ALL, and WITH. All are off by default. |
317
- | `exists` | `ExistsOptions` | Which related tables the EXISTS button lists, and where it appears. |
318
- | `onHoverPart` | `(pathSegments \| null) => void` | The part of the query under the pointer, for lighting it up in your own SQL view. |
319
- | `autoRevealNewNodes` | `boolean` | Pan to nodes as they're added. On by default. |
320
- | `className` | `string` | Added to the root element. |
321
-
322
- Pass objects and functions as stable values (module constants, `useMemo`,
323
- `useCallback`), or the editor redoes work on every render.
324
-
325
- ### Running the query
326
-
327
- With `onRun`, the editor gets a Run button (and Ctrl/⌘+Enter while you're
328
- working in the editor; in your page's other inputs the keys stay theirs, as
329
- Ctrl/⌘+Z for undo does). It never
330
- talks to a database itself. Your `onRun` sends the query to your backend
331
- and returns the rows, and the editor shows them under the canvas.
332
-
333
- ```tsx
334
- <QueryBuilder
335
- schema={schema}
336
- onRun={async (query) => {
337
- const res = await fetch('/reports/preview', { method: 'POST', body: JSON.stringify(query) });
338
- if (!res.ok) throw new Error(await res.text()); // shown as the error
339
- return res.json(); // { rows, columns?, truncated? }
340
- }}
341
- />
342
- ```
343
-
344
- It sends the query rather than SQL so that your backend checks it and
345
- writes the SQL itself. Cap the number of rows there, and return
346
- `truncated: true` when there were more.
347
-
348
- ## Customizing
349
-
350
- Add your own SQL functions, drop some, or keep only what one database has:
351
-
352
- ```ts
353
- import { DEFAULT_FUNCTIONS, functionsForDialect } from '@nongt/visql';
354
-
355
- const functions = {
356
- ...functionsForDialect(DEFAULT_FUNCTIONS, 'postgres'),
357
- RISK_SCORE: { name: 'RISK_SCORE', args: [{ label: 'customer', kind: 'num-expr' }] },
358
- };
359
- ```
360
-
361
- If one of your functions sums rows up, mark it `aggregate: true`. Otherwise
362
- the editor can't know, and won't treat a column that calls it as a group
363
- key.
364
-
365
- Give a column its own input, a customer lookup for instance. Return
366
- `undefined` for the columns you leave to the editor:
367
-
368
- ```tsx
369
- const renderValueInput: RenderValueInput = ({ table, column, value, onChange }) => (
370
- table.name === 'orders' && column.name === 'customer_id'
371
- ? <CustomerPicker value={value} onChange={onChange} />
372
- : undefined
373
- );
374
- ```
375
-
376
- Translate any of the text, and set a font to go with it:
377
-
378
- ```tsx
379
- const messages = { addCondition: 'เพิ่มเงื่อนไข', sectionWhere: 'เงื่อนไข' };
380
- <QueryBuilder messages={messages} fontFamily="Kanit, sans-serif" … />
381
- ```
382
-
383
- Colors are CSS variables on `.qb-root`, or the `theme` prop. The canvas's
384
- own parts (zoom buttons, edges, handles) follow them too:
385
-
386
- ```css
387
- .qb-root { --qb-accent: #e91e63; --qb-canvas-bg: #fafafa; }
388
- ```
389
-
390
- The editor's CSS stays inside `.qb-root`, and your page's global CSS
391
- doesn't get in. To use a component library other than MUI, see
392
- [`docs/ui-adapters.md`](docs/ui-adapters.md).
393
-
394
- ## Packages and entry points
395
-
396
- | Import | What it is |
397
- |---|---|
398
- | `@nongt/visql/mui` | `QueryBuilder` with the MUI kit. Needs `@mui/material` and emotion. |
399
- | `@nongt/visql/mui-date-pickers` | MUI X date and time pickers to plug in through `components`. Needs `@mui/x-date-pickers` and date-fns 3 or 4. Without them you get the browser's own inputs. |
400
- | `@nongt/visql/mui-date-pickers/host` | The same pickers, using your app's own MUI X `LocalizationProvider` around the editor instead of bringing date-fns. Use these when your app is on another date-fns (2, say). |
401
- | `@nongt/visql` | The editor without a UI kit (pass `components`), plus every type and helper. |
402
- | `@nongt/visql/style.css` | The stylesheet. Import it once. |
403
- | `@nongt/visql/core` | The query logic alone: no React, no DOM. |
404
- | `@nongt/visql/sql-import` | `importSql`, for reading SQL someone wrote back into a query. |
405
- | `@nongt/visql/fixtures` | Contract fixtures for your own tests. |
406
- | `@nongt/visql-core` | The last three as a package of their own, for a server. |
407
-
408
- Every peer dependency is optional, since the server-side entries need none
409
- of them. It's ES modules only. From CommonJS, use Node 20.19+ or 22.12+. The
410
- types work with TypeScript's older `moduleResolution: "node"` as well as
411
- `bundler` and `nodenext`.
412
-
413
- ## More documentation
414
-
415
- - [Query reference](docs/query-reference.md): everything a query can hold
416
- (EXISTS, IN, BETWEEN, sub queries, unions, WITH, measures), the helpers
417
- that change a query from code, and parameters.
418
- - [Checking queries](docs/checking-queries.md): `validateQuery`, sums that
419
- are safe in a pivot grid, and contract fixtures.
420
- - [Backend integration](docs/backend-integration.md): the server side, step
421
- by step.
422
- - [Importing SQL](docs/sql-import.md): turning hand-written SQL into a
423
- query.
424
- - [Showing the SQL and problems](docs/sql-preview.md): a SQL view linked to
425
- the editor both ways, and a problems list of your own.
426
- - [Helping users find a table](docs/table-pickers.md): grouping the table
427
- pickers, a description for each table, your own options, buttons or
428
- picker, and adding a table from your own page.
429
- - [UI adapters](docs/ui-adapters.md): using a component library other than
430
- MUI.
431
- - [`docs/design/`](docs/design): why some things work the way they do.
432
-
433
- ## Playground
434
-
435
- The repository's demo app runs the full editor on a sample database, with
436
- the SQL beside it in each dialect and a panel of options to try (read-only,
437
- right-to-left, a light theme, Thai text, hidden tables).
438
-
439
- ```bash
440
- pnpm install
441
- pnpm dev
442
- ```
83
+ The editor fills its container, so give the container a height. `astToSql`
84
+ here writes the values into the SQL, which is fine for showing it. To run a
85
+ query, send it to your server, check it with `validateQuery` and write it
86
+ with `astToParameterizedSql`.
87
+
88
+ ## Documentation
89
+
90
+ Everything else is on the [website](https://nongt.github.io/visql/), which
91
+ runs the editor live in its examples:
92
+
93
+ - [Getting started](https://nongt.github.io/visql/start/browser/), in the
94
+ browser and [on the server](https://nongt.github.io/visql/start/server/)
95
+ - [Guides](https://nongt.github.io/visql/guides/backend-integration/), from
96
+ the backend to customizing the editor
97
+ - [Query reference](https://nongt.github.io/visql/reference/), everything a
98
+ query can hold
99
+ - [API reference](https://nongt.github.io/visql/api/), every package and
100
+ entry point
101
+ - [Playground](https://nongt.github.io/visql/playground/), the full editor
102
+ with every option to try
103
+
104
+ To run the playground from a clone of the repository, `pnpm install` and
105
+ then `pnpm dev`.
443
106
 
444
107
  ## License
445
108
 
@@ -4,7 +4,7 @@ import { DatePicker as g } from "@mui/x-date-pickers/DatePicker";
4
4
  import { c as x } from "./calendarDate-CYlr9TvX.js";
5
5
  import { DateTimePicker as p } from "@mui/x-date-pickers/DateTimePicker";
6
6
  import { TimePicker as U } from "@mui/x-date-pickers/TimePicker";
7
- import { t as T } from "./tokens-BTaVMSOx.js";
7
+ import { t as T } from "./tokens-DV5rTGMj.js";
8
8
  const D = ".MuiPickersOutlinedInput-notchedOutline";
9
9
  function f(r, i = !1) {
10
10
  return {