@nongt/visql 0.4.2 → 0.6.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 (31) hide show
  1. package/README.md +233 -715
  2. package/dist/MuiTimePicker-BjywwrRm.js +112 -0
  3. package/dist/{PipelineEditor-BoFPDUmi.js → PipelineEditor-6fohlut2.js} +3247 -3209
  4. package/dist/{core-api-BRJV9MUQ.js → core-api-Bg_I2ak0.js} +437 -426
  5. package/dist/core.js +2 -2
  6. package/dist/index.js +4 -4
  7. package/dist/{issueLocation-CWUdTtCh.js → issueLocation-CD9XckYv.js} +1276 -1193
  8. package/dist/mui-date-pickers-host.js +20 -0
  9. package/dist/mui-date-pickers.js +14 -113
  10. package/dist/mui.js +161 -155
  11. package/dist/style.css +1 -1
  12. package/dist/types/adapters/mui/MuiDatePicker.d.ts +2 -3
  13. package/dist/types/adapters/mui/QueryBuilder.d.ts +2 -2
  14. package/dist/types/adapters/mui/components.d.ts +2 -2
  15. package/dist/types/adapters/mui/hostPickers.d.ts +8 -0
  16. package/dist/types/adapters/mui/muiPickers.d.ts +6 -5
  17. package/dist/types/core/JoinKeysContext.d.ts +6 -0
  18. package/dist/types/core/components/flow/GroupByFlowNode.d.ts +3 -0
  19. package/dist/types/core/components/flow/SelectFlowNode.d.ts +3 -0
  20. package/dist/types/core/i18n/defaultMessages.d.ts +2 -0
  21. package/dist/types/core/i18n/messages.d.ts +2 -0
  22. package/dist/types/core/joinOnly.d.ts +9 -0
  23. package/dist/types/core/queryValidation.d.ts +5 -2
  24. package/dist/types/core/schema.d.ts +7 -0
  25. package/dist/types/core/ui/index.d.ts +2 -2
  26. package/dist/types/core/ui/types.d.ts +5 -4
  27. package/dist/types/features/queryEditor/PipelineEditor.d.ts +1 -4
  28. package/dist/types/features/queryEditor/SubFlowPanel.d.ts +5 -1
  29. package/dist/types/mui-date-pickers-host.d.ts +12 -0
  30. package/dist/types/mui-date-pickers.d.ts +12 -3
  31. package/package.json +36 -11
package/README.md CHANGED
@@ -1,62 +1,60 @@
1
1
  # visql
2
2
 
