@romedb/studio 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/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 +1984 -0
- package/src/workspace/workspace.css +38 -0
|
@@ -0,0 +1,1984 @@
|
|
|
1
|
+
// The database workspace: browse, structure, console, graph, map and the sheets that
|
|
2
|
+
// edit data. A page extends it and provides the server methods; Studio's own page adds
|
|
3
|
+
// profiles and connections, the Cloud dashboard adds its organization checks.
|
|
4
|
+
// Layout and interactions follow Cossack Studio (MIT); data access goes through RomeDB's
|
|
5
|
+
// typed client with stale-aware atomic writes.
|
|
6
|
+
import { Client, ClientState, Cossack, Shared } from '@cossackframework/core';
|
|
7
|
+
import { component, html, repeat } from '@cossackframework/renderer';
|
|
8
|
+
import { AddSquareIcon } from '@cossackframework/solar-icons/add-square';
|
|
9
|
+
import { CheckCircleIcon } from '@cossackframework/solar-icons/check-circle';
|
|
10
|
+
import { CodeSquareIcon } from '@cossackframework/solar-icons/code-square';
|
|
11
|
+
import { DangerTriangleIcon } from '@cossackframework/solar-icons/danger-triangle';
|
|
12
|
+
import { DatabaseIcon } from '@cossackframework/solar-icons/database';
|
|
13
|
+
import { DocumentsIcon } from '@cossackframework/solar-icons/documents';
|
|
14
|
+
import { EyeIcon } from '@cossackframework/solar-icons/eye';
|
|
15
|
+
import { MapIcon } from '@cossackframework/solar-icons/map';
|
|
16
|
+
import { RefreshIcon } from '@cossackframework/solar-icons/refresh';
|
|
17
|
+
import { SettingsMinimalisticIcon } from '@cossackframework/solar-icons/settings-minimalistic';
|
|
18
|
+
import { ShareCircleIcon } from '@cossackframework/solar-icons/share-circle';
|
|
19
|
+
import { StructureIcon } from '@cossackframework/solar-icons/structure';
|
|
20
|
+
import { AlertDialog, Button, Icon, InputGroup } from '@cossackframework/ui';
|
|
21
|
+
import type { PortableValue } from '@romedb/client';
|
|
22
|
+
import type { runSql, recoverQuery, QueryInput } from '../server/queries';
|
|
23
|
+
import type { saveBatchEdit, saveEdit, EditInput } from '../server/edits';
|
|
24
|
+
import type { BrowseRequest } from '../server/data';
|
|
25
|
+
import { edgeTablesFor } from '../lib/graph';
|
|
26
|
+
import { spatialIndexes } from '../lib/spatial';
|
|
27
|
+
import { studioSchemaCatalog } from '../schema-store';
|
|
28
|
+
import { createObjectSql } from '../schema-draft';
|
|
29
|
+
import { resolveFilterType } from '../lib/filters';
|
|
30
|
+
import { isWriteStatement, splitStatements, statementParameters } from '../lib/sql-text';
|
|
31
|
+
import {
|
|
32
|
+
csvCell, declaredKind, displayValue, editableText, fromJson, kindDefault, kindForValue, kindValue,
|
|
33
|
+
parseRecord, sameValue, toJson, type ValueKind,
|
|
34
|
+
} from '../lib/values';
|
|
35
|
+
import {
|
|
36
|
+
emptyGrid, emptySchema, FILTER_OPERATORS, PAGE_SIZES,
|
|
37
|
+
type BrowseFilter, type BrowseFilterOperator, type BrowseSort, type FilterValueType, type GridResult,
|
|
38
|
+
type GraphDirection, type GraphNode, type GraphRequest, type GraphView, type MapFeature, type MapRequest, type MapView,
|
|
39
|
+
type GridRow, type RestoredDatabase, type RestorePoints, type SqlRun, type StudioForeignKey, type StudioObject, type StudioSchema,
|
|
40
|
+
} from '../lib/studio-types';
|
|
41
|
+
import { BrowseTab } from '../components/studio/BrowseTab';
|
|
42
|
+
import { CellEditorSheet } from '../components/studio/CellEditorSheet';
|
|
43
|
+
import { DatabaseTab } from '../components/studio/DatabaseTab';
|
|
44
|
+
import { GraphTab } from '../components/studio/GraphTab';
|
|
45
|
+
import { MapTab, type MapBoxField } from '../components/studio/MapTab';
|
|
46
|
+
import { InsertRowSheet } from '../components/studio/InsertRowSheet';
|
|
47
|
+
import { NewObjectSheet, type NewObjectKind } from '../components/studio/NewObjectSheet';
|
|
48
|
+
import { QueryHistorySheet } from '../components/studio/QueryHistorySheet';
|
|
49
|
+
import { BatchUpdateSheet, ExportSheet, RowEditorSheet } from '../components/studio/RowSheets';
|
|
50
|
+
import { SqlConsole } from '../components/studio/SqlConsole';
|
|
51
|
+
import { StructureTab } from '../components/studio/StructureTab';
|
|
52
|
+
import { iconButton } from '../components/studio/icon-button';
|
|
53
|
+
import type {
|
|
54
|
+
BatchUpdateState, CellEditor, CellMode, CellSelection, DeleteTarget, ExportFormat, ExportSheetState,
|
|
55
|
+
InsertFieldState, InsertSelection, NewColumnDraft, QueryHistoryEntry, RowEditorState,
|
|
56
|
+
SqlOutput, StudioTab, WriteConfirmation,
|
|
57
|
+
} from '../studio-page';
|
|
58
|
+
import { revisionAfterRejectedWrite } from '../studio-page';
|
|
59
|
+
|
|
60
|
+
type WriteReply = Awaited<ReturnType<typeof saveEdit>>;
|
|
61
|
+
type WriteOutcome = { ok: true; sequence: number } | { ok: false; error: string };
|
|
62
|
+
|
|
63
|
+
export const DEFAULT_SQL = 'SELECT sqlite_version() AS version;';
|
|
64
|
+
export const WORKSPACE_TABS: readonly StudioTab[] = ['browse', 'structure', 'sql', 'graph', 'map', 'database'];
|
|
65
|
+
|
|
66
|
+
export abstract class StudioWorkspace extends Cossack {
|
|
67
|
+
@ClientState() activeConnection = '';
|
|
68
|
+
@ClientState() schema: StudioSchema = emptySchema;
|
|
69
|
+
@ClientState() schemaLoading = false;
|
|
70
|
+
@ClientState() browseResult: GridResult = emptyGrid;
|
|
71
|
+
@ClientState() selected = '';
|
|
72
|
+
@ClientState() page = 1;
|
|
73
|
+
@ClientState() pageSize = 100;
|
|
74
|
+
@ClientState() message = '';
|
|
75
|
+
@ClientState() messageError = false;
|
|
76
|
+
|
|
77
|
+
@ClientState() search = '';
|
|
78
|
+
@ClientState() searchIndex = -1;
|
|
79
|
+
@ClientState() tab: StudioTab = 'browse';
|
|
80
|
+
@ClientState() theme: 'light' | 'dark' = 'dark';
|
|
81
|
+
@ClientState() restoringUrl = false;
|
|
82
|
+
@ClientState() restorePoints: RestorePoints | null = null;
|
|
83
|
+
@ClientState() restorePointsFor = '';
|
|
84
|
+
@ClientState() restorePointsError = '';
|
|
85
|
+
@ClientState() restorePointsBusy = false;
|
|
86
|
+
|
|
87
|
+
@ClientState() showFilter = false;
|
|
88
|
+
@ClientState() filters: BrowseFilter[] = [];
|
|
89
|
+
@ClientState() sort: BrowseSort[] = [];
|
|
90
|
+
@ClientState() filterColumn = '';
|
|
91
|
+
@ClientState() filterOperator: BrowseFilterOperator = 'contains';
|
|
92
|
+
@ClientState() filterValue = '';
|
|
93
|
+
@ClientState() filterType: FilterValueType = 'auto';
|
|
94
|
+
@ClientState() selectedRows: number[] = [];
|
|
95
|
+
@ClientState() browseLoading = false;
|
|
96
|
+
@ClientState() browseLoadFailed = false;
|
|
97
|
+
@ClientState() browseQuery = '';
|
|
98
|
+
@ClientState() customBrowseQuery = false;
|
|
99
|
+
@ClientState() loadedObject = '';
|
|
100
|
+
|
|
101
|
+
@ClientState() inlineEditor: CellEditor | null = null;
|
|
102
|
+
@ClientState() sheetEditor: CellEditor | null = null;
|
|
103
|
+
@ClientState() rowEditor: RowEditorState | null = null;
|
|
104
|
+
@ClientState() deleteTarget: DeleteTarget | null = null;
|
|
105
|
+
@ClientState() exportSheet: ExportSheetState | null = null;
|
|
106
|
+
@ClientState() batchUpdate: BatchUpdateState | null = null;
|
|
107
|
+
@ClientState() showInsert = false;
|
|
108
|
+
@ClientState() insertFields: Record<string, InsertFieldState> = {};
|
|
109
|
+
@ClientState() insertDocument = '{}';
|
|
110
|
+
@ClientState() insertError = '';
|
|
111
|
+
@ClientState() writing = false;
|
|
112
|
+
|
|
113
|
+
@ClientState() sql = DEFAULT_SQL;
|
|
114
|
+
@ClientState() sqlRun: SqlRun | null = null;
|
|
115
|
+
@ClientState() explainRun: SqlRun | null = null;
|
|
116
|
+
@ClientState() sqlOutput: SqlOutput = 'results';
|
|
117
|
+
@ClientState() resultIndex = 0;
|
|
118
|
+
@ClientState() sqlRunning = false;
|
|
119
|
+
@ClientState() sqlExplaining = false;
|
|
120
|
+
@ClientState() sqlOperation = '';
|
|
121
|
+
@ClientState() showSqlOptions = false;
|
|
122
|
+
@ClientState() sqlParameters = '';
|
|
123
|
+
@ClientState() sqlRevision = '';
|
|
124
|
+
@ClientState() rowsReadBudget = '20000';
|
|
125
|
+
@ClientState() vmStepBudget = '1000000';
|
|
126
|
+
@ClientState() pendingWrite: WriteConfirmation | null = null;
|
|
127
|
+
@ClientState() queryHistory: QueryHistoryEntry[] = [];
|
|
128
|
+
@ClientState() historyOpen = false;
|
|
129
|
+
|
|
130
|
+
@ClientState() uncertainWrites: Record<string, string> = {};
|
|
131
|
+
@ClientState() recovering = false;
|
|
132
|
+
|
|
133
|
+
@ClientState() newObjectOpen = false;
|
|
134
|
+
@ClientState() newObjectName = '';
|
|
135
|
+
@ClientState() newObjectKind: NewObjectKind = 'collection';
|
|
136
|
+
@ClientState() newSpatialTable = '';
|
|
137
|
+
@ClientState() newSpatialField = '';
|
|
138
|
+
@ClientState() newSpatialRegion = false;
|
|
139
|
+
|
|
140
|
+
@ClientState() mapIndex = '';
|
|
141
|
+
@ClientState() mapBox: Record<MapBoxField, string> = { west: '-180', south: '-90', east: '180', north: '90', lng: '', lat: '' };
|
|
142
|
+
@ClientState() mapLimit = 500;
|
|
143
|
+
@ClientState() mapView: MapView | null = null;
|
|
144
|
+
@ClientState() mapLoading = false;
|
|
145
|
+
@ClientState() mapSelected = '';
|
|
146
|
+
@ClientState() sqlMapSelected = '';
|
|
147
|
+
@ClientState() newEdgeSource = '';
|
|
148
|
+
@ClientState() newEdgeTarget = '';
|
|
149
|
+
@ClientState() newEdgeCascade = false;
|
|
150
|
+
|
|
151
|
+
@ClientState() graphRoot = '';
|
|
152
|
+
@ClientState() graphEdge = '';
|
|
153
|
+
@ClientState() graphDirection: GraphDirection = 'both';
|
|
154
|
+
@ClientState() graphDepth = 2;
|
|
155
|
+
@ClientState() graphView: GraphView | null = null;
|
|
156
|
+
@ClientState() graphLoading = false;
|
|
157
|
+
@ClientState() newColumns: NewColumnDraft[] = [{ name: 'id', type: 'INTEGER', primary: true, required: true, unique: false }];
|
|
158
|
+
@ClientState() newObjectError = '';
|
|
159
|
+
@ClientState() creatingObject = false;
|
|
160
|
+
|
|
161
|
+
constructor() {
|
|
162
|
+
super();
|
|
163
|
+
// Cossack binds the methods of the page's own class only. The templates here pass
|
|
164
|
+
// methods as callbacks (`onSave: this.saveRowEditor`), so bind the inherited ones too.
|
|
165
|
+
for (let proto = Object.getPrototypeOf(Object.getPrototypeOf(this)); proto && proto !== Cossack.prototype; proto = Object.getPrototypeOf(proto)) {
|
|
166
|
+
for (const name of Object.getOwnPropertyNames(proto)) {
|
|
167
|
+
const value: unknown = Object.getOwnPropertyDescriptor(proto, name)?.value;
|
|
168
|
+
if (name !== 'constructor' && typeof value === 'function' && !Object.hasOwn(this, name)) {
|
|
169
|
+
(this as unknown as Record<string, unknown>)[name] = value.bind(this);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
get activeObject(): StudioObject | undefined {
|
|
176
|
+
return this.schema.objects.find(object => object.name === this.selected);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
get writesBlocked(): boolean {
|
|
180
|
+
const id = this.activeConnection;
|
|
181
|
+
return Boolean(id && (this.uncertainWrites[id] || this.pendingRecoveries(id).length));
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
get historyKey(): string {
|
|
185
|
+
return `romedb-studio:query-history:${this.historyScope()}`;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
@Shared()
|
|
189
|
+
visibleObjects(): StudioObject[] {
|
|
190
|
+
const query = this.search.trim().toLowerCase();
|
|
191
|
+
return this.schema.objects.filter(object => object.name.toLowerCase().includes(query));
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// ---------------------------------------------------------------------------
|
|
195
|
+
// What the page provides. Each data method is a server method of the page: it
|
|
196
|
+
// checks who is asking, then calls the function of the same purpose in `server/`.
|
|
197
|
+
|
|
198
|
+
abstract fetchSchema(id: string): Promise<StudioSchema>;
|
|
199
|
+
abstract fetchRows(id: string, table: string, request: BrowseRequest): Promise<GridResult>;
|
|
200
|
+
abstract executeSql(id: string, operation: string, input: QueryInput): ReturnType<typeof runSql>;
|
|
201
|
+
abstract exploreGraph(id: string, request: GraphRequest): Promise<GraphView>;
|
|
202
|
+
abstract fetchMap(id: string, request: MapRequest): Promise<MapView>;
|
|
203
|
+
abstract fetchRestorePoints(id: string): Promise<RestorePoints>;
|
|
204
|
+
abstract restoreAtPoint(id: string, sequence: number): Promise<RestoredDatabase>;
|
|
205
|
+
abstract cancelOperation(operation: string): Promise<boolean>;
|
|
206
|
+
abstract recoverWrite(id: string, operation: string, recovery: string): ReturnType<typeof recoverQuery>;
|
|
207
|
+
abstract acknowledgeWrite(id: string, recovery: string, nonce: string): Promise<void>;
|
|
208
|
+
abstract writeEdit(id: string, operation: string, input: EditInput): ReturnType<typeof saveEdit>;
|
|
209
|
+
abstract writeBatch(id: string, operation: string, inputs: EditInput[]): ReturnType<typeof saveBatchEdit>;
|
|
210
|
+
|
|
211
|
+
/** The database's name in messages. */
|
|
212
|
+
@Shared()
|
|
213
|
+
workspaceName(): string { return 'this database'; }
|
|
214
|
+
|
|
215
|
+
/** Names the query history kept in the browser for this database. */
|
|
216
|
+
@Shared()
|
|
217
|
+
historyScope(): string { return this.activeConnection || 'none'; }
|
|
218
|
+
|
|
219
|
+
/** Saved writes with an unknown outcome. While there is one, the workspace is read only. */
|
|
220
|
+
@Shared()
|
|
221
|
+
pendingRecoveries(_id: string): string[] { return []; }
|
|
222
|
+
|
|
223
|
+
/** The tabs to show, in the order of WORKSPACE_TABS. */
|
|
224
|
+
@Shared()
|
|
225
|
+
workspaceTabs(): readonly StudioTab[] { return WORKSPACE_TABS; }
|
|
226
|
+
|
|
227
|
+
/** Loads `pendingRecoveries` again. */
|
|
228
|
+
@Client()
|
|
229
|
+
async refreshRecoveries() {}
|
|
230
|
+
|
|
231
|
+
/** Loads what the page shows around the workspace again. */
|
|
232
|
+
@Client()
|
|
233
|
+
async refreshHost() {}
|
|
234
|
+
|
|
235
|
+
/** Adds the page's own query parameters to the address of the current view. */
|
|
236
|
+
@Client()
|
|
237
|
+
writeUrlScope(_url: URL) {}
|
|
238
|
+
|
|
239
|
+
/** False keeps one history entry however the view changes. */
|
|
240
|
+
@Shared()
|
|
241
|
+
pushesHistory(): boolean { return true; }
|
|
242
|
+
|
|
243
|
+
/** True hides everything that changes data: the person may only read this database. */
|
|
244
|
+
@Shared()
|
|
245
|
+
readOnly(): boolean { return false; }
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Whether the workspace names the database revision (the number of the last committed
|
|
249
|
+
* write) in its messages and offers the "Expected revision" option. An application whose
|
|
250
|
+
* users do not work with revisions answers false.
|
|
251
|
+
*/
|
|
252
|
+
@Shared()
|
|
253
|
+
showsRevision(): boolean { return true; }
|
|
254
|
+
|
|
255
|
+
/** What the object list says while no database is open. */
|
|
256
|
+
@Shared()
|
|
257
|
+
noDatabaseText(): string { return 'Connect a database to list its tables and collections.'; }
|
|
258
|
+
|
|
259
|
+
/** Called when an action needs a database and none is open. */
|
|
260
|
+
@Client()
|
|
261
|
+
connectFirst() {}
|
|
262
|
+
|
|
263
|
+
// ---------------------------------------------------------------------------
|
|
264
|
+
// Messages, URL state and opening a database.
|
|
265
|
+
|
|
266
|
+
@Client()
|
|
267
|
+
showMessage(message: string, error = false) {
|
|
268
|
+
this.message = message;
|
|
269
|
+
this.messageError = error;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
@Client()
|
|
273
|
+
syncUrl(push = false) {
|
|
274
|
+
if (this.restoringUrl) return;
|
|
275
|
+
const url = new URL(window.location.href);
|
|
276
|
+
for (const key of ['table', 'tab', 'page', 'pageSize', 'filter', 'sort']) url.searchParams.delete(key);
|
|
277
|
+
this.writeUrlScope(url);
|
|
278
|
+
if (this.selected) url.searchParams.set('table', this.selected);
|
|
279
|
+
if (this.tab !== 'browse') url.searchParams.set('tab', this.tab);
|
|
280
|
+
if (this.page > 1) url.searchParams.set('page', String(this.page));
|
|
281
|
+
if (this.pageSize !== 100) url.searchParams.set('pageSize', String(this.pageSize));
|
|
282
|
+
for (const filter of this.filters) url.searchParams.append('filter', JSON.stringify(filter));
|
|
283
|
+
for (const item of this.sort) url.searchParams.append('sort', JSON.stringify(item));
|
|
284
|
+
window.history[push && this.pushesHistory() ? 'pushState' : 'replaceState']({}, '', url);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** Shows the tab, object, filters, order and page an address names. The schema must be loaded. */
|
|
288
|
+
@Client()
|
|
289
|
+
async restoreViewFromUrl(params: URLSearchParams) {
|
|
290
|
+
const requestedTab = params.get('tab');
|
|
291
|
+
this.tab = requestedTab === 'structure' || requestedTab === 'sql' || requestedTab === 'graph' || requestedTab === 'map' || requestedTab === 'database' ? requestedTab : 'browse';
|
|
292
|
+
const size = Number(params.get('pageSize') ?? 100);
|
|
293
|
+
this.pageSize = PAGE_SIZES.includes(size) ? size : 100;
|
|
294
|
+
const object = this.schema.objects.find(candidate => candidate.name === params.get('table'));
|
|
295
|
+
if (!object) {
|
|
296
|
+
this.selected = '';
|
|
297
|
+
this.loadedObject = '';
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
this.selected = object.name;
|
|
301
|
+
this.filterColumn = object.columns[0]?.name ?? '';
|
|
302
|
+
const columns = new Set(object.columns.map(column => column.name));
|
|
303
|
+
this.filters = params.getAll('filter').flatMap(encoded => {
|
|
304
|
+
try {
|
|
305
|
+
const filter = JSON.parse(encoded) as BrowseFilter;
|
|
306
|
+
return (columns.has(filter.column) || object.model === 'document') && FILTER_OPERATORS.some(operator => operator.value === filter.operator) ? [filter] : [];
|
|
307
|
+
} catch { return []; }
|
|
308
|
+
});
|
|
309
|
+
this.sort = params.getAll('sort').flatMap(encoded => {
|
|
310
|
+
try {
|
|
311
|
+
const item = JSON.parse(encoded) as BrowseSort;
|
|
312
|
+
return typeof item.column === 'string' && (item.direction === 'asc' || item.direction === 'desc') ? [item] : [];
|
|
313
|
+
} catch { return []; }
|
|
314
|
+
});
|
|
315
|
+
await this.reloadRows(object.name, Math.max(1, Number(params.get('page') ?? 1) || 1), this.pageSize, false);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** Makes `id` the current database: clears the view of the earlier one and loads the schema. */
|
|
319
|
+
@Client()
|
|
320
|
+
async openDatabase(id: string, sql = DEFAULT_SQL) {
|
|
321
|
+
this.closeEditors();
|
|
322
|
+
this.activeConnection = id;
|
|
323
|
+
this.selected = '';
|
|
324
|
+
this.loadedObject = '';
|
|
325
|
+
this.browseResult = emptyGrid;
|
|
326
|
+
this.filters = [];
|
|
327
|
+
this.sort = [];
|
|
328
|
+
this.page = 1;
|
|
329
|
+
this.sqlRun = null;
|
|
330
|
+
this.explainRun = null;
|
|
331
|
+
this.mapView = null;
|
|
332
|
+
this.mapSelected = '';
|
|
333
|
+
this.mapIndex = '';
|
|
334
|
+
this.sql = sql;
|
|
335
|
+
this.message = '';
|
|
336
|
+
this.loadQueryHistory();
|
|
337
|
+
await this.reloadSchema();
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
@Client()
|
|
341
|
+
async loadCloudRestorePoints() {
|
|
342
|
+
const id = this.activeConnection;
|
|
343
|
+
if (!id) return;
|
|
344
|
+
this.restorePointsBusy = true; this.restorePointsError = '';
|
|
345
|
+
try {
|
|
346
|
+
const points = await this.fetchRestorePoints(id);
|
|
347
|
+
if (this.activeConnection !== id) return;
|
|
348
|
+
this.restorePoints = points; this.restorePointsFor = id;
|
|
349
|
+
} catch (error) {
|
|
350
|
+
this.restorePoints = null; this.restorePointsFor = id;
|
|
351
|
+
this.restorePointsError = error instanceof Error ? error.message : String(error);
|
|
352
|
+
} finally { this.restorePointsBusy = false; }
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
@Client()
|
|
356
|
+
async restoreCloudPoint(sequence: number) {
|
|
357
|
+
const id = this.activeConnection;
|
|
358
|
+
if (!id || !window.confirm(`Restore this database as of revision ${sequence} into a new Cloud database? This database stays unchanged.`)) return;
|
|
359
|
+
this.restorePointsBusy = true;
|
|
360
|
+
try {
|
|
361
|
+
const restored = await this.restoreAtPoint(id, sequence);
|
|
362
|
+
this.showMessage(`Restored into the new database ${restored.database.name} (${restored.database.id}). Add a connection for it to open it.`);
|
|
363
|
+
} catch (error) {
|
|
364
|
+
this.showMessage(error instanceof Error ? error.message : String(error), true);
|
|
365
|
+
} finally { this.restorePointsBusy = false; }
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
@Client()
|
|
369
|
+
async reloadSchema() {
|
|
370
|
+
const id = this.activeConnection;
|
|
371
|
+
if (!id) return;
|
|
372
|
+
this.schemaLoading = true;
|
|
373
|
+
try {
|
|
374
|
+
const schema = await this.fetchSchema(id);
|
|
375
|
+
if (this.activeConnection !== id) return;
|
|
376
|
+
// Someone who may only read sees every object as views are shown: without edit controls.
|
|
377
|
+
const shown = this.readOnly() ? { ...schema, objects: schema.objects.map(object => ({ ...object, editable: false })) } : schema;
|
|
378
|
+
this.schema = shown;
|
|
379
|
+
studioSchemaCatalog.set(shown);
|
|
380
|
+
if (schema.error) this.showMessage(schema.error, true);
|
|
381
|
+
if (this.selected && !schema.objects.some(object => object.name === this.selected)) {
|
|
382
|
+
this.selected = '';
|
|
383
|
+
this.loadedObject = '';
|
|
384
|
+
this.browseResult = emptyGrid;
|
|
385
|
+
}
|
|
386
|
+
} catch (error) {
|
|
387
|
+
this.showMessage(errorText(error), true);
|
|
388
|
+
} finally {
|
|
389
|
+
this.schemaLoading = false;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
@Client()
|
|
394
|
+
closeEditors() {
|
|
395
|
+
this.inlineEditor = null;
|
|
396
|
+
this.sheetEditor = null;
|
|
397
|
+
this.rowEditor = null;
|
|
398
|
+
this.batchUpdate = null;
|
|
399
|
+
this.exportSheet = null;
|
|
400
|
+
this.deleteTarget = null;
|
|
401
|
+
this.showInsert = false;
|
|
402
|
+
this.selectedRows = [];
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
// ---------------------------------------------------------------------------
|
|
406
|
+
// Browsing.
|
|
407
|
+
|
|
408
|
+
@Client()
|
|
409
|
+
async chooseObject(name: string, filters: BrowseFilter[] = []) {
|
|
410
|
+
this.selected = name;
|
|
411
|
+
this.loadedObject = '';
|
|
412
|
+
this.browseQuery = '';
|
|
413
|
+
this.customBrowseQuery = false;
|
|
414
|
+
this.browseLoadFailed = false;
|
|
415
|
+
this.page = 1;
|
|
416
|
+
this.tab = 'browse';
|
|
417
|
+
this.filters = filters;
|
|
418
|
+
this.sort = [];
|
|
419
|
+
this.filterColumn = this.schema.objects.find(object => object.name === name)?.columns[0]?.name ?? '';
|
|
420
|
+
this.filterValue = '';
|
|
421
|
+
this.filterType = 'auto';
|
|
422
|
+
this.searchIndex = -1;
|
|
423
|
+
this.closeEditors();
|
|
424
|
+
this.syncUrl(true);
|
|
425
|
+
await this.reloadRows(name, 1, this.pageSize);
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
@Client()
|
|
429
|
+
async switchTab(tab: StudioTab) {
|
|
430
|
+
this.startViewTransition(() => {
|
|
431
|
+
this.tab = tab;
|
|
432
|
+
this.syncUrl(true);
|
|
433
|
+
}, ['studio-tab']);
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
@Client()
|
|
437
|
+
async reloadRows(name = this.selected, page = this.page, pageSize = this.pageSize, updateUrl = true) {
|
|
438
|
+
const object = this.schema.objects.find(candidate => candidate.name === name);
|
|
439
|
+
const id = this.activeConnection;
|
|
440
|
+
if (!object || !id) return;
|
|
441
|
+
this.browseLoading = true;
|
|
442
|
+
this.browseLoadFailed = false;
|
|
443
|
+
this.inlineEditor = null;
|
|
444
|
+
this.selectedRows = [];
|
|
445
|
+
try {
|
|
446
|
+
const filters = this.filters.map(filter => ({ ...filter, valueType: resolveFilterType(filter, object, this.schema) }));
|
|
447
|
+
const result = await this.fetchRows(id, object.name, { page, pageSize, filters, sort: this.sort, model: object.model });
|
|
448
|
+
if (this.activeConnection !== id || this.selected !== name) return;
|
|
449
|
+
this.browseResult = result;
|
|
450
|
+
this.page = page;
|
|
451
|
+
this.pageSize = pageSize;
|
|
452
|
+
this.browseQuery = result.query;
|
|
453
|
+
this.customBrowseQuery = false;
|
|
454
|
+
if (result.error) {
|
|
455
|
+
this.loadedObject = '';
|
|
456
|
+
this.browseLoadFailed = true;
|
|
457
|
+
this.showMessage(result.error, true);
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
this.loadedObject = name;
|
|
461
|
+
if (this.messageError) this.message = '';
|
|
462
|
+
if (updateUrl) this.syncUrl();
|
|
463
|
+
} catch (error) {
|
|
464
|
+
this.loadedObject = '';
|
|
465
|
+
this.browseLoadFailed = true;
|
|
466
|
+
this.showMessage(errorText(error), true);
|
|
467
|
+
} finally {
|
|
468
|
+
this.browseLoading = false;
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
@Client()
|
|
474
|
+
async refreshAll() {
|
|
475
|
+
await this.refreshHost();
|
|
476
|
+
await this.refreshRecoveries();
|
|
477
|
+
await this.reloadSchema();
|
|
478
|
+
if (this.selected) await this.reloadRows();
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
@Client()
|
|
482
|
+
async changePage(page: number) {
|
|
483
|
+
if (!this.selected || page === this.page) return;
|
|
484
|
+
await this.reloadRows(this.selected, page, this.pageSize);
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
@Client()
|
|
488
|
+
async changePageSize(value: string) {
|
|
489
|
+
const size = Number(value);
|
|
490
|
+
if (!PAGE_SIZES.includes(size)) return;
|
|
491
|
+
if (this.selected) await this.reloadRows(this.selected, 1, size);
|
|
492
|
+
else this.pageSize = size;
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
@Client()
|
|
496
|
+
onSearchInput(value: string) {
|
|
497
|
+
this.search = value;
|
|
498
|
+
this.searchIndex = this.visibleObjects().length ? 0 : -1;
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
@Client()
|
|
502
|
+
async onSearchKeydown(event: KeyboardEvent) {
|
|
503
|
+
const objects = this.visibleObjects();
|
|
504
|
+
if (!objects.length) return;
|
|
505
|
+
if (event.key === 'ArrowDown') {
|
|
506
|
+
event.preventDefault();
|
|
507
|
+
this.searchIndex = (this.searchIndex + 1 + objects.length) % objects.length;
|
|
508
|
+
} else if (event.key === 'ArrowUp') {
|
|
509
|
+
event.preventDefault();
|
|
510
|
+
this.searchIndex = (this.searchIndex - 1 + objects.length) % objects.length;
|
|
511
|
+
} else if (event.key === 'Enter') {
|
|
512
|
+
event.preventDefault();
|
|
513
|
+
const object = objects[Math.max(0, this.searchIndex)];
|
|
514
|
+
if (object) await this.chooseObject(object.name);
|
|
515
|
+
} else if (event.key === 'Escape') {
|
|
516
|
+
this.search = '';
|
|
517
|
+
this.searchIndex = -1;
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
@Client()
|
|
522
|
+
async toggleSort(column: string) {
|
|
523
|
+
const current = this.sort.find(item => item.column === column);
|
|
524
|
+
this.sort = current?.direction === 'asc'
|
|
525
|
+
? [{ column, direction: 'desc' }]
|
|
526
|
+
: current?.direction === 'desc' ? [] : [{ column, direction: 'asc' }];
|
|
527
|
+
await this.reloadRows(this.selected, 1, this.pageSize);
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
@Client()
|
|
531
|
+
async applyFilter() {
|
|
532
|
+
const column = this.filterColumn.trim() || this.activeObject?.columns[0]?.name || '';
|
|
533
|
+
if (!column) return;
|
|
534
|
+
const needsValue = this.filterOperator !== 'is-null' && this.filterOperator !== 'is-not-null';
|
|
535
|
+
if (needsValue && !this.filterValue.length) return;
|
|
536
|
+
if (this.filters.length >= 8) { this.showMessage('Use at most eight filters.', true); return; }
|
|
537
|
+
this.filters = [...this.filters, {
|
|
538
|
+
column,
|
|
539
|
+
operator: this.filterOperator,
|
|
540
|
+
...(needsValue ? { value: this.filterValue, valueType: this.filterType } : {}),
|
|
541
|
+
}];
|
|
542
|
+
this.filterValue = '';
|
|
543
|
+
await this.reloadRows(this.selected, 1, this.pageSize);
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
@Client()
|
|
547
|
+
async removeFilter(index: number) {
|
|
548
|
+
this.filters = this.filters.filter((_, candidate) => candidate !== index);
|
|
549
|
+
await this.reloadRows(this.selected, 1, this.pageSize);
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
@Client()
|
|
553
|
+
async followForeignKey(foreignKey: StudioForeignKey, rowIndex: number) {
|
|
554
|
+
const target = this.schema.objects.find(object => object.name.toLowerCase() === foreignKey.referencedTable.toLowerCase());
|
|
555
|
+
const row = this.browseResult.rows[rowIndex];
|
|
556
|
+
if (!target || !row) return;
|
|
557
|
+
const filters = foreignKey.columns.flatMap((column): BrowseFilter[] => {
|
|
558
|
+
const value = row[column.column];
|
|
559
|
+
return !value || value.type === 'Null' ? [] : [{ column: column.referencedColumn, operator: 'eq', typed: value }];
|
|
560
|
+
});
|
|
561
|
+
if (filters.length !== foreignKey.columns.length) return;
|
|
562
|
+
await this.chooseObject(target.name, filters);
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
@Client()
|
|
566
|
+
async followRecord(value: PortableValue) {
|
|
567
|
+
if (value.type !== 'Record') return;
|
|
568
|
+
const target = this.schema.objects.find(object => object.name.toLowerCase() === value.value.table.toLowerCase());
|
|
569
|
+
if (!target) { this.showMessage(`${value.value.table} is not available in this database.`, true); return; }
|
|
570
|
+
await this.chooseObject(target.name, [{ column: 'id', operator: 'eq', typed: value }]);
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
// ---------------------------------------------------------------------------
|
|
574
|
+
// Writes. Every change is one atomic, revision-checked request. A request
|
|
575
|
+
// with an unknown outcome is journaled and must be recovered first.
|
|
576
|
+
|
|
577
|
+
@Client()
|
|
578
|
+
async submitEdits(inputs: EditInput[]): Promise<WriteOutcome> {
|
|
579
|
+
const id = this.activeConnection;
|
|
580
|
+
if (!id) return { ok: false, error: 'Connect a database first.' };
|
|
581
|
+
if (this.writesBlocked) return { ok: false, error: 'Recover the saved write with an unknown outcome before making another change.' };
|
|
582
|
+
if (this.writing) return { ok: false, error: 'Another write is still running.' };
|
|
583
|
+
const operation = crypto.randomUUID();
|
|
584
|
+
this.writing = true;
|
|
585
|
+
try {
|
|
586
|
+
const reply: WriteReply = inputs.length === 1 ? await this.writeEdit(id, operation, inputs[0]) : await this.writeBatch(id, operation, inputs);
|
|
587
|
+
await this.acknowledgeReply(id, reply);
|
|
588
|
+
try { await this.refreshRecoveries(); } catch {}
|
|
589
|
+
if ('error' in reply && reply.error) {
|
|
590
|
+
if (reply.error.outcome === 'unknown' || this.pendingRecoveries(id).length) this.uncertainWrites = { ...this.uncertainWrites, [id]: operation };
|
|
591
|
+
const revision = revisionAfterRejectedWrite(inputs[0].revision, reply.error);
|
|
592
|
+
if (revision !== undefined && this.browseResult?.sequence === inputs[0].revision) this.browseResult = { ...this.browseResult, sequence: revision };
|
|
593
|
+
return { ok: false, error: writeError(reply.error) };
|
|
594
|
+
}
|
|
595
|
+
if (!('results' in reply) || !reply.results || reply.results.some(result => result.affected !== '1')) {
|
|
596
|
+
return { ok: false, error: 'The change did not affect exactly one row per statement. Refresh the rows before trying again.' };
|
|
597
|
+
}
|
|
598
|
+
return { ok: true, sequence: reply.sequence };
|
|
599
|
+
} catch {
|
|
600
|
+
this.uncertainWrites = { ...this.uncertainWrites, [id]: operation };
|
|
601
|
+
return { ok: false, error: 'Studio did not receive a reply. The change may or may not have been applied; recover the saved request before another write.' };
|
|
602
|
+
} finally {
|
|
603
|
+
this.writing = false;
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
@Client()
|
|
608
|
+
async acknowledgeReply(id: string, reply: object) {
|
|
609
|
+
if ('acknowledgement' in reply && typeof reply.acknowledgement === 'string' && 'recoveryId' in reply && typeof reply.recoveryId === 'string') {
|
|
610
|
+
try { await this.acknowledgeWrite(id, reply.recoveryId, reply.acknowledgement); } catch {}
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
@Client()
|
|
615
|
+
async recoverPendingWrite() {
|
|
616
|
+
const id = this.activeConnection;
|
|
617
|
+
if (!id || this.recovering) return;
|
|
618
|
+
this.recovering = true;
|
|
619
|
+
try {
|
|
620
|
+
await this.refreshRecoveries();
|
|
621
|
+
const recovery = this.pendingRecoveries(id)[0];
|
|
622
|
+
if (!recovery) {
|
|
623
|
+
const { [id]: _cleared, ...remaining } = this.uncertainWrites;
|
|
624
|
+
this.uncertainWrites = remaining;
|
|
625
|
+
this.showMessage('No saved request is pending. Nothing was left half-written; refresh to see the current data.');
|
|
626
|
+
await this.refreshAll();
|
|
627
|
+
return;
|
|
628
|
+
}
|
|
629
|
+
const reply = await this.recoverWrite(id, crypto.randomUUID(), recovery);
|
|
630
|
+
await this.acknowledgeReply(id, reply);
|
|
631
|
+
await this.refreshRecoveries();
|
|
632
|
+
if ('error' in reply && reply.error) {
|
|
633
|
+
if (reply.error.outcome === 'rolled-back') this.showMessage(`The saved write was rolled back and did not change data (${reply.error.code}).`, true);
|
|
634
|
+
else this.showMessage(`Recovery could not finish: ${reply.error.message}. Try again when the database is reachable.`, true);
|
|
635
|
+
} else if ('sequence' in reply) {
|
|
636
|
+
this.showMessage(this.showsRevision() ? `Recovered the saved write. It is applied at revision ${reply.sequence}.` : 'Recovered the saved write. It is applied.');
|
|
637
|
+
}
|
|
638
|
+
if (!this.pendingRecoveries(id).length) {
|
|
639
|
+
const { [id]: _cleared, ...remaining } = this.uncertainWrites;
|
|
640
|
+
this.uncertainWrites = remaining;
|
|
641
|
+
}
|
|
642
|
+
await this.refreshAll();
|
|
643
|
+
} catch (error) {
|
|
644
|
+
this.showMessage(`Recovery could not finish: ${errorText(error)}`, true);
|
|
645
|
+
} finally {
|
|
646
|
+
this.recovering = false;
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
@Client()
|
|
651
|
+
keyForRow(object: StudioObject, rowIndex: number): Record<string, PortableValue> | null {
|
|
652
|
+
const row = this.browseResult.rows[rowIndex];
|
|
653
|
+
if (!row || !object.keyFields.length) return null;
|
|
654
|
+
const entries: [string, PortableValue][] = [];
|
|
655
|
+
for (const field of object.keyFields) {
|
|
656
|
+
const value = row[field];
|
|
657
|
+
if (!value || value.type === 'Null') return null;
|
|
658
|
+
if (object.model === 'document' && value.type !== 'Record') return null;
|
|
659
|
+
entries.push([field, value]);
|
|
660
|
+
}
|
|
661
|
+
return Object.fromEntries(entries);
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
/** Builds the edit for one row: changed fields for tables, the whole document for collections. */
|
|
665
|
+
@Client()
|
|
666
|
+
rowUpdate(object: StudioObject, rowIndex: number, changes: Record<string, PortableValue>, replace = false): EditInput {
|
|
667
|
+
const key = this.keyForRow(object, rowIndex);
|
|
668
|
+
if (!key) throw new Error('This row has no stable identity and cannot be edited.');
|
|
669
|
+
let body: Record<string, PortableValue>;
|
|
670
|
+
if (object.model === 'document') {
|
|
671
|
+
const current = this.browseResult.rows[rowIndex] ?? {};
|
|
672
|
+
body = replace ? { ...changes } : { ...current };
|
|
673
|
+
if (!replace) for (const [path, value] of Object.entries(changes)) setPath(body, path, value);
|
|
674
|
+
if (!sameValue(body.id, current.id)) throw new Error('The document id cannot change.');
|
|
675
|
+
} else {
|
|
676
|
+
for (const name of Object.keys(changes)) if (object.keyFields.includes(name)) throw new Error('Primary-key columns cannot change.');
|
|
677
|
+
body = changes;
|
|
678
|
+
}
|
|
679
|
+
return { table: object.name, action: 'update', revision: this.browseResult.sequence, key, body: JSON.stringify(body) };
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
@Client()
|
|
683
|
+
async afterWrite(message: string) {
|
|
684
|
+
this.showMessage(message);
|
|
685
|
+
await this.reloadRows(this.selected, this.page, this.pageSize, false);
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
@Client()
|
|
689
|
+
beginCellEdit(rowIndex: number, columnName: string) {
|
|
690
|
+
const object = this.activeObject;
|
|
691
|
+
if (!object?.editable || this.customBrowseQuery || object.keyFields.includes(columnName)) return;
|
|
692
|
+
if (this.writesBlocked) { this.showMessage('Recover the saved write before editing.', true); return; }
|
|
693
|
+
const column = object.columns.find(candidate => candidate.name === columnName);
|
|
694
|
+
if (column?.hidden || column?.readonly) return;
|
|
695
|
+
const raw = this.browseResult.rows[rowIndex]?.[columnName];
|
|
696
|
+
const kind = kindForValue(raw, column);
|
|
697
|
+
const value = editableText(raw, kind);
|
|
698
|
+
const editor: CellEditor = { rowIndex, columnName, value, mode: raw?.type === 'Null' ? 'null' : 'value', kind };
|
|
699
|
+
if ((kind === 'text' || kind === 'integer' || kind === 'number') && value.length <= 200 && !value.includes('\n')) this.inlineEditor = editor;
|
|
700
|
+
else this.sheetEditor = editor;
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
@Client()
|
|
704
|
+
updateInlineValue(value: string) {
|
|
705
|
+
if (this.inlineEditor) this.inlineEditor = { ...this.inlineEditor, value, mode: 'value' };
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
@Client()
|
|
709
|
+
setInlineMode(mode: CellMode) {
|
|
710
|
+
if (this.inlineEditor) this.inlineEditor = { ...this.inlineEditor, mode };
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
@Client()
|
|
714
|
+
async onInlineKeydown(event: KeyboardEvent) {
|
|
715
|
+
if (event.key === 'Escape') {
|
|
716
|
+
event.preventDefault();
|
|
717
|
+
this.inlineEditor = null;
|
|
718
|
+
} else if (event.key === 'Enter') {
|
|
719
|
+
event.preventDefault();
|
|
720
|
+
await this.saveInlineEditor();
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
@Client()
|
|
725
|
+
async saveInlineEditor() {
|
|
726
|
+
const editor = this.inlineEditor;
|
|
727
|
+
const object = this.activeObject;
|
|
728
|
+
if (!editor || !object) return;
|
|
729
|
+
this.inlineEditor = null;
|
|
730
|
+
const original = this.browseResult.rows[editor.rowIndex]?.[editor.columnName];
|
|
731
|
+
try {
|
|
732
|
+
const value: PortableValue = editor.mode === 'null' ? { type: 'Null' } : kindValue(editor.kind, editor.value);
|
|
733
|
+
if (sameValue(value, original)) return;
|
|
734
|
+
const result = await this.submitEdits([this.rowUpdate(object, editor.rowIndex, { [editor.columnName]: value })]);
|
|
735
|
+
if (!result.ok) { this.showMessage(result.error, true); return; }
|
|
736
|
+
await this.afterWrite(`Updated ${editor.columnName}.`);
|
|
737
|
+
} catch (error) {
|
|
738
|
+
this.showMessage(errorText(error), true);
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
@Client()
|
|
743
|
+
updateSheetValue(value: string) {
|
|
744
|
+
if (this.sheetEditor) this.sheetEditor = { ...this.sheetEditor, value, mode: 'value', error: '' };
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
@Client()
|
|
748
|
+
setSheetSelection(selection: CellSelection) {
|
|
749
|
+
const editor = this.sheetEditor;
|
|
750
|
+
if (!editor) return;
|
|
751
|
+
if (selection === 'null') { this.sheetEditor = { ...editor, mode: 'null', error: '' }; return; }
|
|
752
|
+
this.sheetEditor = { ...editor, mode: 'value', kind: selection, value: kindDefault(selection, convertText(editor.value, editor.kind, selection)), error: '' };
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
@Client()
|
|
756
|
+
async saveSheetEditor() {
|
|
757
|
+
const editor = this.sheetEditor;
|
|
758
|
+
const object = this.activeObject;
|
|
759
|
+
if (!editor || !object) return;
|
|
760
|
+
let value: PortableValue;
|
|
761
|
+
try { value = editor.mode === 'null' ? { type: 'Null' } : kindValue(editor.kind, editor.value); }
|
|
762
|
+
catch (error) { this.sheetEditor = { ...editor, error: errorText(error) }; return; }
|
|
763
|
+
try {
|
|
764
|
+
const result = await this.submitEdits([this.rowUpdate(object, editor.rowIndex, { [editor.columnName]: value })]);
|
|
765
|
+
if (!result.ok) { this.sheetEditor = { ...editor, error: result.error }; return; }
|
|
766
|
+
this.sheetEditor = null;
|
|
767
|
+
await this.afterWrite(`Updated ${editor.columnName}.`);
|
|
768
|
+
} catch (error) {
|
|
769
|
+
this.sheetEditor = { ...editor, error: errorText(error) };
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
@Client()
|
|
774
|
+
rowJson(object: StudioObject, rowIndex: number): Record<string, unknown> {
|
|
775
|
+
const row = this.browseResult.rows[rowIndex] ?? {};
|
|
776
|
+
if (object.model === 'document') return Object.fromEntries(Object.entries(row).map(([name, value]) => [name, toJson(value)]));
|
|
777
|
+
return Object.fromEntries(object.columns.filter(column => !column.hidden && row[column.name]).map(column => [column.name, toJson(row[column.name])]));
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
@Client()
|
|
781
|
+
openRowEditor(rowIndex: number) {
|
|
782
|
+
const object = this.activeObject;
|
|
783
|
+
if (!object?.editable || this.customBrowseQuery) return;
|
|
784
|
+
this.rowEditor = { rowIndex, value: JSON.stringify(this.rowJson(object, rowIndex), null, 2), error: '' };
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
@Client()
|
|
788
|
+
setRowEditorValue(value: string) {
|
|
789
|
+
if (this.rowEditor) this.rowEditor = { ...this.rowEditor, value, error: '' };
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
@Client()
|
|
793
|
+
async saveRowEditor() {
|
|
794
|
+
const editor = this.rowEditor;
|
|
795
|
+
const object = this.activeObject;
|
|
796
|
+
if (!editor || !object) return;
|
|
797
|
+
let input: EditInput;
|
|
798
|
+
try {
|
|
799
|
+
const parsed: unknown = JSON.parse(editor.value);
|
|
800
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error(`The ${object.model === 'document' ? 'document' : 'row'} must be a JSON object.`);
|
|
801
|
+
const typed = fromJson(parsed);
|
|
802
|
+
if (typed.type !== 'Object') throw new Error('The row must be a JSON object.');
|
|
803
|
+
if (object.model === 'document') {
|
|
804
|
+
input = this.rowUpdate(object, editor.rowIndex, typed.value, true);
|
|
805
|
+
if (sameValue({ type: 'Object', value: typed.value }, { type: 'Object', value: this.browseResult.rows[editor.rowIndex] ?? {} })) {
|
|
806
|
+
this.rowEditor = null;
|
|
807
|
+
this.showMessage('No changes to save.');
|
|
808
|
+
return;
|
|
809
|
+
}
|
|
810
|
+
} else {
|
|
811
|
+
const current = this.browseResult.rows[editor.rowIndex] ?? {};
|
|
812
|
+
const changes = Object.fromEntries(Object.entries(typed.value).filter(([name, value]) => !sameValue(value, current[name])));
|
|
813
|
+
if (!Object.keys(changes).length) {
|
|
814
|
+
this.rowEditor = null;
|
|
815
|
+
this.showMessage('No changes to save.');
|
|
816
|
+
return;
|
|
817
|
+
}
|
|
818
|
+
input = this.rowUpdate(object, editor.rowIndex, changes);
|
|
819
|
+
}
|
|
820
|
+
} catch (error) {
|
|
821
|
+
this.rowEditor = { ...editor, error: `Invalid row: ${errorText(error)}` };
|
|
822
|
+
return;
|
|
823
|
+
}
|
|
824
|
+
const result = await this.submitEdits([input]);
|
|
825
|
+
if (!result.ok) { this.rowEditor = { ...editor, error: result.error }; return; }
|
|
826
|
+
this.rowEditor = null;
|
|
827
|
+
await this.afterWrite(object.model === 'document' ? 'Document saved.' : 'Row updated.');
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
@Client()
|
|
831
|
+
requestDelete(rowIndex: number) {
|
|
832
|
+
const object = this.activeObject;
|
|
833
|
+
if (object?.editable) this.deleteTarget = { table: object.name, rowIndexes: [rowIndex] };
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
@Client()
|
|
837
|
+
requestDeleteSelected() {
|
|
838
|
+
const object = this.activeObject;
|
|
839
|
+
if (!object?.editable || !this.selectedRows.length) return;
|
|
840
|
+
if (this.selectedRows.length > 32) { this.showMessage('Select at most 32 rows for one atomic delete.', true); return; }
|
|
841
|
+
this.deleteTarget = { table: object.name, rowIndexes: [...this.selectedRows] };
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
@Client()
|
|
845
|
+
async confirmDelete() {
|
|
846
|
+
const target = this.deleteTarget;
|
|
847
|
+
const object = this.activeObject;
|
|
848
|
+
if (!target || !object || object.name !== target.table) return;
|
|
849
|
+
let inputs: EditInput[];
|
|
850
|
+
try {
|
|
851
|
+
inputs = target.rowIndexes.map(index => {
|
|
852
|
+
const key = this.keyForRow(object, index);
|
|
853
|
+
if (!key) throw new Error('Every selected row needs a stable identity.');
|
|
854
|
+
return { table: object.name, action: 'delete', revision: this.browseResult.sequence, key, body: '{}' };
|
|
855
|
+
});
|
|
856
|
+
} catch (error) {
|
|
857
|
+
this.deleteTarget = null;
|
|
858
|
+
this.showMessage(errorText(error), true);
|
|
859
|
+
return;
|
|
860
|
+
}
|
|
861
|
+
const result = await this.submitEdits(inputs);
|
|
862
|
+
this.deleteTarget = null;
|
|
863
|
+
if (!result.ok) { this.showMessage(result.error, true); return; }
|
|
864
|
+
this.selectedRows = [];
|
|
865
|
+
await this.afterWrite(`${inputs.length} row${inputs.length === 1 ? '' : 's'} deleted.`);
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
@Client()
|
|
869
|
+
toggleInsert() {
|
|
870
|
+
const object = this.activeObject;
|
|
871
|
+
const next = !this.showInsert;
|
|
872
|
+
this.showInsert = next;
|
|
873
|
+
this.insertError = '';
|
|
874
|
+
if (!next || !object) return;
|
|
875
|
+
if (object.model === 'document') {
|
|
876
|
+
const document: Record<string, unknown> = { id: { $record: `${object.name}:${newDocumentKey()}` } };
|
|
877
|
+
for (const column of object.columns) {
|
|
878
|
+
if (column.name === 'id' || column.name.includes('.') || !column.required || column.defaultValue !== null) continue;
|
|
879
|
+
const kind = declaredKind(column);
|
|
880
|
+
document[column.name] = kind === 'integer' || kind === 'number' ? 0 : kind === 'boolean' ? false : kind === 'json' ? {} : '';
|
|
881
|
+
}
|
|
882
|
+
this.insertDocument = JSON.stringify(document, null, 2);
|
|
883
|
+
return;
|
|
884
|
+
}
|
|
885
|
+
const singleIntegerKey = object.keyFields.length === 1 && object.columns.find(column => column.name === object.keyFields[0])?.affinity === 'integer';
|
|
886
|
+
this.insertFields = Object.fromEntries(object.columns.filter(column => !column.hidden).map(column => {
|
|
887
|
+
const valueKind = declaredKind(column);
|
|
888
|
+
const omit = column.defaultValue !== null || column.nullable || (singleIntegerKey && column.primaryKeyPosition > 0);
|
|
889
|
+
return [column.name, { mode: omit ? 'omit' : 'value', valueKind, value: kindDefault(valueKind, '') } satisfies InsertFieldState];
|
|
890
|
+
}));
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
@Client()
|
|
894
|
+
setInsertValue(name: string, value: string) {
|
|
895
|
+
const field = this.insertFields[name] ?? { mode: 'value', valueKind: 'text', value: '' };
|
|
896
|
+
this.insertFields = { ...this.insertFields, [name]: { ...field, mode: 'value', value } };
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
@Client()
|
|
900
|
+
setInsertSelection(name: string, selection: InsertSelection) {
|
|
901
|
+
const field = this.insertFields[name] ?? { mode: 'value', valueKind: 'text', value: '' };
|
|
902
|
+
if (selection === 'omit' || selection === 'null') {
|
|
903
|
+
this.insertFields = { ...this.insertFields, [name]: { ...field, mode: selection } };
|
|
904
|
+
return;
|
|
905
|
+
}
|
|
906
|
+
this.insertFields = { ...this.insertFields, [name]: { mode: 'value', valueKind: selection, value: kindDefault(selection, convertText(field.value, field.valueKind, selection)) } };
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
@Client()
|
|
910
|
+
regenerateInsertValue(name: string, kind: ValueKind) {
|
|
911
|
+
this.setInsertValue(name, kindDefault(kind, ''));
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
@Client()
|
|
915
|
+
async submitInsert() {
|
|
916
|
+
const object = this.activeObject;
|
|
917
|
+
if (!object) return;
|
|
918
|
+
this.insertError = '';
|
|
919
|
+
let body: Record<string, PortableValue>;
|
|
920
|
+
try {
|
|
921
|
+
if (object.model === 'document') {
|
|
922
|
+
const typed = fromJson(JSON.parse(this.insertDocument));
|
|
923
|
+
if (typed.type !== 'Object') throw new Error('The document must be a JSON object.');
|
|
924
|
+
const id = typed.value.id;
|
|
925
|
+
if (id?.type !== 'Record' || id.value.table.toLowerCase() !== object.name.toLowerCase()) {
|
|
926
|
+
throw new Error(`Set "id" to a record ID in this collection, for example {"$record": "${object.name}:new_id"}.`);
|
|
927
|
+
}
|
|
928
|
+
body = typed.value;
|
|
929
|
+
} else {
|
|
930
|
+
body = {};
|
|
931
|
+
for (const column of object.columns.filter(candidate => !candidate.hidden)) {
|
|
932
|
+
const field = this.insertFields[column.name];
|
|
933
|
+
if (!field || field.mode === 'omit') continue;
|
|
934
|
+
try { body[column.name] = field.mode === 'null' ? { type: 'Null' } : kindValue(field.valueKind, field.value); }
|
|
935
|
+
catch (error) { throw new Error(`${column.name}: ${errorText(error)}`); }
|
|
936
|
+
}
|
|
937
|
+
if (!Object.keys(body).length) throw new Error('Enter at least one value. Omitted columns use their defaults.');
|
|
938
|
+
}
|
|
939
|
+
} catch (error) {
|
|
940
|
+
this.insertError = errorText(error);
|
|
941
|
+
return;
|
|
942
|
+
}
|
|
943
|
+
const result = await this.submitEdits([{ table: object.name, action: 'insert', revision: this.browseResult.sequence, key: {}, body: JSON.stringify(body) }]);
|
|
944
|
+
if (!result.ok) { this.insertError = result.error; return; }
|
|
945
|
+
this.showInsert = false;
|
|
946
|
+
this.insertFields = {};
|
|
947
|
+
await this.afterWrite(object.model === 'document' ? 'Document inserted.' : 'Row inserted.');
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
@Client()
|
|
951
|
+
toggleRowSelection(rowIndex: number, checked: boolean) {
|
|
952
|
+
this.selectedRows = checked ? [...new Set([...this.selectedRows, rowIndex])] : this.selectedRows.filter(index => index !== rowIndex);
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
@Client()
|
|
956
|
+
toggleAllRows(checked: boolean) {
|
|
957
|
+
this.selectedRows = checked ? this.browseResult.rows.map((_, index) => index) : [];
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
@Client()
|
|
961
|
+
openBatchUpdate() {
|
|
962
|
+
const object = this.activeObject;
|
|
963
|
+
if (!object) return;
|
|
964
|
+
if (this.selectedRows.length > 32) { this.showMessage('Select at most 32 rows for one atomic update.', true); return; }
|
|
965
|
+
const column = object.columns.find(candidate => !candidate.hidden && !candidate.readonly && !object.keyFields.includes(candidate.name));
|
|
966
|
+
const kind = column ? declaredKind(column) : 'text';
|
|
967
|
+
this.batchUpdate = { column: column?.name ?? '', mode: 'value', kind, value: kindDefault(kind, ''), error: '' };
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
@Client()
|
|
971
|
+
async submitBatchUpdate() {
|
|
972
|
+
const object = this.activeObject;
|
|
973
|
+
const update = this.batchUpdate;
|
|
974
|
+
if (!object?.editable || !update || !this.selectedRows.length) return;
|
|
975
|
+
let inputs: EditInput[];
|
|
976
|
+
try {
|
|
977
|
+
if (!update.column.trim()) throw new Error('Choose a column.');
|
|
978
|
+
if (object.keyFields.includes(update.column)) throw new Error('Row identity columns cannot change.');
|
|
979
|
+
const value: PortableValue = update.mode === 'null' ? { type: 'Null' } : kindValue(update.kind, update.value);
|
|
980
|
+
inputs = this.selectedRows.map(index => this.rowUpdate(object, index, { [update.column.trim()]: value }));
|
|
981
|
+
} catch (error) {
|
|
982
|
+
this.batchUpdate = { ...update, error: errorText(error) };
|
|
983
|
+
return;
|
|
984
|
+
}
|
|
985
|
+
const result = await this.submitEdits(inputs);
|
|
986
|
+
if (!result.ok) { this.batchUpdate = { ...update, error: result.error }; return; }
|
|
987
|
+
this.batchUpdate = null;
|
|
988
|
+
this.selectedRows = [];
|
|
989
|
+
await this.afterWrite(`${inputs.length} row${inputs.length === 1 ? '' : 's'} updated.`);
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
@Client()
|
|
993
|
+
setBatchSelection(selection: CellSelection) {
|
|
994
|
+
const update = this.batchUpdate;
|
|
995
|
+
if (!update) return;
|
|
996
|
+
this.batchUpdate = selection === 'null'
|
|
997
|
+
? { ...update, mode: 'null', error: '' }
|
|
998
|
+
: { ...update, mode: 'value', kind: selection, value: kindDefault(selection, convertText(update.value, update.kind, selection)), error: '' };
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
@Client()
|
|
1002
|
+
setBatchColumn(column: string) {
|
|
1003
|
+
const update = this.batchUpdate;
|
|
1004
|
+
if (!update) return;
|
|
1005
|
+
const definition = this.activeObject?.columns.find(candidate => candidate.name === column);
|
|
1006
|
+
const kind = definition ? declaredKind(definition) : update.kind;
|
|
1007
|
+
this.batchUpdate = { ...update, column, kind, value: kind === update.kind ? update.value : kindDefault(kind, ''), error: '' };
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
@Client()
|
|
1011
|
+
openExport(rowIndexes: number[], collection = false) {
|
|
1012
|
+
if (!this.activeObject) return;
|
|
1013
|
+
this.exportSheet = { rowIndexes, format: 'json', collection, columns: [...this.gridColumns()] };
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
@Shared()
|
|
1017
|
+
gridColumns(): string[] {
|
|
1018
|
+
const object = this.activeObject;
|
|
1019
|
+
if (!object) return [];
|
|
1020
|
+
const declared = object.columns.filter(column => !column.hidden).map(column => column.name);
|
|
1021
|
+
if (!this.browseResult.columns.length) return declared;
|
|
1022
|
+
return object.model === 'document' && !this.customBrowseQuery ? [...new Set([...declared, ...this.browseResult.columns])] : this.browseResult.columns;
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
@Client()
|
|
1026
|
+
toggleExportColumn(name: string, checked: boolean) {
|
|
1027
|
+
if (!this.exportSheet) return;
|
|
1028
|
+
this.exportSheet = {
|
|
1029
|
+
...this.exportSheet,
|
|
1030
|
+
columns: checked ? [...new Set([...this.exportSheet.columns, name])] : this.exportSheet.columns.filter(column => column !== name),
|
|
1031
|
+
};
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
@Client()
|
|
1035
|
+
downloadExport() {
|
|
1036
|
+
const object = this.activeObject;
|
|
1037
|
+
const state = this.exportSheet;
|
|
1038
|
+
if (!object || !state || !state.columns.length) return;
|
|
1039
|
+
const rows = state.rowIndexes.map(index => this.browseResult.rows[index]).filter(Boolean) as GridRow[];
|
|
1040
|
+
const records = rows.map(row => Object.fromEntries(state.columns.filter(column => row[column]).map(column => [column, toJson(row[column])])));
|
|
1041
|
+
const content = state.format === 'json'
|
|
1042
|
+
? JSON.stringify(state.collection || records.length !== 1 ? records : records[0], null, 2)
|
|
1043
|
+
: [
|
|
1044
|
+
state.columns.map(csvCell).join(','),
|
|
1045
|
+
...rows.map(row => state.columns.map(column => csvCell(row[column] && row[column].type !== 'Null' ? displayValue(row[column]) : '')).join(',')),
|
|
1046
|
+
].join('\r\n');
|
|
1047
|
+
const blob = new Blob([content], { type: state.format === 'json' ? 'application/json' : 'text/csv;charset=utf-8' });
|
|
1048
|
+
const url = URL.createObjectURL(blob);
|
|
1049
|
+
const anchor = document.createElement('a');
|
|
1050
|
+
anchor.href = url;
|
|
1051
|
+
anchor.download = `${object.name}-${state.collection || rows.length !== 1 ? 'rows' : 'row'}.${state.format}`;
|
|
1052
|
+
anchor.click();
|
|
1053
|
+
URL.revokeObjectURL(url);
|
|
1054
|
+
this.exportSheet = null;
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
// ---------------------------------------------------------------------------
|
|
1058
|
+
// Graph explorer.
|
|
1059
|
+
|
|
1060
|
+
@Shared()
|
|
1061
|
+
graphEdgeTable(): string {
|
|
1062
|
+
const edges = this.schema.objects.filter(object => object.edge);
|
|
1063
|
+
if (edges.some(object => object.name === this.graphEdge)) return this.graphEdge;
|
|
1064
|
+
let table = '';
|
|
1065
|
+
try { table = parseRecord(this.graphRoot.trim()).value.table; } catch {}
|
|
1066
|
+
return (table ? edgeTablesFor(this.schema, table)[0]?.name : undefined) ?? edges[0]?.name ?? '';
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
@Client()
|
|
1070
|
+
async runGraph() {
|
|
1071
|
+
const id = this.activeConnection;
|
|
1072
|
+
if (!id) return;
|
|
1073
|
+
let root: PortableValue;
|
|
1074
|
+
try { root = parseRecord(this.graphRoot.trim()); }
|
|
1075
|
+
catch (error) { this.graphView = { nodes: [], edges: [], query: '', durationMs: 0, sequence: 0, error: errorText(error) }; return; }
|
|
1076
|
+
this.graphLoading = true;
|
|
1077
|
+
try {
|
|
1078
|
+
this.graphView = await this.exploreGraph(id, { root, edge: this.graphEdgeTable(), direction: this.graphDirection, depth: this.graphDepth });
|
|
1079
|
+
} finally {
|
|
1080
|
+
this.graphLoading = false;
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
|
|
1084
|
+
@Client()
|
|
1085
|
+
async exploreFrom(node: GraphNode) {
|
|
1086
|
+
this.graphRoot = node.label;
|
|
1087
|
+
const current = this.schema.objects.find(object => object.name === this.graphEdge)?.edge;
|
|
1088
|
+
if (!current || (current.source !== node.table && current.target !== node.table)) {
|
|
1089
|
+
this.graphEdge = edgeTablesFor(this.schema, node.table)[0]?.name ?? this.graphEdge;
|
|
1090
|
+
}
|
|
1091
|
+
await this.runGraph();
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
@Client()
|
|
1095
|
+
async exploreRecord(record: PortableValue) {
|
|
1096
|
+
if (record.type !== 'Record') return;
|
|
1097
|
+
this.graphRoot = displayValue(record);
|
|
1098
|
+
this.graphEdge = edgeTablesFor(this.schema, record.value.table)[0]?.name ?? '';
|
|
1099
|
+
await this.switchTab('graph');
|
|
1100
|
+
await this.runGraph();
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
@Client()
|
|
1104
|
+
openGraphInSql() {
|
|
1105
|
+
if (!this.graphView?.query) return;
|
|
1106
|
+
this.sql = this.graphView.query;
|
|
1107
|
+
this.sqlOutput = 'graph';
|
|
1108
|
+
void this.switchTab('sql');
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
// ---------------------------------------------------------------------------
|
|
1112
|
+
// Map view.
|
|
1113
|
+
|
|
1114
|
+
/** The chosen spatial index, else one on the selected collection, else the first one. */
|
|
1115
|
+
@Shared()
|
|
1116
|
+
mapIndexName(): string {
|
|
1117
|
+
const indexes = spatialIndexes(this.schema);
|
|
1118
|
+
if (indexes.some(entry => entry.index.name === this.mapIndex)) return this.mapIndex;
|
|
1119
|
+
return (indexes.find(entry => entry.table === this.selected) ?? indexes[0])?.index.name ?? '';
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
@Client()
|
|
1123
|
+
async runMap() {
|
|
1124
|
+
const id = this.activeConnection;
|
|
1125
|
+
const entry = spatialIndexes(this.schema).find(candidate => candidate.index.name === this.mapIndexName());
|
|
1126
|
+
if (!id || !entry) return;
|
|
1127
|
+
const number = (field: MapBoxField) => {
|
|
1128
|
+
const text = this.mapBox[field].trim();
|
|
1129
|
+
if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(text)) throw new Error(`Enter a number for ${field === 'lng' ? 'longitude' : field === 'lat' ? 'latitude' : field}.`);
|
|
1130
|
+
return Number(text);
|
|
1131
|
+
};
|
|
1132
|
+
const request: MapRequest = { table: entry.table, index: entry.index.name, limit: this.mapLimit };
|
|
1133
|
+
try {
|
|
1134
|
+
if (entry.index.geometry === 'point') request.bbox = [number('west'), number('south'), number('east'), number('north')];
|
|
1135
|
+
if (entry.index.geometry === 'region' && (this.mapBox.lng.trim() || this.mapBox.lat.trim())) request.point = [number('lng'), number('lat')];
|
|
1136
|
+
} catch (error) {
|
|
1137
|
+
this.mapView = { features: [], rows: 0, limit: this.mapLimit, truncated: false, query: '', durationMs: 0, sequence: 0, error: errorText(error) };
|
|
1138
|
+
return;
|
|
1139
|
+
}
|
|
1140
|
+
this.mapLoading = true;
|
|
1141
|
+
try {
|
|
1142
|
+
this.mapView = await this.fetchMap(id, request);
|
|
1143
|
+
this.mapSelected = '';
|
|
1144
|
+
} finally {
|
|
1145
|
+
this.mapLoading = false;
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
@Client()
|
|
1150
|
+
async openMap(index: string) {
|
|
1151
|
+
this.mapIndex = index;
|
|
1152
|
+
this.mapView = null;
|
|
1153
|
+
this.mapSelected = '';
|
|
1154
|
+
await this.switchTab('map');
|
|
1155
|
+
await this.runMap();
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
@Client()
|
|
1159
|
+
async searchMapArea(bbox: [number, number, number, number]) {
|
|
1160
|
+
const [west, south, east, north] = bbox;
|
|
1161
|
+
this.mapBox = { ...this.mapBox, west: String(west), south: String(south), east: String(east), north: String(north) };
|
|
1162
|
+
await this.runMap();
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
@Client()
|
|
1166
|
+
openMapInSql() {
|
|
1167
|
+
if (!this.mapView?.query) return;
|
|
1168
|
+
this.sql = this.mapView.query;
|
|
1169
|
+
this.sqlOutput = 'map';
|
|
1170
|
+
void this.switchTab('sql');
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
// ---------------------------------------------------------------------------
|
|
1174
|
+
// SQL console and browse query.
|
|
1175
|
+
|
|
1176
|
+
@Client()
|
|
1177
|
+
setSql(value: string) {
|
|
1178
|
+
this.sql = value;
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
@Client()
|
|
1182
|
+
setBrowseQuery(value: string) {
|
|
1183
|
+
this.browseQuery = value;
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1186
|
+
@Client()
|
|
1187
|
+
async runSqlFromEditor() {
|
|
1188
|
+
await this.startSql(this.sql, 'sql');
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
@Client()
|
|
1192
|
+
async runBrowseQuery() {
|
|
1193
|
+
if (!this.selected) return;
|
|
1194
|
+
const statement = this.browseQuery.trim();
|
|
1195
|
+
if (!statement || statement === this.browseResult.query) {
|
|
1196
|
+
await this.reloadRows();
|
|
1197
|
+
return;
|
|
1198
|
+
}
|
|
1199
|
+
await this.startSql(statement, 'browse');
|
|
1200
|
+
}
|
|
1201
|
+
|
|
1202
|
+
/** Reads run immediately. Statements that change data wait for confirmation. */
|
|
1203
|
+
@Client()
|
|
1204
|
+
async startSql(text: string, source: 'sql' | 'browse') {
|
|
1205
|
+
if (!this.activeConnection || this.sqlRunning) return;
|
|
1206
|
+
const statements = splitStatements(text);
|
|
1207
|
+
if (!statements.length) return;
|
|
1208
|
+
if (statements.length > 32) { this.showMessage('Run at most 32 statements in one request.', true); return; }
|
|
1209
|
+
if (statements.some(isWriteStatement)) {
|
|
1210
|
+
if (this.readOnly()) { this.showMessage('This statement changes data, and you may only read this database.', true); return; }
|
|
1211
|
+
if (this.writesBlocked) { this.showMessage('Recover the saved write with an unknown outcome before running another write.', true); return; }
|
|
1212
|
+
this.pendingWrite = { statements: statements.length, source };
|
|
1213
|
+
return;
|
|
1214
|
+
}
|
|
1215
|
+
await this.executeStatements(statements, 'read', source);
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
@Client()
|
|
1219
|
+
async confirmPendingWrite() {
|
|
1220
|
+
const pending = this.pendingWrite;
|
|
1221
|
+
this.pendingWrite = null;
|
|
1222
|
+
if (!pending) return;
|
|
1223
|
+
if (pending.source === 'create') { await this.createObject(); return; }
|
|
1224
|
+
const text = pending.source === 'browse' ? this.browseQuery : this.sql;
|
|
1225
|
+
await this.executeStatements(splitStatements(text), 'write', pending.source);
|
|
1226
|
+
}
|
|
1227
|
+
|
|
1228
|
+
@Client()
|
|
1229
|
+
buildQueryInput(statements: string[], mode: 'read' | 'write'): QueryInput {
|
|
1230
|
+
let parameters: Record<string, PortableValue> = {};
|
|
1231
|
+
if (this.sqlParameters.trim()) {
|
|
1232
|
+
const typed = fromJson(JSON.parse(this.sqlParameters));
|
|
1233
|
+
if (typed.type !== 'Object') throw new Error('Parameters must be a JSON object such as {"$id": 1}.');
|
|
1234
|
+
parameters = typed.value;
|
|
1235
|
+
}
|
|
1236
|
+
const limits: Record<string, number> = {};
|
|
1237
|
+
for (const [name, text] of [['rowsRead', this.rowsReadBudget], ['vmSteps', this.vmStepBudget]] as const) {
|
|
1238
|
+
if (!text.trim()) continue;
|
|
1239
|
+
if (!/^\d+$/.test(text.trim()) || Number(text) > 1_000_000) throw new Error('Work budgets must be whole numbers from 0 to 1,000,000.');
|
|
1240
|
+
limits[name] = Number(text);
|
|
1241
|
+
}
|
|
1242
|
+
if (this.sqlRevision.trim() && !/^\d+$/.test(this.sqlRevision.trim())) throw new Error('The expected revision must be a whole number.');
|
|
1243
|
+
return {
|
|
1244
|
+
statements: statements.map(sql => ({
|
|
1245
|
+
sql,
|
|
1246
|
+
parameters: JSON.stringify(statementParameters(sql, parameters)),
|
|
1247
|
+
})),
|
|
1248
|
+
mode,
|
|
1249
|
+
limits,
|
|
1250
|
+
...(mode === 'write' && this.sqlRevision.trim() ? { ifSequence: Number(this.sqlRevision) } : {}),
|
|
1251
|
+
};
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
@Client()
|
|
1255
|
+
async executeStatements(statements: string[], mode: 'read' | 'write', source: 'sql' | 'browse', explain = false) {
|
|
1256
|
+
const id = this.activeConnection;
|
|
1257
|
+
if (!id) return;
|
|
1258
|
+
let input: QueryInput;
|
|
1259
|
+
try { input = this.buildQueryInput(explain ? statements.map(statement => /^\s*EXPLAIN\b/i.test(statement) ? statement : `EXPLAIN QUERY PLAN ${statement}`) : statements, mode); }
|
|
1260
|
+
catch (error) { this.showMessage(errorText(error), true); return; }
|
|
1261
|
+
const operation = crypto.randomUUID();
|
|
1262
|
+
this.sqlOperation = operation;
|
|
1263
|
+
if (explain) this.sqlExplaining = true; else this.sqlRunning = true;
|
|
1264
|
+
if (source === 'browse') this.browseLoading = true;
|
|
1265
|
+
if (mode === 'write') this.writing = true;
|
|
1266
|
+
const text = statements.join(';\n');
|
|
1267
|
+
try {
|
|
1268
|
+
const reply = await this.executeSql(id, operation, input);
|
|
1269
|
+
await this.acknowledgeReply(id, reply);
|
|
1270
|
+
const run = reply.run;
|
|
1271
|
+
if (mode === 'write') {
|
|
1272
|
+
try { await this.refreshRecoveries(); } catch {}
|
|
1273
|
+
if (run.error && (run.error.outcome === 'unknown' || this.pendingRecoveries(id).length)) this.uncertainWrites = { ...this.uncertainWrites, [id]: operation };
|
|
1274
|
+
}
|
|
1275
|
+
if (!explain) this.recordQuery(text, run, source);
|
|
1276
|
+
if (explain) {
|
|
1277
|
+
this.explainRun = run;
|
|
1278
|
+
this.sqlOutput = 'explain';
|
|
1279
|
+
this.resultIndex = Math.max(0, run.results.length - 1);
|
|
1280
|
+
} else if (source === 'sql') {
|
|
1281
|
+
this.sqlRun = run;
|
|
1282
|
+
this.sqlOutput = this.sqlOutput === 'graph' || this.sqlOutput === 'map' ? this.sqlOutput : 'results';
|
|
1283
|
+
this.sqlMapSelected = '';
|
|
1284
|
+
this.resultIndex = Math.max(0, run.results.length - 1);
|
|
1285
|
+
}
|
|
1286
|
+
if (run.error) {
|
|
1287
|
+
this.showMessage(`${run.error.code}: ${run.error.message}`, true);
|
|
1288
|
+
return;
|
|
1289
|
+
}
|
|
1290
|
+
const last = run.results[run.results.length - 1];
|
|
1291
|
+
this.showMessage(explain
|
|
1292
|
+
? `Query plan generated in ${run.durationMs.toFixed(1)} ms`
|
|
1293
|
+
: mode === 'write'
|
|
1294
|
+
? `Write applied${this.showsRevision() ? ` at revision ${run.sequence}` : ''} · ${run.results.reduce((sum, result) => sum + result.affectedRows, 0)} affected row(s) · ${run.durationMs.toFixed(1)} ms`
|
|
1295
|
+
: `${last?.rows.length ?? 0} returned row${last?.rows.length === 1 ? '' : 's'} · ${run.durationMs.toFixed(1)} ms`);
|
|
1296
|
+
if (mode === 'write') {
|
|
1297
|
+
await this.reloadSchema();
|
|
1298
|
+
if (this.selected && source === 'sql') await this.reloadRows(this.selected, this.page, this.pageSize, false);
|
|
1299
|
+
}
|
|
1300
|
+
if (source === 'browse' && this.selected) {
|
|
1301
|
+
if (mode === 'write') await this.reloadRows(this.selected, 1, this.pageSize, false);
|
|
1302
|
+
else if (last) {
|
|
1303
|
+
this.browseResult = { ...this.browseResult, columns: last.columns, rows: last.rows, totalRows: last.rows.length, page: 1, objectName: this.selected, query: text };
|
|
1304
|
+
this.loadedObject = this.selected;
|
|
1305
|
+
this.customBrowseQuery = true;
|
|
1306
|
+
this.selectedRows = [];
|
|
1307
|
+
this.inlineEditor = null;
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
} catch (error) {
|
|
1311
|
+
if (mode === 'write') this.uncertainWrites = { ...this.uncertainWrites, [id]: operation };
|
|
1312
|
+
this.showMessage(mode === 'write'
|
|
1313
|
+
? 'Studio did not receive a reply. The write may or may not have been applied; recover the saved request before another write.'
|
|
1314
|
+
: `The request failed: ${errorText(error)}`, true);
|
|
1315
|
+
} finally {
|
|
1316
|
+
this.sqlOperation = '';
|
|
1317
|
+
this.sqlRunning = false;
|
|
1318
|
+
this.sqlExplaining = false;
|
|
1319
|
+
this.browseLoading = false;
|
|
1320
|
+
if (mode === 'write') this.writing = false;
|
|
1321
|
+
}
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1324
|
+
@Client()
|
|
1325
|
+
async runExplainFromEditor() {
|
|
1326
|
+
const statements = splitStatements(this.sql);
|
|
1327
|
+
if (!statements.length || this.sqlRunning || this.sqlExplaining) return;
|
|
1328
|
+
await this.executeStatements(statements, 'read', 'sql', true);
|
|
1329
|
+
}
|
|
1330
|
+
|
|
1331
|
+
@Client()
|
|
1332
|
+
async cancelSql() {
|
|
1333
|
+
if (this.sqlOperation) await this.cancelOperation(this.sqlOperation);
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
@Client()
|
|
1337
|
+
setSqlOption(name: 'parameters' | 'revision' | 'rowsRead' | 'vmSteps', value: string) {
|
|
1338
|
+
if (name === 'parameters') this.sqlParameters = value;
|
|
1339
|
+
if (name === 'revision') this.sqlRevision = value;
|
|
1340
|
+
if (name === 'rowsRead') this.rowsReadBudget = value;
|
|
1341
|
+
if (name === 'vmSteps') this.vmStepBudget = value;
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
@Client()
|
|
1345
|
+
loadQueryHistory() {
|
|
1346
|
+
try {
|
|
1347
|
+
const stored: unknown = JSON.parse(localStorage.getItem(this.historyKey) ?? '[]');
|
|
1348
|
+
if (!Array.isArray(stored)) { this.queryHistory = []; return; }
|
|
1349
|
+
this.queryHistory = stored.flatMap((entry): QueryHistoryEntry[] => {
|
|
1350
|
+
if (!entry || typeof entry.id !== 'string' || typeof entry.statement !== 'string' || typeof entry.executedAt !== 'number') return [];
|
|
1351
|
+
return [{
|
|
1352
|
+
id: entry.id,
|
|
1353
|
+
statement: entry.statement,
|
|
1354
|
+
executedAt: entry.executedAt,
|
|
1355
|
+
durationMs: typeof entry.durationMs === 'number' ? entry.durationMs : 0,
|
|
1356
|
+
error: typeof entry.error === 'string' ? entry.error : null,
|
|
1357
|
+
favorite: entry.favorite === true,
|
|
1358
|
+
source: entry.source === 'browse' ? 'browse' : 'sql',
|
|
1359
|
+
}];
|
|
1360
|
+
}).slice(0, 200);
|
|
1361
|
+
} catch {
|
|
1362
|
+
this.queryHistory = [];
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
|
|
1366
|
+
@Client()
|
|
1367
|
+
persistQueryHistory() {
|
|
1368
|
+
try { localStorage.setItem(this.historyKey, JSON.stringify(this.queryHistory.slice(0, 200))); }
|
|
1369
|
+
catch { /* History is optional when browser storage is disabled or full. */ }
|
|
1370
|
+
}
|
|
1371
|
+
|
|
1372
|
+
@Client()
|
|
1373
|
+
recordQuery(statement: string, run: SqlRun, source: QueryHistoryEntry['source']) {
|
|
1374
|
+
const normalized = statement.trim();
|
|
1375
|
+
if (!normalized) return;
|
|
1376
|
+
this.queryHistory = [{
|
|
1377
|
+
id: crypto.randomUUID(),
|
|
1378
|
+
statement: normalized,
|
|
1379
|
+
executedAt: Date.now(),
|
|
1380
|
+
durationMs: run.durationMs,
|
|
1381
|
+
error: run.error ? `${run.error.code}: ${run.error.message}` : null,
|
|
1382
|
+
favorite: false,
|
|
1383
|
+
source,
|
|
1384
|
+
}, ...this.queryHistory].slice(0, 200);
|
|
1385
|
+
this.persistQueryHistory();
|
|
1386
|
+
}
|
|
1387
|
+
|
|
1388
|
+
@Client()
|
|
1389
|
+
toggleQueryFavorite(id: string) {
|
|
1390
|
+
this.queryHistory = this.queryHistory.map(entry => entry.id === id ? { ...entry, favorite: !entry.favorite } : entry);
|
|
1391
|
+
this.persistQueryHistory();
|
|
1392
|
+
}
|
|
1393
|
+
|
|
1394
|
+
@Client()
|
|
1395
|
+
clearQueryHistory() {
|
|
1396
|
+
this.queryHistory = this.queryHistory.filter(entry => entry.favorite);
|
|
1397
|
+
this.persistQueryHistory();
|
|
1398
|
+
}
|
|
1399
|
+
|
|
1400
|
+
@Client()
|
|
1401
|
+
loadHistoryQuery(entry: QueryHistoryEntry) {
|
|
1402
|
+
this.sql = entry.statement;
|
|
1403
|
+
this.sqlOutput = 'results';
|
|
1404
|
+
this.tab = 'sql';
|
|
1405
|
+
this.historyOpen = false;
|
|
1406
|
+
this.syncUrl(true);
|
|
1407
|
+
}
|
|
1408
|
+
|
|
1409
|
+
@Client()
|
|
1410
|
+
async runHistoryQuery(entry: QueryHistoryEntry) {
|
|
1411
|
+
this.loadHistoryQuery(entry);
|
|
1412
|
+
await this.runSqlFromEditor();
|
|
1413
|
+
}
|
|
1414
|
+
|
|
1415
|
+
// ---------------------------------------------------------------------------
|
|
1416
|
+
// New table or collection.
|
|
1417
|
+
|
|
1418
|
+
@Client()
|
|
1419
|
+
openNewObject() {
|
|
1420
|
+
if (!this.activeConnection) { this.connectFirst(); return; }
|
|
1421
|
+
this.newObjectOpen = true;
|
|
1422
|
+
this.newObjectError = '';
|
|
1423
|
+
}
|
|
1424
|
+
|
|
1425
|
+
@Shared()
|
|
1426
|
+
newEdgeDraft() {
|
|
1427
|
+
return { source: this.newEdgeSource, target: this.newEdgeTarget, cascade: this.newEdgeCascade };
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
@Shared()
|
|
1431
|
+
newSpatialDraft() {
|
|
1432
|
+
return { table: this.newSpatialTable, field: this.newSpatialField, region: this.newSpatialRegion };
|
|
1433
|
+
}
|
|
1434
|
+
|
|
1435
|
+
@Shared()
|
|
1436
|
+
newObjectSql(): string {
|
|
1437
|
+
try { return createObjectSql(this.newObjectName.trim(), this.newObjectKind, this.newColumns, this.newEdgeDraft(), this.newSpatialDraft()); }
|
|
1438
|
+
catch { return ''; }
|
|
1439
|
+
}
|
|
1440
|
+
|
|
1441
|
+
@Client()
|
|
1442
|
+
openNewObjectInSql() {
|
|
1443
|
+
const sql = this.newObjectSql();
|
|
1444
|
+
if (!sql) return;
|
|
1445
|
+
this.sql = sql;
|
|
1446
|
+
this.newObjectOpen = false;
|
|
1447
|
+
this.tab = 'sql';
|
|
1448
|
+
this.syncUrl(true);
|
|
1449
|
+
}
|
|
1450
|
+
|
|
1451
|
+
@Client()
|
|
1452
|
+
requestCreateObject() {
|
|
1453
|
+
try { createObjectSql(this.newObjectName.trim(), this.newObjectKind, this.newColumns, this.newEdgeDraft(), this.newSpatialDraft()); }
|
|
1454
|
+
catch (error) { this.newObjectError = errorText(error); return; }
|
|
1455
|
+
if (this.newObjectKind === 'spatial') {
|
|
1456
|
+
const name = this.newObjectName.trim().toLowerCase();
|
|
1457
|
+
if (this.schema.objects.some(object => object.indexes.some(index => index.name.toLowerCase() === name))) {
|
|
1458
|
+
this.newObjectError = `An index named ${this.newObjectName.trim()} already exists.`;
|
|
1459
|
+
return;
|
|
1460
|
+
}
|
|
1461
|
+
if (!this.schema.objects.some(object => object.model === 'document' && object.name === this.newSpatialTable)) {
|
|
1462
|
+
this.newObjectError = 'Choose a document collection.';
|
|
1463
|
+
return;
|
|
1464
|
+
}
|
|
1465
|
+
this.newObjectError = '';
|
|
1466
|
+
this.pendingWrite = { statements: 1, source: 'create' };
|
|
1467
|
+
return;
|
|
1468
|
+
}
|
|
1469
|
+
if (this.newObjectKind === 'table' && !this.newColumns.some(column => column.primary)) {
|
|
1470
|
+
this.newObjectError = 'Mark at least one primary-key column so Studio can edit rows.';
|
|
1471
|
+
return;
|
|
1472
|
+
}
|
|
1473
|
+
if (this.schema.objects.some(object => object.name.toLowerCase() === this.newObjectName.trim().toLowerCase())) {
|
|
1474
|
+
this.newObjectError = `${this.newObjectName.trim()} already exists.`;
|
|
1475
|
+
return;
|
|
1476
|
+
}
|
|
1477
|
+
this.newObjectError = '';
|
|
1478
|
+
this.pendingWrite = { statements: 1, source: 'create' };
|
|
1479
|
+
}
|
|
1480
|
+
|
|
1481
|
+
@Client()
|
|
1482
|
+
async createObject() {
|
|
1483
|
+
const id = this.activeConnection;
|
|
1484
|
+
const name = this.newObjectName.trim();
|
|
1485
|
+
let sql: string;
|
|
1486
|
+
try { sql = createObjectSql(name, this.newObjectKind, this.newColumns, this.newEdgeDraft(), this.newSpatialDraft()); }
|
|
1487
|
+
catch (error) { this.newObjectError = errorText(error); return; }
|
|
1488
|
+
this.creatingObject = true;
|
|
1489
|
+
this.writing = true;
|
|
1490
|
+
const operation = crypto.randomUUID();
|
|
1491
|
+
try {
|
|
1492
|
+
const reply = await this.executeSql(id, operation, { statements: [{ sql, parameters: '{}' }], mode: 'write' });
|
|
1493
|
+
await this.acknowledgeReply(id, reply);
|
|
1494
|
+
try { await this.refreshRecoveries(); } catch {}
|
|
1495
|
+
if (reply.run.error) {
|
|
1496
|
+
if (reply.run.error.outcome === 'unknown' || this.pendingRecoveries(id).length) this.uncertainWrites = { ...this.uncertainWrites, [id]: operation };
|
|
1497
|
+
this.newObjectError = `${reply.run.error.code}: ${reply.run.error.message}`;
|
|
1498
|
+
return;
|
|
1499
|
+
}
|
|
1500
|
+
this.recordQuery(sql, reply.run, 'sql');
|
|
1501
|
+
this.newObjectOpen = false;
|
|
1502
|
+
this.newObjectName = '';
|
|
1503
|
+
this.newColumns = [{ name: 'id', type: 'INTEGER', primary: true, required: true, unique: false }];
|
|
1504
|
+
await this.reloadSchema();
|
|
1505
|
+
if (this.newObjectKind === 'spatial') {
|
|
1506
|
+
const table = this.newSpatialTable;
|
|
1507
|
+
await this.chooseObject(table);
|
|
1508
|
+
await this.switchTab('structure');
|
|
1509
|
+
this.showMessage(`Created spatial index ${name} on ${table}.`);
|
|
1510
|
+
return;
|
|
1511
|
+
}
|
|
1512
|
+
await this.chooseObject(name);
|
|
1513
|
+
this.showMessage(`Created ${this.newObjectKind === 'edge' ? 'edge table' : this.newObjectKind} ${name}.`);
|
|
1514
|
+
} catch {
|
|
1515
|
+
this.uncertainWrites = { ...this.uncertainWrites, [id]: operation };
|
|
1516
|
+
this.newObjectError = 'Studio did not receive a reply. Recover the saved request before trying again.';
|
|
1517
|
+
} finally {
|
|
1518
|
+
this.creatingObject = false;
|
|
1519
|
+
this.writing = false;
|
|
1520
|
+
}
|
|
1521
|
+
}
|
|
1522
|
+
|
|
1523
|
+
// ---------------------------------------------------------------------------
|
|
1524
|
+
// Rendering. A page places these parts in its own layout.
|
|
1525
|
+
|
|
1526
|
+
/** The search box, the New object button and the list of tables, collections and views. */
|
|
1527
|
+
@Shared()
|
|
1528
|
+
renderObjectList(lead: unknown = '') {
|
|
1529
|
+
const objects = this.visibleObjects();
|
|
1530
|
+
const connection = this.schema.connection;
|
|
1531
|
+
return html`
|
|
1532
|
+
<div class="space-y-2 border-b p-3">
|
|
1533
|
+
${lead}
|
|
1534
|
+
<div class="flex items-center gap-1">
|
|
1535
|
+
${component(InputGroup, {
|
|
1536
|
+
class: 'min-w-0 flex-1',
|
|
1537
|
+
placeholder: 'Search tables and collections…',
|
|
1538
|
+
role: 'combobox',
|
|
1539
|
+
'aria-expanded': Boolean(objects.length),
|
|
1540
|
+
'aria-controls': 'studio-object-list',
|
|
1541
|
+
'aria-activedescendant': this.searchIndex >= 0 ? `studio-object-${this.searchIndex}` : undefined,
|
|
1542
|
+
'data-testid': 'object-search',
|
|
1543
|
+
disabled: !connection,
|
|
1544
|
+
'.value': this.search,
|
|
1545
|
+
'@input': (event: InputEvent) => this.onSearchInput((event.target as HTMLInputElement).value),
|
|
1546
|
+
'@keydown': this.onSearchKeydown,
|
|
1547
|
+
})}
|
|
1548
|
+
${this.readOnly() ? '' : iconButton('studio-new-object-tip', AddSquareIcon, 'Create table or collection', this.openNewObject, {
|
|
1549
|
+
'data-testid': 'new-object',
|
|
1550
|
+
disabled: !connection,
|
|
1551
|
+
})}
|
|
1552
|
+
</div>
|
|
1553
|
+
</div>
|
|
1554
|
+
<nav id="studio-object-list" class="min-h-0 flex-1 overflow-y-auto p-2" aria-label="Database objects" role="listbox">
|
|
1555
|
+
${repeat(objects, candidate => candidate.name, (candidate, index) => {
|
|
1556
|
+
const selected = candidate.name === this.selected;
|
|
1557
|
+
const highlighted = index === this.searchIndex && Boolean(this.search);
|
|
1558
|
+
return html`
|
|
1559
|
+
<button
|
|
1560
|
+
id="studio-object-${index}"
|
|
1561
|
+
role="option"
|
|
1562
|
+
aria-selected="${selected}"
|
|
1563
|
+
class="flex w-full items-center gap-2.5 rounded-md px-3 py-2 text-left text-sm hover:bg-sidebar-accent ${selected || highlighted ? 'bg-sidebar-accent font-medium' : ''}"
|
|
1564
|
+
data-testid="object-${candidate.name}"
|
|
1565
|
+
title="${objectLabel(candidate)}: ${candidate.name}"
|
|
1566
|
+
@mousemove="${() => { if (this.search) this.searchIndex = index; }}"
|
|
1567
|
+
@click="${() => this.chooseObject(candidate.name)}"
|
|
1568
|
+
>
|
|
1569
|
+
<span class="shrink-0 ${selected ? candidate.kind === 'view' ? 'text-chart-2' : 'text-primary' : 'text-muted-foreground'}">
|
|
1570
|
+
${component(Icon, {
|
|
1571
|
+
entry: objectIcon(candidate),
|
|
1572
|
+
variant: selected ? 'bold' : candidate.kind === 'view' ? 'line' : 'duotone',
|
|
1573
|
+
size: 16,
|
|
1574
|
+
})}
|
|
1575
|
+
</span>
|
|
1576
|
+
<span class="truncate">${candidate.name}</span>
|
|
1577
|
+
${candidate.edge ? html`<span class="ml-auto shrink-0 truncate text-[11px] text-muted-foreground" title="${candidate.edge.source} → ${candidate.edge.target}">${candidate.edge.source} → ${candidate.edge.target}</span>` : ''}
|
|
1578
|
+
</button>
|
|
1579
|
+
`;
|
|
1580
|
+
})}
|
|
1581
|
+
${connection && !this.schemaLoading && !this.schema.objects.length ? html`
|
|
1582
|
+
<div class="p-3 text-sm text-muted-foreground">
|
|
1583
|
+
This database is empty.
|
|
1584
|
+
${this.readOnly() ? '' : html`<button type="button" class="mt-2 block text-primary hover:underline" @click="${this.openNewObject}">Create a table or collection</button>`}
|
|
1585
|
+
</div>
|
|
1586
|
+
` : ''}
|
|
1587
|
+
${!connection ? html`<p class="p-3 text-sm text-muted-foreground">${this.noDatabaseText()}</p>` : ''}
|
|
1588
|
+
</nav>
|
|
1589
|
+
`;
|
|
1590
|
+
}
|
|
1591
|
+
|
|
1592
|
+
/** The confirmations for a delete and for a write from the console. */
|
|
1593
|
+
@Shared()
|
|
1594
|
+
renderDialogs() {
|
|
1595
|
+
return html`
|
|
1596
|
+
${component(AlertDialog, {
|
|
1597
|
+
id: 'studio-delete-dialog',
|
|
1598
|
+
open: Boolean(this.deleteTarget),
|
|
1599
|
+
title: `Delete ${this.deleteTarget?.rowIndexes.length ?? 0} selected row${this.deleteTarget?.rowIndexes.length === 1 ? '' : 's'}?`,
|
|
1600
|
+
description: `This runs immediately against ${this.deleteTarget?.table ?? 'the table'} as one atomic write and cannot be undone.`,
|
|
1601
|
+
cancelLabel: 'Cancel',
|
|
1602
|
+
actionLabel: this.writing ? 'Deleting…' : 'Delete',
|
|
1603
|
+
actionDisabled: this.writing,
|
|
1604
|
+
onOpenChange: () => { this.deleteTarget = null; },
|
|
1605
|
+
onAction: this.confirmDelete,
|
|
1606
|
+
'data-testid': 'delete-dialog',
|
|
1607
|
+
})}
|
|
1608
|
+
${component(AlertDialog, {
|
|
1609
|
+
id: 'studio-write-dialog',
|
|
1610
|
+
open: Boolean(this.pendingWrite),
|
|
1611
|
+
title: this.pendingWrite?.source === 'create'
|
|
1612
|
+
? `Create ${this.newObjectKind === 'spatial' ? 'spatial index' : this.newObjectKind === 'edge' ? 'edge table' : this.newObjectKind} ${this.newObjectName.trim()}?`
|
|
1613
|
+
: `Run ${this.pendingWrite?.statements ?? 0} statement${this.pendingWrite?.statements === 1 ? '' : 's'} as an atomic write?`,
|
|
1614
|
+
description: `${this.pendingWrite?.source === 'create' ? 'The new object is created' : 'All statements succeed or none apply. The change is applied'} immediately to ${this.workspaceName()}${this.schema.connection?.remote ? ', a remote database' : ''}.`,
|
|
1615
|
+
cancelLabel: 'Cancel',
|
|
1616
|
+
actionLabel: 'Run write',
|
|
1617
|
+
onOpenChange: () => { this.pendingWrite = null; },
|
|
1618
|
+
onAction: this.confirmPendingWrite,
|
|
1619
|
+
'data-testid': 'write-dialog',
|
|
1620
|
+
})}
|
|
1621
|
+
`;
|
|
1622
|
+
}
|
|
1623
|
+
|
|
1624
|
+
@Shared()
|
|
1625
|
+
renderWorkspace(object: StudioObject | undefined, recoveryCount: number) {
|
|
1626
|
+
const tabs = this.workspaceTabs();
|
|
1627
|
+
return html`
|
|
1628
|
+
<div class="flex h-12 shrink-0 items-center justify-between border-b px-4">
|
|
1629
|
+
<div class="flex items-center gap-1" role="tablist" aria-label="Workspace">
|
|
1630
|
+
${([
|
|
1631
|
+
['browse', DatabaseIcon, 'Browse'],
|
|
1632
|
+
['structure', StructureIcon, 'Structure'],
|
|
1633
|
+
['sql', CodeSquareIcon, 'Console'],
|
|
1634
|
+
['graph', ShareCircleIcon, 'Graph'],
|
|
1635
|
+
['map', MapIcon, 'Map'],
|
|
1636
|
+
['database', SettingsMinimalisticIcon, 'Database'],
|
|
1637
|
+
] as const).filter(([item]) => tabs.includes(item)).map(([item, icon, label]) => component(Button, {
|
|
1638
|
+
variant: this.tab === item ? 'secondary' : 'ghost',
|
|
1639
|
+
size: 'sm',
|
|
1640
|
+
class: 'gap-2',
|
|
1641
|
+
role: 'tab',
|
|
1642
|
+
'aria-selected': this.tab === item,
|
|
1643
|
+
'data-testid': `tab-${item}`,
|
|
1644
|
+
'@click': () => this.switchTab(item),
|
|
1645
|
+
}, html`${component(Icon, { entry: icon, size: 16 })}<span>${label}</span>`))}
|
|
1646
|
+
</div>
|
|
1647
|
+
<div class="flex items-center gap-1">
|
|
1648
|
+
${this.tab === 'browse' && object
|
|
1649
|
+
? iconButton('studio-refresh-rows-tip', RefreshIcon, 'Refresh rows', () => this.reloadRows(), { disabled: this.browseLoading, 'data-testid': 'refresh-rows' })
|
|
1650
|
+
: iconButton('studio-refresh-schema-tip', RefreshIcon, 'Refresh schema', this.refreshAll, { disabled: this.schemaLoading, 'data-testid': 'refresh-schema' })}
|
|
1651
|
+
${this.tab === 'browse' && object?.editable && !this.customBrowseQuery
|
|
1652
|
+
? iconButton('studio-insert-row-tip', AddSquareIcon, this.showInsert ? 'Close insert form' : object.model === 'document' ? 'Insert document' : 'Insert row', this.toggleInsert, {
|
|
1653
|
+
'data-testid': 'insert-row',
|
|
1654
|
+
variant: this.showInsert ? 'secondary' : 'ghost',
|
|
1655
|
+
disabled: this.writesBlocked,
|
|
1656
|
+
})
|
|
1657
|
+
: ''}
|
|
1658
|
+
</div>
|
|
1659
|
+
</div>
|
|
1660
|
+
|
|
1661
|
+
${this.writesBlocked ? html`
|
|
1662
|
+
<div class="flex shrink-0 flex-wrap items-center gap-3 border-b bg-destructive/10 px-4 py-2 text-sm text-destructive" role="alert" data-testid="recovery-banner">
|
|
1663
|
+
${component(Icon, { entry: DangerTriangleIcon, size: 17 })}
|
|
1664
|
+
<span class="min-w-0 flex-1">
|
|
1665
|
+
${recoveryCount
|
|
1666
|
+
? `${recoveryCount} saved write${recoveryCount === 1 ? ' has' : 's have'} an unknown outcome. Recover before making more changes; Studio resends the exact request and never applies it twice.`
|
|
1667
|
+
: 'The last write did not get a reply. Check its outcome before making more changes.'}
|
|
1668
|
+
</span>
|
|
1669
|
+
${component(Button, { size: 'sm', variant: 'outline', disabled: this.recovering, 'data-testid': 'recover-write', '@click': this.recoverPendingWrite },
|
|
1670
|
+
this.recovering ? 'Recovering…' : recoveryCount ? 'Recover write' : 'Check outcome')}
|
|
1671
|
+
</div>
|
|
1672
|
+
` : ''}
|
|
1673
|
+
|
|
1674
|
+
${this.message ? html`
|
|
1675
|
+
<div class="${this.messageError ? 'bg-destructive/10 text-destructive' : 'bg-muted/60 text-muted-foreground'} flex shrink-0 items-center gap-2 border-b px-4 py-2 text-sm" role="status" data-testid="status-message">
|
|
1676
|
+
${this.messageError ? '' : html`
|
|
1677
|
+
<span class="shrink-0 text-emerald-600 dark:text-emerald-400" aria-hidden="true">${component(Icon, { entry: CheckCircleIcon, size: 17 })}</span>
|
|
1678
|
+
`}
|
|
1679
|
+
<span class="min-w-0 flex-1">${this.message}</span>
|
|
1680
|
+
<button type="button" class="shrink-0 text-xs opacity-70 hover:opacity-100" aria-label="Dismiss message" @click="${() => { this.message = ''; }}">✕</button>
|
|
1681
|
+
</div>
|
|
1682
|
+
` : ''}
|
|
1683
|
+
|
|
1684
|
+
<div class="studio-tab-panel flex min-h-0 flex-1 flex-col">
|
|
1685
|
+
${component(BrowseTab, {
|
|
1686
|
+
object,
|
|
1687
|
+
active: this.tab === 'browse',
|
|
1688
|
+
schema: this.schema,
|
|
1689
|
+
result: this.browseResult,
|
|
1690
|
+
loadedObject: this.loadedObject,
|
|
1691
|
+
page: this.page,
|
|
1692
|
+
pageSize: this.pageSize,
|
|
1693
|
+
selectedRows: this.selectedRows,
|
|
1694
|
+
customQuery: this.customBrowseQuery,
|
|
1695
|
+
query: this.browseQuery,
|
|
1696
|
+
loading: this.browseLoading,
|
|
1697
|
+
loadFailed: this.browseLoadFailed,
|
|
1698
|
+
showFilter: this.showFilter,
|
|
1699
|
+
filters: this.filters,
|
|
1700
|
+
sort: this.sort,
|
|
1701
|
+
filterColumn: this.filterColumn,
|
|
1702
|
+
filterOperator: this.filterOperator,
|
|
1703
|
+
filterValue: this.filterValue,
|
|
1704
|
+
filterType: this.filterType,
|
|
1705
|
+
theme: this.theme,
|
|
1706
|
+
inlineEditor: this.inlineEditor,
|
|
1707
|
+
writesBlocked: this.writesBlocked,
|
|
1708
|
+
onToggleFilter: () => { this.showFilter = !this.showFilter; },
|
|
1709
|
+
onRemoveFilter: this.removeFilter,
|
|
1710
|
+
onRunQuery: this.runBrowseQuery,
|
|
1711
|
+
onFilterColumnChange: (column: string) => { this.filterColumn = column; },
|
|
1712
|
+
onFilterOperatorChange: (operator: BrowseFilterOperator) => { this.filterOperator = operator; },
|
|
1713
|
+
onFilterValueChange: (value: string) => { this.filterValue = value; },
|
|
1714
|
+
onFilterTypeChange: (type: FilterValueType) => { this.filterType = type; },
|
|
1715
|
+
onApplyFilter: this.applyFilter,
|
|
1716
|
+
onQueryChange: this.setBrowseQuery,
|
|
1717
|
+
onDeleteSelected: this.requestDeleteSelected,
|
|
1718
|
+
onBatchUpdate: this.openBatchUpdate,
|
|
1719
|
+
onExport: this.openExport,
|
|
1720
|
+
onClearSelection: () => { this.selectedRows = []; },
|
|
1721
|
+
onToggleAllRows: this.toggleAllRows,
|
|
1722
|
+
onToggleSort: this.toggleSort,
|
|
1723
|
+
onToggleRow: this.toggleRowSelection,
|
|
1724
|
+
onBeginCellEdit: this.beginCellEdit,
|
|
1725
|
+
onInlineValueChange: this.updateInlineValue,
|
|
1726
|
+
onInlineKeydown: this.onInlineKeydown,
|
|
1727
|
+
onSaveInlineEditor: this.saveInlineEditor,
|
|
1728
|
+
onInlineModeChange: this.setInlineMode,
|
|
1729
|
+
onFollowForeignKey: this.followForeignKey,
|
|
1730
|
+
onFollowRecord: this.followRecord,
|
|
1731
|
+
onEditRow: this.openRowEditor,
|
|
1732
|
+
onDeleteRow: this.requestDelete,
|
|
1733
|
+
onPageSizeChange: this.changePageSize,
|
|
1734
|
+
onPageChange: this.changePage,
|
|
1735
|
+
})}
|
|
1736
|
+
${component(StructureTab, {
|
|
1737
|
+
object,
|
|
1738
|
+
active: this.tab === 'structure',
|
|
1739
|
+
theme: this.theme,
|
|
1740
|
+
schema: this.schema,
|
|
1741
|
+
onOpenTable: (name: string) => {
|
|
1742
|
+
const target = this.schema.objects.find(candidate => candidate.name.toLowerCase() === name.toLowerCase());
|
|
1743
|
+
if (target) void this.chooseObject(target.name);
|
|
1744
|
+
},
|
|
1745
|
+
onOpenMap: (index: string) => this.openMap(index),
|
|
1746
|
+
onOpenGraph: (edge: string) => {
|
|
1747
|
+
this.graphEdge = edge;
|
|
1748
|
+
this.graphView = null;
|
|
1749
|
+
void this.switchTab('graph');
|
|
1750
|
+
},
|
|
1751
|
+
})}
|
|
1752
|
+
${component(SqlConsole, {
|
|
1753
|
+
active: this.tab === 'sql',
|
|
1754
|
+
sql: this.sql,
|
|
1755
|
+
theme: this.theme,
|
|
1756
|
+
schema: this.schema,
|
|
1757
|
+
output: this.sqlOutput,
|
|
1758
|
+
run: this.sqlRun,
|
|
1759
|
+
explainRun: this.explainRun,
|
|
1760
|
+
resultIndex: this.resultIndex,
|
|
1761
|
+
running: this.sqlRunning,
|
|
1762
|
+
explaining: this.sqlExplaining,
|
|
1763
|
+
showOptions: this.showSqlOptions,
|
|
1764
|
+
parameters: this.sqlParameters,
|
|
1765
|
+
revision: this.sqlRevision,
|
|
1766
|
+
showRevision: this.showsRevision(),
|
|
1767
|
+
rowsRead: this.rowsReadBudget,
|
|
1768
|
+
vmSteps: this.vmStepBudget,
|
|
1769
|
+
onSqlChange: this.setSql,
|
|
1770
|
+
onRun: this.runSqlFromEditor,
|
|
1771
|
+
onExplain: this.runExplainFromEditor,
|
|
1772
|
+
onCancel: this.cancelSql,
|
|
1773
|
+
onOpenHistory: () => { this.historyOpen = true; },
|
|
1774
|
+
onToggleOptions: () => { this.showSqlOptions = !this.showSqlOptions; },
|
|
1775
|
+
onOptionChange: this.setSqlOption,
|
|
1776
|
+
onOutputChange: (output: SqlOutput) => { this.sqlOutput = output; this.resultIndex = 0; },
|
|
1777
|
+
onResultIndexChange: (index: number) => { this.resultIndex = index; this.sqlMapSelected = ''; },
|
|
1778
|
+
mapSelected: this.sqlMapSelected,
|
|
1779
|
+
onSelectMapFeature: (feature: MapFeature) => { this.sqlMapSelected = feature.key; },
|
|
1780
|
+
onOpenRecord: (record: PortableValue) => this.followRecord(record),
|
|
1781
|
+
})}
|
|
1782
|
+
${component(GraphTab, {
|
|
1783
|
+
active: this.tab === 'graph',
|
|
1784
|
+
schema: this.schema,
|
|
1785
|
+
root: this.graphRoot,
|
|
1786
|
+
edge: this.graphEdgeTable(),
|
|
1787
|
+
direction: this.graphDirection,
|
|
1788
|
+
depth: this.graphDepth,
|
|
1789
|
+
view: this.graphView,
|
|
1790
|
+
loading: this.graphLoading,
|
|
1791
|
+
onRootChange: (root: string) => { this.graphRoot = root; },
|
|
1792
|
+
onEdgeChange: (edge: string) => { this.graphEdge = edge; },
|
|
1793
|
+
onDirectionChange: (direction: GraphDirection) => { this.graphDirection = direction; },
|
|
1794
|
+
onDepthChange: (depth: number) => { this.graphDepth = depth; },
|
|
1795
|
+
onExplore: () => this.runGraph(),
|
|
1796
|
+
onSelectNode: (node: GraphNode) => this.exploreFrom(node),
|
|
1797
|
+
onOpenSql: this.openGraphInSql,
|
|
1798
|
+
})}
|
|
1799
|
+
${component(MapTab, {
|
|
1800
|
+
active: this.tab === 'map',
|
|
1801
|
+
schema: this.schema,
|
|
1802
|
+
index: this.mapIndexName(),
|
|
1803
|
+
box: this.mapBox,
|
|
1804
|
+
limit: this.mapLimit,
|
|
1805
|
+
view: this.mapView,
|
|
1806
|
+
selected: this.mapSelected,
|
|
1807
|
+
loading: this.mapLoading,
|
|
1808
|
+
onIndexChange: (index: string) => { this.mapIndex = index; },
|
|
1809
|
+
onBoxChange: (field: MapBoxField, value: string) => { this.mapBox = { ...this.mapBox, [field]: value }; },
|
|
1810
|
+
onLimitChange: (limit: number) => { this.mapLimit = limit; },
|
|
1811
|
+
onLoad: () => this.runMap(),
|
|
1812
|
+
onSelectArea: (bbox: [number, number, number, number]) => this.searchMapArea(bbox),
|
|
1813
|
+
onSelectFeature: (feature: MapFeature) => { this.mapSelected = feature.key; },
|
|
1814
|
+
onOpenRecord: (record: PortableValue) => this.followRecord(record),
|
|
1815
|
+
onOpenSql: this.openMapInSql,
|
|
1816
|
+
})}
|
|
1817
|
+
${component(DatabaseTab, { schema: this.schema, active: this.tab === 'database',
|
|
1818
|
+
restorePoints: this.restorePointsFor === this.activeConnection ? this.restorePoints : null,
|
|
1819
|
+
restorePointsError: this.restorePointsFor === this.activeConnection ? this.restorePointsError : '',
|
|
1820
|
+
restorePointsBusy: this.restorePointsBusy,
|
|
1821
|
+
onLoadRestorePoints: this.loadCloudRestorePoints, onRestorePoint: this.restoreCloudPoint })}
|
|
1822
|
+
</div>
|
|
1823
|
+
`;
|
|
1824
|
+
}
|
|
1825
|
+
|
|
1826
|
+
@Shared()
|
|
1827
|
+
renderSheets(object: StudioObject | undefined) {
|
|
1828
|
+
return html`
|
|
1829
|
+
${component(InsertRowSheet, {
|
|
1830
|
+
object,
|
|
1831
|
+
open: this.showInsert,
|
|
1832
|
+
fields: this.insertFields,
|
|
1833
|
+
document: this.insertDocument,
|
|
1834
|
+
error: this.insertError,
|
|
1835
|
+
theme: this.theme,
|
|
1836
|
+
inserting: this.writing,
|
|
1837
|
+
onClose: () => { this.showInsert = false; },
|
|
1838
|
+
onValueChange: this.setInsertValue,
|
|
1839
|
+
onSelectionChange: this.setInsertSelection,
|
|
1840
|
+
onRegenerateValue: this.regenerateInsertValue,
|
|
1841
|
+
onDocumentChange: (value: string) => { this.insertDocument = value; this.insertError = ''; },
|
|
1842
|
+
onSubmit: this.submitInsert,
|
|
1843
|
+
})}
|
|
1844
|
+
${component(QueryHistorySheet, {
|
|
1845
|
+
open: this.historyOpen,
|
|
1846
|
+
connectionLabel: this.workspaceName(),
|
|
1847
|
+
history: this.queryHistory,
|
|
1848
|
+
onClose: () => { this.historyOpen = false; },
|
|
1849
|
+
onClear: this.clearQueryHistory,
|
|
1850
|
+
onToggleFavorite: this.toggleQueryFavorite,
|
|
1851
|
+
onLoad: this.loadHistoryQuery,
|
|
1852
|
+
onRun: this.runHistoryQuery,
|
|
1853
|
+
})}
|
|
1854
|
+
${component(CellEditorSheet, {
|
|
1855
|
+
object,
|
|
1856
|
+
editor: this.sheetEditor,
|
|
1857
|
+
theme: this.theme,
|
|
1858
|
+
saving: this.writing,
|
|
1859
|
+
onClose: () => { this.sheetEditor = null; },
|
|
1860
|
+
onSelectionChange: this.setSheetSelection,
|
|
1861
|
+
onValueChange: this.updateSheetValue,
|
|
1862
|
+
onSave: this.saveSheetEditor,
|
|
1863
|
+
})}
|
|
1864
|
+
${component(RowEditorSheet, {
|
|
1865
|
+
object,
|
|
1866
|
+
editor: this.rowEditor,
|
|
1867
|
+
theme: this.theme,
|
|
1868
|
+
saving: this.writing,
|
|
1869
|
+
onClose: () => { this.rowEditor = null; },
|
|
1870
|
+
onChange: this.setRowEditorValue,
|
|
1871
|
+
onSave: this.saveRowEditor,
|
|
1872
|
+
})}
|
|
1873
|
+
${component(ExportSheet, {
|
|
1874
|
+
object,
|
|
1875
|
+
state: this.exportSheet,
|
|
1876
|
+
browseColumns: this.gridColumns(),
|
|
1877
|
+
onClose: () => { this.exportSheet = null; },
|
|
1878
|
+
onFormatChange: (format: ExportFormat) => { if (this.exportSheet) this.exportSheet = { ...this.exportSheet, format }; },
|
|
1879
|
+
onToggleColumn: this.toggleExportColumn,
|
|
1880
|
+
onDownload: this.downloadExport,
|
|
1881
|
+
})}
|
|
1882
|
+
${component(BatchUpdateSheet, {
|
|
1883
|
+
object,
|
|
1884
|
+
state: this.batchUpdate,
|
|
1885
|
+
selectedCount: this.selectedRows.length,
|
|
1886
|
+
saving: this.writing,
|
|
1887
|
+
theme: this.theme,
|
|
1888
|
+
onClose: () => { this.batchUpdate = null; },
|
|
1889
|
+
onColumnChange: this.setBatchColumn,
|
|
1890
|
+
onSelectionChange: this.setBatchSelection,
|
|
1891
|
+
onValueChange: (value: string) => { if (this.batchUpdate) this.batchUpdate = { ...this.batchUpdate, value, mode: 'value', error: '' }; },
|
|
1892
|
+
onSubmit: this.submitBatchUpdate,
|
|
1893
|
+
})}
|
|
1894
|
+
${component(NewObjectSheet, {
|
|
1895
|
+
open: this.newObjectOpen,
|
|
1896
|
+
name: this.newObjectName,
|
|
1897
|
+
kind: this.newObjectKind,
|
|
1898
|
+
columns: this.newColumns,
|
|
1899
|
+
collections: this.schema.objects.filter(object => object.model === 'document' && !object.edge).map(object => object.name),
|
|
1900
|
+
edgeSource: this.newEdgeSource,
|
|
1901
|
+
edgeTarget: this.newEdgeTarget,
|
|
1902
|
+
edgeCascade: this.newEdgeCascade,
|
|
1903
|
+
onEdgeChange: (source: string, target: string, cascade: boolean) => { this.newEdgeSource = source; this.newEdgeTarget = target; this.newEdgeCascade = cascade; this.newObjectError = ''; },
|
|
1904
|
+
spatialTable: this.newSpatialTable,
|
|
1905
|
+
spatialField: this.newSpatialField,
|
|
1906
|
+
spatialRegion: this.newSpatialRegion,
|
|
1907
|
+
onSpatialChange: (table: string, field: string, region: boolean) => { this.newSpatialTable = table; this.newSpatialField = field; this.newSpatialRegion = region; this.newObjectError = ''; },
|
|
1908
|
+
sql: this.newObjectSql(),
|
|
1909
|
+
error: this.newObjectError,
|
|
1910
|
+
theme: this.theme,
|
|
1911
|
+
creating: this.creatingObject,
|
|
1912
|
+
writesBlocked: this.writesBlocked,
|
|
1913
|
+
onClose: () => { this.newObjectOpen = false; },
|
|
1914
|
+
onNameChange: (name: string) => { this.newObjectName = name; this.newObjectError = ''; },
|
|
1915
|
+
onKindChange: (kind: NewObjectKind) => {
|
|
1916
|
+
this.newObjectKind = kind;
|
|
1917
|
+
this.newObjectError = '';
|
|
1918
|
+
if (kind === 'spatial' && !this.newSpatialTable && this.activeObject?.model === 'document') this.newSpatialTable = this.activeObject.name;
|
|
1919
|
+
},
|
|
1920
|
+
onColumnChange: (index: number, column: NewColumnDraft) => { this.newColumns = this.newColumns.map((candidate, position) => position === index ? column : candidate); this.newObjectError = ''; },
|
|
1921
|
+
onAddColumn: () => { this.newColumns = [...this.newColumns, { name: `column_${this.newColumns.length + 1}`, type: 'TEXT', primary: false, required: false, unique: false }]; },
|
|
1922
|
+
onRemoveColumn: (index: number) => { this.newColumns = this.newColumns.filter((_, position) => position !== index); },
|
|
1923
|
+
onOpenInSql: this.openNewObjectInSql,
|
|
1924
|
+
onCreate: this.requestCreateObject,
|
|
1925
|
+
})}
|
|
1926
|
+
`;
|
|
1927
|
+
}
|
|
1928
|
+
}
|
|
1929
|
+
|
|
1930
|
+
/** Random record key that needs no quoting in RomeQL. */
|
|
1931
|
+
function newDocumentKey(): string {
|
|
1932
|
+
const alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789';
|
|
1933
|
+
const bytes = crypto.getRandomValues(new Uint8Array(15));
|
|
1934
|
+
return `d${Array.from(bytes, byte => alphabet[byte % alphabet.length]).join('')}`;
|
|
1935
|
+
}
|
|
1936
|
+
|
|
1937
|
+
export function objectIcon(object: StudioObject) {
|
|
1938
|
+
return object.kind === 'view' ? EyeIcon : object.edge ? ShareCircleIcon : object.model === 'document' ? DocumentsIcon : DatabaseIcon;
|
|
1939
|
+
}
|
|
1940
|
+
|
|
1941
|
+
export function objectLabel(object: StudioObject): string {
|
|
1942
|
+
return object.kind === 'view' ? 'View' : object.edge ? 'Edge table' : object.model === 'document' ? 'Collection' : 'Table';
|
|
1943
|
+
}
|
|
1944
|
+
|
|
1945
|
+
export function errorText(error: unknown): string {
|
|
1946
|
+
return error instanceof Error ? error.message : String(error);
|
|
1947
|
+
}
|
|
1948
|
+
|
|
1949
|
+
function writeError(error: { code: string; message: string; outcome: string; sequence?: number }): string {
|
|
1950
|
+
if (error.code === 'RDB_CONFLICT') {
|
|
1951
|
+
return 'This data changed after it was loaded, so the write was not applied. Refresh the rows and try again.';
|
|
1952
|
+
}
|
|
1953
|
+
const outcome = error.outcome === 'rolled-back' ? 'Nothing was changed.' : error.outcome === 'not-sent' ? 'The request was not sent.' : error.outcome === 'unknown' ? 'The outcome is unknown; recover the saved request.' : '';
|
|
1954
|
+
return `${error.message} ${outcome}`.trim();
|
|
1955
|
+
}
|
|
1956
|
+
|
|
1957
|
+
/** Keeps the current text when switching kinds if it still makes sense. */
|
|
1958
|
+
function convertText(text: string, from: ValueKind, to: ValueKind): string {
|
|
1959
|
+
if (from === to) return text;
|
|
1960
|
+
if (to === 'json') {
|
|
1961
|
+
try { return JSON.stringify(toJson(kindValue(from, text)), null, 2); } catch { return text ? JSON.stringify(text) : ''; }
|
|
1962
|
+
}
|
|
1963
|
+
if (from === 'json') {
|
|
1964
|
+
try {
|
|
1965
|
+
const parsed: unknown = JSON.parse(text);
|
|
1966
|
+
return typeof parsed === 'string' || typeof parsed === 'number' || typeof parsed === 'boolean' ? String(parsed) : '';
|
|
1967
|
+
} catch { return ''; }
|
|
1968
|
+
}
|
|
1969
|
+
return ['uuid-v4', 'uuid-v7', 'timestamp'].includes(to) ? '' : text;
|
|
1970
|
+
}
|
|
1971
|
+
|
|
1972
|
+
/** Sets a dotted path inside a document, creating nested objects as needed. */
|
|
1973
|
+
function setPath(target: Record<string, PortableValue>, path: string, value: PortableValue) {
|
|
1974
|
+
const parts = path.split('.');
|
|
1975
|
+
const last = parts.pop()!;
|
|
1976
|
+
let current = target;
|
|
1977
|
+
for (const part of parts) {
|
|
1978
|
+
const next = current[part];
|
|
1979
|
+
const object: Extract<PortableValue, { type: 'Object' }> = next?.type === 'Object' ? { type: 'Object', value: { ...next.value } } : { type: 'Object', value: {} };
|
|
1980
|
+
current[part] = object;
|
|
1981
|
+
current = object.value;
|
|
1982
|
+
}
|
|
1983
|
+
current[last] = value;
|
|
1984
|
+
}
|