@nongt/visql 0.4.2 → 0.5.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.
- package/README.md +219 -718
- package/dist/MuiTimePicker-BjywwrRm.js +112 -0
- package/dist/{PipelineEditor-BoFPDUmi.js → PipelineEditor-Cx_c0xZL.js} +1426 -1422
- package/dist/{core-api-BRJV9MUQ.js → core-api-DzslKd1R.js} +437 -426
- package/dist/core.js +1 -1
- package/dist/index.js +3 -3
- package/dist/mui-date-pickers-host.js +20 -0
- package/dist/mui-date-pickers.js +14 -113
- package/dist/mui.js +161 -155
- package/dist/types/adapters/mui/MuiDatePicker.d.ts +2 -3
- package/dist/types/adapters/mui/QueryBuilder.d.ts +2 -2
- package/dist/types/adapters/mui/components.d.ts +2 -2
- package/dist/types/adapters/mui/hostPickers.d.ts +8 -0
- package/dist/types/adapters/mui/muiPickers.d.ts +6 -5
- package/dist/types/core/ui/index.d.ts +2 -2
- package/dist/types/core/ui/types.d.ts +5 -4
- package/dist/types/features/queryEditor/PipelineEditor.d.ts +1 -4
- package/dist/types/mui-date-pickers-host.d.ts +12 -0
- package/dist/types/mui-date-pickers.d.ts +12 -3
- package/package.json +33 -10
package/README.md
CHANGED
|
@@ -1,62 +1,60 @@
|
|
|
1
1
|
# visql
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
-
|
|
33
|
-
|
|
34
|
-
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
-
|
|
38
|
-
|
|
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
|
-
#
|
|
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
|
-
|
|
51
|
+
```bash
|
|
54
52
|
pnpm add @nongt/visql-core
|
|
55
53
|
```
|
|
56
54
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
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
|
|
83
|
+
The editor fills its container, so give the container a height.
|
|
86
84
|
|
|
87
|
-
##
|
|
85
|
+
## Describing your database
|
|
88
86
|
|
|
89
|
-
|
|
90
|
-
|
|
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
|
|
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,36 @@ export const schema: DatabaseSchema = {
|
|
|
123
121
|
},
|
|
124
122
|
],
|
|
125
123
|
relations: [
|
|
126
|
-
// orders.customer_id
|
|
127
|
-
// from the
|
|
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
|
|
134
|
-
`
|
|
135
|
-
|
|
136
|
-
|
|
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
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
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.
|
|
142
140
|
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
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.
|
|
141
|
+
Relations also tell the editor which side of a join has many rows. Joining
|
|
142
|
+
`orders` to `order_items` repeats each order once per item, so a SUM of the
|
|
143
|
+
order totals comes out too high without any error. The editor warns about
|
|
144
|
+
that on the canvas, and `validateQuery` reports it as `fanOut`.
|
|
167
145
|
|
|
168
146
|
## The query value
|
|
169
147
|
|
|
170
|
-
`onChange`
|
|
171
|
-
|
|
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.
|
|
148
|
+
`onChange` gives you a `QueryValue`. It's plain JSON, apart from date and
|
|
149
|
+
`bigint` values:
|
|
173
150
|
|
|
174
151
|
```ts
|
|
175
152
|
interface QueryPipeline {
|
|
176
|
-
id: string; //
|
|
153
|
+
id: string; // stays the same through every edit
|
|
177
154
|
from: { table: string; alias?: string };
|
|
178
155
|
joins: { id: string; table: string; joinType: 'inner' | 'left' | 'right' | 'full'; on?: ExpressionNode }[];
|
|
179
156
|
where?: ExpressionNode;
|
|
@@ -182,671 +159,187 @@ interface QueryPipeline {
|
|
|
182
159
|
select: { id: string; expression: ExpressionNode; alias?: string }[];
|
|
183
160
|
distinct?: boolean;
|
|
184
161
|
orderBy?: { id: string; expression: ExpressionNode; direction: 'asc' | 'desc' }[];
|
|
185
|
-
limit?: number;
|
|
162
|
+
limit?: number;
|
|
186
163
|
offset?: number;
|
|
187
164
|
}
|
|
188
|
-
type QueryValue = QueryPipeline | { id: string }; // { id }
|
|
165
|
+
type QueryValue = QueryPipeline | { id: string }; // { id } while no table is picked yet
|
|
189
166
|
```
|
|
190
167
|
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
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.
|
|
168
|
+
Use it the way you'd use an `<input>`: pass `value` and `onChange` and hand
|
|
169
|
+
back what you're given, or pass `defaultValue` and let the editor keep its
|
|
170
|
+
own state. `value={null}` starts an empty query. A query with a different
|
|
171
|
+
`id` starts a new undo history.
|
|
198
172
|
|
|
199
|
-
|
|
173
|
+
A date in a query is a calendar day or a wall-clock time, not a moment in
|
|
174
|
+
time. 3 October 2026 is stored as `2026-10-03T00:00:00Z` and written to SQL
|
|
175
|
+
as `'2026-10-03'`, the same day whether the browser is in Bangkok or the
|
|
176
|
+
server runs in UTC. If you build one in code, `new Date('2026-10-03')` is
|
|
177
|
+
that day, but `new Date(2026, 9, 3)` is local midnight, which is the day
|
|
178
|
+
before east of UTC.
|
|
200
179
|
|
|
201
|
-
|
|
202
|
-
import { loadQuery, saveQuery, QueryFormatError } from '@nongt/visql/core';
|
|
180
|
+
### Storing it
|
|
203
181
|
|
|
204
|
-
|
|
182
|
+
```ts
|
|
183
|
+
import { loadQuery, saveQuery } from '@nongt/visql/core';
|
|
205
184
|
|
|
206
|
-
|
|
185
|
+
db.save(report.id, JSON.stringify(saveQuery(query)));
|
|
186
|
+
const query = loadQuery(JSON.parse(db.load(report.id)));
|
|
207
187
|
```
|
|
208
188
|
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
189
|
+
`saveQuery` adds a format version. `loadQuery` upgrades a query saved by an
|
|
190
|
+
older version as it reads it, and refuses one saved by a newer version
|
|
191
|
+
(a `QueryFormatError` of kind `'newerVersion'`) rather than guessing. That
|
|
192
|
+
can happen after a rolled-back deploy. It doesn't check the query against
|
|
193
|
+
your schema, because a table may have been dropped since the query was
|
|
194
|
+
saved, so run `validateQuery` after loading.
|
|
214
195
|
|
|
215
|
-
## SQL
|
|
196
|
+
## Getting SQL out
|
|
216
197
|
|
|
217
|
-
To
|
|
198
|
+
To run a query, generate it with parameters. The values go to the driver
|
|
199
|
+
separately from the SQL text:
|
|
218
200
|
|
|
219
201
|
```ts
|
|
220
202
|
import { astToParameterizedSql } from '@nongt/visql';
|
|
221
203
|
|
|
222
204
|
const { sql, params } = astToParameterizedSql(query, 'postgres');
|
|
223
|
-
//
|
|
224
|
-
//
|
|
205
|
+
// SELECT * FROM "orders" WHERE "orders"."status" = $1 AND "orders"."total" > $2
|
|
206
|
+
// ['open', 100]
|
|
225
207
|
await pg.query(sql, params);
|
|
226
208
|
```
|
|
227
209
|
|
|
228
|
-
|
|
210
|
+
Every value becomes a parameter, wherever it is: `?` in MySQL, `$1` in
|
|
211
|
+
PostgreSQL, `@p1` in SQL Server. Names are quoted. Function names and other
|
|
212
|
+
parts that can't be parameters are checked against plain patterns. Dates
|
|
213
|
+
are sent as text, because drivers would otherwise shift a `Date` into the
|
|
214
|
+
server's time zone.
|
|
229
215
|
|
|
230
|
-
To
|
|
216
|
+
To show a query to someone, `astToSql(query, 'mysql')` writes the values
|
|
217
|
+
inline.
|
|
231
218
|
|
|
232
|
-
|
|
233
|
-
|
|
219
|
+
If the names in your schema aren't the database's real ones (handy when you
|
|
220
|
+
want saved queries to survive a rename), pass `resolveName`:
|
|
234
221
|
|
|
235
|
-
|
|
222
|
+
```ts
|
|
223
|
+
const physical: Record<string, string> = {
|
|
224
|
+
timecard: 'fact_timecard',
|
|
225
|
+
'timecard.minutes': 'worked_minutes',
|
|
226
|
+
};
|
|
227
|
+
astToParameterizedSql(query, 'mysql', {
|
|
228
|
+
resolveName: (table, column) => physical[column ? `${table}.${column}` : table] ?? column ?? table,
|
|
229
|
+
});
|
|
230
|
+
// FROM fact_timecard AS timecard ... timecard.worked_minutes
|
|
236
231
|
```
|
|
237
232
|
|
|
238
|
-
## On the
|
|
233
|
+
## On the server
|
|
239
234
|
|
|
240
|
-
|
|
235
|
+
Treat a query that arrives from a browser, or comes out of your database,
|
|
236
|
+
as untrusted. The editor's `tableFilter` and `columnFilter` only hide things
|
|
237
|
+
on screen. The check that actually enforces them is `validateQuery` on the
|
|
238
|
+
server.
|
|
241
239
|
|
|
242
240
|
```ts
|
|
243
|
-
|
|
244
|
-
import {
|
|
245
|
-
astToParameterizedSql, hasBaseTable, validateQuery, type QueryValue,
|
|
246
|
-
} from '@nongt/visql/core';
|
|
241
|
+
import { astToParameterizedSql, hasBaseTable, validateQuery } from '@nongt/visql-core';
|
|
247
242
|
|
|
248
243
|
app.get('/reports/:id/rows', async (req, res) => {
|
|
249
|
-
const query = await reports.load(req.params.id);
|
|
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.
|
|
244
|
+
const query = await reports.load(req.params.id);
|
|
252
245
|
const issues = validateQuery(schema, query, {
|
|
253
246
|
tableFilter: (t) => req.user.canSee(t.name),
|
|
254
247
|
});
|
|
255
|
-
// Errors mean
|
|
248
|
+
// Errors mean don't run it. Warnings (no LIMIT, rows a join repeats) can run.
|
|
256
249
|
if (issues.some((i) => i.severity === 'error')) return res.status(400).json({ issues });
|
|
257
|
-
|
|
258
|
-
if (!hasBaseTable(valid)) return res.json([]); // nothing chosen yet
|
|
250
|
+
if (!hasBaseTable(query)) return res.json([]);
|
|
259
251
|
|
|
260
|
-
const { sql, params } = astToParameterizedSql(
|
|
252
|
+
const { sql, params } = astToParameterizedSql(query, 'postgres');
|
|
261
253
|
res.json(await db.query(sql, params));
|
|
262
254
|
});
|
|
263
255
|
```
|
|
264
256
|
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
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.
|
|
519
|
-
|
|
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
|
-
```
|
|
257
|
+
To limit every report to a tenant, use `scopeQuery`, not `addCondition`.
|
|
258
|
+
A report can read the same table in several places: a sub query, an
|
|
259
|
+
EXISTS, a second copy of the table in a self join. Each of those has to be
|
|
260
|
+
limited, or the report can still use other tenants' rows. `scopeQuery`
|
|
261
|
+
reaches all of them, and throws a `ScopeError` when it can't.
|
|
571
262
|
|
|
572
|
-
`
|
|
573
|
-
|
|
574
|
-
|
|
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).
|
|
263
|
+
[`docs/backend-integration.md`](docs/backend-integration.md) walks through
|
|
264
|
+
the whole server side in order: loading, checking, scoping, parameters,
|
|
265
|
+
writing the SQL, and the contract fixtures to run in CI.
|
|
630
266
|
|
|
631
267
|
## Props
|
|
632
268
|
|
|
633
269
|
| Prop | Type | |
|
|
634
270
|
|---|---|---|
|
|
635
|
-
| `schema` | `DatabaseSchema` | **Required.** Tables, columns
|
|
636
|
-
| `value` / `defaultValue` | `QueryValue \| null` |
|
|
637
|
-
| `onChange` | `(query: QueryValue) => void` |
|
|
638
|
-
| `ref` | `Ref<QueryBuilderHandle>` | `resetHistory()
|
|
639
|
-
| `readOnly` | `boolean` |
|
|
640
|
-
| `tableFilter` | `(table) => boolean` | Tables this user may see
|
|
271
|
+
| `schema` | `DatabaseSchema` | **Required.** Tables, columns and relations. |
|
|
272
|
+
| `value` / `defaultValue` | `QueryValue \| null` | The query, controlled or uncontrolled. |
|
|
273
|
+
| `onChange` | `(query: QueryValue) => void` | Called on every edit, undo and redo. |
|
|
274
|
+
| `ref` | `Ref<QueryBuilderHandle>` | `resetHistory()`, `goToIssue(issue)` to take the user to a problem, and `run()`. |
|
|
275
|
+
| `readOnly` | `boolean` | Look around the query without changing it. |
|
|
276
|
+
| `tableFilter` | `(table) => boolean` | Tables this user may see. They're never added automatically either. |
|
|
641
277
|
| `columnFilter` | `(table, column) => boolean` | Columns this user may see. |
|
|
642
|
-
| `functions` | `FunctionRegistry` | SQL functions
|
|
643
|
-
| `renderValueInput` | `RenderValueInput` | Your own input for
|
|
644
|
-
| `messages` | `Partial<Messages>` | Interface text,
|
|
645
|
-
| `theme` | `Partial<QueryBuilderTheme>` |
|
|
646
|
-
| `fontFamily` | `string` | The editor's font
|
|
647
|
-
| `components` | `Partial<UIComponents>` |
|
|
648
|
-
| `onSchemaIssues` | `(issues: SchemaIssue[]) => void` |
|
|
649
|
-
| `onIssues` | `(issues: QueryIssue[]) => void` | The query's problems
|
|
650
|
-
| `showIssues` | `boolean` |
|
|
651
|
-
| `typeMismatch` | `'warning' \| 'error'` | How values
|
|
652
|
-
| `dialect` | `'mysql' \| 'mssql' \| 'postgres'` |
|
|
653
|
-
| `betweenOnText` | `'never' \| 'withoutOptions' \| 'always'` |
|
|
654
|
-
| `hideWarnings` | `QueryWarningKind[]` | Warnings not to show
|
|
655
|
-
| `onRun` | `(query) => RunResult \| void \| Promise<…>` | Adds a Run button
|
|
656
|
-
| `direction` | `'ltr' \| 'rtl'` | Which way the canvas grows
|
|
657
|
-
| `orientation` | `'horizontal' \| 'vertical'` |
|
|
658
|
-
| `subqueries` | `{ in
|
|
659
|
-
| `exists` | `ExistsOptions` |
|
|
660
|
-
| `
|
|
661
|
-
| `
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
`useMemo`,
|
|
278
|
+
| `functions` | `FunctionRegistry` | The SQL functions on offer. Defaults to `DEFAULT_FUNCTIONS`. |
|
|
279
|
+
| `renderValueInput` | `RenderValueInput` | Your own input for some columns' values. |
|
|
280
|
+
| `messages` | `Partial<Messages>` | Interface text, for translations. See `DEFAULT_MESSAGES`. |
|
|
281
|
+
| `theme` | `Partial<QueryBuilderTheme>` | Colors. See `DEFAULT_THEME`. |
|
|
282
|
+
| `fontFamily` | `string` | The editor's font. Defaults to the page's. |
|
|
283
|
+
| `components` | `Partial<UIComponents>` | Swap single UI pieces, or bring a whole kit. |
|
|
284
|
+
| `onSchemaIssues` | `(issues: SchemaIssue[]) => void` | Problems found in the schema. |
|
|
285
|
+
| `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. |
|
|
286
|
+
| `showIssues` | `boolean` | The problem count above the canvas, with a list that takes the user to each one. On by default. |
|
|
287
|
+
| `typeMismatch` | `'warning' \| 'error'` | How to report values whose types don't go together. Use the same setting as your server. |
|
|
288
|
+
| `dialect` | `'mysql' \| 'mssql' \| 'postgres'` | Only offer what this database supports. Anything already in the query stays and is reported. |
|
|
289
|
+
| `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". |
|
|
290
|
+
| `hideWarnings` | `QueryWarningKind[]` | Warnings not to show, such as `['crossJoin']`. |
|
|
291
|
+
| `onRun` | `(query) => RunResult \| void \| Promise<…>` | Adds a Run button. See below. |
|
|
292
|
+
| `direction` | `'ltr' \| 'rtl'` | Which way the canvas grows. |
|
|
293
|
+
| `orientation` | `'horizontal' \| 'vertical'` | Lay the main sections out side by side, or stacked for a narrow space. |
|
|
294
|
+
| `subqueries` | `{ in?, union?, shared? }` | Turn on sub queries after IN, UNION ALL, and WITH. All are off by default. |
|
|
295
|
+
| `exists` | `ExistsOptions` | Which related tables the EXISTS button lists, and where it appears. |
|
|
296
|
+
| `onHoverPart` | `(pathSegments \| null) => void` | The part of the query under the pointer, for lighting it up in your own SQL view. |
|
|
297
|
+
| `autoRevealNewNodes` | `boolean` | Pan to nodes as they're added. On by default. |
|
|
298
|
+
| `className` | `string` | Added to the root element. |
|
|
299
|
+
|
|
300
|
+
Pass objects and functions as stable values (module constants, `useMemo`,
|
|
301
|
+
`useCallback`), or the editor redoes work on every render.
|
|
665
302
|
|
|
666
303
|
### Running the query
|
|
667
304
|
|
|
668
|
-
|
|
305
|
+
With `onRun`, the editor gets a Run button (and Ctrl/⌘+Enter). It never
|
|
306
|
+
talks to a database itself. Your `onRun` sends the query to your backend
|
|
307
|
+
and returns the rows, and the editor shows them under the canvas.
|
|
669
308
|
|
|
670
309
|
```tsx
|
|
671
310
|
<QueryBuilder
|
|
672
311
|
schema={schema}
|
|
673
312
|
onRun={async (query) => {
|
|
674
313
|
const res = await fetch('/reports/preview', { method: 'POST', body: JSON.stringify(query) });
|
|
675
|
-
if (!res.ok) throw new Error(await res.text());
|
|
676
|
-
return res.json();
|
|
314
|
+
if (!res.ok) throw new Error(await res.text()); // shown as the error
|
|
315
|
+
return res.json(); // { rows, columns?, truncated? }
|
|
677
316
|
}}
|
|
678
317
|
/>
|
|
679
318
|
```
|
|
680
319
|
|
|
681
|
-
It
|
|
682
|
-
|
|
683
|
-
|
|
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`.
|
|
320
|
+
It sends the query rather than SQL so that your backend checks it and
|
|
321
|
+
writes the SQL itself. Cap the number of rows there, and return
|
|
322
|
+
`truncated: true` when there were more.
|
|
806
323
|
|
|
807
324
|
## Customizing
|
|
808
325
|
|
|
809
|
-
|
|
326
|
+
Add your own SQL functions, drop some, or keep only what one database has:
|
|
810
327
|
|
|
811
328
|
```ts
|
|
812
329
|
import { DEFAULT_FUNCTIONS, functionsForDialect } from '@nongt/visql';
|
|
813
330
|
|
|
814
331
|
const functions = {
|
|
815
332
|
...functionsForDialect(DEFAULT_FUNCTIONS, 'postgres'),
|
|
816
|
-
RISK_SCORE: {
|
|
817
|
-
name: 'RISK_SCORE',
|
|
818
|
-
args: [{ label: 'customer', kind: 'num-expr' }],
|
|
819
|
-
},
|
|
333
|
+
RISK_SCORE: { name: 'RISK_SCORE', args: [{ label: 'customer', kind: 'num-expr' }] },
|
|
820
334
|
};
|
|
821
335
|
```
|
|
822
336
|
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
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:
|
|
337
|
+
If one of your functions sums rows up, mark it `aggregate: true`. Otherwise
|
|
338
|
+
the editor can't know, and won't treat a column that calls it as a group
|
|
339
|
+
key.
|
|
340
|
+
|
|
341
|
+
Give a column its own input, a customer lookup for instance. Return
|
|
342
|
+
`undefined` for the columns you leave to the editor:
|
|
850
343
|
|
|
851
344
|
```tsx
|
|
852
345
|
const renderValueInput: RenderValueInput = ({ table, column, value, onChange }) => (
|
|
@@ -856,62 +349,70 @@ const renderValueInput: RenderValueInput = ({ table, column, value, onChange })
|
|
|
856
349
|
);
|
|
857
350
|
```
|
|
858
351
|
|
|
859
|
-
|
|
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/…`):
|
|
352
|
+
Translate any of the text, and set a font to go with it:
|
|
868
353
|
|
|
869
354
|
```tsx
|
|
870
|
-
|
|
355
|
+
const messages = { addCondition: 'เพิ่มเงื่อนไข', sectionWhere: 'เงื่อนไข' };
|
|
356
|
+
<QueryBuilder messages={messages} fontFamily="Kanit, sans-serif" … />
|
|
871
357
|
```
|
|
872
358
|
|
|
873
|
-
|
|
874
|
-
CSS on `.qb-root`:
|
|
359
|
+
Colors are CSS variables on `.qb-root`, or the `theme` prop:
|
|
875
360
|
|
|
876
361
|
```css
|
|
877
362
|
.qb-root { --qb-accent: #e91e63; --qb-canvas-bg: #fafafa; }
|
|
878
363
|
```
|
|
879
364
|
|
|
880
|
-
|
|
881
|
-
|
|
365
|
+
The editor's CSS stays inside `.qb-root`, and your page's global CSS
|
|
366
|
+
doesn't get in. To use a component library other than MUI, see
|
|
367
|
+
[`docs/ui-adapters.md`](docs/ui-adapters.md).
|
|
882
368
|
|
|
883
|
-
##
|
|
369
|
+
## Packages and entry points
|
|
884
370
|
|
|
885
|
-
| Import | What |
|
|
371
|
+
| Import | What it is |
|
|
886
372
|
|---|---|
|
|
887
373
|
| `@nongt/visql/mui` | `QueryBuilder` with the MUI kit. Needs `@mui/material` and emotion. |
|
|
888
|
-
| `@nongt/visql/mui-date-pickers` |
|
|
889
|
-
| `@nongt/visql` | The
|
|
890
|
-
| `@nongt/visql
|
|
891
|
-
| `@nongt/visql/
|
|
892
|
-
| `@nongt/visql/
|
|
893
|
-
| `@nongt/visql/
|
|
894
|
-
| `@nongt/visql
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
374
|
+
| `@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. |
|
|
375
|
+
| `@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). |
|
|
376
|
+
| `@nongt/visql` | The editor without a UI kit (pass `components`), plus every type and helper. |
|
|
377
|
+
| `@nongt/visql/style.css` | The stylesheet. Import it once. |
|
|
378
|
+
| `@nongt/visql/core` | The query logic alone: no React, no DOM. |
|
|
379
|
+
| `@nongt/visql/sql-import` | `importSql`, for reading SQL someone wrote back into a query. |
|
|
380
|
+
| `@nongt/visql/fixtures` | Contract fixtures for your own tests. |
|
|
381
|
+
| `@nongt/visql-core` | The last three as a package of their own, for a server. |
|
|
382
|
+
|
|
383
|
+
Every peer dependency is optional, since the server-side entries need none
|
|
384
|
+
of them. It's ES modules only. From CommonJS, use Node 20.19+ or 22.12+. The
|
|
385
|
+
types work with TypeScript's older `moduleResolution: "node"` as well as
|
|
386
|
+
`bundler` and `nodenext`.
|
|
387
|
+
|
|
388
|
+
## More documentation
|
|
389
|
+
|
|
390
|
+
- [Query reference](docs/query-reference.md): everything a query can hold
|
|
391
|
+
(EXISTS, IN, BETWEEN, sub queries, unions, WITH, measures), the helpers
|
|
392
|
+
that change a query from code, and parameters.
|
|
393
|
+
- [Checking queries](docs/checking-queries.md): `validateQuery`, sums that
|
|
394
|
+
are safe in a pivot grid, and contract fixtures.
|
|
395
|
+
- [Backend integration](docs/backend-integration.md): the server side, step
|
|
396
|
+
by step.
|
|
397
|
+
- [Importing SQL](docs/sql-import.md): turning hand-written SQL into a
|
|
398
|
+
query.
|
|
399
|
+
- [Showing the SQL and problems](docs/sql-preview.md): a SQL view linked to
|
|
400
|
+
the editor both ways, and a problems list of your own.
|
|
401
|
+
- [UI adapters](docs/ui-adapters.md): using a component library other than
|
|
402
|
+
MUI.
|
|
403
|
+
- [`docs/design/`](docs/design): why some things work the way they do.
|
|
898
404
|
|
|
899
405
|
## Playground
|
|
900
406
|
|
|
901
|
-
The repository's demo app
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
text (in the Kanit font), hidden tables and parameterized SQL.
|
|
407
|
+
The repository's demo app runs the full editor on a sample database, with
|
|
408
|
+
the SQL beside it in each dialect and a panel of options to try (read-only,
|
|
409
|
+
right-to-left, a light theme, Thai text, hidden tables).
|
|
905
410
|
|
|
906
411
|
```bash
|
|
907
412
|
pnpm install
|
|
908
413
|
pnpm dev
|
|
909
414
|
```
|
|
910
415
|
|
|
911
|
-
## Contributing
|
|
912
|
-
|
|
913
|
-
See [CONTRIBUTING.md](CONTRIBUTING.md).
|
|
914
|
-
|
|
915
416
|
## License
|
|
916
417
|
|
|
917
418
|
[MIT](LICENSE)
|