3
- A visual SQL query builder for React. Users build a query on a node canvas —
4
- tables and joins, WHERE conditions, selected columns — without writing SQL,
5
- and your app gets a plain JSON query it can store, reload and turn into SQL.
6
-
7
- - **FROM / JOIN**: pick a base table and add more. Join conditions are
8
- suggested from your schema's foreign keys, and a table that doesn't relate
9
- directly to the query brings the tables in between with it. A **derived
10
- table** (a query of its own, joined like a table) is edited on a canvas
11
- of its own.
12
- - **WHERE**: conditions and nested AND / OR / NOT groups, reordered by
13
- dragging.
14
- - **Related rows (EXISTS)**: keep rows that have, or don't have, related
15
- rows ("stores with a sale of tea"), picked from the tables your schema's
16
- foreign keys relate, with conditions of their own. No repeated rows,
17
- unlike a JOIN.
18
- - **IN (sub query)**: compare with the column of a query of its own
19
- (`customer_id IN (SELECT id FROM customer WHERE city = 'Bangkok')`), and
20
- NOT IN. Off by default (`subqueries={{ in: true }}`).
21
- - **NULL checks**: `IS NULL` / `IS NOT NULL`. Comparisons follow plain
22
- SQL: one against a NULL matches nothing, even under NOT. To include the
23
- blanks, add `OR … IS NULL`.
24
- - **GROUP BY / HAVING**: summarize with SUM, COUNT (rows, values or
25
- distinct values), AVG, MIN, MAX and STRING_AGG (a group's values
26
- joined into one text; MySQL's GROUP_CONCAT), and the other columns become the
27
- group keys by themselves: `city` beside `SUM(total)` groups by city.
28
- Group Rows shows once a column sums something up, to add keys that
29
- aren't columns and keep only the groups that match a condition. A
30
- column that can't be a key (one mixing a sum and a plain column) is
31
- flagged before the database rejects it.
32
- - **SELECT**: a list of columns, each one any expression, with an alias,
33
- and DISTINCT.
34
- - **ORDER BY, LIMIT/OFFSET**: sort keys (any expression, ascending or
35
- descending) and row counts — `LIMIT`/`OFFSET` for MySQL and PostgreSQL,
36
- `TOP` / `OFFSET … FETCH` for SQL Server.
37
- - **Expressions everywhere**: fields, values, SQL functions, arithmetic,
38
- `IF` and `CASE`, edited on their own sub-canvas when they grow.
39
- - **Run**: with `onRun`, a Run button (and Ctrl/⌘+Enter) hands the query
40
- to your backend and shows the rows it returns under the canvas.
41
- - **Undo / redo** (Ctrl/⌘+Z), **SQL for MySQL, SQL Server and PostgreSQL**,
42
- read-only mode, per-user table/column visibility, translatable text,
43
- themeable colors, and a swappable UI kit (MUI by default).
3
+ visql is a React component for building SQL queries without writing SQL.
4
+ People lay a query out on a canvas (the tables, how they join, the
5
+ conditions, the groups, the columns they want) and your app gets back a
6
+ JSON description of it. You can store that, open it again later, check
7
+ it, and turn it into SQL for MySQL, PostgreSQL or SQL Server.
8
+
9
+ I built it for report screens, where the people asking the questions know
10
+ the data but not SQL. Because the query travels as data rather than as SQL,
11
+ nothing a browser sends is ever run as SQL: your backend checks the query
12
+ and writes the SQL itself.
13
+
14
+ > visql is published as is, under the MIT license. I'm not taking issues or
15
+ > pull requests at the moment.
16
+
17
+ ## What's in it
18
+
19
+ The canvas follows the order a database works in: FROM, then WHERE, then
20
+ grouping, then SELECT, then sorting and paging.
21
+
22
+ - Tables and joins, with the join condition suggested from your foreign
23
+ keys. Pick a table that isn't directly related and the tables in between
24
+ come with it.
25
+ - Conditions in nested AND / OR / NOT groups, reordered by dragging. That
26
+ includes IN, BETWEEN, IS NULL, and EXISTS for "customers with at least
27
+ one order over 1,000".
28
+ - GROUP BY and HAVING. Add a SUM next to a column and the column becomes a
29
+ group key by itself.
30
+ - Any expression as a value or a column: functions, IF, CASE, arithmetic.
31
+ When one gets big, it opens on a canvas of its own.
32
+ - Sub queries, UNION ALL and WITH, each edited on its own canvas. These are
33
+ off until you turn them on.
34
+ - A Run button that hands the query to your backend and shows the rows it
35
+ returns.
36
+ - Undo and redo, read-only mode, per-user table and column visibility,
37
+ translations, themes, right-to-left and vertical layouts, and a
38
+ swappable UI kit (MUI is the default).
44
39
 
45
40
  ## Install
46
41
 
47
42
  ```bash
48
- # the editor
49
43
  pnpm add @nongt/visql react react-dom @xyflow/react iconoir-react
50
- # for the MUI preset (the usual choice):
44
+ # the MUI kit, which is what most apps use
51
45
  pnpm add @mui/material @emotion/react @emotion/styled @emotion/cache
46
+ ```
47
+
48
+ On a server you only need the query logic, which comes as its own package
49
+ with no dependencies:
52
50
 
53
- # a backend: the query logic alone, nothing else comes with it
51
+ ```bash
54
52
  pnpm add @nongt/visql-core
55
53
  ```
56
54
 
57
- > **No support.** @nongt/visql is published as is, under the MIT license, and isn't taking issues or contributions for now. Both packages are released together, always with the same version.
58
-
59
- Every peer is optional, since the backend entries need none of them. The editor needs `react`, `react-dom`, `@xyflow/react` and `iconoir-react`; the MUI kit needs MUI and emotion. `@nongt/visql-core` has no dependencies at all. A backend should install `@nongt/visql-core` rather than `@nongt/visql`: it holds only what a backend uses, and some registries (GitHub Packages) drop `peerDependenciesMeta`, which would make every peer required.
55
+ The editor works with React 18.2 or later, and 19. Both packages are always
56
+ released together with the same version. Keep the editor and the server on
57
+ the same version so the server can read every query the editor writes.
60
58
 
61
59
  ## Quick start
62
60
 
@@ -82,12 +80,12 @@ export function ReportEditor() {
82
80
  }
83
81
  ```
84
82
 
85
- The editor fills its container, so give it a height.
83
+ The editor fills its container, so give the container a height.
86
84
 
87
- ## The schema
85
+ ## Describing your database
88
86
 
89
- Describe the database the user builds queries against. Tables and columns
90
- fill the pickers. Relations (foreign keys) drive join suggestions.
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.
91
89
 
92
90
  ```ts
93
91
  import type { DatabaseSchema } from '@nongt/visql';
@@ -105,7 +103,7 @@ export const schema: DatabaseSchema = {
105
103
  name: 'status',
106
104
  label: 'Status',
107
105
  type: 'varchar',
108
- // Values compared against this column come from a dropdown.
106
+ // Values compared with this column are picked from a list.
109
107
  options: [
110
108
  { value: 'open', label: 'Open' },
111
109
  { value: 'shipped', label: 'Shipped' },
@@ -123,57 +121,50 @@ export const schema: DatabaseSchema = {
123
121
  },
124
122
  ],
125
123
  relations: [
126
- // orders.customer_id references customers.id — declare each key once,
127
- // from the "many" side.
124
+ // orders.customer_id points at customers.id. Declare each key once,
125
+ // from the table that holds it.
128
126
  { fromTable: 'orders', fromColumn: 'customer_id', toTable: 'customers', toColumn: 'id' },
129
127
  ],
130
128
  };
131
129
  ```
132
130
 
133
- Column types: `varchar`, `integer`, `decimal`, `date`, `dateTime`, `time`,
134
- `boolean`. A value compared with a column gets the input of its type. The
135
- editor checks the schema when it changes (`validateSchema`) and reports
136
- problems through `onSchemaIssues`, or `console.warn` without it.
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.
137
135
 
138
- **A date or time kept as text.** Some databases keep a date or a time as
139
- text in a form of their own: a time as `'09:30'`, a day as `'20261003'`.
140
- Declare the column as the date or time it is, with that form as its
141
- `format`:
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:
142
145
 
143
146
  ```ts
144
- { name: 'opens_at', label: 'Opens At', type: 'time', format: 'HH:mm' }
145
- { name: 'opened_on', label: 'Opened On', type: 'date', format: 'YYYYMMDD' }
147
+ { name: 'employee_key', label: 'Employee key', type: 'integer', joinOnly: true }
146
148
  ```
147
149
 
148
- - **Tokens:** `YYYY`, `MM` (month), `DD`, `HH` (00–23), `mm` (minute),
149
- `ss`. The rest is written as it is.
150
- - **In the editor:** users still pick a date or a time, and the query keeps
151
- it its own way (a time as `'09:30:00'`).
152
- - **In the SQL:** pass the schema to `astToSql` / `astToParameterizedSql`
153
- (`{ schema }`). A value compared with the column, or in IN's list, is
154
- written in its form, a param's value too.
155
- - **Ordering:** `<` and `>` compare the text, so only a form that goes from
156
- the largest unit down (`YYYY-MM-DD`, `HH:mm`) orders the way the dates do.
157
- - **`validateSchema`** reports a format on a column of another type, one
158
- with no tokens, and a time's format with a day in it (`invalidFormat`).
159
-
160
- Relations also tell the editor which side of a join is "many": the table
161
- holding the foreign key. Joining from the one side to the many side
162
- (`orders` → `order_items`) repeats each row of the one side, once per
163
- matching row. A SUM, AVG or COUNT over a repeated table's columns then
164
- comes out too high, without any error. The editor flags it on the FROM node,
165
- and `validateQuery` reports a `fanOut` warning. A join whose condition isn't
166
- a declared relation can't be told apart, so it isn't flagged.
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.
167
154
 
168
- ## The query value
155
+ Relations also tell the editor which side of a join has many rows. Joining
156
+ `orders` to `order_items` repeats each order once per item, so a SUM of the
157
+ order totals comes out too high without any error. The editor warns about
158
+ that on the canvas, and `validateQuery` reports it as `fanOut`.
169
159
 
170
- `onChange` hands you a `QueryValue`: plain JSON, except for a literal value that's a `Date` or a `bigint`. Store it with `saveQuery` (see *Storing a query* below).
160
+ ## The query value
171
161
 
172
- A `Date` in a query is a **calendar day or a wall-clock time, not an instant**, held in its UTC fields: 3 Oct 2026 is `2026-10-03T00:00:00Z`, so it's the same day wherever the query is built, stored or turned into SQL (a browser in Bangkok, a server in UTC). SQL writes it without a zone: `'2026-10-03'`, or `'2026-10-03 09:30:00'` with a time. In code, `new Date('2026-10-03')` is that day (JavaScript reads a date-only text as UTC); `new Date(2026, 9, 3)` is local midnight, the day before east of UTC. A query that needs a time zone is a job for a parameter.
162
+ `onChange` gives you a `QueryValue`. It's plain JSON, apart from date and
163
+ `bigint` values:
173
164
 
174
165
  ```ts
175
166
  interface QueryPipeline {
176
- id: string; // the query's identity — stays the same through every edit
167
+ id: string; // stays the same through every edit
177
168
  from: { table: string; alias?: string };
178
169
  joins: { id: string; table: string; joinType: 'inner' | 'left' | 'right' | 'full'; on?: ExpressionNode }[];
179
170
  where?: ExpressionNode;
@@ -182,671 +173,189 @@ interface QueryPipeline {
182
173
  select: { id: string; expression: ExpressionNode; alias?: string }[];
183
174
  distinct?: boolean;
184
175
  orderBy?: { id: string; expression: ExpressionNode; direction: 'asc' | 'desc' }[];
185
- limit?: number; // non-negative integers
176
+ limit?: number;
186
177
  offset?: number;
187
178
  }
188
- type QueryValue = QueryPipeline | { id: string }; // { id } = no base table chosen yet
179
+ type QueryValue = QueryPipeline | { id: string }; // { id } while no table is picked yet
189
180
  ```
190
181
 
191
- - **Controlled** (`value` + `onChange`): the editor shows exactly `value`.
192
- Pass back what `onChange` gave you, as you would with an `<input>`.
193
- - **Uncontrolled** (`defaultValue`, optionally `onChange`): the editor keeps
194
- its own state.
195
- - `value={null}` starts a new empty query. A query with a different `id`
196
- starts a fresh undo history. After loading different content into the
197
- same query, call `resetHistory()` on the ref.
182
+ Use it the way you'd use an `<input>`: pass `value` and `onChange` and hand
183
+ back what you're given, or pass `defaultValue` and let the editor keep its
184
+ own state. `value={null}` starts an empty query. A query with a different
185
+ `id` starts a new undo history.
198
186
 
199
- ### Storing a query
187
+ A date in a query is a calendar day or a wall-clock time, not a moment in
188
+ time. 3 October 2026 is stored as `2026-10-03T00:00:00Z` and written to SQL
189
+ as `'2026-10-03'`, the same day whether the browser is in Bangkok or the
190
+ server runs in UTC. If you build one in code, `new Date('2026-10-03')` is
191
+ that day, but `new Date(2026, 9, 3)` is local midnight, which is the day
192
+ before east of UTC.
200
193
 
201
- ```ts
202
- import { loadQuery, saveQuery, QueryFormatError } from '@nongt/visql/core';
194
+ ### Storing it
203
195
 
204
- db.save(report.id, JSON.stringify(saveQuery(query))); // { version, query }
196
+ ```ts
197
+ import { loadQuery, saveQuery } from '@nongt/visql/core';
205
198
 
206
- const query = loadQuery(JSON.parse(db.load(report.id))); // the same query back
199
+ db.save(report.id, JSON.stringify(saveQuery(query)));
200
+ const query = loadQuery(JSON.parse(db.load(report.id)));
207
201
  ```
208
202
 
209
- - `saveQuery` writes the current format with its version (`QUERY_FORMAT_VERSION`). A `Date` or `bigint` literal is stored as a tagged string, which plain JSON can't carry.
210
- - `loadQuery` gives back exactly what was saved. A query saved by an earlier version of this package is migrated to the current format as it's read (format 2: IN's values as a list, see *IN*; formats 3 and 4 only add unions and shared queries).
211
- - A query saved by a *later* version is refused with a `QueryFormatError` of kind `'newerVersion'`, not guessed at. This happens after a rolled-back deploy, or with two versions running side by side.
212
- - Anything that isn't a stored query gets kind `'invalid'`. A bare query with no version counts as invalid too.
213
- - `loadQuery` doesn't check the query against a schema. Run `validateQuery` after loading: a stored query can name a table or column that has since been removed, and it reports those as `unknownTable` / `unknownColumn` (see *Checking a query*).
203
+ `saveQuery` adds a format version. `loadQuery` upgrades a query saved by an
204
+ older version as it reads it, and refuses one saved by a newer version
205
+ (a `QueryFormatError` of kind `'newerVersion'`) rather than guessing. That
206
+ can happen after a rolled-back deploy. It doesn't check the query against
207
+ your schema, because a table may have been dropped since the query was
208
+ saved, so run `validateQuery` after loading.
214
209
 
215
- ## SQL output
210
+ ## Getting SQL out
216
211
 
217
- To **run** a query, get it with bound parameters — the values travel separately from the SQL, the safe way to pass them to a database driver:
212
+ To run a query, generate it with parameters. The values go to the driver
213
+ separately from the SQL text:
218
214
 
219
215
  ```ts
220
216
  import { astToParameterizedSql } from '@nongt/visql';
221
217
 
222
218
  const { sql, params } = astToParameterizedSql(query, 'postgres');
223
- // sql: SELECT * FROM "orders" WHERE "orders"."status" = $1 AND "orders"."total" > $2
224
- // params: ['open', 100]
219
+ // SELECT * FROM "orders" WHERE "orders"."status" = $1 AND "orders"."total" > $2
220
+ // ['open', 100]
225
221
  await pg.query(sql, params);
226
222
  ```
227
223
 
228
- Placeholders are `?` for MySQL, `$1, $2, …` for PostgreSQL and `@p1, @p2, …` for SQL Server. A date is sent as text, `'2026-10-03'` or `'2026-10-03 09:30:00'`, never as a `Date`: drivers write a `Date` in the server's own time zone (`pg` and `mysql2` by default), which would shift a calendar day or wall-clock time. Each database reads the text as the column's type. Pass the schema (`{ schema }`) when it has columns with a `format`. Every value becomes a parameter: in WHERE, JOIN ON and SELECT, including inside functions, `IF`/`CASE` and `IN` lists. Table and column names are quoted (with the quote character escaped), and function names, date units and type names are checked against plain patterns, since those can't be parameters.
224
+ Every value becomes a parameter, wherever it is: `?` in MySQL, `$1` in
225
+ PostgreSQL, `@p1` in SQL Server. Names are quoted. Function names and other
226
+ parts that can't be parameters are checked against plain patterns. Dates
227
+ are sent as text, because drivers would otherwise shift a `Date` into the
228
+ server's time zone.
229
229
 
230
- To **show** a query, `astToSql` writes the values inline (strings quoted and escaped):
230
+ To show a query to someone, `astToSql(query, 'mysql')` writes the values
231
+ inline.
231
232
 
232
- ```ts
233
- import { astToSql } from '@nongt/visql';
233
+ If the names in your schema aren't the database's real ones (handy when you
234
+ want saved queries to survive a rename), pass `resolveName`:
234
235
 
235
- astToSql(query, 'mysql'); // 'mysql' | 'mssql' | 'postgres'
236
+ ```ts
237
+ const physical: Record<string, string> = {
238
+ timecard: 'fact_timecard',
239
+ 'timecard.minutes': 'worked_minutes',
240
+ };
241
+ astToParameterizedSql(query, 'mysql', {
242
+ resolveName: (table, column) => physical[column ? `${table}.${column}` : table] ?? column ?? table,
243
+ });
244
+ // FROM fact_timecard AS timecard ... timecard.worked_minutes
236
245
  ```
237
246
 
238
- ## On the backend
247
+ ## On the server
239
248
 
240
- `@nongt/visql/core` has the query logic without the editor — no React, no DOM, no dependencies — and so does **`@nongt/visql-core`**, the same entries as a package of their own, for a backend to install alone. A server can take over everything after the user edits: store the query JSON, and turn it into parameterized SQL itself. The frontend then only ever handles the query structure, never SQL.
249
+ Treat a query that arrives from a browser, or comes out of your database,
250
+ as untrusted. The editor's `tableFilter` and `columnFilter` only hide things
251
+ on screen. The check that actually enforces them is `validateQuery` on the
252
+ server.
241
253
 
242
254
  ```ts
243
- // server
244
- import {
245
- astToParameterizedSql, hasBaseTable, validateQuery, type QueryValue,
246
- } from '@nongt/visql/core';
255
+ import { astToParameterizedSql, hasBaseTable, validateQuery } from '@nongt/visql-core';
247
256
 
248
257
  app.get('/reports/:id/rows', async (req, res) => {
249
- const query = await reports.load(req.params.id); // the JSON onChange produced
250
- // A stored or received query is untrusted: check it against the schema and
251
- // this user's permissions — the same filters the editor was given.
258
+ const query = await reports.load(req.params.id);
252
259
  const issues = validateQuery(schema, query, {
253
260
  tableFilter: (t) => req.user.canSee(t.name),
254
261
  });
255
- // Errors mean "don't run it"; warnings (fan-out, no LIMIT…) can run.
262
+ // Errors mean don't run it. Warnings (no LIMIT, rows a join repeats) can run.
256
263
  if (issues.some((i) => i.severity === 'error')) return res.status(400).json({ issues });
257
- const valid = query as QueryValue;
258
- if (!hasBaseTable(valid)) return res.json([]); // nothing chosen yet
264
+ if (!hasBaseTable(query)) return res.json([]);
259
265
 
260
- const { sql, params } = astToParameterizedSql(valid, 'postgres');
266
+ const { sql, params } = astToParameterizedSql(query, 'postgres');
261
267
  res.json(await db.query(sql, params));
262
268
  });
263
269
  ```
264
270
 
265
- **A step-by-step guide** for a backend (loading, checking, scoping every query to a tenant, params, writing the SQL, grids that sum rows themselves, combining two tables of facts, contract fixtures in CI) is in [`docs/backend-integration.md`](docs/backend-integration.md).
266
-
267
- ### Changing a query from code
268
-
269
- The same functions the editor uses are exported, so a change made in code behaves exactly like one made in the UI: ids, suggested join conditions, intermediate tables, and tables a condition refers to get joined. Build expressions with `expr`.
270
-
271
- ```ts
272
- import { addCondition, astToParameterizedSql, expr } from '@nongt/visql/core';
273
-
274
- // (their WHERE) AND status = :status
275
- const scoped = addCondition(schema, query,
276
- expr.eq(expr.field('orders', 'status'), expr.param('status')));
277
-
278
- const { sql, params } = astToParameterizedSql(scoped, 'postgres', {
279
- values: { status: 'open' }, // a param without a value is an error
280
- });
281
- ```
282
-
283
- **Scoping to a tenant: `scopeQuery`, not `addCondition`.** `addCondition` only adds to the query's WHERE (and a FROM union's queries). A tenant or site limit must reach every query body that reads such a table: sub queries, measures, unions joined or nested, IN sub queries and EXISTS. A body left out still filters by another tenant's rows ("who worked overtime *anywhere*"). `scopeQuery(schema, query, { requires, condition })` does that, and throws a `ScopeError` naming the body it can't scope. `unscopedBodies` checks a query. See [`docs/backend-integration.md`](docs/backend-integration.md), step 3.
284
-
285
- Also: `addJoin`, `removeJoin`, `addSelectItem`, `addGroupBy`, `setHaving`, `addOrderBy`, `setPaging` (LIMIT/OFFSET), `setDistinct`, `setBaseTable`, `requireBaseTable`. In a controlled editor, pass the result back as `value`: it shows, and it's one undo step.
286
-
287
- **Grouped automatically.** Once a query sums anything up (an aggregate in SELECT, HAVING or ORDER BY), each SELECT column with no aggregate in it becomes a GROUP BY key, marked `fromSelect: <the column's id>`. That key follows its column: it changes with it, and goes with it, or once nothing is summed up any more. A key without `fromSelect` is one of your own and is never touched; a column it already covers gets none. ORDER BY keys never become keys, since that would change the grouping unseen. In a grouped query, a field in HAVING or a sort key that isn't inside an aggregate can only be one value per group, so the editor offers only the keys' columns there (inside `SUM(...)` and the like, any column), and SELECT's columns that sum something up, by name. Picking one of those puts a copy of its formula in, marked `fromSelect: <the column's id>`, which follows the column. The SQL names the column by its alias in MySQL (`HAVING sales > 1000`) and repeats the formula in PostgreSQL and SQL Server, which don't take an alias there (`HAVING SUM(total_price) > 1000`). The editor applies this to every edit, and so do the helpers (`addSelectItem`, `addGroupBy`, `addCondition`, `setHaving`, `addOrderBy`). A query built by hand keeps what it has; `validateQuery` still reports a column that isn't grouped.
288
-
289
- **Related rows (EXISTS).** To keep rows by what's related to them, without the repeated rows a JOIN would bring, add an EXISTS. Its `link` matches a related row to the outer one. Its own conditions name only its own tables; a table they use that it doesn't have is joined inside it, through the relations.
290
-
291
- ```ts
292
- // Customers with a sale in Bangkok
293
- const withSales = addCondition(schema, query, expr.exists(
294
- { from: { table: 'sale_transaction' },
295
- where: expr.eq(expr.field('store', 'city'), expr.value('Bangkok')) }, // joins store inside it
296
- expr.eq(expr.field('sale_transaction', 'customer_id'), expr.field('customer', 'id')),
297
- ));
298
- // Without one: expr.not(expr.exists(…)) — NOT EXISTS
299
- ```
300
-
301
- In the editor, the **EXISTS** button on a group of conditions lists the related tables (the `exists` prop decides which, and where it's offered). The node reads "Has Sale Transaction linked by Store · Store ID where …"; its own conditions open on a canvas of their own, whose field pickers list its tables and those it can reach through the relations (a table named like one of the outer query's is left out). NOT around it is NOT EXISTS.
302
-
303
- `validateQuery` checks the scoping:
304
- - its conditions name its own tables only;
305
- - a table it shares with the outer query needs an alias (`ambiguousTable`);
306
- - no aggregates inside it;
307
- - it's a condition, never a value.
308
-
309
- See `docs/design/exists-conditions.md`.
310
-
311
- **IN.** IN's values are a list, one item each: `{ type: 'list', items: [...] }`, written `x IN (1, 2, 3)` (each a placeholder in parameterized SQL). In code, `expr.in(field, [1, 2, 3])`, or `expr.in(field, expr.list(1, expr.param('id')))` for expressions such as params. A param in the list gets the type of the column IN compares with (`queryParams`).
312
-
313
- **BETWEEN.** A range is one condition, `x BETWEEN low AND high` (both bounds included): `operator: 'BETWEEN'` with its two bounds as a list of two, low then high. In code, `expr.between(field, 1, 10)`, or with expressions such as params or relative dates: `expr.between(field, expr.param('from'), expr.param('to'))`. NOT BETWEEN is `expr.not(expr.between(…))`. Both bounds take the compared column's type, for params and values alike. The editor offers BETWEEN for numbers, dates and times, with two inputs, and on text only as the `betweenOnText` prop says; going to or from IN keeps the values.
314
-
315
- In the editor, each value is a chip, in the kit's `ListInput` (see *UI adapters*). The MUI kit's is an Autocomplete:
316
- - **Adding:** a value is typed and added on Enter once it reads as one of the column's type. A date is typed `YYYY-MM-DD`, as the placeholder says. A column's options are picked instead.
317
- - **Leaving the field:** what's typed is added if it reads as a value, else dropped.
318
- - **Many values:** the field stays one row high, with `+N` for the chips that don't fit, and shows every row while it has focus.
319
-
320
- A kit without a `ListInput`, or a column with a host's own input (`renderValueInput`), gets the editor's own chips with an input of the values' type after them (a date picker for a date), where Enter or **+** adds a value.
321
-
322
- Picking IN turns the value already there into the first item; leaving IN keeps the first item.
323
-
324
- `validateQuery` reports:
325
- - a list anywhere but after IN (`invalidStructure`), or IN with anything else but a list or a sub query;
326
- - an empty list, or a value not filled in, as `incomplete`.
327
-
328
- Queries saved before format 2 had IN's values as one comma-separated text (`'1, 2, 3'`): `loadQuery` reads them into lists.
329
-
330
- **Unions of tables.** A derived table's query can stack the rows of several queries: `{ union: [branch, branch, …], all: true }`, written `(… UNION ALL …) AS alias`. This keeps every detail row of two tables (hours worked and leave taken, say) once, for an app that sums them up itself. A join between the two would repeat them. The design and its decisions are in `docs/design/union-tables.md`.
331
- - **Branches:** each is a derived table's query (`from`, `joins`, `where?`, `select`, …), in a scope of its own, with no ORDER BY or paging.
332
- - **Columns:** the union's columns are its first branch's names. Every branch lists as many, by the same names, in order, of types that go together. `validateQuery` reports `unionColumns` and `unionTypes`.
333
- - **Typed NULLs:** a value only some branches have is a NULL with a type in the others, `{ type: 'literal', value: null, as: 'number' }`. It's written `CAST(NULL AS DECIMAL(38, 10))` or `NULL::numeric`. Without the type, a database may take the column's type from the NULL. In the editor, **Empty** in a value's type menu picks one (a SELECT column, a function's argument, IF/CASE's results; never a comparison), typed as what it replaces.
334
- - **`UNION ALL` or `UNION`:** `all: true` keeps every row; `all: false` writes `UNION`, which merges rows that are the same in every column (e.g. every city with a store or a customer, once). Never use `UNION` for detail rows a grid sums: two equal rows are two records. `addUnionTable` always makes `UNION ALL`.
335
- - **Reading one:** `isUnion(query)` and `branchesOf(query)`. A `QueryPath` reaches a branch as `id#index`.
336
- - **In the editor** (`subqueries={{ union: true }}`, off by default):
337
- - **Adding:** "+ Add Table / Sub Query" gets a group, **Add rows from another table**, listing the tables `unionableTables` gives. Picking one adds its rows (`addUnionTable`, with the options given instead of `true`).
338
- - **The FROM node** lists the union's tables one under another. Each opens its query on a canvas of its own ("Open Store's query"), and has its own remove button (the last one's removes the union). Any table can be removed (`removeUnionTable`). Its own columns (those only it fills) go with it, unless the query reads one in a condition, a join's ON, a group key or a sort key: that column stays, NULL in every row left, so nothing breaks. One table left stays a union of one, so another can be added again (issue 153), and **Make it a plain query** on its row makes it the query's own again (`unwrapUnion`: merged into the query when that keeps its meaning, else a plain sub query).
339
- - **Free-form** (`subqueries={{ union: { free: true } }}`, issue 153): any queries, no relation needed, each a full query of its own (groups, sums) on its own canvas. **Create Union** (an empty query's base-table picker) starts one. **Union with another query** (for a query of tables) makes the query the union's first and opens the second's canvas. **Add query** on the union's row adds another. A new query is added once its first table is picked, with a typed NULL for each of the union's columns, shown as "Empty for this table" until filled in. In code: `createUnion`, `unionWithQuery`, `addUnionBranch`, `unionName`. A union of one query is a union too: one being made, or with the others removed. Unions can be made on a sub query's canvas too, and joined (**Join a union**, `addUnionJoin`). The union's row offers **Leave out duplicate rows** (`UNION`, `setUnionAll`). A column renamed on any of its queries' canvases is renamed in the others and wherever the query reads it (`keepUnionsAligned`; `renameUnionColumn` in code). `removeUnionTable(query, index, unionId)` removes a join's union's query; with one left, the join reads that query.
340
- - **On a table's canvas:** conditions are that table's own. A column added, removed, renamed or reordered there is the same in the other tables, as a typed NULL where they have no value (`keepUnionsAligned`, run on every edit by `settleQuery`, so code edits keep a union whole too).
341
-
342
- **Building a union: `addUnionTable`.** Lining branches up by hand is easy to get silently wrong, so build a union with the helper. Take hours worked (`timecard`) and leave taken (`leave`), both per employee:
343
-
344
- ```ts
345
- import { addUnionTable, unionableTables, unionTableColumns } from '@nongt/visql/core';
346
-
347
- // hours: FROM timecard JOIN employee, SELECT employee.name, timecard.minutes
348
- const both = addUnionTable(schema, hours, {
349
- table: 'leave',
350
- columns: [{ expression: expr.field('leave', 'days') }], // its own columns
351
- where: expr.compare(expr.field('leave', 'days'), '>', expr.value(0)), // its own condition
352
- });
353
- // SELECT stacked.name, stacked.minutes, stacked.days
354
- // FROM (SELECT employee.name, timecard.minutes, NULL AS days FROM timecard …
355
- // UNION ALL
356
- // SELECT employee.name, NULL AS minutes, leave.days FROM leave …) AS stacked
357
- ```
358
-
359
- - **The first call** turns a query of one table's detail rows into the union. The query has no aggregates, GROUP BY, HAVING, DISTINCT or ORDER BY; LIMIT and OFFSET stay on it. Later calls add a branch.
360
- - **Shared columns:** a column of a table every branch's table reaches through the relations (the employee, here) is filled in every branch. The new branch joins what it needs.
361
- - **Own columns:** a column of a branch's table itself (`minutes`, `days`) is filled in its own branch and is a typed NULL in the others. A grid's SUM, AVG or COUNT of it then skips the other tables' rows.
362
- - **Conditions:**
363
- - One on shared tables is copied into the new branch.
364
- - One on a branch's own table stays in its branch.
365
- - One naming both can't be placed: it throws rather than leave a branch unfiltered.
366
- - **`addCondition` on a query reading such a union** puts a condition naming tables into **every** branch. (To scope a query to a tenant, use `scopeQuery`, which also reaches unions that are joined or inside sub queries.) It throws, changing nothing, when a branch can't reach a table it names. A condition naming the union (`stacked.name = …`) is the outer query's own.
367
-
368
- The options (the fourth argument):
369
- - **`unshared`: a shared column the new table can't reach.** Hours by project unioned with leave, which has no project, is the example.
370
- - `'refuse'` (the default): it throws, naming the column. The union only ever has what every table reaches.
371
- - `'null'`: it's a typed NULL in that branch, and a grid shows leave under "(No value)" for project. **Beware**: a condition on that column outside the union (`stacked.project = 'Alpha'`) drops every leave row, since they're all NULL there.
372
- - **`source: true`** adds a `source` column, each branch's label (`label` in the spec, else the table's label). It tells the tables' rows apart, for drill-down and as a pivot dimension. Off by default.
373
- - **`rowMarkers: true`** adds a `rows_<table>` column per table: 1 in its own branch, NULL in the others. A COUNT of it counts that table's rows, which COUNT(*) can't. Off by default.
374
- - **`alias`:** the union's name (default `stacked`).
375
-
376
- Helpers:
377
- - `unionableTables(schema, query, { unshared })` lists the tables `addUnionTable` would take, worked out from the relations.
378
- - `unionTableColumns(schema, query)` gives each column of the union: its kind (`shared`, `own`, `source`, `rows`), the tables that fill it, and those that leave it NULL. An app can label "(No value)" knowingly with it.
379
-
380
- **IN (sub query).** IN's right side can a query of its own picking one column: `{ type: 'subquery', id, query }` (`query` as a derived table's: `from`, `joins`, `where?`, `groupBy?`, `having?`, `select`), written `x IN (SELECT …)`. NOT IN is a NOT around it, written `x NOT IN (SELECT …)`. Its tables are its own: it isn't linked to the query around it. `validateQuery` checks it as a query of its own:
381
- - one column, no more or fewer (`subqueryColumns`);
382
- - only as IN's right side;
383
- - a warning on NOT IN (`notInSubquery`), which keeps no rows at all once the sub query gives a single NULL (NOT EXISTS doesn't have this trap).
384
-
385
- That trap is why the editor offers it only when asked: `subqueries={{ in: true }}` adds **Sub query** to the type menu of IN's value. Like **Create Sub Query**, its canvas opens empty: its first table makes it, with the column that links it to the field on the left (by the relations) already picked, and leaving before that adds nothing. It takes one column. It reads `(SELECT id FROM customer)` on the condition, with the button that opens it again. In code:
386
-
387
- ```ts
388
- expr.in(expr.field('sale_transaction', 'customer_id'), expr.subquery({
389
- from: { table: 'customer' },
390
- select: expr.field('customer', 'id'),
391
- where: expr.eq(expr.field('customer', 'city'), expr.value('Bangkok')),
392
- }))
393
- // NOT IN: expr.not(expr.in(…))
394
- ```
395
-
396
- Its params are the query's (`queryParams`, `fillParams`), its names are resolved in its own scope, and it's grouped automatically like any query.
397
-
398
- **Derived tables.** A join can be a query of its own instead of a table: `{ id, alias, joinType, query: { from, joins, where?, groupBy?, having?, select }, on }`, written `JOIN (SELECT …) AS alias`. Outside, its columns are its SELECT's names (an alias, else a field's column). Inside, only its own tables. It's how sums from two fact tables are put side by side without the repeated rows a plain join brings: each summed on its own, then joined. In the editor it's a **sub query**: **Create Sub Query**, last in "+ Add Table / Sub Query", opens its canvas to pick its first table, which adds it LEFT joined as `sub_query_1` (rename it in its FROM row). The icon after its alias opens its own canvas (FROM, conditions, Group Rows, columns — no Sort & Limit), and its columns are offered by name everywhere outside it. One that sums up all its rows (every column an aggregate, no GROUP BY) has a single row — a total to compare with, as in "each store's share of all sales" — and can be **joined to every row**: a `CROSS JOIN`, no condition. It can be the base too (`from: { id, alias, query }`, written `FROM (SELECT …) AS alias`) — "Choose a base table" offers Create Sub Query too — which is how a summary of a summary is made: the average store's sales, as an AVG over a derived table of each store's SUM. So `from` is `TableFrom | DerivedFrom`, as a join is `TableJoin | DerivedJoin`: check `from.query` before reading `from.table`. `validateQuery` checks it as a query of its own, and the fan-out warning knows that one grouped by what its ON matches has one row per match. See `docs/design/drill-across.md`.
399
-
400
- **Shared queries (WITH).** A query can be named once at the top and used like a table anywhere in the query: as the base, joined, inside a sub query or an EXISTS's joins. Written `WITH name AS (…)`, it is edited in one place and changes everywhere it's used. The design is in `docs/design/shared-queries.md` (issue 194).
401
- - **The query:** `shared: [{ id, name, query }]`, on the whole query only, in order. A `WITH` inside a sub query (which PostgreSQL and MySQL allow, SQL Server doesn't) isn't supported on purpose: the top-level list is seen from inside every sub query already, and keeping it there keeps the SQL valid in all three dialects. The import moves such a `WITH` to the top. See the design doc for the reasons. Each may use the ones before it, never itself or a later one (no `RECURSIVE`). Its `query` is a derived table's, or a union.
402
- - **A place using one:** `{ shared: id, alias }` as `from`, or `{ id, shared: id, alias, joinType, on }` as a join. Fields name it by its alias, and its columns are its SELECT's names, as a derived table's. The alias stays when the shared query is renamed, so nothing naming it changes. So `from` is now `TableFrom | DerivedFrom | SharedFrom`: check `from.table !== undefined` before reading it as a schema table.
403
- - **The SQL:** `WITH` first, so its params come first: `WITH sales AS (…) SELECT … JOIN sales AS s ON …`. The same in the three dialects. **MySQL needs 8.0**: 5.7 has no `WITH`.
404
- - **`validateQuery`:**
405
- - each shared query is checked as a derived table's query, in a scope of its own;
406
- - a place using an unknown one is `unknownTable`; one using itself or a later one is `sharedOrder`;
407
- - two with one name is `duplicateTableName`;
408
- - one used nowhere is `unusedShared`, a warning.
409
- - **Everything that walks a query reaches them:** params (`queryParams`), `resolveNames`, column formats, `settleQuery` and `scopeQuery` (each shared query is a body of its own, scoped where it reads a table).
410
- - **In code:**
411
- - `addSharedQuery(query, name, nested)` adds one; `sharedQueryName(schema, query)` names it `shared_query_<n>`.
412
- - `joinSharedQuery(query, body, id)` and `setSharedBase(query, body, id)` use one.
413
- - `makeShared(query, derivedId)` turns a sub query into one; `makeSubQuery(query, path)` copies one back into a place as its own sub query.
414
- - `renameSharedQuery(query, id, name)` renames one.
415
- - `removeSharedQuery(query, id, 'subQueries' | 'removeUses')` removes one: its places become sub queries, or go.
416
- - `sharedUses(query)` says where each is used.
417
- - **Stored format 4:** an older version of the package refuses a query with them instead of reading it wrong.
418
- - **In the editor** (`subqueries={{ shared: true }}`, off by default):
419
- - **Making one:** **Create Shared Query** in "+ Add Table / Sub Query" opens its canvas, empty; its first table makes it, joined where it was asked for (its ON started as a sub query's), or as the base of an empty query.
420
- - **Using one:** the same pickers list the shared queries first, a group of their own. On a shared query's own canvas, only those before it are listed, and one made there goes before it.
421
- - **The Shared Queries section:** the first section of the main canvas's chain, before FROM. With none yet, it's a "+" (**New Shared Query**: one made before it's used, for a query you already have in mind). Each row has:
422
- - its name, renamed in place (its places keep their aliases);
423
- - where it's used ("Used in 2 places"), the places lighting up in FROM while the row is hovered;
424
- - an icon opening its canvas;
425
- - a remove button. One used nowhere goes at once. For a used one you choose: each place gets a copy as a sub query of its own (the rows stay the same), or the places go too. A shared query that's a query's base can't take that base with it.
426
- - **Make Shared** on a sub query's row moves its query into the section, on any canvas, and its row then uses it. **Make Sub Query** on a place's row gives that place a copy of its own.
427
- - **A place using one:** a row of FROM by its alias, with the same icon opening the shared query. Its columns are offered in field pickers like a sub query's.
428
- - **Removing the base table:** the shared queries stay; one can then be picked as the base.
429
- - **Already in a query:** a shared query is shown and editable even with the option off.
430
- - **The outline, Find and the problems list** reach them: the outline lists them first, each opening its canvas; Find finds them by name; `unusedShared` pulses its row.
431
-
432
- **Measures from another fact.** To put two facts side by side per group (sales and sales targets per city), sum something up in the report, then pick **Measure from…** in a SELECT column's type menu: the table, then what to sum up of it. `addMeasure(schema, query, { table, value, where?, selectId? })` does the same in code. The measure is a sub query of the other fact summed down to the report's GROUP BY keys, LEFT joined on them (`=` for a column the schema says is never NULL, NULL-safe otherwise), read by `MAX(...)` in a column named after it (`sales_target_amount`), with the group keys made columns first if they weren't, so each row says which group it is; the report's WHERE conditions about what both facts share (the store's province, not the sale's price) are copied into it. It's **kept in step with the report**: change the grouping or those conditions and it follows, in the same undo step (`keepMeasuresInStep`; the helpers `addCondition` and `addGroupBy` apply it too). Its FROM row's "Keep in step with the report" toggle turns that off, making its parts editable. `measureFacts` says which tables can be a measure for a query, and `validateQuery` reports one out of step (`drillAcrossOutOfStep`) or a condition it can't follow (`drillAcrossFilterMixed`, a warning).
433
-
434
- **A value's input follows its type.** A value in a comparison gets the input of what it's compared with:
435
-
436
- | Compared with | Input | Stored as |
437
- |---|---|---|
438
- | a `varchar` column, text function | text | string |
439
- | an `integer` column, `COUNT`, `LENGTH`… | whole number | number |
440
- | a `decimal` column, `SUM`, `AVG`… | number | number |
441
- | a `date` column, `CURDATE()`… | date picker | `Date` (a calendar day) |
442
- | a `dateTime` column, `NOW()` | date and time | `Date` |
443
- | a `time` column | time of day | `'HH:MM:SS'` |
444
- | a `boolean` column | yes / no | boolean |
445
-
446
- - **Columns:** `boolean` and `time` are column types too.
447
- - **Functions:** they declare a result type in the registry (`returns`: a type, or `'arg'` for their first argument's, like `MIN` or `COALESCE`). A custom function without one leaves the value's type to the user.
448
- - **What follows the type:**
449
- - the operators: text has `LIKE`/`REGEXP`; numbers, dates and times are ordered; yes/no is only `=`/`!=`;
450
- - IN's list and a `LIKE`/`REGEXP` pattern stay text.
451
- - **When what a value is compared with changes:** the value is converted if it reads cleanly as the new type (`'42'` → `42`), else cleared, in the same undo step.
452
- - **With nothing typed to compare it with** (a value against a value, an argument that takes anything): the type badge offers **Text / Number / Date / Yes-No**. The pick is kept on the value as `as`.
453
-
454
- **How long what's typed can be.** Every input has a limit, and `validateQuery` holds a query from code to the same (`tooLong`, an error):
455
- - names (a column's alias, a sub query's, a parameter's, a function's): `MAX_NAME_LENGTH`, 63 characters, the most every dialect keeps as is;
456
- - a text value: `MAX_TEXT_LENGTH`, 1,000;
457
- - a number: `MAX_NUMBER_DIGITS`, 15 significant digits, what a JS number keeps exactly. A longer one is refused in the input rather than stored as some other number;
458
- - a CAST's type name: `MAX_TYPE_NAME_LENGTH`, 40;
459
- - LIMIT and OFFSET: whole numbers up to `Number.MAX_SAFE_INTEGER`.
460
-
461
- The constants are exported from `@nongt/visql/core`, so a backend checks the same numbers. A value already too long when a query is loaded still shows, reported, not cut.
462
-
463
- ### Parameters
464
-
465
- A **parameter** (`{ type: 'param', name }`, shown as `:name`) is a value that isn't stored in the query. It's given when the SQL is generated. Either a user puts one in the editor (pick "Parameter" for a value, e.g. `hire_date >= :startDate`), or your code adds one, like `tenantId` above.
466
-
467
- - Every parameter must get a value. `astToParameterizedSql(q, d, { values })` binds them, and `astToSql(q, d, { values })` writes them as literals. Either one throws if a parameter has no value. Without `values`, `astToSql` shows `:name`, for display.
468
- - **Relative dates** ("30 days ago", "start of last month", issue 140): a value compared with a date can be a **Relative date** in the editor. It's a param that records what's meant, `{ type: 'param', name: 'day_minus_30', relative: { unit: 'day', offset: -30 } }` (`expr.param(name, { relative })` in code). The library never computes a date: your code gives its value, in your user's time zone and with your calendar. `queryParams` lists it with its `relative`, and `relativeDateLabel` gives its words. See [`docs/backend-integration.md`](docs/backend-integration.md), *Relative dates*.
469
- - **Values come from your code, not from the request as is.** `queryParams(query, schema)` lists the parameters a saved query needs, each with the type of the column it's compared against. Use it to ask the user for exactly those, check what they send, and drop anything else. Never let a user's input set a value your own code adds, such as `tenantId`. The editor can't stop a user from naming a parameter `tenantId`, so pick the names your code adds after the user's values, or reject user values with those names.
470
-
471
- ### Checking a query
472
-
473
- `validateQuery` checks the query's shape, that nothing is left unfinished (a field with no column, a comparison with no value or with NULL, a value left blank, a join with no ON condition, a function call missing an argument), that every table, column and function exists and is allowed (a hidden one reads as unknown, not as hidden), the join order, that with DISTINCT every sort key is a selected column, and grouping: aggregates only in SELECT, HAVING and ORDER BY, and in a grouped query nothing but group keys and aggregates (no database accepts otherwise), that a parameter isn't compared against columns of different types, and (as a warning) sums over rows a join repeats. `tableFilter`/`columnFilter` in the editor only hide things in its UI — the backend check is what enforces them.
474
-
475
- A value left blank and the empty text are both `''`. In the editor a user marks a text value as the empty text with the `''` toggle next to it; the query records that as `{ type: 'literal', value: '', empty: true }`, and only an unmarked `''` counts as unfinished. It's written into the SQL as `??`, like a field with no column. `expr.value('')`, and a param's `''` from `values`, are marked for you.
476
-
477
- **Types** (`typeMismatch`). Values of types that don't go together are reported:
478
- - **A value that doesn't read as the type it's compared with:** `'abc'` against a whole number. `'42'` against one, or `'2026-10-03'` against a date, reads fine.
479
- - **A column compared with a column (or a function's result) of another type.** Numbers go with numbers, and a date with a date and time.
480
- - **LIKE or REGEXP** on what isn't text.
481
- - **Each of IN's values** against its left side.
482
- - **IF's and CASE's results** against the first one whose type is known.
483
-
484
- It's a warning by default, since the database may convert. `{ typeMismatch: 'error' }` makes it an error, for an application that wants types kept (the editor's `typeMismatch` prop does the same there). The editor's inputs already keep values to the type, so in the editor it's mostly a column against a column.
485
-
486
- A REGEXP pattern that isn't a regular expression is an error (`invalidPattern`). It's read as JavaScript reads one: the databases' syntax is close to it, not the same.
487
-
488
- A query without a LIMIT reads every row. Two options deal with that, both off unless you set them:
489
- - `validateQuery(schema, query, { requireLimit: true })` warns about a query with no LIMIT (`noLimit`). With `{ max: 10000 }`, it also warns about a LIMIT above `max` (`limitTooHigh`). A query that sums the whole table into one row needs no LIMIT.
490
- - `astToParameterizedSql(query, dialect, { defaultLimit: 1000 })` (and `astToSql`) writes that LIMIT for a query without one. The query's own LIMIT is kept, and the stored query isn't changed.
491
-
492
- Each issue is `{ kind, severity, path, pathSegments, message }`:
493
- - `kind`: one of `QUERY_ISSUE_KINDS`, e.g. `'unknownColumn'`. Kinds are public API, so map them to your own error codes. Renaming or removing a kind is a breaking change (a major version), and adding one is a minor version.
494
- - `severity`: `'error'` (don't run it) or `'warning'` (worth telling the user, but it can run).
495
- - `path` and `pathSegments`: where the issue is, as text (`joins[0].on.left`) and as segments for a JSON path (`['joins', 0, 'on', 'left']`).
496
- - `message`: meant for people. It can change in any version.
497
-
498
- ### Aggregating outside SQL (pivot grids)
499
-
500
- `validateQuery`'s `fanOut` warning only sees aggregates in the query itself. An app that sums up detail rows itself, such as a pivot grid in the browser, gets an unaggregated query. A SUM there over rows a join repeats comes out too high just the same, and nothing warns. Four functions from `@nongt/visql/core` give it what `fanOut` knows:
501
-
502
- - **`joinMultiplicity(query, schema)`:** per join, `{ joinId, key, parent, side }`.
503
- - `one`: each parent row meets at most one of its rows.
504
- - `many`: the parent's rows repeat, once per match.
505
- - `cross`: every row repeats.
506
- - `unknown`: its ON isn't a declared relation.
507
- - A derived table grouped by what its ON matches is `one`, and so is a CROSS JOIN of a single row.
508
- - **`repeatedTables(query, schema, { unknown })`:** the tables whose rows repeat, by the names fields use. `unknown: 'repeat'` counts an `unknown` join as `many`, the safe answer when no one can be asked. The default, `'ignore'`, is what `fanOut` does.
509
- - **`rowsPerBase(query, schema)`:** `'one'` when the result has at most one row per base row.
510
- - `'many'` when the joins repeat the base rows, or a RIGHT/FULL join adds rows with none.
511
- - `'unknown'` when a join it can't tell about might repeat them.
512
- - **`repeatedReads(expression, repeated)`:** the repeated tables an expression reads.
513
-
514
- The recipe for detail rows a grid can sum up:
515
- 1. **`rowsPerBase(query, schema) === 'one'`**, and the query has no aggregates, GROUP BY, DISTINCT or LIMIT, so every base row is there, once.
516
- 2. **Per SELECT column**, `repeatedReads(column.expression, repeatedTables(query, schema, { unknown: 'repeat' }))`:
517
- - **Empty:** any aggregation is safe.
518
- - **Not empty:** the column repeats per row it meets (a dimension's name, a derived table's per-order total). MIN, MAX and COUNT DISTINCT are safe; SUM, AVG and COUNT aren't.
271
+ To limit every report to a tenant, use `scopeQuery`, not `addCondition`.
272
+ A report can read the same table in several places: a sub query, an
273
+ EXISTS, a second copy of the table in a self join. Each of those has to be
274
+ limited, or the report can still use other tenants' rows. `scopeQuery`
275
+ reaches all of them, and throws a `ScopeError` when it can't.
519
276
 
520
- ```ts
521
- import { repeatedReads, repeatedTables, rowsPerBase } from '@nongt/visql/core';
522
-
523
- if (rowsPerBase(query, schema) !== 'one') throw new Error('rows repeat: sum in SQL instead');
524
- const repeated = repeatedTables(query, schema, { unknown: 'repeat' });
525
- const safeToSum = query.select.filter((c) => repeatedReads(c.expression, repeated).length === 0);
526
- ```
527
-
528
- ### Logical table and column names
529
-
530
- Table and column names in the schema are identifiers. They don't have to be the database's own. Give the editor **logical names** (`timecard.minutes`), so a saved query keeps working when the database is renamed and the physical names never leave your backend. Then pass `resolveName` when generating the SQL:
531
-
532
- ```ts
533
- const physical: Record<string, string> = {
534
- timecard: 'fact_timecard',
535
- 'timecard.minutes': 'worked_minutes',
536
- };
537
-
538
- const { sql, params } = astToParameterizedSql(query, 'mysql', {
539
- values,
540
- // (table) → its SQL name; (table, column) → the column's.
541
- resolveName: (table, column) => physical[column ? `${table}.${column}` : table]
542
- ?? column ?? table,
543
- });
544
- ```
545
-
546
- `astToSql` takes the same option. Aliases are kept as they are. A table whose name changes, and that has no alias, gets its logical name as one: `FROM fact_timecard AS timecard`, its columns `timecard.worked_minutes`. The physical names appear only where the tables are named. Two logical tables can then be one physical table, for example a date dimension in two roles:
547
-
548
- ```sql
549
- INNER JOIN dim_date AS pay_date ON hours.pay_date_key = pay_date.date_key
550
- INNER JOIN dim_date AS actual_date ON hours.actual_date_key = actual_date.date_key
551
- ```
552
-
553
- ### Importing SQL
554
-
555
- `@nongt/visql/sql-import` reads SQL someone wrote back into a query: one `SELECT`, in MySQL, PostgreSQL or SQL Server. Like `core`, it has no React and no dependencies. The editor has no import button of its own. You build the UI around it, for example a "SQL" tab where a user edits the query's SQL directly and saves it:
556
-
557
- ```ts
558
- import { importSql } from '@nongt/visql/sql-import';
559
- import { astToSql, validateQuery } from '@nongt/visql/core';
560
-
561
- // Show the query as SQL to edit…
562
- const text = astToSql(saved, 'postgres');
563
-
564
- // …and on save, read the edited SQL back.
565
- const { query, problems } = importSql(edited, { dialect: 'postgres', schema });
566
- if (!query) return showProblems(problems); // each has `at`: { line, column, offset, length }
567
- // Keep the saved query's id, and check it as any received query.
568
- const next = { ...query, id: saved.id };
569
- const issues = validateQuery(schema, next, { tableFilter: (t) => user.canSee(t.name) });
570
- ```
571
-
572
- `importSql` matches names against the schema you pass, but it doesn't know a user's permissions. Run `validateQuery` with the same filters as for any query you receive.
573
-
574
- **Two modes:**
575
- - **`'strict'`** (the default) gives no query if anything is wrong.
576
- - **`'lenient'`** gives a query whenever its tables can be read, and never quietly changes which rows it returns:
577
- - **An error leaves a blank field.** Something it can't take that could change the rows (a condition, a GROUP BY key, a sort key under a LIMIT) becomes a blank field and is reported as an error. `validateQuery` then reports the query as incomplete, so it can't run until someone fixes it in the editor.
578
- - **A warning means something was left out.** Something that changes only the columns or the order (a SELECT column, a sort key, `NULLS FIRST`) is left out, and reported as a warning saying so.
579
-
580
- **What it reads:**
581
- - **Names** are matched case-insensitively and written as the schema has them. A column without its table gets the one table that has it.
582
- - **Each dialect's own forms:**
583
- - quoting;
584
- - `TOP`, `LIMIT a, b` and `OFFSET … FETCH`;
585
- - date arithmetic: `INTERVAL`, `DATEADD`, `DATEDIFF`, `DATEPART`, `DATE_TRUNC`;
586
- - `GROUP_CONCAT`, `STRING_AGG` and `WITHIN GROUP`;
587
- - `IF` and `IIF`.
588
- - **Sub queries** in FROM and in joins (a `UNION` too), `IN (SELECT …)`, and `EXISTS`.
589
- - **`WITH`** (issue 194): each query becomes a shared query, kept as written. A column list (`WITH x (a, b) AS …`) names its columns. A `WITH` inside a sub query moves to the top, renamed when its name is taken. A name in FROM or a join is a `WITH` query's before a schema table's, as in SQL. PostgreSQL's `[NOT] MATERIALIZED` is left out with a warning: it changes how the query is planned, not its rows.
590
- - **Forms rewritten into the same query in other words:**
591
- - `<=>` and `IS NOT DISTINCT FROM` become `=`, or both NULL.
592
- - `FROM a, b` becomes a `CROSS JOIN`.
593
- - A `UNION` of whole queries becomes `SELECT *` from it as a sub query.
594
- - **Grouping:** the result is grouped as every edit in the editor groups it. A column next to an aggregate but missing from `GROUP BY` is added to it, with a warning.
595
-
596
- **Reported, since a query can't hold them:**
597
- - arithmetic and `||`;
598
- - window functions and `FILTER`;
599
- - `WITH RECURSIVE` (and a `WITH` query naming itself), a `WITH` query as an EXISTS's first table, `INTERSECT` / `EXCEPT` and `JOIN … USING`;
600
- - a sub query used as a value;
601
- - positional params (`?`, `$1`). `:name` and `@name` read as params.
602
- - functions not in the registry, unless you pass `allowUnknownFunctions`.
603
-
604
- **Formatting:** what `astToSql` writes reads back as the same query. Whitespace, comments and the forms above don't come back as they were written: the SQL a user saves comes out in the package's own formatting next time.
605
-
606
- ### Contract fixtures
607
-
608
- If you store queries and generate their SQL with this package, run its contract fixtures in your own tests. When an upgrade changes what a stored query means, they fail in your CI, instead of a report coming out different later. Each case is a query, with the `validateQuery` issues it gets and its parameterized SQL in every dialect. Any change to a fixture's output is listed in the changelog.
609
-
610
- ```ts
611
- import fixtures from '@nongt/visql/fixtures';
612
- import { astToParameterizedSql, hasBaseTable, validateQuery } from '@nongt/visql/core';
613
-
614
- test.each(fixtures.cases.map((c) => [c.name, c]))('%s', (_, {
615
- query, values, names, defaultLimit, issues, results,
616
- }) => {
617
- expect(validateQuery(fixtures.schema, query).map(({ kind, severity, path }) => ({ kind, severity, path })))
618
- .toEqual(issues);
619
- if (!hasBaseTable(query)) return;
620
- const resolveName = names && ((t, c) => names[c ? `${t}.${c}` : t] ?? c ?? t);
621
- for (const [dialect, expected] of Object.entries(results)) {
622
- const run = () => astToParameterizedSql(query, dialect, { values, resolveName, defaultLimit });
623
- if ('error' in expected) expect(run).toThrow(expected.error);
624
- else expect(run()).toEqual(expected);
625
- }
626
- });
627
- ```
628
-
629
- It's ES modules only; from CommonJS, use Node 20.19+ / 22.12+ (`require()` of ESM).
277
+ [`docs/backend-integration.md`](docs/backend-integration.md) walks through
278
+ the whole server side in order: loading, checking, scoping, parameters,
279
+ writing the SQL, and the contract fixtures to run in CI.
630
280
 
631
281
  ## Props
632
282
 
633
283
  | Prop | Type | |
634
284
  |---|---|---|
635
- | `schema` | `DatabaseSchema` | **Required.** Tables, columns, relations. |
636
- | `value` / `defaultValue` | `QueryValue \| null` | Controlled / uncontrolled query. |
637
- | `onChange` | `(query: QueryValue) => void` | Every edit, undo and redo. |
638
- | `ref` | `Ref<QueryBuilderHandle>` | `resetHistory()` clears the undo history; `goToIssue(issue)` takes the user to a problem; `run()` runs the query (see below). |
639
- | `readOnly` | `boolean` | Show and explore the query, but no editing. |
640
- | `tableFilter` | `(table) => boolean` | Tables this user may see and add (never added automatically either). |
285
+ | `schema` | `DatabaseSchema` | **Required.** Tables, columns and relations. |
286
+ | `value` / `defaultValue` | `QueryValue \| null` | The query, controlled or uncontrolled. |
287
+ | `onChange` | `(query: QueryValue) => void` | Called on every edit, undo and redo. |
288
+ | `ref` | `Ref<QueryBuilderHandle>` | `resetHistory()`, `goToIssue(issue)` to take the user to a problem, and `run()`. |
289
+ | `readOnly` | `boolean` | Look around the query without changing it. |
290
+ | `tableFilter` | `(table) => boolean` | Tables this user may see. They're never added automatically either. |
641
291
  | `columnFilter` | `(table, column) => boolean` | Columns this user may see. |
642
- | `functions` | `FunctionRegistry` | SQL functions offered (default `DEFAULT_FUNCTIONS`). |
643
- | `renderValueInput` | `RenderValueInput` | Your own input for values of particular columns. |
644
- | `messages` | `Partial<Messages>` | Interface text, e.g. a translation (see `DEFAULT_MESSAGES`). |
645
- | `theme` | `Partial<QueryBuilderTheme>` | Color overrides (see `DEFAULT_THEME`). |
646
- | `fontFamily` | `string` | The editor's font, e.g. per language (default: the page's). |
647
- | `components` | `Partial<UIComponents>` | Replace single UI primitives (MUI preset), or a full kit (core entry). |
648
- | `onSchemaIssues` | `(issues: SchemaIssue[]) => void` | Schema problems. |
649
- | `onIssues` | `(issues: QueryIssue[]) => void` | The query's problems (`validateQuery`), on mount and whenever they change. Ready to run or save when none is an error. |
650
- | `showIssues` | `boolean` | Show the problems' count above the canvas, with their list (pick one to go to it: the canvas pans there and pulses its node). Default `true`; never when read-only. |
651
- | `typeMismatch` | `'warning' \| 'error'` | How values of types that don't go together are reported (default `'warning'`). Pass your backend's `validateQuery` setting, so the editor says what it will. |
652
- | `dialect` | `'mysql' \| 'mssql' \| 'postgres'` | The database the query is for. The pickers then offer only what it has: functions narrowed with `functionsForDialect`, and in SQL Server no `REGEXP` and no "Different values" STRING_AGG. Anything the query already holds stays shown and is reported (`dialectUnsupported`). Without it, everything is offered. Pass the same dialect your backend gives `validateQuery`. |
653
- | `betweenOnText` | `'never' \| 'withoutOptions' \| 'always'` | Where BETWEEN is offered on text (default `'never'`: numbers, dates and times only). Text is ordered by the database's collation, so a text range rarely means what it reads as: `name BETWEEN 'A' AND 'M'` leaves out "Mary". `'withoutOptions'` offers it on text except columns with `options` (codes such as a gender); `'always'` on any text. A BETWEEN already in the query is shown either way. |
654
- | `hideWarnings` | `QueryWarningKind[]` | Warnings not to show (in the problems list, `onIssues`, and on the canvas), e.g. `['crossJoin']`. Any of `QUERY_WARNING_KINDS`; errors always show. `validateQuery` takes the same option. |
655
- | `onRun` | `(query) => RunResult \| void \| Promise<…>` | Adds a Run button: hands the query to your backend and shows the rows it returns (see *Running the query*). |
656
- | `direction` | `'ltr' \| 'rtl'` | Which way the canvas grows (default `'ltr'`). |
657
- | `orientation` | `'horizontal' \| 'vertical'` | Which way the main canvas's chain flows (default `'horizontal'`): FROM, the conditions, Group Rows, SELECT and Sort & Limit side by side, or stacked top to bottom, with HAVING's tree beside Group Rows. For a tall, narrow space. Combines with `direction`, which says which side things start from. Only the sections are stacked: inside one, a condition tree keeps its operator beside its conditions, which already run downward. |
658
- | `subqueries` | `{ in?: boolean; union?: boolean \| { unshared?, source?, rowMarkers?, free? }; shared?: boolean }` | `in: true` offers a sub query as IN's value (off by default: NOT IN's NULL trap, see *IN (sub query)*). `union` offers adding another table's rows (UNION ALL, see *Building a union*), with `addUnionTable`'s options; `free: true` among them also offers unions of any queries (*Unions of tables*). `shared: true` offers shared queries (`WITH`, issue 194: "Create Shared Query" and the shared queries to use, see *Shared queries (WITH)*); the backend needs stored format 4, and MySQL 8. Any kind already in the query is shown and editable whatever this says. |
659
- | `exists` | `ExistsOptions` | The EXISTS button: `relations` it lists (`'toMany'`, the default: tables pointing at the query's; `'both'`: also those the query's point at) and where it's offered (`in`, default `['where', 'having']`, `'joinOn'` when asked for, `[]` for nowhere). An EXISTS already in the query is shown and editable anywhere. |
660
- | `autoRevealNewNodes` | `boolean` | Pan to newly added nodes (default `true`). |
661
- | `className` | `string` | On the root element. |
662
-
663
- Pass object and function props as stable values (module constants,
664
- `useMemo`, `useCallback`).
292
+ | `functions` | `FunctionRegistry` | The SQL functions on offer. Defaults to `DEFAULT_FUNCTIONS`. |
293
+ | `renderValueInput` | `RenderValueInput` | Your own input for some columns' values. |
294
+ | `messages` | `Partial<Messages>` | Interface text, for translations. See `DEFAULT_MESSAGES`. |
295
+ | `theme` | `Partial<QueryBuilderTheme>` | Colors. See `DEFAULT_THEME`. |
296
+ | `fontFamily` | `string` | The editor's font. Defaults to the page's. |
297
+ | `components` | `Partial<UIComponents>` | Swap single UI pieces, or bring a whole kit. |
298
+ | `onSchemaIssues` | `(issues: SchemaIssue[]) => void` | Problems found in the schema. |
299
+ | `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. |
300
+ | `showIssues` | `boolean` | The problem count above the canvas, with a list that takes the user to each one. On by default. |
301
+ | `typeMismatch` | `'warning' \| 'error'` | How to report values whose types don't go together. Use the same setting as your server. |
302
+ | `dialect` | `'mysql' \| 'mssql' \| 'postgres'` | Only offer what this database supports. Anything already in the query stays and is reported. |
303
+ | `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". |
304
+ | `hideWarnings` | `QueryWarningKind[]` | Warnings not to show, such as `['crossJoin']`. |
305
+ | `onRun` | `(query) => RunResult \| void \| Promise<…>` | Adds a Run button. See below. |
306
+ | `direction` | `'ltr' \| 'rtl'` | Which way the canvas grows. |
307
+ | `orientation` | `'horizontal' \| 'vertical'` | Lay the main sections out side by side, or stacked for a narrow space. |
308
+ | `subqueries` | `{ in?, union?, shared? }` | Turn on sub queries after IN, UNION ALL, and WITH. All are off by default. |
309
+ | `exists` | `ExistsOptions` | Which related tables the EXISTS button lists, and where it appears. |
310
+ | `onHoverPart` | `(pathSegments \| null) => void` | The part of the query under the pointer, for lighting it up in your own SQL view. |
311
+ | `autoRevealNewNodes` | `boolean` | Pan to nodes as they're added. On by default. |
312
+ | `className` | `string` | Added to the root element. |
313
+
314
+ Pass objects and functions as stable values (module constants, `useMemo`,
315
+ `useCallback`), or the editor redoes work on every render.
665
316
 
666
317
  ### Running the query
667
318
 
668
- Give the editor `onRun` and it gets a **Run** button above the canvas (and Ctrl/⌘+Enter). It's on while the query has a table and no errors; otherwise its tooltip says why. The editor never reaches a database: `onRun` gets the query, sends it to your backend, and returns the rows to show under the canvas.
319
+ With `onRun`, the editor gets a Run button (and Ctrl/⌘+Enter while you're
320
+ working in the editor; in your page's other inputs the keys stay theirs, as
321
+ Ctrl/⌘+Z for undo does). It never
322
+ talks to a database itself. Your `onRun` sends the query to your backend
323
+ and returns the rows, and the editor shows them under the canvas.
669
324
 
670
325
  ```tsx
671
326
  <QueryBuilder
672
327
  schema={schema}
673
328
  onRun={async (query) => {
674
329
  const res = await fetch('/reports/preview', { method: 'POST', body: JSON.stringify(query) });
675
- if (!res.ok) throw new Error(await res.text()); // shown as the failure
676
- return res.json(); // { rows, columns?, truncated? }
330
+ if (!res.ok) throw new Error(await res.text()); // shown as the error
331
+ return res.json(); // { rows, columns?, truncated? }
677
332
  }}
678
333
  />
679
334
  ```
680
335
 
681
- It hands over the query, not SQL, on purpose: the backend checks it and writes the SQL itself (as above), so it never runs SQL a browser sent. Cap the rows there (a LIMIT, or `setPaging`) and say `truncated: true` when there were more.
682
-
683
- - `rows` are objects keyed by column name. `columns` sets their order (default: the keys as first seen).
684
- - Return nothing to show the rows your own way instead.
685
- - While one is running, a new run replaces it. Edits after a run leave its rows up, marked as outdated.
686
- - Runs in read-only mode too. `run()` on the ref does the same as the button.
687
-
688
- ### Linking your SQL view to the editor
689
-
690
- If you show the query's SQL, you can link it to the editor both ways, as the playground's SQL preview does:
691
- - **From the SQL:** the part under the pointer lights up, and a click takes the user to it in the editor. The editor opens the sub-canvas it's in, pans there, pulses it once the canvas has stopped moving, and puts the focus in its input.
692
- - **From the editor:** the part under the pointer on any canvas lights up in the SQL. That can be a condition, one side of it, a function's argument in a panel, a SELECT column or FROM's table.
693
-
694
- The main entry has what it takes:
695
-
696
- - **`astToSqlWithSpans(query, dialect, options)`** gives `{ sql, spans }`.
697
- - The SQL is exactly what `astToSql` writes, or `astToParameterizedSql` with `parameterized: true`. It takes the same options.
698
- - Each span is `{ start, end, pathSegments }`. Every node, SELECT column (or SELECT `*`), FROM and join, GROUP BY and ORDER BY key, LIMIT and OFFSET has one. Spans nest, outer ones first.
699
- - **`spanAt(spans, offset)`** gives the innermost span at a character, which is the most specific part there.
700
- - **`spansFor(spans, pathSegments)`** gives where a part is: its own span, or for a section written in pieces (`['select']`), each of its parts'.
701
- - **`sqlOffsetAt(element, x, y)`** gives the character of the SQL under a point on the page (`clientX`, `clientY`), or `undefined` when the point isn't on one, for example past a line's end.
702
- - `element` holds the SQL as its text.
703
- - The text can be split into elements by any syntax highlighter (Prism, highlight.js, Shiki…): its characters, in order, are the SQL's.
704
- - **`sqlRangeOf(element, start, end)`** gives a DOM `Range` over a span, to highlight it.
705
- - **The editor's `onHoverPart`** prop reports the part under the pointer as its `pathSegments`, or `null` once it's on none. It is called only when that changes, in the next animation frame after the pointer event (the latest part only), so setting state there is safe.
706
- - **The editor's `goToIssue`** (on its ref) goes to a part. The span paths are the ones `validateQuery` gives its issues, so it takes them as they are. Without a severity, the part pulses in the focus ring's colour.
707
-
708
- ```tsx
709
- import {
710
- useEffect, useMemo, useRef, useState, type MouseEvent, type RefObject,
711
- } from 'react';
712
- import {
713
- astToSqlWithSpans, spanAt, spansFor, sqlOffsetAt, sqlRangeOf,
714
- type QueryBuilderHandle, type QueryPipeline, type SqlSpan,
715
- } from '@nongt/visql';
716
-
717
- function SqlPreview({ query, editor, hovered }: {
718
- query: QueryPipeline;
719
- editor: RefObject<QueryBuilderHandle | null>; // the editor's ref
720
- hovered: (string | number)[] | null; // the editor's onHoverPart
721
- }) {
722
- const { sql, spans } = useMemo(() => astToSqlWithSpans(query, 'postgres'), [query]);
723
- const box = useRef<HTMLPreElement>(null);
724
- const [pointed, setPointed] = useState<SqlSpan>();
725
-
726
- // The part under the pointer: the innermost span at that character.
727
- const spanUnder = (e: MouseEvent) => {
728
- const offset = sqlOffsetAt(box.current!, e.clientX, e.clientY);
729
- return offset === undefined ? undefined : spanAt(spans, offset);
730
- };
731
-
732
- // Light up the part under the pointer here, else the one hovered in the
733
- // editor (CSS Custom Highlight API); forget it when the SQL changes.
734
- useEffect(() => setPointed(undefined), [sql]);
735
- const lit = pointed ? [pointed] : (hovered && spansFor(spans, hovered)) || [];
736
- useEffect(() => {
737
- if (lit.length === 0) return undefined;
738
- const ranges = lit.map((s) => sqlRangeOf(box.current!, s.start, s.end));
739
- CSS.highlights.set('sql-part', new Highlight(...ranges));
740
- return () => {
741
- CSS.highlights.delete('sql-part');
742
- };
743
- }, [lit.map((s) => `${s.start}-${s.end}`).join()]);
744
-
745
- return (
746
- <pre
747
- ref={box}
748
- style={{ cursor: pointed ? 'pointer' : undefined }}
749
- onMouseMove={(e) => setPointed(spanUnder(e))}
750
- onMouseLeave={() => setPointed(undefined)}
751
- onClick={(e) => {
752
- const span = spanUnder(e);
753
- if (span) editor.current?.goToIssue({ pathSegments: span.pathSegments });
754
- }}
755
- >
756
- {sql /* or your syntax highlighter's output of it */}
757
- </pre>
758
- );
759
- }
760
- ```
761
-
762
- ```css
763
- ::highlight(sql-part) { background-color: rgb(56 189 248 / 0.3); }
764
- ```
765
-
766
- ```tsx
767
- const editor = useRef<QueryBuilderHandle>(null);
768
- const [hovered, setHovered] = useState<(string | number)[] | null>(null);
769
-
770
- <QueryBuilder ref={editor} schema={schema} value={query} onChange={setQuery} onHoverPart={setHovered} />
771
- {query && hasBaseTable(query) && <SqlPreview query={query} editor={editor} hovered={hovered} />}
772
- ```
773
-
774
- - **Highlighting:** the CSS Custom Highlight API leaves the highlighter's markup alone. It is in every current browser. Without it, skip the highlight and clicks still work.
775
- - **Parameterized SQL:** pass `{ parameterized: true }`. A value's span is then its placeholder (`$1`).
776
- - **A long query:** the playground's preview also scrolls a part hovered in the editor into view when it's out of sight.
777
- - **A complete preview:** the playground's own is `src/features/queryViewer/QueryViewer.tsx`, with Prism, a dialect switch and that scrolling.
778
-
779
- ### Showing problems your own way
780
-
781
- The editor counts the query's problems above the canvas, and picking one goes to it. To show them your own way instead, take them from `onIssues`, turn the editor's list off with `showIssues={false}`, and send the user to one with `goToIssue` on the ref. It does exactly what picking one in the editor's list does: opens the sub-canvas the problem is in, pans there and pulses its node.
782
-
783
- ```tsx
784
- const editor = useRef<QueryBuilderHandle>(null);
785
- const [issues, setIssues] = useState<QueryIssue[]>([]);
786
-
787
- <QueryBuilder ref={editor} schema={schema} showIssues={false} onIssues={setIssues} />
788
- <ul>
789
- {issues.map((issue) => (
790
- <li key={issue.path} onClick={() => editor.current?.goToIssue(issue)}>{issue.message}</li>
791
- ))}
792
- </ul>
793
- ```
794
-
795
- An issue from your backend's `validateQuery` works too; only its `pathSegments` and `severity` are used. One about an older version of the query goes as far as its path still leads. `goToIssue` returns `false` when there's nowhere to go: there's no query yet, or the issue is about the whole query. It works in read-only mode as well.
796
-
797
- To say where each problem is, as the editor's list does, `issueLocation(query, issue.pathSegments, { schema, functions })` gives the steps to it, in the user's terms:
798
-
799
- ```ts
800
- issueLocation(query, ['select', 2, 'expression', 'args', 1], { schema });
801
- // [{ kind: 'section', section: 'select' }, { kind: 'column', number: 3, name: 'total' },
802
- // { kind: 'function', name: 'ROUND' }, { kind: 'argument', number: 2, label: 'decimals' }]
803
- ```
804
-
805
- Each step is data: a section, a sub query by its name, a column by its alias or label, a condition by its place, and so on. You word the steps in your own language. The editor's list shows the example above as `Columns Selection › total › ROUND › decimals`.
336
+ It sends the query rather than SQL so that your backend checks it and
337
+ writes the SQL itself. Cap the number of rows there, and return
338
+ `truncated: true` when there were more.
806
339
 
807
340
  ## Customizing
808
341
 
809
- **Functions**: add your own, drop some, or keep one dialect's:
342
+ Add your own SQL functions, drop some, or keep only what one database has:
810
343
 
811
344
  ```ts
812
345
  import { DEFAULT_FUNCTIONS, functionsForDialect } from '@nongt/visql';
813
346
 
814
347
  const functions = {
815
348
  ...functionsForDialect(DEFAULT_FUNCTIONS, 'postgres'),
816
- RISK_SCORE: {
817
- name: 'RISK_SCORE',
818
- args: [{ label: 'customer', kind: 'num-expr' }],
819
- },
349
+ RISK_SCORE: { name: 'RISK_SCORE', args: [{ label: 'customer', kind: 'num-expr' }] },
820
350
  };
821
351
  ```
822
352
 
823
- Mark one `aggregate: true` (like `SUM`) and the editor offers it only in
824
- SELECT, HAVING and ORDER BY, and counts it when checking grouping. **A
825
- custom aggregate must set it**: a function the registry doesn't know might
826
- sum rows up, so a column calling one is never made a GROUP BY key by
827
- itself. With `allowUnknownFunctions`, `validateQuery` warns about such a
828
- column in a grouped query (`unknownAggregate`). `aliases` lists other names
829
- a function goes by: typing one in a picker finds it.
830
-
831
- **STRING_AGG** joins a group's values into one text, after an optional
832
- separator (`', '` by default, written into the SQL, never a parameter).
833
- Each database gets its own form: `GROUP_CONCAT(x SEPARATOR ', ')` in
834
- MySQL, `STRING_AGG(CAST(x AS TEXT), ', ')` in PostgreSQL,
835
- `STRING_AGG(CAST(x AS NVARCHAR(MAX)), ', ')` in SQL Server. `distinct: true`
836
- on the call joins each different value once; SQL Server can't, so the SQL
837
- functions throw and `validateQuery` with `dialect: 'mssql'` reports it
838
- (`dialectUnsupported`). The values come in no particular order unless
839
- the call has an `orderBy` (`[{ expression, direction: 'asc' | 'desc' }]`, the
840
- editor's "Add Sort" on its node, sorting by the value itself to begin
841
- with): `ORDER BY` inside it, `WITHIN GROUP (ORDER BY …)` in SQL Server.
842
- Two limits, reported by `validateQuery` with a `dialect`: with DISTINCT,
843
- PostgreSQL sorts only by the value itself; SQL Server sorts every
844
- STRING_AGG of one query alike (one's keys may extend the other's). MySQL cuts
845
- the text at `group_concat_max_len` (1024 bytes by default) with only a
846
- warning; raise it for long lists.
847
-
848
- **Custom value inputs**: e.g. a lookup for customer ids. Return `undefined`
849
- for any column you don't handle:
353
+ If one of your functions sums rows up, mark it `aggregate: true`. Otherwise
354
+ the editor can't know, and won't treat a column that calls it as a group
355
+ key.
356
+
357
+ Give a column its own input, a customer lookup for instance. Return
358
+ `undefined` for the columns you leave to the editor:
850
359
 
851
360
  ```tsx
852
361
  const renderValueInput: RenderValueInput = ({ table, column, value, onChange }) => (
@@ -856,62 +365,71 @@ const renderValueInput: RenderValueInput = ({ table, column, value, onChange })
856
365
  );
857
366
  ```
858
367
 
859
- **Text**: any subset of `DEFAULT_MESSAGES`:
860
-
861
- ```ts
862
- const messages = { addCondition: 'เพิ่มเงื่อนไข', sectionWhere: 'เงื่อนไข' };
863
- ```
864
-
865
- **Fonts**: the editor uses your page's font, or `fontFamily`, which also
866
- reaches its dropdowns and menus. Pick it per language, next to `messages`
867
- (and load the font yourself: a webfont stylesheet, `@fontsource/…`):
368
+ Translate any of the text, and set a font to go with it:
868
369
 
869
370
  ```tsx
870
- <QueryBuilder messages={THAI_MESSAGES} fontFamily="Kanit, sans-serif" … />
371
+ const messages = { addCondition: 'เพิ่มเงื่อนไข', sectionWhere: 'เงื่อนไข' };
372
+ <QueryBuilder messages={messages} fontFamily="Kanit, sans-serif" … />
871
373
  ```
872
374
 
873
- **Colors**: every color is a role-named token, set through `theme` or in
874
- CSS on `.qb-root`:
375
+ Colors are CSS variables on `.qb-root`, or the `theme` prop. The canvas's
376
+ own parts (zoom buttons, edges, handles) follow them too:
875
377
 
876
378
  ```css
877
379
  .qb-root { --qb-accent: #e91e63; --qb-canvas-bg: #fafafa; }
878
380
  ```
879
381
 
880
- **Styles don't leak**: the editor's CSS is scoped to `.qb-root` in cascade
881
- layers, and your page's global CSS doesn't reach inside it.
382
+ The editor's CSS stays inside `.qb-root`, and your page's global CSS
383
+ doesn't get in. To use a component library other than MUI, see
384
+ [`docs/ui-adapters.md`](docs/ui-adapters.md).
882
385
 
883
- ## Entry points
386
+ ## Packages and entry points
884
387
 
885
- | Import | What |
388
+ | Import | What it is |
886
389
  |---|---|
887
390
  | `@nongt/visql/mui` | `QueryBuilder` with the MUI kit. Needs `@mui/material` and emotion. |
888
- | `@nongt/visql/mui-date-pickers` | The MUI X pickers to plug in: `MuiDatePicker`, `MuiDateTimePicker`, `MuiTimePicker` (`components={{ DatePicker: MuiDatePicker, DateTimePicker: MuiDateTimePicker, TimePicker: MuiTimePicker }}`). Each is optional: without one, the browser's own date, date-and-time or time field. Needs `@mui/x-date-pickers` and `date-fns`. |
889
- | `@nongt/visql` | The editor with no UI kit (`components` required), plus types and helpers: `astToSql`, `DEFAULT_FUNCTIONS`, `DEFAULT_MESSAGES`, `DEFAULT_THEME`, `validateSchema`, … |
890
- | `@nongt/visql/core` | The query logic only — types, `astToSql` / `astToParameterizedSql`, `validateSchema` / `filterSchema`, the function registry. No React, no DOM, no dependencies: for a backend. |
891
- | `@nongt/visql/fixtures` | Contract fixtures, as data: queries and the SQL and issues this version makes of them (see below). |
892
- | `@nongt/visql/sql-import` | `importSql`: SQL someone wrote, read back into a query (see [Importing SQL](#importing-sql)). No React, no DOM, no dependencies. |
893
- | `@nongt/visql/style.css` | The stylesheet. Import once. |
894
- | `@nongt/visql-core` | **A package of its own** for a backend: the same as `@nongt/visql/core`, with `/sql-import` and `/fixtures`, and no dependencies or peers. Released with the same version. |
895
-
896
- To use a component library other than MUI, see
897
- [docs/ui-adapters.md](docs/ui-adapters.md).
391
+ | `@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. |
392
+ | `@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). |
393
+ | `@nongt/visql` | The editor without a UI kit (pass `components`), plus every type and helper. |
394
+ | `@nongt/visql/style.css` | The stylesheet. Import it once. |
395
+ | `@nongt/visql/core` | The query logic alone: no React, no DOM. |
396
+ | `@nongt/visql/sql-import` | `importSql`, for reading SQL someone wrote back into a query. |
397
+ | `@nongt/visql/fixtures` | Contract fixtures for your own tests. |
398
+ | `@nongt/visql-core` | The last three as a package of their own, for a server. |
399
+
400
+ Every peer dependency is optional, since the server-side entries need none
401
+ of them. It's ES modules only. From CommonJS, use Node 20.19+ or 22.12+. The
402
+ types work with TypeScript's older `moduleResolution: "node"` as well as
403
+ `bundler` and `nodenext`.
404
+
405
+ ## More documentation
406
+
407
+ - [Query reference](docs/query-reference.md): everything a query can hold
408
+ (EXISTS, IN, BETWEEN, sub queries, unions, WITH, measures), the helpers
409
+ that change a query from code, and parameters.
410
+ - [Checking queries](docs/checking-queries.md): `validateQuery`, sums that
411
+ are safe in a pivot grid, and contract fixtures.
412
+ - [Backend integration](docs/backend-integration.md): the server side, step
413
+ by step.
414
+ - [Importing SQL](docs/sql-import.md): turning hand-written SQL into a
415
+ query.
416
+ - [Showing the SQL and problems](docs/sql-preview.md): a SQL view linked to
417
+ the editor both ways, and a problems list of your own.
418
+ - [UI adapters](docs/ui-adapters.md): using a component library other than
419
+ MUI.
420
+ - [`docs/design/`](docs/design): why some things work the way they do.
898
421
 
899
422
  ## Playground
900
423
 
901
- The repository's demo app is the playground: the full editor on a sample
902
- database, the SQL it produces in each dialect, and a **Demo options** panel
903
- to try read-only mode, right-to-left flow, a light theme, Thai interface
904
- text (in the Kanit font), hidden tables and parameterized SQL.
424
+ The repository's demo app runs the full editor on a sample database, with
425
+ the SQL beside it in each dialect and a panel of options to try (read-only,
426
+ right-to-left, a light theme, Thai text, hidden tables).
905
427
 
906
428
  ```bash
907
429
  pnpm install
908
430
  pnpm dev
909
431
  ```
910
432
 
911
- ## Contributing
912
-
913
- See [CONTRIBUTING.md](CONTRIBUTING.md).
914
-
915
433
  ## License
916
434
 
917
435
  [MIT](LICENSE)