@nongt/visql 0.0.0-stage → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +916 -2
- package/dist/PipelineEditor-DNZkDSaY.js +10042 -0
- package/dist/calendarDate-CYlr9TvX.js +43 -0
- package/dist/core-api-BDCnbFHY.js +1056 -0
- package/dist/core.js +80 -0
- package/dist/fixtures.js +7 -0
- package/dist/index.js +145 -0
- package/dist/issueLocation-Cw5sttQL.js +3183 -0
- package/dist/mui-date-pickers.js +117 -0
- package/dist/mui.js +510 -0
- package/dist/schema-z95dxLxu.js +839 -0
- package/dist/sql-import.js +1366 -0
- package/dist/style.css +1 -0
- package/dist/tokens-BTaVMSOx.js +95 -0
- package/dist/types/adapters/mui/MuiDatePicker.d.ts +12 -0
- package/dist/types/adapters/mui/MuiDateTimePicker.d.ts +10 -0
- package/dist/types/adapters/mui/MuiListInput.d.ts +9 -0
- package/dist/types/adapters/mui/MuiTimePicker.d.ts +10 -0
- package/dist/types/adapters/mui/QueryBuilder.d.ts +12 -0
- package/dist/types/adapters/mui/components.d.ts +16 -0
- package/dist/types/adapters/mui/index.d.ts +6 -0
- package/dist/types/adapters/mui/muiPickers.d.ts +6 -0
- package/dist/types/adapters/mui/pickerStyles.d.ts +28 -0
- package/dist/types/adapters/mui/theme.d.ts +11 -0
- package/dist/types/core/BetweenOnTextContext.d.ts +11 -0
- package/dist/types/core/DialectContext.d.ts +10 -0
- package/dist/types/core/DrillDownContext.d.ts +22 -0
- package/dist/types/core/ExistsContext.d.ts +29 -0
- package/dist/types/core/FlowDirectionContext.d.ts +8 -0
- package/dist/types/core/FlowOrientationContext.d.ts +6 -0
- package/dist/types/core/FunctionsContext.d.ts +25 -0
- package/dist/types/core/GroupKeysContext.d.ts +18 -0
- package/dist/types/core/MeasureLockContext.d.ts +12 -0
- package/dist/types/core/ReadOnlyContext.d.ts +6 -0
- package/dist/types/core/SchemaContext.d.ts +8 -0
- package/dist/types/core/SubqueryContext.d.ts +16 -0
- package/dist/types/core/UnionBranchContext.d.ts +6 -0
- package/dist/types/core/ValueInputContext.d.ts +24 -0
- package/dist/types/core/absolutePath.d.ts +57 -0
- package/dist/types/core/ast.d.ts +154 -0
- package/dist/types/core/astChildren.d.ts +4 -0
- package/dist/types/core/astEqual.d.ts +4 -0
- package/dist/types/core/astMap.d.ts +21 -0
- package/dist/types/core/calendarDate.d.ts +21 -0
- package/dist/types/core/columnFormats.d.ts +23 -0
- package/dist/types/core/components/BoolPicker.d.ts +8 -0
- package/dist/types/core/components/NumberInput.d.ts +8 -0
- package/dist/types/core/components/ReadOnlyPart.d.ts +10 -0
- package/dist/types/core/components/TextInput.d.ts +8 -0
- package/dist/types/core/components/expression/BinaryView.d.ts +10 -0
- package/dist/types/core/components/expression/ExprSummary.d.ts +12 -0
- package/dist/types/core/components/expression/ExpressionTypeSelector.d.ts +35 -0
- package/dist/types/core/components/expression/ExpressionView.d.ts +30 -0
- package/dist/types/core/components/expression/FieldView.d.ts +15 -0
- package/dist/types/core/components/expression/FormulaPeek.d.ts +14 -0
- package/dist/types/core/components/expression/FunctionArgInput.d.ts +22 -0
- package/dist/types/core/components/expression/FunctionView.d.ts +7 -0
- package/dist/types/core/components/expression/ListView.d.ts +20 -0
- package/dist/types/core/components/expression/LiteralView.d.ts +23 -0
- package/dist/types/core/components/expression/LogicalView.d.ts +9 -0
- package/dist/types/core/components/expression/MeasureMenu.d.ts +21 -0
- package/dist/types/core/components/expression/ParamView.d.ts +13 -0
- package/dist/types/core/components/expression/RelativeDateView.d.ts +15 -0
- package/dist/types/core/components/expression/SubqueryView.d.ts +8 -0
- package/dist/types/core/components/expression/formulaClasses.d.ts +8 -0
- package/dist/types/core/components/flow/CaseBranchFlowNode.d.ts +5 -0
- package/dist/types/core/components/flow/CaseElseFlowNode.d.ts +5 -0
- package/dist/types/core/components/flow/CaseFlowNode.d.ts +5 -0
- package/dist/types/core/components/flow/ConditionFlowNode.d.ts +5 -0
- package/dist/types/core/components/flow/CreateConditionFlowNode.d.ts +14 -0
- package/dist/types/core/components/flow/CreateHavingFlowNode.d.ts +11 -0
- package/dist/types/core/components/flow/DistinctToggle.d.ts +10 -0
- package/dist/types/core/components/flow/ExistsFlowNode.d.ts +9 -0
- package/dist/types/core/components/flow/FromFlowNode.d.ts +110 -0
- package/dist/types/core/components/flow/FunctionArgFlowNode.d.ts +5 -0
- package/dist/types/core/components/flow/FunctionCallFlowNode.d.ts +5 -0
- package/dist/types/core/components/flow/FunctionSortKeys.d.ts +10 -0
- package/dist/types/core/components/flow/GroupBgNode.d.ts +14 -0
- package/dist/types/core/components/flow/GroupByFlowNode.d.ts +29 -0
- package/dist/types/core/components/flow/IfElseFlowNode.d.ts +5 -0
- package/dist/types/core/components/flow/IfFlowNode.d.ts +5 -0
- package/dist/types/core/components/flow/IfThenFlowNode.d.ts +5 -0
- package/dist/types/core/components/flow/LeafConditionFrame.d.ts +19 -0
- package/dist/types/core/components/flow/LogicalFlowNode.d.ts +5 -0
- package/dist/types/core/components/flow/MoveTooltip.d.ts +19 -0
- package/dist/types/core/components/flow/NotFlowNode.d.ts +5 -0
- package/dist/types/core/components/flow/OrderByFlowNode.d.ts +32 -0
- package/dist/types/core/components/flow/SectionLabelFlowNode.d.ts +7 -0
- package/dist/types/core/components/flow/SelectFlowNode.d.ts +49 -0
- package/dist/types/core/components/flow/SharedQueriesFlowNode.d.ts +39 -0
- package/dist/types/core/components/flow/SummaryPill.d.ts +12 -0
- package/dist/types/core/components/flow/WarningNote.d.ts +9 -0
- package/dist/types/core/components/flow/chainSides.d.ts +18 -0
- package/dist/types/core/components/flow/dragContext.d.ts +12 -0
- package/dist/types/core/components/flow/moveTooltipHysteresis.d.ts +18 -0
- package/dist/types/core/components/flow/useRowDrag.d.ts +34 -0
- package/dist/types/core/components/flow/useRowReorderFlip.d.ts +30 -0
- package/dist/types/core/derivedTables.d.ts +98 -0
- package/dist/types/core/distinctSort.d.ts +7 -0
- package/dist/types/core/drillPath.d.ts +11 -0
- package/dist/types/core/exists.d.ts +7 -0
- package/dist/types/core/existsMenu.d.ts +61 -0
- package/dist/types/core/expressionFlow.d.ts +428 -0
- package/dist/types/core/fanOut.d.ts +58 -0
- package/dist/types/core/findParts.d.ts +19 -0
- package/dist/types/core/flowTrees.d.ts +20 -0
- package/dist/types/core/focusKey.d.ts +10 -0
- package/dist/types/core/formula.d.ts +24 -0
- package/dist/types/core/formulaPeek.d.ts +16 -0
- package/dist/types/core/functionRegistry.d.ts +117 -0
- package/dist/types/core/grouping.d.ts +58 -0
- package/dist/types/core/history.d.ts +25 -0
- package/dist/types/core/i18n/defaultMessages.d.ts +367 -0
- package/dist/types/core/i18n/messages.d.ts +273 -0
- package/dist/types/core/i18n/relativeDateWords.d.ts +3 -0
- package/dist/types/core/id.d.ts +5 -0
- package/dist/types/core/issueAnchor.d.ts +29 -0
- package/dist/types/core/issueLocation.d.ts +105 -0
- package/dist/types/core/limits.d.ts +17 -0
- package/dist/types/core/measures.d.ts +51 -0
- package/dist/types/core/params.d.ts +30 -0
- package/dist/types/core/pipelineAnchor.d.ts +118 -0
- package/dist/types/core/pipelineFlow.d.ts +271 -0
- package/dist/types/core/queryAst.d.ts +201 -0
- package/dist/types/core/queryHelpers.d.ts +113 -0
- package/dist/types/core/queryValidation.d.ts +206 -0
- package/dist/types/core/relativeDates.d.ts +11 -0
- package/dist/types/core/resolveNames.d.ts +17 -0
- package/dist/types/core/rowRange.d.ts +3 -0
- package/dist/types/core/schema.d.ts +119 -0
- package/dist/types/core/scopeQuery.d.ts +45 -0
- package/dist/types/core/selectColumns.d.ts +23 -0
- package/dist/types/core/settleQuery.d.ts +11 -0
- package/dist/types/core/sharedQueries.d.ts +66 -0
- package/dist/types/core/sqlGen.d.ts +102 -0
- package/dist/types/core/sqlOffsets.d.ts +5 -0
- package/dist/types/core/sqlSpans.d.ts +33 -0
- package/dist/types/core/storedQuery.d.ts +43 -0
- package/dist/types/core/summarize.d.ts +3 -0
- package/dist/types/core/theme/tokens.d.ts +74 -0
- package/dist/types/core/ui/UIContext.d.ts +6 -0
- package/dist/types/core/ui/index.d.ts +12 -0
- package/dist/types/core/ui/types.d.ts +264 -0
- package/dist/types/core/unionTables.d.ts +121 -0
- package/dist/types/core/useValueTypes.d.ts +12 -0
- package/dist/types/core/valueTypes.d.ts +54 -0
- package/dist/types/core-api.d.ts +20 -0
- package/dist/types/features/queryEditor/ExpressionFlowCanvas.d.ts +10 -0
- package/dist/types/features/queryEditor/FindBox.d.ts +12 -0
- package/dist/types/features/queryEditor/FlowCanvas.d.ts +96 -0
- package/dist/types/features/queryEditor/FocusPulse.d.ts +10 -0
- package/dist/types/features/queryEditor/IssuesButton.d.ts +16 -0
- package/dist/types/features/queryEditor/PipelineEditor.d.ts +210 -0
- package/dist/types/features/queryEditor/QueryOutline.d.ts +16 -0
- package/dist/types/features/queryEditor/ResultsPanel.d.ts +11 -0
- package/dist/types/features/queryEditor/RunButton.d.ts +11 -0
- package/dist/types/features/queryEditor/SubFlowPanel.d.ts +24 -0
- package/dist/types/features/queryEditor/UndoRedoToast.d.ts +6 -0
- package/dist/types/features/queryEditor/canvasPositioning.d.ts +81 -0
- package/dist/types/features/queryEditor/findKeys.d.ts +3 -0
- package/dist/types/features/queryEditor/flowDragUtils.d.ts +16 -0
- package/dist/types/features/queryEditor/focusContext.d.ts +24 -0
- package/dist/types/features/queryEditor/hoveredPart.d.ts +32 -0
- package/dist/types/features/queryEditor/issueFocusParts.d.ts +9 -0
- package/dist/types/features/queryEditor/issueLocationText.d.ts +7 -0
- package/dist/types/features/queryEditor/issueText.d.ts +11 -0
- package/dist/types/features/queryEditor/outlineSections.d.ts +23 -0
- package/dist/types/features/queryEditor/run.d.ts +36 -0
- package/dist/types/features/queryEditor/sectionLabels.d.ts +15 -0
- package/dist/types/features/queryEditor/treeScopeContext.d.ts +14 -0
- package/dist/types/features/queryEditor/useRemeasureOnDirectionChange.d.ts +7 -0
- package/dist/types/features/queryEditor/useRevealNewNodes.d.ts +35 -0
- package/dist/types/features/queryEditor/withTreeScope.d.ts +10 -0
- package/dist/types/fixtures.d.ts +44 -0
- package/dist/types/index.d.ts +13 -0
- package/dist/types/mui-date-pickers.d.ts +3 -0
- package/dist/types/mui.d.ts +2 -0
- package/dist/types/sql-import.d.ts +3 -0
- package/dist/types/sqlImport/context.d.ts +71 -0
- package/dist/types/sqlImport/expressions.d.ts +11 -0
- package/dist/types/sqlImport/importSql.d.ts +28 -0
- package/dist/types/sqlImport/parse.d.ts +6 -0
- package/dist/types/sqlImport/syntax.d.ts +245 -0
- package/dist/types/sqlImport/tokenize.d.ts +26 -0
- package/package.json +164 -3
package/README.md
CHANGED
|
@@ -1,3 +1,917 @@
|
|
|
1
|
-
#
|
|
1
|
+
# visql
|
|
2
2
|
|
|
3
|
-
|
|
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).
|
|
44
|
+
|
|
45
|
+
## Install
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
# the editor
|
|
49
|
+
pnpm add @nongt/visql react react-dom @xyflow/react iconoir-react
|
|
50
|
+
# for the MUI preset (the usual choice):
|
|
51
|
+
pnpm add @mui/material @emotion/react @emotion/styled @emotion/cache
|
|
52
|
+
|
|
53
|
+
# a backend: the query logic alone, nothing else comes with it
|
|
54
|
+
pnpm add @nongt/visql-core
|
|
55
|
+
```
|
|
56
|
+
|
|
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.
|
|
60
|
+
|
|
61
|
+
## Quick start
|
|
62
|
+
|
|
63
|
+
```tsx
|
|
64
|
+
import { useState } from 'react';
|
|
65
|
+
import { QueryBuilder } from '@nongt/visql/mui';
|
|
66
|
+
import { astToSql, hasBaseTable, type QueryValue } from '@nongt/visql';
|
|
67
|
+
import '@nongt/visql/style.css';
|
|
68
|
+
import { schema } from './schema';
|
|
69
|
+
|
|
70
|
+
export function ReportEditor() {
|
|
71
|
+
const [query, setQuery] = useState<QueryValue | null>(null);
|
|
72
|
+
const sql = query && hasBaseTable(query) ? astToSql(query, 'postgres') : '';
|
|
73
|
+
|
|
74
|
+
return (
|
|
75
|
+
<>
|
|
76
|
+
<div style={{ height: 600 }}>
|
|
77
|
+
<QueryBuilder schema={schema} value={query} onChange={setQuery} />
|
|
78
|
+
</div>
|
|
79
|
+
<pre>{sql}</pre>
|
|
80
|
+
</>
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
The editor fills its container, so give it a height.
|
|
86
|
+
|
|
87
|
+
## The schema
|
|
88
|
+
|
|
89
|
+
Describe the database the user builds queries against. Tables and columns
|
|
90
|
+
fill the pickers. Relations (foreign keys) drive join suggestions.
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
import type { DatabaseSchema } from '@nongt/visql';
|
|
94
|
+
|
|
95
|
+
export const schema: DatabaseSchema = {
|
|
96
|
+
tables: [
|
|
97
|
+
{
|
|
98
|
+
name: 'orders',
|
|
99
|
+
label: 'Orders',
|
|
100
|
+
columns: [
|
|
101
|
+
{ name: 'id', label: 'ID', type: 'integer' },
|
|
102
|
+
{ name: 'customer_id', label: 'Customer', type: 'integer' },
|
|
103
|
+
{ name: 'placed_at', label: 'Placed At', type: 'dateTime' },
|
|
104
|
+
{
|
|
105
|
+
name: 'status',
|
|
106
|
+
label: 'Status',
|
|
107
|
+
type: 'varchar',
|
|
108
|
+
// Values compared against this column come from a dropdown.
|
|
109
|
+
options: [
|
|
110
|
+
{ value: 'open', label: 'Open' },
|
|
111
|
+
{ value: 'shipped', label: 'Shipped' },
|
|
112
|
+
],
|
|
113
|
+
},
|
|
114
|
+
],
|
|
115
|
+
},
|
|
116
|
+
{
|
|
117
|
+
name: 'customers',
|
|
118
|
+
label: 'Customers',
|
|
119
|
+
columns: [
|
|
120
|
+
{ name: 'id', label: 'ID', type: 'integer' },
|
|
121
|
+
{ name: 'name', label: 'Name', type: 'varchar' },
|
|
122
|
+
],
|
|
123
|
+
},
|
|
124
|
+
],
|
|
125
|
+
relations: [
|
|
126
|
+
// orders.customer_id references customers.id — declare each key once,
|
|
127
|
+
// from the "many" side.
|
|
128
|
+
{ fromTable: 'orders', fromColumn: 'customer_id', toTable: 'customers', toColumn: 'id' },
|
|
129
|
+
],
|
|
130
|
+
};
|
|
131
|
+
```
|
|
132
|
+
|
|
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.
|
|
137
|
+
|
|
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`:
|
|
142
|
+
|
|
143
|
+
```ts
|
|
144
|
+
{ name: 'opens_at', label: 'Opens At', type: 'time', format: 'HH:mm' }
|
|
145
|
+
{ name: 'opened_on', label: 'Opened On', type: 'date', format: 'YYYYMMDD' }
|
|
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.
|
|
167
|
+
|
|
168
|
+
## The query value
|
|
169
|
+
|
|
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).
|
|
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.
|
|
173
|
+
|
|
174
|
+
```ts
|
|
175
|
+
interface QueryPipeline {
|
|
176
|
+
id: string; // the query's identity — stays the same through every edit
|
|
177
|
+
from: { table: string; alias?: string };
|
|
178
|
+
joins: { id: string; table: string; joinType: 'inner' | 'left' | 'right' | 'full'; on?: ExpressionNode }[];
|
|
179
|
+
where?: ExpressionNode;
|
|
180
|
+
groupBy?: { id: string; expression: ExpressionNode; fromSelect?: string }[];
|
|
181
|
+
having?: ExpressionNode;
|
|
182
|
+
select: { id: string; expression: ExpressionNode; alias?: string }[];
|
|
183
|
+
distinct?: boolean;
|
|
184
|
+
orderBy?: { id: string; expression: ExpressionNode; direction: 'asc' | 'desc' }[];
|
|
185
|
+
limit?: number; // non-negative integers
|
|
186
|
+
offset?: number;
|
|
187
|
+
}
|
|
188
|
+
type QueryValue = QueryPipeline | { id: string }; // { id } = no base table chosen yet
|
|
189
|
+
```
|
|
190
|
+
|
|
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.
|
|
198
|
+
|
|
199
|
+
### Storing a query
|
|
200
|
+
|
|
201
|
+
```ts
|
|
202
|
+
import { loadQuery, saveQuery, QueryFormatError } from '@nongt/visql/core';
|
|
203
|
+
|
|
204
|
+
db.save(report.id, JSON.stringify(saveQuery(query))); // { version, query }
|
|
205
|
+
|
|
206
|
+
const query = loadQuery(JSON.parse(db.load(report.id))); // the same query back
|
|
207
|
+
```
|
|
208
|
+
|
|
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*).
|
|
214
|
+
|
|
215
|
+
## SQL output
|
|
216
|
+
|
|
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:
|
|
218
|
+
|
|
219
|
+
```ts
|
|
220
|
+
import { astToParameterizedSql } from '@nongt/visql';
|
|
221
|
+
|
|
222
|
+
const { sql, params } = astToParameterizedSql(query, 'postgres');
|
|
223
|
+
// sql: SELECT * FROM "orders" WHERE "orders"."status" = $1 AND "orders"."total" > $2
|
|
224
|
+
// params: ['open', 100]
|
|
225
|
+
await pg.query(sql, params);
|
|
226
|
+
```
|
|
227
|
+
|
|
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.
|
|
229
|
+
|
|
230
|
+
To **show** a query, `astToSql` writes the values inline (strings quoted and escaped):
|
|
231
|
+
|
|
232
|
+
```ts
|
|
233
|
+
import { astToSql } from '@nongt/visql';
|
|
234
|
+
|
|
235
|
+
astToSql(query, 'mysql'); // 'mysql' | 'mssql' | 'postgres'
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
## On the backend
|
|
239
|
+
|
|
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.
|
|
241
|
+
|
|
242
|
+
```ts
|
|
243
|
+
// server
|
|
244
|
+
import {
|
|
245
|
+
astToParameterizedSql, hasBaseTable, validateQuery, type QueryValue,
|
|
246
|
+
} from '@nongt/visql/core';
|
|
247
|
+
|
|
248
|
+
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.
|
|
252
|
+
const issues = validateQuery(schema, query, {
|
|
253
|
+
tableFilter: (t) => req.user.canSee(t.name),
|
|
254
|
+
});
|
|
255
|
+
// Errors mean "don't run it"; warnings (fan-out, no LIMIT…) can run.
|
|
256
|
+
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
|
|
259
|
+
|
|
260
|
+
const { sql, params } = astToParameterizedSql(valid, 'postgres');
|
|
261
|
+
res.json(await db.query(sql, params));
|
|
262
|
+
});
|
|
263
|
+
```
|
|
264
|
+
|
|
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.
|
|
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
|
+
```
|
|
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).
|
|
630
|
+
|
|
631
|
+
## Props
|
|
632
|
+
|
|
633
|
+
| Prop | Type | |
|
|
634
|
+
|---|---|---|
|
|
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). |
|
|
641
|
+
| `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`).
|
|
665
|
+
|
|
666
|
+
### Running the query
|
|
667
|
+
|
|
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.
|
|
669
|
+
|
|
670
|
+
```tsx
|
|
671
|
+
<QueryBuilder
|
|
672
|
+
schema={schema}
|
|
673
|
+
onRun={async (query) => {
|
|
674
|
+
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? }
|
|
677
|
+
}}
|
|
678
|
+
/>
|
|
679
|
+
```
|
|
680
|
+
|
|
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`.
|
|
806
|
+
|
|
807
|
+
## Customizing
|
|
808
|
+
|
|
809
|
+
**Functions**: add your own, drop some, or keep one dialect's:
|
|
810
|
+
|
|
811
|
+
```ts
|
|
812
|
+
import { DEFAULT_FUNCTIONS, functionsForDialect } from '@nongt/visql';
|
|
813
|
+
|
|
814
|
+
const functions = {
|
|
815
|
+
...functionsForDialect(DEFAULT_FUNCTIONS, 'postgres'),
|
|
816
|
+
RISK_SCORE: {
|
|
817
|
+
name: 'RISK_SCORE',
|
|
818
|
+
args: [{ label: 'customer', kind: 'num-expr' }],
|
|
819
|
+
},
|
|
820
|
+
};
|
|
821
|
+
```
|
|
822
|
+
|
|
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:
|
|
850
|
+
|
|
851
|
+
```tsx
|
|
852
|
+
const renderValueInput: RenderValueInput = ({ table, column, value, onChange }) => (
|
|
853
|
+
table.name === 'orders' && column.name === 'customer_id'
|
|
854
|
+
? <CustomerPicker value={value} onChange={onChange} />
|
|
855
|
+
: undefined
|
|
856
|
+
);
|
|
857
|
+
```
|
|
858
|
+
|
|
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/…`):
|
|
868
|
+
|
|
869
|
+
```tsx
|
|
870
|
+
<QueryBuilder messages={THAI_MESSAGES} fontFamily="Kanit, sans-serif" … />
|
|
871
|
+
```
|
|
872
|
+
|
|
873
|
+
**Colors**: every color is a role-named token, set through `theme` or in
|
|
874
|
+
CSS on `.qb-root`:
|
|
875
|
+
|
|
876
|
+
```css
|
|
877
|
+
.qb-root { --qb-accent: #e91e63; --qb-canvas-bg: #fafafa; }
|
|
878
|
+
```
|
|
879
|
+
|
|
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.
|
|
882
|
+
|
|
883
|
+
## Entry points
|
|
884
|
+
|
|
885
|
+
| Import | What |
|
|
886
|
+
|---|---|
|
|
887
|
+
| `@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).
|
|
898
|
+
|
|
899
|
+
## Playground
|
|
900
|
+
|
|
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.
|
|
905
|
+
|
|
906
|
+
```bash
|
|
907
|
+
pnpm install
|
|
908
|
+
pnpm dev
|
|
909
|
+
```
|
|
910
|
+
|
|
911
|
+
## Contributing
|
|
912
|
+
|
|
913
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md).
|
|
914
|
+
|
|
915
|
+
## License
|
|
916
|
+
|
|
917
|
+
[MIT](LICENSE)
|