@romedb/studio 0.0.0-stage → 0.1.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.md +20 -0
- package/README.md +15 -2
- package/package.json +36 -4
- package/src/components/CodeEditor.ts +298 -0
- package/src/components/studio/BrowseTab.ts +457 -0
- package/src/components/studio/CellEditorSheet.ts +165 -0
- package/src/components/studio/DatabaseTab.ts +148 -0
- package/src/components/studio/GraphCanvas.ts +90 -0
- package/src/components/studio/GraphTab.ts +110 -0
- package/src/components/studio/InsertRowSheet.ts +180 -0
- package/src/components/studio/MapCanvas.ts +177 -0
- package/src/components/studio/MapTab.ts +121 -0
- package/src/components/studio/NewObjectSheet.ts +235 -0
- package/src/components/studio/QueryHistorySheet.ts +111 -0
- package/src/components/studio/RowSheets.ts +226 -0
- package/src/components/studio/SqlConsole.ts +281 -0
- package/src/components/studio/StructureTab.ts +209 -0
- package/src/components/studio/icon-button.ts +21 -0
- package/src/lib/filters.ts +44 -0
- package/src/lib/graph.ts +214 -0
- package/src/lib/romeql.ts +106 -0
- package/src/lib/spatial.ts +518 -0
- package/src/lib/sql-text.ts +208 -0
- package/src/lib/studio-types.ts +268 -0
- package/src/lib/values.ts +305 -0
- package/src/monaco-standalone.d.ts +27 -0
- package/src/schema-draft.ts +41 -0
- package/src/schema-store.ts +8 -0
- package/src/server/backend.ts +77 -0
- package/src/server/data.ts +142 -0
- package/src/server/edits.ts +92 -0
- package/src/server/graph.ts +66 -0
- package/src/server/queries.ts +108 -0
- package/src/server/schema.ts +272 -0
- package/src/server/spatial.ts +74 -0
- package/src/studio-page.ts +84 -0
- package/src/workspace/StudioWorkspace.ts +1970 -0
- package/src/workspace/workspace.css +38 -0
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
// Adapted from Cossack Studio's StructureTab (MIT) for RomeDB tables, collections and views.
|
|
2
|
+
import { Component, Cossack } from '@cossackframework/core';
|
|
3
|
+
import { component, html } from '@cossackframework/renderer';
|
|
4
|
+
import { KeyIcon } from '@cossackframework/solar-icons/key';
|
|
5
|
+
import { Badge, Button, Checkbox, Icon } from '@cossackframework/ui';
|
|
6
|
+
import type { StudioObject, StudioSchema } from '../../lib/studio-types';
|
|
7
|
+
import { CodeEditor } from '../CodeEditor';
|
|
8
|
+
import { spatialKindLabel } from '../../lib/spatial';
|
|
9
|
+
|
|
10
|
+
export interface StructureTabProps {
|
|
11
|
+
object?: StudioObject;
|
|
12
|
+
schema: StudioSchema;
|
|
13
|
+
theme: 'light' | 'dark';
|
|
14
|
+
active: boolean;
|
|
15
|
+
onOpenTable: (name: string) => void;
|
|
16
|
+
onOpenGraph: (edge: string) => void;
|
|
17
|
+
onOpenMap: (index: string) => void;
|
|
18
|
+
[key: string]: unknown;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
@Component()
|
|
22
|
+
export class StructureTab extends Cossack {
|
|
23
|
+
declare props: StructureTabProps;
|
|
24
|
+
|
|
25
|
+
render() {
|
|
26
|
+
const { object, active } = this.props;
|
|
27
|
+
if (!object) {
|
|
28
|
+
return html`
|
|
29
|
+
<div class="${active ? 'block' : 'hidden'} min-h-0 flex-1 p-6 text-muted-foreground">
|
|
30
|
+
Select a database object.
|
|
31
|
+
</div>
|
|
32
|
+
`;
|
|
33
|
+
}
|
|
34
|
+
const isDocument = object.model === 'document';
|
|
35
|
+
return html`
|
|
36
|
+
<div class="${active ? 'block' : 'hidden'} min-h-0 flex-1 overflow-auto p-5" data-testid="structure-panel">
|
|
37
|
+
<div class="mb-4 flex flex-wrap items-center gap-2">
|
|
38
|
+
<h2 class="text-lg font-semibold">${object.name}</h2>
|
|
39
|
+
${component(Badge, { variant: 'secondary' }, object.model === 'document' ? 'Document collection' : object.model === 'view' ? 'View' : 'Relational table')}
|
|
40
|
+
${isDocument ? component(Badge, { variant: 'outline' }, object.strict ? 'Strict schema' : 'Flexible schema') : ''}
|
|
41
|
+
${object.edge ? component(Badge, { variant: 'default', 'data-testid': 'edge-badge' }, 'Edge table') : ''}
|
|
42
|
+
</div>
|
|
43
|
+
|
|
44
|
+
${object.edge ? html`
|
|
45
|
+
<section class="mb-6 rounded-md border p-4" data-testid="edge-structure">
|
|
46
|
+
<h3 class="mb-2 font-semibold">Edge declaration</h3>
|
|
47
|
+
<p class="font-mono text-sm">
|
|
48
|
+
<button type="button" class="text-primary hover:underline" @click="${() => this.props.onOpenTable(object.edge!.source)}">${object.edge.source}</button>
|
|
49
|
+
→ ${object.name} →
|
|
50
|
+
<button type="button" class="text-primary hover:underline" @click="${() => this.props.onOpenTable(object.edge!.target)}">${object.edge.target}</button>
|
|
51
|
+
</p>
|
|
52
|
+
<p class="mt-2 text-sm text-muted-foreground">
|
|
53
|
+
On delete: <strong>${object.edge.onDelete}</strong> —
|
|
54
|
+
${object.edge.onDelete === 'cascade' ? 'deleting a node also deletes its edges in this table.' : 'a node with edges in this table cannot be deleted.'}
|
|
55
|
+
<code class="rounded bg-muted px-1">source</code> and <code class="rounded bg-muted px-1">target</code> are immutable.
|
|
56
|
+
Outgoing and incoming adjacency indexes are maintained automatically.
|
|
57
|
+
</p>
|
|
58
|
+
<div class="mt-3">${component(Button, { size: 'sm', variant: 'outline', 'data-testid': 'open-graph', '@click': () => this.props.onOpenGraph(object.name) }, 'Explore in Graph')}</div>
|
|
59
|
+
</section>
|
|
60
|
+
` : ''}
|
|
61
|
+
${object.edgeTables?.length ? html`
|
|
62
|
+
<section class="mb-6" data-testid="node-edge-tables">
|
|
63
|
+
<h3 class="mb-2 font-semibold">Edge tables</h3>
|
|
64
|
+
<div class="flex flex-wrap gap-2">
|
|
65
|
+
${object.edgeTables.map(name => html`<button type="button" class="rounded-md border px-2 py-1 font-mono text-sm text-primary hover:bg-accent" @click="${() => this.props.onOpenTable(name)}">${name}</button>`)}
|
|
66
|
+
</div>
|
|
67
|
+
<p class="mt-2 text-sm text-muted-foreground">Drop these edge tables before dropping this collection.</p>
|
|
68
|
+
</section>
|
|
69
|
+
` : ''}
|
|
70
|
+
|
|
71
|
+
<table class="w-full text-sm" data-testid="structure-table">
|
|
72
|
+
<thead><tr class="border-b text-left">
|
|
73
|
+
<th class="p-2">${isDocument ? 'Field' : 'Column'}</th>
|
|
74
|
+
<th class="p-2">Type</th>
|
|
75
|
+
${isDocument ? '' : html`<th class="p-2">Affinity</th>`}
|
|
76
|
+
<th class="p-2 text-center">Nullable</th>
|
|
77
|
+
<th class="p-2">Default</th>
|
|
78
|
+
<th class="p-2">${isDocument ? 'Rules' : 'Key'}</th>
|
|
79
|
+
</tr></thead>
|
|
80
|
+
<tbody>${object.columns.map(column => html`
|
|
81
|
+
<tr class="border-b">
|
|
82
|
+
<td class="p-2 font-medium">${column.name}${column.hidden ? html`<span class="ml-1 text-xs text-muted-foreground">(generated)</span>` : ''}</td>
|
|
83
|
+
<td class="p-2 font-mono" data-testid="column-type-${column.name}">${column.dataType || '—'}</td>
|
|
84
|
+
${isDocument ? '' : html`<td class="p-2">${column.affinity}</td>`}
|
|
85
|
+
<td class="p-2 text-center">${component(Checkbox, {
|
|
86
|
+
checked: column.nullable,
|
|
87
|
+
disabled: true,
|
|
88
|
+
'aria-label': `${column.name} ${column.nullable ? 'is nullable' : 'is required'}`,
|
|
89
|
+
})}</td>
|
|
90
|
+
<td class="p-2 font-mono">${column.defaultValue ?? '—'}</td>
|
|
91
|
+
<td class="p-2">
|
|
92
|
+
${column.primaryKeyPosition ? html`
|
|
93
|
+
<span class="inline-flex items-center gap-1.5 text-primary" title="${isDocument ? 'Record ID' : `Primary key position ${column.primaryKeyPosition}`}">
|
|
94
|
+
${component(Icon, { entry: KeyIcon, size: 16 })}
|
|
95
|
+
<span>${isDocument ? 'Record ID' : `PK ${column.primaryKeyPosition}`}</span>
|
|
96
|
+
</span>
|
|
97
|
+
` : isDocument ? html`
|
|
98
|
+
<span class="text-xs text-muted-foreground">
|
|
99
|
+
${[column.required ? 'required' : '', column.readonly ? 'read only' : '', column.check ? `check ${column.check}` : ''].filter(Boolean).join(' · ') || '—'}
|
|
100
|
+
</span>
|
|
101
|
+
` : '—'}
|
|
102
|
+
</td>
|
|
103
|
+
</tr>
|
|
104
|
+
`)}</tbody>
|
|
105
|
+
</table>
|
|
106
|
+
${isDocument && object.columns.length === 1 ? html`
|
|
107
|
+
<p class="mt-2 text-sm text-muted-foreground">
|
|
108
|
+
No fields are defined. Documents may contain any fields; use <code class="rounded bg-muted px-1">DEFINE FIELD</code> to add validation.
|
|
109
|
+
</p>
|
|
110
|
+
` : ''}
|
|
111
|
+
|
|
112
|
+
<section class="mt-6">
|
|
113
|
+
<h3 class="mb-2 font-semibold">Row identity</h3>
|
|
114
|
+
${object.keyFields.length ? html`
|
|
115
|
+
<div class="flex flex-wrap gap-2" data-testid="row-locators">
|
|
116
|
+
${component(Badge, { variant: 'default' }, isDocument ? 'Record ID: id' : `Primary key: ${object.keyFields.join(', ')}`)}
|
|
117
|
+
</div>
|
|
118
|
+
` : html`<p class="text-sm text-muted-foreground">${object.readOnlyReason}</p>`}
|
|
119
|
+
</section>
|
|
120
|
+
|
|
121
|
+
${isDocument ? '' : html`
|
|
122
|
+
<section class="mt-6">
|
|
123
|
+
<h3 class="mb-2 font-semibold">Foreign keys</h3>
|
|
124
|
+
${object.foreignKeys.length ? html`
|
|
125
|
+
<table class="w-full text-sm" data-testid="foreign-key-table">
|
|
126
|
+
<thead><tr class="border-b text-left">
|
|
127
|
+
<th class="p-2">Columns</th><th class="p-2">References</th>
|
|
128
|
+
<th class="p-2">On update</th><th class="p-2">On delete</th>
|
|
129
|
+
</tr></thead>
|
|
130
|
+
<tbody>${object.foreignKeys.map(foreignKey => html`
|
|
131
|
+
<tr class="border-b">
|
|
132
|
+
<td class="p-2 font-mono">${foreignKey.columns.map(column => column.column).join(', ')}</td>
|
|
133
|
+
<td class="p-2 font-mono">
|
|
134
|
+
<button type="button" class="text-primary hover:underline" @click="${() => this.props.onOpenTable(foreignKey.referencedTable)}">${foreignKey.referencedTable}</button>
|
|
135
|
+
(${foreignKey.columns.map(column => column.referencedColumn).join(', ')})
|
|
136
|
+
</td>
|
|
137
|
+
<td class="p-2">${foreignKey.onUpdate ?? '—'}</td>
|
|
138
|
+
<td class="p-2">${foreignKey.onDelete ?? '—'}</td>
|
|
139
|
+
</tr>
|
|
140
|
+
`)}</tbody>
|
|
141
|
+
</table>
|
|
142
|
+
` : html`<p class="text-sm text-muted-foreground">No foreign keys declared.</p>`}
|
|
143
|
+
</section>
|
|
144
|
+
`}
|
|
145
|
+
|
|
146
|
+
<section class="mt-6">
|
|
147
|
+
<h3 class="mb-2 font-semibold">Indexes</h3>
|
|
148
|
+
${object.indexes.length ? html`
|
|
149
|
+
<table class="w-full text-sm" data-testid="index-table">
|
|
150
|
+
<thead><tr class="border-b text-left">
|
|
151
|
+
<th class="p-2">Name</th><th class="p-2">Kind</th><th class="p-2">${isDocument ? 'Paths' : 'Columns'}</th>
|
|
152
|
+
<th class="p-2">Unique</th>${isDocument ? '' : html`<th class="p-2">Origin</th><th class="p-2">Partial</th>`}
|
|
153
|
+
</tr></thead>
|
|
154
|
+
<tbody>${object.indexes.map(index => html`
|
|
155
|
+
<tr class="border-b">
|
|
156
|
+
<td class="p-2 font-mono">${index.name}</td>
|
|
157
|
+
<td class="p-2" data-testid="index-kind-${index.name}">
|
|
158
|
+
<span class="inline-flex flex-wrap items-center gap-2">
|
|
159
|
+
<span>${spatialKindLabel(index)}</span>
|
|
160
|
+
${index.kind === 'Spatial' && isDocument ? component(Button, { size: 'sm', variant: 'outline', class: 'h-7 px-2 text-xs', 'data-testid': `open-map-${index.name}`, '@click': () => this.props.onOpenMap(index.name) }, 'Show on Map') : ''}
|
|
161
|
+
</span>
|
|
162
|
+
</td>
|
|
163
|
+
<td class="p-2 font-mono">${index.columns.join(', ') || '(automatic)'}</td>
|
|
164
|
+
<td class="p-2">${component(Checkbox, { checked: index.unique, disabled: true, 'aria-label': `${index.name} unique` })}</td>
|
|
165
|
+
${isDocument ? '' : html`
|
|
166
|
+
<td class="p-2">${index.origin}</td>
|
|
167
|
+
<td class="p-2">${component(Checkbox, { checked: index.partial, disabled: true, 'aria-label': `${index.name} partial` })}</td>
|
|
168
|
+
`}
|
|
169
|
+
</tr>
|
|
170
|
+
`)}</tbody>
|
|
171
|
+
</table>
|
|
172
|
+
` : html`<p class="text-sm text-muted-foreground">No indexes declared.</p>`}
|
|
173
|
+
${object.indexes.some(index => index.kind === 'Spatial') ? html`
|
|
174
|
+
<p class="mt-2 text-sm text-muted-foreground" data-testid="spatial-index-help">
|
|
175
|
+
Point indexes serve <code class="rounded bg-muted px-1">search::near</code>, <code class="rounded bg-muted px-1">search::bbox</code>,
|
|
176
|
+
<code class="rounded bg-muted px-1">search::polygon</code> and <code class="rounded bg-muted px-1">search::nearest</code>.
|
|
177
|
+
Region indexes hold Polygon and MultiPolygon values and serve <code class="rounded bg-muted px-1">search::containing</code>.
|
|
178
|
+
${object.indexes.some(index => index.spatialFormat === 'latitude') ? html`Latitude-format indexes keep working; <code class="rounded bg-muted px-1">REINDEX name</code> upgrades them to the two-dimensional format.` : ''}
|
|
179
|
+
</p>
|
|
180
|
+
` : ''}
|
|
181
|
+
</section>
|
|
182
|
+
|
|
183
|
+
${isDocument && object.capabilities?.length ? html`
|
|
184
|
+
<section class="mt-6">
|
|
185
|
+
<h3 class="mb-2 font-semibold">Collection capabilities</h3>
|
|
186
|
+
<div class="flex flex-wrap gap-2">${object.capabilities.map(capability => component(Badge, { variant: 'outline' }, capability.replaceAll('_', ' ')))}</div>
|
|
187
|
+
</section>
|
|
188
|
+
` : ''}
|
|
189
|
+
|
|
190
|
+
${object.sql ? html`
|
|
191
|
+
<section class="mt-6">
|
|
192
|
+
<h3 class="mb-2 font-semibold">Definition</h3>
|
|
193
|
+
${component(CodeEditor, {
|
|
194
|
+
class: 'h-[12rem]',
|
|
195
|
+
value: object.sql,
|
|
196
|
+
language: 'sql',
|
|
197
|
+
theme: this.props.theme,
|
|
198
|
+
schema: this.props.schema,
|
|
199
|
+
enabled: active,
|
|
200
|
+
readOnly: true,
|
|
201
|
+
ariaLabel: `${object.name} definition`,
|
|
202
|
+
'data-testid': 'structure-sql',
|
|
203
|
+
})}
|
|
204
|
+
</section>
|
|
205
|
+
` : ''}
|
|
206
|
+
</div>
|
|
207
|
+
`;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { component } from '@cossackframework/renderer';
|
|
2
|
+
import type { IconEntry } from '@cossackframework/solar-icons/types';
|
|
3
|
+
import { Button, Icon, Tooltip } from '@cossackframework/ui';
|
|
4
|
+
|
|
5
|
+
/** Ghost icon button with a tooltip, as used throughout Cossack Studio. */
|
|
6
|
+
export function iconButton(
|
|
7
|
+
id: string,
|
|
8
|
+
icon: IconEntry,
|
|
9
|
+
label: string,
|
|
10
|
+
onClick: () => unknown,
|
|
11
|
+
options: Record<string, unknown> = {},
|
|
12
|
+
) {
|
|
13
|
+
return component(Tooltip, { id, label, side: 'bottom' }, component(Button, {
|
|
14
|
+
variant: 'ghost',
|
|
15
|
+
size: 'icon',
|
|
16
|
+
'aria-label': label,
|
|
17
|
+
'aria-describedby': id,
|
|
18
|
+
'@click': onClick,
|
|
19
|
+
...options,
|
|
20
|
+
}, component(Icon, { entry: icon, size: 17 })));
|
|
21
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { BrowseFilter, FilterValueType, StudioObject, StudioSchema } from './studio-types';
|
|
2
|
+
import { declaredKind } from './values';
|
|
3
|
+
|
|
4
|
+
const TEXT_OPERATORS = new Set(['contains', 'starts-with', 'ends-with']);
|
|
5
|
+
|
|
6
|
+
/** Text matching operators always compare strings. */
|
|
7
|
+
export function isTextOperator(operator: string): boolean {
|
|
8
|
+
return TEXT_OPERATORS.has(operator);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Chooses the typed value for an "Auto" filter. RomeDB compares typed values,
|
|
13
|
+
* so `5` must be an Integer for an INTEGER column but a String for TEXT.
|
|
14
|
+
*/
|
|
15
|
+
export function resolveFilterType(filter: BrowseFilter, object: StudioObject | undefined, schema: StudioSchema): Exclude<FilterValueType, 'auto'> {
|
|
16
|
+
if (isTextOperator(filter.operator)) return 'text';
|
|
17
|
+
if (filter.valueType && filter.valueType !== 'auto') return filter.valueType;
|
|
18
|
+
const value = filter.value ?? '';
|
|
19
|
+
const column = object?.columns.find(candidate => candidate.name === filter.column);
|
|
20
|
+
if (column && object?.model !== 'document') {
|
|
21
|
+
if (column.affinity === 'integer') return /^-?\d+$/.test(value) ? 'integer' : 'text';
|
|
22
|
+
if (column.affinity === 'real' || column.affinity === 'numeric') return numeric(value) ? 'number' : 'text';
|
|
23
|
+
if (column.affinity === 'text') return 'text';
|
|
24
|
+
}
|
|
25
|
+
if (column && object?.model === 'document' && column.dataType !== 'any') {
|
|
26
|
+
const kind = declaredKind(column);
|
|
27
|
+
if (kind === 'integer' && /^-?\d+$/.test(value)) return 'integer';
|
|
28
|
+
if (kind === 'number' && numeric(value)) return 'number';
|
|
29
|
+
if (kind === 'boolean' && (value === 'true' || value === 'false')) return 'boolean';
|
|
30
|
+
if (kind === 'record') return 'record';
|
|
31
|
+
if (kind === 'text' || kind === 'date' || kind === 'datetime' || kind === 'timestamp') return 'text';
|
|
32
|
+
}
|
|
33
|
+
if (filter.column === 'id' && object?.model === 'document') return 'record';
|
|
34
|
+
if (value === 'true' || value === 'false') return 'boolean';
|
|
35
|
+
if (/^-?\d+$/.test(value)) return 'integer';
|
|
36
|
+
if (numeric(value)) return 'number';
|
|
37
|
+
const table = value.match(/^([A-Za-z_][\w]*):\S/)?.[1];
|
|
38
|
+
if (table && schema.objects.some(candidate => candidate.name.toLowerCase() === table.toLowerCase())) return 'record';
|
|
39
|
+
return 'text';
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function numeric(value: string): boolean {
|
|
43
|
+
return /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(value);
|
|
44
|
+
}
|
package/src/lib/graph.ts
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import type { PortableValue } from '@romedb/client';
|
|
2
|
+
import type { GraphEdge, GraphNode, GraphRequest, StatementResult, StudioObject, StudioSchema } from './studio-types';
|
|
3
|
+
import { quoteIdentifier } from './sql-text';
|
|
4
|
+
import { recordText } from './values';
|
|
5
|
+
|
|
6
|
+
type RecordValue = Extract<PortableValue, { type: 'Record' }>;
|
|
7
|
+
|
|
8
|
+
export const MAX_EXPLORE_DEPTH = 4;
|
|
9
|
+
export const MAX_GRAPH_NODES = 500;
|
|
10
|
+
|
|
11
|
+
/** Edge tables that can start a traversal at a record of `table`. */
|
|
12
|
+
export function edgeTablesFor(schema: StudioSchema, table: string): StudioObject[] {
|
|
13
|
+
const name = table.toLowerCase();
|
|
14
|
+
return schema.objects.filter(object => object.edge && (object.edge.source === name || object.edge.target === name));
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Builds the neighborhood query for the graph explorer. A self-referencing edge
|
|
19
|
+
* table uses bounded REACHABLE recursion; other edge tables use one hop in the
|
|
20
|
+
* only direction their declaration allows. Each row carries the edge that first
|
|
21
|
+
* reached its node, with that edge's real direction.
|
|
22
|
+
*/
|
|
23
|
+
export function graphQuery(schema: StudioSchema, request: GraphRequest): { sql: string; display: string } {
|
|
24
|
+
if (request.root?.type !== 'Record') throw new Error('Enter a record ID such as people:alice.');
|
|
25
|
+
const rootTable = request.root.value.table.toLowerCase();
|
|
26
|
+
const start = schema.objects.find(object => object.model === 'document' && object.name.toLowerCase() === rootTable);
|
|
27
|
+
if (!start || start.edge) throw new Error(`${request.root.value.table} is not a node collection.`);
|
|
28
|
+
const edges = schema.objects.find(object => object.name === request.edge && object.edge);
|
|
29
|
+
if (!edges?.edge) throw new Error('Choose an edge table.');
|
|
30
|
+
if (!Number.isSafeInteger(request.depth) || request.depth < 1 || request.depth > MAX_EXPLORE_DEPTH) {
|
|
31
|
+
throw new Error(`Choose a depth from 1 to ${MAX_EXPLORE_DEPTH}.`);
|
|
32
|
+
}
|
|
33
|
+
const { source, target } = edges.edge;
|
|
34
|
+
const recursive = source === target && source === rootTable;
|
|
35
|
+
let arrow: string;
|
|
36
|
+
let next: string;
|
|
37
|
+
if (recursive) {
|
|
38
|
+
arrow = request.direction === 'out' ? '->' : request.direction === 'in' ? '<-' : '<->';
|
|
39
|
+
next = source;
|
|
40
|
+
} else if (source === rootTable && request.direction !== 'in') {
|
|
41
|
+
arrow = '->';
|
|
42
|
+
next = target;
|
|
43
|
+
} else if (target === rootTable && request.direction !== 'out') {
|
|
44
|
+
arrow = '<-';
|
|
45
|
+
next = source;
|
|
46
|
+
} else {
|
|
47
|
+
throw new Error(`${edges.name} connects ${source} to ${target}; it cannot leave ${rootTable} in that direction.`);
|
|
48
|
+
}
|
|
49
|
+
const depth = recursive ? ` DEPTH 1 TO ${request.depth} MODE REACHABLE` : '';
|
|
50
|
+
const body = (root: string) => `${root} ${arrow} ${quoteIdentifier(edges.name)} ${arrow} ${quoteIdentifier(next)}${depth}`;
|
|
51
|
+
const tail = ` AS g JOIN ${quoteIdentifier(edges.name)} AS e ON e.id = g.edge ORDER BY g.depth, g.node LIMIT ${MAX_GRAPH_NODES}`;
|
|
52
|
+
const select = 'SELECT g.node, g.depth, e.id, e.source, e.target FROM GRAPH(';
|
|
53
|
+
return {
|
|
54
|
+
sql: `${select}${body('$root')})${tail}`,
|
|
55
|
+
display: `${select}${body(recordText(request.root.value))})${tail}`,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Nodes and edges for the explorer from rows of (node, depth, edge, source, target). */
|
|
60
|
+
export function exploreGraph(root: RecordValue, edgeTable: string, result: StatementResult): { nodes: GraphNode[]; edges: GraphEdge[] } {
|
|
61
|
+
const builder = new GraphBuilder();
|
|
62
|
+
builder.node(root, 0);
|
|
63
|
+
for (const row of result.rows) {
|
|
64
|
+
const node = row[result.columns[0]];
|
|
65
|
+
const depth = row[result.columns[1]];
|
|
66
|
+
const edge = row[result.columns[2]];
|
|
67
|
+
const source = row[result.columns[3]];
|
|
68
|
+
const target = row[result.columns[4]];
|
|
69
|
+
if (node?.type !== 'Record') continue;
|
|
70
|
+
builder.node(node, depth?.type === 'Integer' ? Number(depth.value) : 1);
|
|
71
|
+
if (source?.type === 'Record' && target?.type === 'Record') {
|
|
72
|
+
builder.node(source, Number.POSITIVE_INFINITY);
|
|
73
|
+
builder.node(target, Number.POSITIVE_INFINITY);
|
|
74
|
+
builder.edge(edge?.type === 'Record' ? edge : null, source, target, edgeTable);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return builder.finish();
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Draws a result as a graph when it contains record paths or edges:
|
|
82
|
+
* `nodes`/`edges` path arrays, `source`/`target` edge rows, or `root`/`node`
|
|
83
|
+
* pairs. Returns null when no row has a recognizable shape.
|
|
84
|
+
*/
|
|
85
|
+
export function resultGraph(result: StatementResult): { nodes: GraphNode[]; edges: GraphEdge[] } | null {
|
|
86
|
+
const builder = new GraphBuilder();
|
|
87
|
+
const has = (name: string) => result.columns.includes(name);
|
|
88
|
+
for (const row of result.rows) {
|
|
89
|
+
const nodes = row.nodes;
|
|
90
|
+
const edges = row.edges;
|
|
91
|
+
if (has('nodes') && nodes?.type === 'Array' && nodes.value.every(isRecord)) {
|
|
92
|
+
const path = nodes.value as RecordValue[];
|
|
93
|
+
path.forEach((node, index) => builder.node(node, index));
|
|
94
|
+
const ids = edges?.type === 'Array' ? edges.value : [];
|
|
95
|
+
for (let index = 1; index < path.length; index += 1) {
|
|
96
|
+
const id = ids[index - 1];
|
|
97
|
+
builder.edge(isRecord(id) ? id : null, path[index - 1], path[index], isRecord(id) ? id.value.table : '');
|
|
98
|
+
}
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
const source = row.source;
|
|
102
|
+
const target = row.target;
|
|
103
|
+
if (has('source') && has('target') && isRecord(source) && isRecord(target)) {
|
|
104
|
+
const id = row.id;
|
|
105
|
+
builder.node(source, Number.POSITIVE_INFINITY);
|
|
106
|
+
builder.node(target, Number.POSITIVE_INFINITY);
|
|
107
|
+
builder.edge(isRecord(id) ? id : null, source, target, isRecord(id) ? id.value.table : '');
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
const root = row.root;
|
|
111
|
+
const node = row.node;
|
|
112
|
+
if (has('root') && has('node') && isRecord(root) && isRecord(node)) {
|
|
113
|
+
const depth = row.depth;
|
|
114
|
+
builder.node(root, 0);
|
|
115
|
+
builder.node(node, depth?.type === 'Integer' ? Number(depth.value) : Number.POSITIVE_INFINITY);
|
|
116
|
+
const edge = row.edge;
|
|
117
|
+
builder.edge(isRecord(edge) ? edge : null, root, node, isRecord(edge) ? edge.value.table : 'path');
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
const graph = builder.finish();
|
|
121
|
+
return graph.nodes.length ? graph : null;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export interface Placement { key: string; x: number; y: number; ring: number }
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Concentric layout. Ring 0 holds the first node; each further ring holds nodes
|
|
128
|
+
* one more undirected hop away. Unreached nodes share the outer ring.
|
|
129
|
+
*/
|
|
130
|
+
export function layoutGraph(nodes: GraphNode[], edges: GraphEdge[], ringGap = 130): { placements: Map<string, Placement>; size: number } {
|
|
131
|
+
const neighbors = new Map<string, string[]>(nodes.map(node => [node.key, []]));
|
|
132
|
+
for (const edge of edges) {
|
|
133
|
+
neighbors.get(edge.source)?.push(edge.target);
|
|
134
|
+
neighbors.get(edge.target)?.push(edge.source);
|
|
135
|
+
}
|
|
136
|
+
const ring = new Map<string, number>();
|
|
137
|
+
const ordered = [...nodes].sort((a, b) => a.depth - b.depth);
|
|
138
|
+
const queue: string[] = [];
|
|
139
|
+
if (ordered[0]) {
|
|
140
|
+
ring.set(ordered[0].key, 0);
|
|
141
|
+
queue.push(ordered[0].key);
|
|
142
|
+
}
|
|
143
|
+
while (queue.length) {
|
|
144
|
+
const current = queue.shift()!;
|
|
145
|
+
for (const next of neighbors.get(current) ?? []) {
|
|
146
|
+
if (!ring.has(next)) {
|
|
147
|
+
ring.set(next, ring.get(current)! + 1);
|
|
148
|
+
queue.push(next);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
const outer = Math.max(0, ...ring.values()) + 1;
|
|
153
|
+
const rings = new Map<number, string[]>();
|
|
154
|
+
for (const node of nodes) {
|
|
155
|
+
const level = ring.get(node.key) ?? outer;
|
|
156
|
+
if (!rings.has(level)) rings.set(level, []);
|
|
157
|
+
rings.get(level)!.push(node.key);
|
|
158
|
+
}
|
|
159
|
+
const deepest = Math.max(0, ...rings.keys());
|
|
160
|
+
const size = (deepest + 1) * ringGap * 2;
|
|
161
|
+
const center = size / 2;
|
|
162
|
+
const placements = new Map<string, Placement>();
|
|
163
|
+
for (const [level, keys] of rings) {
|
|
164
|
+
keys.forEach((key, index) => {
|
|
165
|
+
const angle = (2 * Math.PI * index) / keys.length - Math.PI / 2 + level * 0.35;
|
|
166
|
+
const radius = level * ringGap;
|
|
167
|
+
placements.set(key, { key, ring: level, x: center + radius * Math.cos(angle), y: center + radius * Math.sin(angle) });
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
return { placements, size: Math.max(size, ringGap * 2) };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Categorical colors that stay distinct in light and dark themes. */
|
|
174
|
+
const TABLE_COLORS = ['#4e79a7', '#f28e2b', '#59a14f', '#e15759', '#76b7b2', '#b07aa1', '#edc948', '#9c755f'];
|
|
175
|
+
|
|
176
|
+
/** Stable color for a table name. */
|
|
177
|
+
export function tableColor(table: string): string {
|
|
178
|
+
let hash = 0;
|
|
179
|
+
for (const character of table) hash = (hash * 31 + character.charCodeAt(0)) >>> 0;
|
|
180
|
+
return TABLE_COLORS[hash % TABLE_COLORS.length];
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function isRecord(value: PortableValue | undefined): value is RecordValue {
|
|
184
|
+
return value?.type === 'Record';
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
class GraphBuilder {
|
|
188
|
+
private nodes = new Map<string, GraphNode>();
|
|
189
|
+
private edges = new Map<string, GraphEdge>();
|
|
190
|
+
|
|
191
|
+
node(id: RecordValue, depth: number) {
|
|
192
|
+
const key = recordText(id.value);
|
|
193
|
+
const existing = this.nodes.get(key);
|
|
194
|
+
if (existing) {
|
|
195
|
+
existing.depth = Math.min(existing.depth, depth);
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
if (this.nodes.size >= MAX_GRAPH_NODES) return;
|
|
199
|
+
this.nodes.set(key, { key, id, label: key, table: id.value.table, depth });
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
edge(id: RecordValue | null, source: RecordValue, target: RecordValue, label: string) {
|
|
203
|
+
const from = recordText(source.value);
|
|
204
|
+
const to = recordText(target.value);
|
|
205
|
+
if (!this.nodes.has(from) || !this.nodes.has(to)) return;
|
|
206
|
+
const key = id ? recordText(id.value) : `${from}->${to}`;
|
|
207
|
+
if (!this.edges.has(key)) this.edges.set(key, { key, id, source: from, target: to, label });
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
finish() {
|
|
211
|
+
const nodes = [...this.nodes.values()].map(node => ({ ...node, depth: Number.isFinite(node.depth) ? node.depth : 1 }));
|
|
212
|
+
return { nodes, edges: [...this.edges.values()] };
|
|
213
|
+
}
|
|
214
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// RomeQL editor vocabulary: keywords, functions and common statement starts.
|
|
2
|
+
// Keywords follow the RomeQL parser (turso/romedb/parser) plus the SQL subset
|
|
3
|
+
// RomeDB keeps from SQLite. Spatial names live in ./spatial.
|
|
4
|
+
import { SPATIAL_KEYWORDS, spatialCompletions } from './spatial';
|
|
5
|
+
|
|
6
|
+
export const ROMEQL_KEYWORDS: readonly string[] = [...new Set([
|
|
7
|
+
// RomeQL documents, fields, relations, functions and indexes.
|
|
8
|
+
'DOCUMENT', 'CONTENT', 'MERGE', 'PATCH', 'UNSET', 'UPSERT', 'DEFINE', 'REMOVE', 'FIELD', 'RELATION',
|
|
9
|
+
'TYPE', 'VALUE', 'ARRAY', 'REQUIRED', 'NULLABLE', 'READONLY', 'FLEXIBLE', 'STRICT', 'SCHEMA', 'OVERWRITE',
|
|
10
|
+
'FUNCTION', 'RETURNS', 'LANGUAGE', 'JAVASCRIPT', 'FULLTEXT', 'VECTOR', 'INFO', 'FOR', 'DB', 'FETCH', 'TO',
|
|
11
|
+
'RELATE', 'EDGE', 'GRAPH', 'DEPTH', 'MODE', 'REACHABLE', 'PATHS', 'PATH',
|
|
12
|
+
...SPATIAL_KEYWORDS,
|
|
13
|
+
// SQL.
|
|
14
|
+
'ABORT', 'ADD', 'ALL', 'ALTER', 'ANALYZE', 'AND', 'AS', 'ASC', 'ATTACH', 'AUTOINCREMENT', 'BEGIN', 'BETWEEN', 'BY',
|
|
15
|
+
'CASCADE', 'CASE', 'CAST', 'CHECK', 'COLLATE', 'COLUMN', 'COMMIT', 'CONFLICT', 'CREATE', 'CROSS',
|
|
16
|
+
'CURRENT_DATE', 'CURRENT_TIME', 'CURRENT_TIMESTAMP', 'DEFAULT', 'DEFERRED', 'DELETE', 'DESC', 'DETACH',
|
|
17
|
+
'DISTINCT', 'DO', 'DROP', 'ELSE', 'END', 'ESCAPE', 'EXCEPT', 'EXCLUSIVE', 'EXISTS', 'EXPLAIN', 'FAIL', 'FALSE',
|
|
18
|
+
'FOREIGN', 'FROM', 'FULL', 'GLOB', 'GROUP', 'HAVING', 'IF', 'IGNORE', 'IMMEDIATE', 'IN', 'INDEX', 'INDEXED',
|
|
19
|
+
'INNER', 'INSERT', 'INTERSECT', 'INTO', 'IS', 'ISNULL', 'JOIN', 'KEY', 'LEFT', 'LIKE', 'LIMIT', 'MATCH',
|
|
20
|
+
'NATURAL', 'NOT', 'NOTHING', 'NOTNULL', 'NULL', 'OF', 'OFFSET', 'ON', 'OR', 'ORDER', 'OUTER', 'PLAN', 'PRAGMA',
|
|
21
|
+
'PRIMARY', 'QUERY', 'RECURSIVE', 'REFERENCES', 'REGEXP', 'RELEASE', 'RENAME', 'REPLACE', 'RESTRICT',
|
|
22
|
+
'RETURNING', 'RIGHT', 'ROLLBACK', 'ROWID', 'SAVEPOINT', 'SELECT', 'SET', 'TABLE', 'TEMP', 'TEMPORARY', 'THEN',
|
|
23
|
+
'TRANSACTION', 'TRIGGER', 'TRUE', 'UNION', 'UNIQUE', 'UPDATE', 'USING', 'VACUUM', 'VALUES', 'VIEW', 'WHEN',
|
|
24
|
+
'WHERE', 'WITH', 'WITHOUT',
|
|
25
|
+
])];
|
|
26
|
+
|
|
27
|
+
/** Multi-word statement starts that are hard to discover one keyword at a time. */
|
|
28
|
+
export const ROMEQL_STATEMENTS: readonly { text: string; detail: string }[] = [
|
|
29
|
+
{ text: 'INFO FOR DB', detail: 'Tables, collections and views' },
|
|
30
|
+
{ text: 'INFO FOR TABLE ', detail: 'Fields, indexes and relations of one table' },
|
|
31
|
+
{ text: 'INFO FOR INDEX ', detail: 'One index' },
|
|
32
|
+
{ text: 'EXPLAIN QUERY PLAN ', detail: 'Query plan without running the query' },
|
|
33
|
+
{ text: 'INSERT INTO ', detail: 'Insert a document or row' },
|
|
34
|
+
{ text: 'DEFINE FIELD ', detail: 'Validate a collection field' },
|
|
35
|
+
{ text: 'DEFINE RELATION ', detail: 'Declare an indexed inverse relationship' },
|
|
36
|
+
{ text: 'REMOVE FIELD ', detail: 'Remove a field definition' },
|
|
37
|
+
{ text: 'CREATE EDGE TABLE ', detail: 'Graph edge table: FROM source TO target' },
|
|
38
|
+
{ text: 'CREATE SEARCH INDEX ', detail: 'FULLTEXT, VECTOR or SPATIAL index' },
|
|
39
|
+
{ text: 'CREATE FUNCTION ', detail: 'Stored JavaScript function' },
|
|
40
|
+
];
|
|
41
|
+
|
|
42
|
+
/** Namespaced and engine functions outside the spatial set. */
|
|
43
|
+
export const ROMEQL_FUNCTIONS: readonly { name: string; signature: string; detail: string }[] = [
|
|
44
|
+
{ name: 'type::record', signature: "('table', key)", detail: 'record ID' },
|
|
45
|
+
{ name: 'record::id', signature: '(record)', detail: 'key' },
|
|
46
|
+
{ name: 'record::table', signature: '(record)', detail: 'table name' },
|
|
47
|
+
{ name: 'record::fetch', signature: '(reference)', detail: 'linked record' },
|
|
48
|
+
{ name: 'relation::fetch', signature: "(target, 'relation'[, limit[, after]])", detail: 'page of linked records' },
|
|
49
|
+
{ name: 'doc::get', signature: "(document, 'path')", detail: 'value at path' },
|
|
50
|
+
{ name: 'doc::has', signature: "(document, 'path')", detail: 'boolean' },
|
|
51
|
+
{ name: 'doc::keys', signature: '(document)', detail: 'array of keys' },
|
|
52
|
+
{ name: 'doc::values', signature: '(document)', detail: 'array of values' },
|
|
53
|
+
{ name: 'doc::entries', signature: '(document)', detail: 'array of [key, value]' },
|
|
54
|
+
{ name: 'doc::from_entries', signature: '(entries)', detail: 'document' },
|
|
55
|
+
{ name: 'doc::row', signature: '(alias)', detail: 'whole row as a document' },
|
|
56
|
+
{ name: 'doc::before', signature: '()', detail: 'document before the write' },
|
|
57
|
+
{ name: 'doc::after', signature: '()', detail: 'document after the write' },
|
|
58
|
+
{ name: 'doc::diff', signature: '()', detail: 'changes made by the write' },
|
|
59
|
+
{ name: 'array::new', signature: '(value, ...)', detail: 'array' },
|
|
60
|
+
{ name: 'array::len', signature: '(array)', detail: 'length' },
|
|
61
|
+
{ name: 'array::contains', signature: '(array, value)', detail: 'boolean' },
|
|
62
|
+
{ name: 'array::append', signature: '(array, value)', detail: 'array' },
|
|
63
|
+
{ name: 'array::distinct', signature: '(array)', detail: 'array' },
|
|
64
|
+
{ name: 'array::flatten', signature: '(array)', detail: 'array' },
|
|
65
|
+
{ name: 'array::unnest', signature: '(array)', detail: 'one row per element' },
|
|
66
|
+
{ name: 'string::slugify', signature: '(text)', detail: 'URL slug' },
|
|
67
|
+
{ name: 'string::normalize', signature: '(text)', detail: 'normalized text' },
|
|
68
|
+
{ name: 'search::text', signature: "('index', query, limit)", detail: 'id, score (BM25)' },
|
|
69
|
+
{ name: 'search::vector', signature: "('index', query, limit[, allowed_ids])", detail: 'id, distance' },
|
|
70
|
+
{ name: 'search::analyze', signature: "('index', text)", detail: 'full-text tokens' },
|
|
71
|
+
{ name: 'romedb_version', signature: '()', detail: 'RomeDB engine version (2.7.0 and later)' },
|
|
72
|
+
{ name: 'sqlite_version', signature: '()', detail: 'SQLite compatibility version' },
|
|
73
|
+
];
|
|
74
|
+
|
|
75
|
+
export interface RomeqlCompletion {
|
|
76
|
+
label: string;
|
|
77
|
+
insertText: string;
|
|
78
|
+
filterText: string;
|
|
79
|
+
detail: string;
|
|
80
|
+
kind: 'keyword' | 'function' | 'snippet';
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* RomeQL completions for the text before the cursor. After `name::` only that
|
|
85
|
+
* namespace's functions are offered, completing the part after `::`.
|
|
86
|
+
*/
|
|
87
|
+
export function romeqlCompletions(linePrefix: string): RomeqlCompletion[] {
|
|
88
|
+
const spatial: RomeqlCompletion[] = spatialCompletions(linePrefix);
|
|
89
|
+
const namespace = /\b([a-z]+)::\w*$/i.exec(linePrefix)?.[1]?.toLowerCase();
|
|
90
|
+
if (namespace) {
|
|
91
|
+
const own = ROMEQL_FUNCTIONS.filter(entry => entry.name.startsWith(`${namespace}::`)).map(entry => ({
|
|
92
|
+
label: entry.name,
|
|
93
|
+
insertText: entry.name.slice(namespace.length + 2),
|
|
94
|
+
filterText: entry.name.slice(namespace.length + 2),
|
|
95
|
+
detail: `${entry.signature} → ${entry.detail}`,
|
|
96
|
+
kind: 'function' as const,
|
|
97
|
+
}));
|
|
98
|
+
return [...spatial.filter(entry => entry.label.toLowerCase().startsWith(`${namespace}::`)), ...own];
|
|
99
|
+
}
|
|
100
|
+
return [
|
|
101
|
+
...spatial,
|
|
102
|
+
...ROMEQL_FUNCTIONS.map(entry => ({ label: entry.name, insertText: entry.name, filterText: entry.name, detail: `${entry.signature} → ${entry.detail}`, kind: 'function' as const })),
|
|
103
|
+
...ROMEQL_STATEMENTS.map(entry => ({ label: entry.text.trim(), insertText: entry.text, filterText: entry.text.split(' ', 1)[0]!, detail: entry.detail, kind: 'snippet' as const })),
|
|
104
|
+
...ROMEQL_KEYWORDS.map(keyword => ({ label: keyword, insertText: keyword, filterText: keyword, detail: 'RomeQL keyword', kind: 'keyword' as const })),
|
|
105
|
+
];
|
|
106
|
+
}
|