@rebasepro/studio 0.17.3 → 0.18.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 +0 -1
- package/README.md +12 -4
- package/dist/{ApiKeysView-DiCurTEU.js → ApiKeysView-EIvegrUk.js} +54 -39
- package/dist/ApiKeysView-EIvegrUk.js.map +1 -0
- package/dist/{BackupsView-DNS6LdVg.js → BackupsView-DVkKzaPR.js} +29 -31
- package/dist/BackupsView-DVkKzaPR.js.map +1 -0
- package/dist/{BranchesView-CM3B-ER3.js → BranchesView-Df8hQ8wE.js} +85 -24
- package/dist/BranchesView-Df8hQ8wE.js.map +1 -0
- package/dist/{CronJobsView-BHtJZeJZ.js → CronJobsView-CLOGjb-L.js} +32 -27
- package/dist/CronJobsView-CLOGjb-L.js.map +1 -0
- package/dist/{RLSEditor-CBX4uD66.js → RLSEditor-Sa1D34ny.js} +724 -615
- package/dist/RLSEditor-Sa1D34ny.js.map +1 -0
- package/dist/{SQLEditor-ByecwX8B.js → SQLEditor-BfNA8xM3.js} +9 -4
- package/dist/{SQLEditor-ByecwX8B.js.map → SQLEditor-BfNA8xM3.js.map} +1 -1
- package/dist/{SchemaVisualizer-D6tMZgeC.js → SchemaVisualizer-DTDMYL6o.js} +84 -110
- package/dist/SchemaVisualizer-DTDMYL6o.js.map +1 -0
- package/dist/{StorageView-BGDeC5GI.js → StorageView-Ed9Q_VlB.js} +5 -32
- package/dist/StorageView-Ed9Q_VlB.js.map +1 -0
- package/dist/components/RLSEditor/saveRules.d.ts +38 -0
- package/dist/components/RebaseStudio.d.ts +1 -1
- package/dist/components/SchemaVisualizer/schema-visualizer.utils.d.ts +5 -2
- package/dist/components/SchemaVisualizer/useSchemaGraph.d.ts +0 -4
- package/dist/components/load-failure-view.d.ts +17 -0
- package/dist/components/load-failure.d.ts +47 -0
- package/dist/index.es.js +56 -36
- package/dist/index.es.js.map +1 -1
- package/dist/load-failure-C6OMJSGC.js +31 -0
- package/dist/load-failure-C6OMJSGC.js.map +1 -0
- package/dist/load-failure-view-CBTB_h-h.js +48 -0
- package/dist/load-failure-view-CBTB_h-h.js.map +1 -0
- package/package.json +36 -21
- package/dist/ApiKeysView-DiCurTEU.js.map +0 -1
- package/dist/BackupsView-DNS6LdVg.js.map +0 -1
- package/dist/BranchesView-CM3B-ER3.js.map +0 -1
- package/dist/CronJobsView-BHtJZeJZ.js.map +0 -1
- package/dist/RLSEditor-CBX4uD66.js.map +0 -1
- package/dist/SchemaVisualizer-D6tMZgeC.js.map +0 -1
- package/dist/StorageView-BGDeC5GI.js.map +0 -1
- package/dist/components/StorageView/storage-failure.d.ts +0 -34
- package/src/components/ApiExplorer/ApiExplorer.tsx +0 -299
- package/src/components/ApiExplorer/EndpointDetail.tsx +0 -279
- package/src/components/ApiExplorer/TryItPanel.tsx +0 -499
- package/src/components/ApiExplorer/parseSpec.ts +0 -104
- package/src/components/ApiExplorer/types.ts +0 -84
- package/src/components/ApiKeys/ApiKeysView.tsx +0 -479
- package/src/components/ApiKeys/CreateApiKeyDialog.tsx +0 -711
- package/src/components/ApiKeys/permissions.ts +0 -145
- package/src/components/AuthSimulationSelector.tsx +0 -72
- package/src/components/Backups/BackupsView.tsx +0 -185
- package/src/components/Branches/BranchesView.tsx +0 -386
- package/src/components/CronJobs/CronJobsView.tsx +0 -413
- package/src/components/JSEditor/JSEditor.tsx +0 -1100
- package/src/components/JSEditor/JSEditorSidebar.tsx +0 -350
- package/src/components/JSEditor/JSMonacoEditor.tsx +0 -410
- package/src/components/LogsExplorer/LogsExplorer.tsx +0 -273
- package/src/components/LogsExplorer/useLogTail.ts +0 -356
- package/src/components/RLSEditor/PolicyEditor.tsx +0 -399
- package/src/components/RLSEditor/RLSEditor.tsx +0 -1128
- package/src/components/RLSEditor/index.ts +0 -1
- package/src/components/RLSEditor/policy-presets.ts +0 -176
- package/src/components/RLSEditor/saveSecurityRules.ts +0 -48
- package/src/components/RebaseStudio.tsx +0 -174
- package/src/components/SQLEditor/ExplainVisualizer.tsx +0 -128
- package/src/components/SQLEditor/MonacoEditor.tsx +0 -203
- package/src/components/SQLEditor/SQLEditor.tsx +0 -1518
- package/src/components/SQLEditor/SQLEditorSidebar.tsx +0 -173
- package/src/components/SQLEditor/SchemaBrowser.tsx +0 -168
- package/src/components/SQLEditor/sql_editor_types.ts +0 -18
- package/src/components/SchemaVisualizer/RelationEdge.tsx +0 -102
- package/src/components/SchemaVisualizer/SchemaVisualizer.tsx +0 -710
- package/src/components/SchemaVisualizer/TableNode.tsx +0 -257
- package/src/components/SchemaVisualizer/schema-visualizer.utils.ts +0 -140
- package/src/components/SchemaVisualizer/useLiveRls.ts +0 -86
- package/src/components/SchemaVisualizer/useSchemaGraph.ts +0 -426
- package/src/components/StorageView/StorageView.tsx +0 -1588
- package/src/components/StorageView/storage-failure.ts +0 -63
- package/src/components/StudioHomePage.tsx +0 -430
- package/src/index.ts +0 -31
- package/src/utils/parseSpec.test.ts +0 -309
- package/src/utils/sql_utils.test.ts +0 -265
- package/src/utils/sql_utils.ts +0 -291
|
@@ -1,1518 +0,0 @@
|
|
|
1
|
-
|
|
2
|
-
import { IconForView } from "@rebasepro/app";
|
|
3
|
-
import { useStudioCollectionRegistry, useStudioSidePanelController } from "@rebasepro/app";
|
|
4
|
-
import React, { useState, useEffect, useCallback, useRef, useMemo } from "react";
|
|
5
|
-
import { createPortal } from "react-dom";
|
|
6
|
-
import {
|
|
7
|
-
Alert,
|
|
8
|
-
Button,
|
|
9
|
-
Checkbox,
|
|
10
|
-
Chip,
|
|
11
|
-
CircularProgress,
|
|
12
|
-
cls,
|
|
13
|
-
DatabaseIcon,
|
|
14
|
-
defaultBorderMixin,
|
|
15
|
-
Dialog,
|
|
16
|
-
DialogActions,
|
|
17
|
-
DialogContent,
|
|
18
|
-
DialogTitle,
|
|
19
|
-
IconButton,
|
|
20
|
-
iconSize,
|
|
21
|
-
InputLabel,
|
|
22
|
-
Menu,
|
|
23
|
-
MenuIcon,
|
|
24
|
-
MenuItem,
|
|
25
|
-
MoreVerticalIcon,
|
|
26
|
-
Paper,
|
|
27
|
-
PencilIcon,
|
|
28
|
-
PlayIcon,
|
|
29
|
-
PlusIcon,
|
|
30
|
-
ResizablePanels,
|
|
31
|
-
Select,
|
|
32
|
-
SelectItem,
|
|
33
|
-
Tab,
|
|
34
|
-
Tabs,
|
|
35
|
-
TerminalIcon,
|
|
36
|
-
TextareaAutosize,
|
|
37
|
-
TextField,
|
|
38
|
-
Tooltip,
|
|
39
|
-
Typography,
|
|
40
|
-
VirtualTable,
|
|
41
|
-
VirtualTableColumn,
|
|
42
|
-
XIcon
|
|
43
|
-
} from "@rebasepro/ui";
|
|
44
|
-
|
|
45
|
-
import { useRebaseContext, useSnackbarController, ConfirmationDialog, ErrorView, useTranslation } from "@rebasepro/app";
|
|
46
|
-
import { isArrayValue, isRecordValue, readStoredJson, readStoredString, writeStoredJson, writeStoredString } from "@rebasepro/utils";
|
|
47
|
-
import { MonacoEditor } from "./MonacoEditor";
|
|
48
|
-
import { SQLEditorSidebar, Snippet } from "./SQLEditorSidebar";
|
|
49
|
-
import { parseFirst } from "pgsql-ast-parser";
|
|
50
|
-
import { determineTableAndPK, resolveQueryCollections, ResolvedQueryCollection } from "../../utils/sql_utils";
|
|
51
|
-
import { ExplainVisualizer } from "./ExplainVisualizer";
|
|
52
|
-
|
|
53
|
-
import type { SQLEditorColumnInfo, TableInfo } from "./sql_editor_types";
|
|
54
|
-
|
|
55
|
-
export type { SQLEditorColumnInfo, TableInfo };
|
|
56
|
-
|
|
57
|
-
const QueryLoadingView = () => {
|
|
58
|
-
const [elapsed, setElapsed] = useState(0);
|
|
59
|
-
|
|
60
|
-
useEffect(() => {
|
|
61
|
-
const start = Date.now();
|
|
62
|
-
let timeoutId: ReturnType<typeof setTimeout> | null = null;
|
|
63
|
-
let cancelled = false;
|
|
64
|
-
|
|
65
|
-
const tick = () => {
|
|
66
|
-
if (cancelled) return;
|
|
67
|
-
if (document.visibilityState === "visible") {
|
|
68
|
-
setElapsed(Date.now() - start);
|
|
69
|
-
}
|
|
70
|
-
timeoutId = setTimeout(tick, 100);
|
|
71
|
-
};
|
|
72
|
-
|
|
73
|
-
tick();
|
|
74
|
-
|
|
75
|
-
const handleVisibility = () => {
|
|
76
|
-
if (document.visibilityState === "visible") {
|
|
77
|
-
setElapsed(Date.now() - start);
|
|
78
|
-
}
|
|
79
|
-
};
|
|
80
|
-
document.addEventListener("visibilitychange", handleVisibility);
|
|
81
|
-
|
|
82
|
-
return () => {
|
|
83
|
-
cancelled = true;
|
|
84
|
-
if (timeoutId) clearTimeout(timeoutId);
|
|
85
|
-
document.removeEventListener("visibilitychange", handleVisibility);
|
|
86
|
-
};
|
|
87
|
-
}, []);
|
|
88
|
-
|
|
89
|
-
return (
|
|
90
|
-
<div className="flex-grow flex items-center justify-center">
|
|
91
|
-
<div className="text-center">
|
|
92
|
-
<CircularProgress size="medium"/>
|
|
93
|
-
<Typography variant="body2" className="mt-4 text-text-secondary dark:text-text-secondary-dark font-mono tracking-tight animate-pulse">
|
|
94
|
-
EXECUTING QUERY...
|
|
95
|
-
</Typography>
|
|
96
|
-
<div className="mt-2 text-xs font-mono text-text-disabled dark:text-text-disabled-dark">
|
|
97
|
-
{(elapsed / 1000).toFixed(1)}s elapsed
|
|
98
|
-
</div>
|
|
99
|
-
</div>
|
|
100
|
-
</div>
|
|
101
|
-
);
|
|
102
|
-
};
|
|
103
|
-
|
|
104
|
-
const STORAGE_KEY_TABS = "rebase_sql_tabs";
|
|
105
|
-
const STORAGE_KEY_ACTIVE_TAB = "rebase_sql_active_tab";
|
|
106
|
-
|
|
107
|
-
const FixedEditorOverlay = ({
|
|
108
|
-
displayValue,
|
|
109
|
-
onSave,
|
|
110
|
-
onCancel
|
|
111
|
-
}: {
|
|
112
|
-
displayValue: string,
|
|
113
|
-
onSave: (val: string | null) => void,
|
|
114
|
-
onCancel: () => void
|
|
115
|
-
}) => {
|
|
116
|
-
const [rect, setRect] = useState<DOMRect | null>(null);
|
|
117
|
-
const [windowSize, setWindowSize] = useState({ width: 1000,
|
|
118
|
-
height: 1000 });
|
|
119
|
-
const anchorRef = useRef<HTMLDivElement>(null);
|
|
120
|
-
|
|
121
|
-
useEffect(() => {
|
|
122
|
-
if (anchorRef.current && anchorRef.current.parentElement) {
|
|
123
|
-
setRect(anchorRef.current.parentElement.getBoundingClientRect());
|
|
124
|
-
}
|
|
125
|
-
if (typeof window !== "undefined") {
|
|
126
|
-
setWindowSize({ width: window.innerWidth,
|
|
127
|
-
height: window.innerHeight });
|
|
128
|
-
const handleResize = () => setWindowSize({ width: window.innerWidth,
|
|
129
|
-
height: window.innerHeight });
|
|
130
|
-
window.addEventListener("resize", handleResize);
|
|
131
|
-
return () => window.removeEventListener("resize", handleResize);
|
|
132
|
-
}
|
|
133
|
-
return undefined;
|
|
134
|
-
}, []);
|
|
135
|
-
|
|
136
|
-
if (!rect) {
|
|
137
|
-
return <div ref={anchorRef} className="w-full h-full min-h-[20px]" />;
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
let top = rect.top - 2;
|
|
141
|
-
let left = rect.left - 2;
|
|
142
|
-
const minWidth = Math.max(rect.width + 4, 250);
|
|
143
|
-
const minHeight = rect.height + 4;
|
|
144
|
-
|
|
145
|
-
if (left + minWidth > windowSize.width) {
|
|
146
|
-
left = Math.max(10, windowSize.width - minWidth - 10);
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
// Calculate a max height that doesn't overflow the bottom
|
|
150
|
-
const maxAvailableHeight = Math.max(50, windowSize.height - top - 10);
|
|
151
|
-
const resolvedMaxHeight = Math.min(300, maxAvailableHeight);
|
|
152
|
-
|
|
153
|
-
// If even the min height overflows, adjust top
|
|
154
|
-
if (top + minHeight > windowSize.height) {
|
|
155
|
-
top = Math.max(10, windowSize.height - minHeight - 10);
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
return (
|
|
159
|
-
<div ref={anchorRef} className="w-full h-full min-h-[20px]">
|
|
160
|
-
{createPortal(
|
|
161
|
-
<div
|
|
162
|
-
className="fixed z-[9999] bg-surface-50 dark:bg-surface-900 border-2 border-primary dark:border-primary-dark shadow-xl flex flex-col"
|
|
163
|
-
style={{
|
|
164
|
-
top,
|
|
165
|
-
left,
|
|
166
|
-
minWidth,
|
|
167
|
-
minHeight,
|
|
168
|
-
maxWidth: Math.min(400, windowSize.width - left - 10)
|
|
169
|
-
}}
|
|
170
|
-
>
|
|
171
|
-
<TextareaAutosize
|
|
172
|
-
className="w-full h-full bg-transparent outline-none border-none ring-0 font-mono text-[13px] text-text-primary dark:text-text-primary-dark px-4 py-1.5 resize-none overflow-y-auto"
|
|
173
|
-
defaultValue={displayValue}
|
|
174
|
-
autoFocus
|
|
175
|
-
style={{ minHeight: "32px",
|
|
176
|
-
maxHeight: resolvedMaxHeight }}
|
|
177
|
-
onFocus={(e) => {
|
|
178
|
-
const val = e.target.value;
|
|
179
|
-
e.target.value = "";
|
|
180
|
-
e.target.value = val;
|
|
181
|
-
}}
|
|
182
|
-
onBlur={(e) => {
|
|
183
|
-
onSave(e.target.value || null);
|
|
184
|
-
onCancel();
|
|
185
|
-
}}
|
|
186
|
-
onKeyDown={(e) => {
|
|
187
|
-
if (e.key === "Enter" && !e.shiftKey) {
|
|
188
|
-
e.preventDefault();
|
|
189
|
-
onSave((e.currentTarget as HTMLTextAreaElement).value || null);
|
|
190
|
-
onCancel();
|
|
191
|
-
}
|
|
192
|
-
if (e.key === "Escape") onCancel();
|
|
193
|
-
}}
|
|
194
|
-
/>
|
|
195
|
-
</div>,
|
|
196
|
-
document.body
|
|
197
|
-
)}
|
|
198
|
-
</div>
|
|
199
|
-
);
|
|
200
|
-
};
|
|
201
|
-
|
|
202
|
-
const getStoragePrefix = (baseUrl?: string) => {
|
|
203
|
-
if (!baseUrl) return "default";
|
|
204
|
-
return baseUrl.replace(/^https?:\/\//, "").replace(/[^a-zA-Z0-9]/g, "_");
|
|
205
|
-
};
|
|
206
|
-
|
|
207
|
-
/** The part of a tab that is persisted; the rest is per-session. */
|
|
208
|
-
type StoredTab = {
|
|
209
|
-
id: string;
|
|
210
|
-
name: string;
|
|
211
|
-
sql: string;
|
|
212
|
-
database?: string;
|
|
213
|
-
role?: string;
|
|
214
|
-
};
|
|
215
|
-
|
|
216
|
-
/**
|
|
217
|
-
* Whether a stored entry is a tab this release can restore. Storage holds
|
|
218
|
-
* whatever the last version to run wrote, so the fields are checked rather
|
|
219
|
-
* than assumed.
|
|
220
|
-
*/
|
|
221
|
-
function isStoredTab(value: unknown): value is StoredTab {
|
|
222
|
-
if (typeof value !== "object" || value === null) return false;
|
|
223
|
-
const tab = value as Record<string, unknown>;
|
|
224
|
-
return typeof tab.id === "string"
|
|
225
|
-
&& typeof tab.name === "string"
|
|
226
|
-
&& typeof tab.sql === "string";
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
export const SQLEditor = () => {
|
|
230
|
-
const { databaseAdmin, client } = useRebaseContext();
|
|
231
|
-
const sidePanelController = useStudioSidePanelController();
|
|
232
|
-
const snackbarController = useSnackbarController();
|
|
233
|
-
const collectionRegistry = useStudioCollectionRegistry();
|
|
234
|
-
|
|
235
|
-
const { t } = useTranslation();
|
|
236
|
-
|
|
237
|
-
const projectPrefix = useMemo(() => getStoragePrefix(client?.baseUrl), [client?.baseUrl]);
|
|
238
|
-
|
|
239
|
-
// Schema state
|
|
240
|
-
const [schemas, setSchemas] = useState<Record<string, TableInfo[]>>({});
|
|
241
|
-
const [isSchemaLoading, setIsSchemaLoading] = useState(true);
|
|
242
|
-
const schemaFetchedRef = useRef(false);
|
|
243
|
-
const [schemaError, setSchemaError] = useState<string | null>(null);
|
|
244
|
-
|
|
245
|
-
// Connection state
|
|
246
|
-
const [selectedDatabase, setSelectedDatabase] = useState<string | undefined>(() => {
|
|
247
|
-
const projectPrefixSync = client?.baseUrl ? client.baseUrl.replace(/^https?:\/\//, "").replace(/[^a-zA-Z0-9]/g, "_") : "default";
|
|
248
|
-
return readStoredString(`rebase_sql_selected_db_${projectPrefixSync}`) || undefined;
|
|
249
|
-
});
|
|
250
|
-
const [selectedRole, setSelectedRole] = useState<string | undefined>(() => {
|
|
251
|
-
const projectPrefixSync = client?.baseUrl ? client.baseUrl.replace(/^https?:\/\//, "").replace(/[^a-zA-Z0-9]/g, "_") : "default";
|
|
252
|
-
return readStoredString(`rebase_sql_selected_role_${projectPrefixSync}`) || undefined;
|
|
253
|
-
});
|
|
254
|
-
|
|
255
|
-
const [availableDatabases, setAvailableDatabases] = useState<string[]>([]);
|
|
256
|
-
const [availableRoles, setAvailableRoles] = useState<string[]>([]);
|
|
257
|
-
const [isLoadingConfig, setIsLoadingConfig] = useState(true);
|
|
258
|
-
const [connectionConfigError, setConnectionConfigError] = useState<string | null>(null);
|
|
259
|
-
|
|
260
|
-
// Tabbed interface state
|
|
261
|
-
const [tabs, setTabs] = useState<Array<{
|
|
262
|
-
id: string,
|
|
263
|
-
name: string,
|
|
264
|
-
sql: string,
|
|
265
|
-
database?: string,
|
|
266
|
-
role?: string,
|
|
267
|
-
results: Record<string, unknown>[] | null,
|
|
268
|
-
loading: boolean,
|
|
269
|
-
error: string | null,
|
|
270
|
-
execTime: number | null,
|
|
271
|
-
lastExecutedSql: string | null
|
|
272
|
-
}>>(() => {
|
|
273
|
-
const projectPrefixSync = getStoragePrefix(client?.baseUrl);
|
|
274
|
-
// This runs during the first render, so anything it throws takes the
|
|
275
|
-
// whole editor down — and the value that threw is still in storage on
|
|
276
|
-
// reload. `readStoredJson` turns unreadable and wrong-shaped state into
|
|
277
|
-
// the default set of tabs instead, and `isStoredTab` drops the
|
|
278
|
-
// individual entries an older release wrote differently: a tab with no
|
|
279
|
-
// `id` never matches the active tab and cannot be closed.
|
|
280
|
-
const saved = readStoredJson<unknown[]>(
|
|
281
|
-
`rebase_sql_tabs_${projectPrefixSync}`,
|
|
282
|
-
{ fallback: [], accept: isArrayValue }
|
|
283
|
-
);
|
|
284
|
-
const restored = saved.filter(isStoredTab).map(t => ({
|
|
285
|
-
...t,
|
|
286
|
-
results: null,
|
|
287
|
-
loading: false,
|
|
288
|
-
error: null,
|
|
289
|
-
execTime: null,
|
|
290
|
-
lastExecutedSql: null
|
|
291
|
-
}));
|
|
292
|
-
if (restored.length > 0) return restored;
|
|
293
|
-
return [{
|
|
294
|
-
id: "1",
|
|
295
|
-
name: "Query 1",
|
|
296
|
-
sql: "SELECT * FROM ",
|
|
297
|
-
database: readStoredString(`rebase_sql_selected_db_${projectPrefixSync}`) || undefined,
|
|
298
|
-
role: readStoredString(`rebase_sql_selected_role_${projectPrefixSync}`) || undefined,
|
|
299
|
-
results: null,
|
|
300
|
-
loading: false,
|
|
301
|
-
error: null,
|
|
302
|
-
execTime: null,
|
|
303
|
-
lastExecutedSql: null
|
|
304
|
-
}];
|
|
305
|
-
});
|
|
306
|
-
const [activeTabId, setActiveTabId] = useState<string>(() => {
|
|
307
|
-
const projectPrefixSync = client?.baseUrl ? client.baseUrl.replace(/^https?:\/\//, "").replace(/[^a-zA-Z0-9]/g, "_") : "default";
|
|
308
|
-
return readStoredString(`rebase_sql_active_tab_${projectPrefixSync}`) || "1";
|
|
309
|
-
});
|
|
310
|
-
|
|
311
|
-
const activeTab = tabs.find(t => t.id === activeTabId) || tabs[0];
|
|
312
|
-
|
|
313
|
-
// Helper to update active tab state
|
|
314
|
-
const updateActiveTab = useCallback((update: Partial<typeof activeTab>) => {
|
|
315
|
-
setTabs(prev => prev.map(t => t.id === activeTabId ? { ...t,
|
|
316
|
-
...update } : t));
|
|
317
|
-
}, [activeTabId]);
|
|
318
|
-
|
|
319
|
-
const sql = activeTab.sql;
|
|
320
|
-
const results = activeTab.results;
|
|
321
|
-
const loading = activeTab.loading;
|
|
322
|
-
const error = activeTab.error;
|
|
323
|
-
const execTime = activeTab.execTime;
|
|
324
|
-
|
|
325
|
-
const setSql = (newSql: string) => updateActiveTab({ sql: newSql });
|
|
326
|
-
const setResults = (newResults: Record<string, unknown>[] | null) => updateActiveTab({ results: newResults });
|
|
327
|
-
const setLoading = (newLoading: boolean) => updateActiveTab({ loading: newLoading });
|
|
328
|
-
const setError = (newError: string | null) => updateActiveTab({ error: newError });
|
|
329
|
-
|
|
330
|
-
useEffect(() => {
|
|
331
|
-
let mounted = true;
|
|
332
|
-
const fetchConnectionConfig = async () => {
|
|
333
|
-
if (!databaseAdmin?.fetchAvailableDatabases || !databaseAdmin?.fetchAvailableRoles || !databaseAdmin?.executeSql) {
|
|
334
|
-
setConnectionConfigError(t("studio_sql_sql_not_supported"));
|
|
335
|
-
setIsLoadingConfig(false);
|
|
336
|
-
return;
|
|
337
|
-
}
|
|
338
|
-
|
|
339
|
-
try {
|
|
340
|
-
const [dbs, roles, currentDbFromApi, currentUserResult] = await Promise.all([
|
|
341
|
-
databaseAdmin.fetchAvailableDatabases(),
|
|
342
|
-
databaseAdmin.fetchAvailableRoles(),
|
|
343
|
-
typeof databaseAdmin?.fetchCurrentDatabase === "function" ? databaseAdmin.fetchCurrentDatabase() : Promise.resolve(undefined),
|
|
344
|
-
databaseAdmin.executeSql("SELECT current_user AS role").catch(() => [])
|
|
345
|
-
]);
|
|
346
|
-
|
|
347
|
-
if (mounted) {
|
|
348
|
-
setAvailableDatabases(dbs);
|
|
349
|
-
setAvailableRoles(roles);
|
|
350
|
-
|
|
351
|
-
const loadedDb = readStoredString(`rebase_sql_selected_db_${projectPrefix}`) || undefined;
|
|
352
|
-
const loadedRole = readStoredString(`rebase_sql_selected_role_${projectPrefix}`) || undefined;
|
|
353
|
-
|
|
354
|
-
const initialActiveTabId = readStoredString(`rebase_sql_active_tab_${projectPrefix}`) || "1";
|
|
355
|
-
// The old guard caught a parse failure but not a parse
|
|
356
|
-
// *success* of the wrong shape, and the `.find` below sat
|
|
357
|
-
// outside it — so an object where an array was expected
|
|
358
|
-
// still threw.
|
|
359
|
-
const initialTabs = readStoredJson<Array<{ id?: string; database?: string; role?: string }>>(
|
|
360
|
-
`rebase_sql_tabs_${projectPrefix}`,
|
|
361
|
-
{ fallback: [], accept: isArrayValue }
|
|
362
|
-
);
|
|
363
|
-
const currentActiveTab = initialTabs.find(t => t.id === initialActiveTabId);
|
|
364
|
-
|
|
365
|
-
let actualDb = currentActiveTab?.database || loadedDb;
|
|
366
|
-
if (actualDb && !dbs.includes(actualDb)) actualDb = undefined;
|
|
367
|
-
if (!actualDb && dbs.length > 0) {
|
|
368
|
-
actualDb = currentDbFromApi && dbs.includes(currentDbFromApi) ? currentDbFromApi : dbs[0];
|
|
369
|
-
}
|
|
370
|
-
|
|
371
|
-
if (actualDb) {
|
|
372
|
-
setSelectedDatabase(actualDb);
|
|
373
|
-
writeStoredString(`rebase_sql_selected_db_${projectPrefix}`, actualDb);
|
|
374
|
-
setTabs(prev => prev.map(t => t.id === initialActiveTabId && (!t.database || !dbs.includes(t.database)) ? { ...t,
|
|
375
|
-
database: actualDb } : t));
|
|
376
|
-
}
|
|
377
|
-
|
|
378
|
-
const currentUser = (currentUserResult?.[0] as Record<string, unknown> | undefined)?.role as string | undefined;
|
|
379
|
-
let actualRole = currentActiveTab?.role || loadedRole;
|
|
380
|
-
|
|
381
|
-
if (actualRole && !roles.includes(actualRole)) actualRole = undefined;
|
|
382
|
-
if (!actualRole && roles.length > 0) {
|
|
383
|
-
if (currentUser && roles.includes(currentUser)) {
|
|
384
|
-
actualRole = currentUser;
|
|
385
|
-
} else {
|
|
386
|
-
actualRole = roles.includes("postgres") ? "postgres" : roles[0];
|
|
387
|
-
}
|
|
388
|
-
}
|
|
389
|
-
|
|
390
|
-
if (actualRole) {
|
|
391
|
-
setSelectedRole(actualRole);
|
|
392
|
-
writeStoredString(`rebase_sql_selected_role_${projectPrefix}`, actualRole);
|
|
393
|
-
setTabs(prev => prev.map(t => t.id === initialActiveTabId && (!t.role || !roles.includes(t.role)) ? { ...t,
|
|
394
|
-
role: actualRole } : t));
|
|
395
|
-
}
|
|
396
|
-
}
|
|
397
|
-
} catch (err: unknown) {
|
|
398
|
-
console.error("Failed to fetch databases or roles:", err);
|
|
399
|
-
if (mounted) {
|
|
400
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
401
|
-
setConnectionConfigError(t("studio_sql_fetch_error", { message }));
|
|
402
|
-
}
|
|
403
|
-
} finally {
|
|
404
|
-
if (mounted) {
|
|
405
|
-
setIsLoadingConfig(false);
|
|
406
|
-
}
|
|
407
|
-
}
|
|
408
|
-
};
|
|
409
|
-
|
|
410
|
-
fetchConnectionConfig();
|
|
411
|
-
|
|
412
|
-
return () => { mounted = false; };
|
|
413
|
-
}, [databaseAdmin, projectPrefix]);
|
|
414
|
-
|
|
415
|
-
const handleDatabaseChange = (db: string, tabId?: string) => {
|
|
416
|
-
setSelectedDatabase(db);
|
|
417
|
-
writeStoredString(`rebase_sql_selected_db_${projectPrefix}`, db);
|
|
418
|
-
setTabs(prev => prev.map(t => t.id === (tabId || activeTabId) ? { ...t,
|
|
419
|
-
database: db } : t));
|
|
420
|
-
// Reset so the schema will be re-fetched for the new database
|
|
421
|
-
schemaFetchedRef.current = false;
|
|
422
|
-
};
|
|
423
|
-
|
|
424
|
-
const handleRoleChange = (role: string, tabId?: string) => {
|
|
425
|
-
setSelectedRole(role);
|
|
426
|
-
writeStoredString(`rebase_sql_selected_role_${projectPrefix}`, role);
|
|
427
|
-
setTabs(prev => prev.map(t => t.id === (tabId || activeTabId) ? { ...t,
|
|
428
|
-
role } : t));
|
|
429
|
-
};
|
|
430
|
-
|
|
431
|
-
const handleTabChange = useCallback((newTabId: string) => {
|
|
432
|
-
setActiveTabId(newTabId);
|
|
433
|
-
const newTab = tabs.find(t => t.id === newTabId);
|
|
434
|
-
if (newTab) {
|
|
435
|
-
if (newTab.database && newTab.database !== selectedDatabase) {
|
|
436
|
-
setSelectedDatabase(newTab.database);
|
|
437
|
-
writeStoredString(`rebase_sql_selected_db_${projectPrefix}`, newTab.database);
|
|
438
|
-
schemaFetchedRef.current = false;
|
|
439
|
-
} else if (!newTab.database && selectedDatabase) {
|
|
440
|
-
setTabs(prev => prev.map(t => t.id === newTabId ? { ...t,
|
|
441
|
-
database: selectedDatabase } : t));
|
|
442
|
-
}
|
|
443
|
-
|
|
444
|
-
if (newTab.role && newTab.role !== selectedRole) {
|
|
445
|
-
setSelectedRole(newTab.role);
|
|
446
|
-
writeStoredString(`rebase_sql_selected_role_${projectPrefix}`, newTab.role);
|
|
447
|
-
} else if (!newTab.role && selectedRole) {
|
|
448
|
-
setTabs(prev => prev.map(t => t.id === newTabId ? { ...t,
|
|
449
|
-
role: selectedRole } : t));
|
|
450
|
-
}
|
|
451
|
-
}
|
|
452
|
-
}, [tabs, selectedDatabase, selectedRole, projectPrefix]);
|
|
453
|
-
|
|
454
|
-
const fetchSchema = useCallback(async () => {
|
|
455
|
-
if (!databaseAdmin?.executeSql) {
|
|
456
|
-
setSchemaError(t("studio_sql_sql_not_supported"));
|
|
457
|
-
setIsSchemaLoading(false);
|
|
458
|
-
return;
|
|
459
|
-
}
|
|
460
|
-
|
|
461
|
-
setIsSchemaLoading(true);
|
|
462
|
-
setSchemaError(null);
|
|
463
|
-
try {
|
|
464
|
-
const sql = `
|
|
465
|
-
SELECT
|
|
466
|
-
c.table_schema as schema,
|
|
467
|
-
c.table_name as "table",
|
|
468
|
-
c.column_name as "column",
|
|
469
|
-
c.data_type as "data_type",
|
|
470
|
-
CASE WHEN kcu.column_name IS NOT NULL THEN true ELSE false END as "is_pk"
|
|
471
|
-
FROM
|
|
472
|
-
information_schema.columns c
|
|
473
|
-
LEFT JOIN information_schema.table_constraints tc
|
|
474
|
-
ON tc.table_schema = c.table_schema
|
|
475
|
-
AND tc.table_name = c.table_name
|
|
476
|
-
AND tc.constraint_type = 'PRIMARY KEY'
|
|
477
|
-
LEFT JOIN information_schema.key_column_usage kcu
|
|
478
|
-
ON kcu.constraint_name = tc.constraint_name
|
|
479
|
-
AND kcu.table_schema = tc.table_schema
|
|
480
|
-
AND kcu.table_name = tc.table_name
|
|
481
|
-
AND kcu.column_name = c.column_name
|
|
482
|
-
WHERE
|
|
483
|
-
c.table_schema NOT IN ('information_schema', 'pg_catalog')
|
|
484
|
-
ORDER BY
|
|
485
|
-
c.table_schema, c.table_name, c.ordinal_position;
|
|
486
|
-
`;
|
|
487
|
-
// Pass the selected database so schema introspection targets the right DB.
|
|
488
|
-
const result = await databaseAdmin!.executeSql!(sql, { database: selectedDatabase });
|
|
489
|
-
|
|
490
|
-
const processGrouped = (data: Record<string, unknown>[]) => {
|
|
491
|
-
const grouped = data.reduce((acc: Record<string, TableInfo[]>, curr: Record<string, unknown>) => {
|
|
492
|
-
const schema = (curr.schema || curr.SCHEMA || curr.table_schema || "public") as string;
|
|
493
|
-
const table = (curr.table || curr.TABLE || curr.table_name) as string;
|
|
494
|
-
const column = (curr.column || curr.COLUMN || curr.column_name) as string;
|
|
495
|
-
const dataType = (curr.data_type || curr.DATA_TYPE || "") as string;
|
|
496
|
-
const isPrimaryKey = curr.is_pk === true || curr.is_pk === "true";
|
|
497
|
-
|
|
498
|
-
if (!acc[schema]) acc[schema] = [];
|
|
499
|
-
let tableInfo = acc[schema].find(t => t.tableName === table);
|
|
500
|
-
if (!tableInfo) {
|
|
501
|
-
tableInfo = { schemaName: schema,
|
|
502
|
-
tableName: table,
|
|
503
|
-
columns: [] };
|
|
504
|
-
acc[schema].push(tableInfo);
|
|
505
|
-
}
|
|
506
|
-
tableInfo.columns.push({ name: column,
|
|
507
|
-
dataType,
|
|
508
|
-
isPrimaryKey });
|
|
509
|
-
return acc;
|
|
510
|
-
}, {});
|
|
511
|
-
setSchemas(grouped);
|
|
512
|
-
};
|
|
513
|
-
|
|
514
|
-
if (!result || !Array.isArray(result)) {
|
|
515
|
-
if (result && typeof result === "object" && "rows" in result && Array.isArray((result as { rows: Record<string, unknown>[] }).rows)) {
|
|
516
|
-
processGrouped((result as { rows: Record<string, unknown>[] }).rows);
|
|
517
|
-
} else {
|
|
518
|
-
setSchemaError(t("studio_sql_unexpected_format", { type: typeof result }));
|
|
519
|
-
setSchemas({});
|
|
520
|
-
}
|
|
521
|
-
} else if (result.length === 0) {
|
|
522
|
-
setSchemas({});
|
|
523
|
-
setSchemaError(t("studio_sql_no_tables"));
|
|
524
|
-
} else {
|
|
525
|
-
processGrouped(result);
|
|
526
|
-
}
|
|
527
|
-
|
|
528
|
-
schemaFetchedRef.current = true;
|
|
529
|
-
} catch (e: unknown) {
|
|
530
|
-
console.error("Schema fetch error:", e);
|
|
531
|
-
const message = e instanceof Error ? e.message : String(e);
|
|
532
|
-
setSchemaError(t("studio_sql_schema_fetch_error", { message }));
|
|
533
|
-
} finally {
|
|
534
|
-
setIsSchemaLoading(false);
|
|
535
|
-
}
|
|
536
|
-
}, [databaseAdmin, selectedDatabase]);
|
|
537
|
-
|
|
538
|
-
useEffect(() => {
|
|
539
|
-
// Fetch schema after config finishes loading, and re-fetch when the selected database changes.
|
|
540
|
-
if (!isLoadingConfig && !schemaFetchedRef.current) {
|
|
541
|
-
fetchSchema();
|
|
542
|
-
}
|
|
543
|
-
}, [fetchSchema, isLoadingConfig, selectedDatabase]);
|
|
544
|
-
|
|
545
|
-
const [autoLimit, setAutoLimit] = useState(true);
|
|
546
|
-
const [isConfirmDialogOpen, setIsConfirmDialogOpen] = useState(false);
|
|
547
|
-
const [pendingAction, setPendingAction] = useState<(() => void) | null>(null);
|
|
548
|
-
|
|
549
|
-
// Inline editing state
|
|
550
|
-
const [editingCell, setEditingCell] = useState<{ rowIndex: number, columnKey: string, initialValue: unknown } | null>(null);
|
|
551
|
-
|
|
552
|
-
const handleDoubleClick = useCallback((rowIndex: number, columnKey: string, initialValue: unknown, rowData: Record<string, unknown>) => {
|
|
553
|
-
if (!activeTab.lastExecutedSql) {
|
|
554
|
-
snackbarController.open({
|
|
555
|
-
type: "error",
|
|
556
|
-
message: t("studio_sql_cannot_edit_missing_query")
|
|
557
|
-
});
|
|
558
|
-
return;
|
|
559
|
-
}
|
|
560
|
-
|
|
561
|
-
const resolution = determineTableAndPK(activeTab.lastExecutedSql, columnKey, schemas);
|
|
562
|
-
|
|
563
|
-
if (resolution.error || !resolution.primaryKeys || resolution.primaryKeys.length === 0) {
|
|
564
|
-
snackbarController.open({
|
|
565
|
-
type: "error",
|
|
566
|
-
message: resolution.error || t("studio_sql_cannot_resolve_table")
|
|
567
|
-
});
|
|
568
|
-
return;
|
|
569
|
-
}
|
|
570
|
-
|
|
571
|
-
// Check all PK values are present in the row
|
|
572
|
-
const missingPKs = resolution.primaryKeys.filter(
|
|
573
|
-
pk => rowData[pk.resultColumn] === undefined || rowData[pk.resultColumn] === null
|
|
574
|
-
);
|
|
575
|
-
if (missingPKs.length > 0) {
|
|
576
|
-
snackbarController.open({
|
|
577
|
-
type: "error",
|
|
578
|
-
message: t("studio_sql_missing_pk", { columns: missingPKs.map(pk => `"${pk.resultColumn}"`).join(", ") })
|
|
579
|
-
});
|
|
580
|
-
return;
|
|
581
|
-
}
|
|
582
|
-
|
|
583
|
-
setEditingCell({ rowIndex,
|
|
584
|
-
columnKey,
|
|
585
|
-
initialValue });
|
|
586
|
-
}, [activeTab.lastExecutedSql, schemas, snackbarController]);
|
|
587
|
-
|
|
588
|
-
const handleCellSave = useCallback(async (newValue: string | null, rowData: Record<string, unknown>, columnKey: string, rowIndex: number) => {
|
|
589
|
-
if (!editingCell || !activeTab.lastExecutedSql) return;
|
|
590
|
-
|
|
591
|
-
setEditingCell(null); // Optimistically close
|
|
592
|
-
|
|
593
|
-
if (newValue === editingCell.initialValue) return;
|
|
594
|
-
|
|
595
|
-
const resolution = determineTableAndPK(activeTab.lastExecutedSql, columnKey, schemas);
|
|
596
|
-
if (resolution.error || !resolution.tableName || !resolution.primaryKeys || resolution.primaryKeys.length === 0) {
|
|
597
|
-
snackbarController.open({ type: "error",
|
|
598
|
-
message: resolution.error || "Resolution failed." });
|
|
599
|
-
return;
|
|
600
|
-
}
|
|
601
|
-
|
|
602
|
-
const tableName = resolution.tableName;
|
|
603
|
-
|
|
604
|
-
const formatValue = (val: unknown) => {
|
|
605
|
-
if (val === null || val === undefined) return "NULL";
|
|
606
|
-
if (typeof val === "number") return val;
|
|
607
|
-
if (typeof val === "boolean") return val ? "TRUE" : "FALSE";
|
|
608
|
-
return `'${String(val).replace(/'/g, "''")}'`;
|
|
609
|
-
};
|
|
610
|
-
|
|
611
|
-
// Resolve the actual DB column name for the edited column (may differ from the result alias)
|
|
612
|
-
// e.g. if the query has `a.name AS author_name`, columnKey = "author_name" but DB column = "name"
|
|
613
|
-
const resolveDbColumnName = (resultColKey: string): string => {
|
|
614
|
-
try {
|
|
615
|
-
const ast = parseFirst(activeTab.lastExecutedSql!);
|
|
616
|
-
if (ast.type === "select" && ast.columns) {
|
|
617
|
-
for (const col of ast.columns) {
|
|
618
|
-
if (col.expr?.type === "ref") {
|
|
619
|
-
const alias = col.alias?.name;
|
|
620
|
-
const colName = col.expr.name;
|
|
621
|
-
if (alias === resultColKey || (!alias && colName === resultColKey)) {
|
|
622
|
-
return colName;
|
|
623
|
-
}
|
|
624
|
-
}
|
|
625
|
-
}
|
|
626
|
-
}
|
|
627
|
-
} catch { /* fall back to columnKey */ }
|
|
628
|
-
return resultColKey;
|
|
629
|
-
};
|
|
630
|
-
|
|
631
|
-
const dbColumnName = resolveDbColumnName(columnKey);
|
|
632
|
-
|
|
633
|
-
// Build composite WHERE clause
|
|
634
|
-
const whereConditions = resolution.primaryKeys.map(
|
|
635
|
-
pk => `"${pk.dbColumn}" = ${formatValue(rowData[pk.resultColumn])}`
|
|
636
|
-
).join(" AND ");
|
|
637
|
-
|
|
638
|
-
const updateSql = `UPDATE "${tableName}" SET "${dbColumnName}" = ${formatValue(newValue)} WHERE ${whereConditions};`;
|
|
639
|
-
|
|
640
|
-
try {
|
|
641
|
-
if (databaseAdmin?.executeSql) {
|
|
642
|
-
await databaseAdmin.executeSql(updateSql, { database: selectedDatabase,
|
|
643
|
-
role: selectedRole });
|
|
644
|
-
|
|
645
|
-
const newResults = [...(activeTab.results || [])];
|
|
646
|
-
if (newResults[rowIndex]) {
|
|
647
|
-
newResults[rowIndex] = { ...newResults[rowIndex],
|
|
648
|
-
[columnKey]: newValue };
|
|
649
|
-
}
|
|
650
|
-
updateActiveTab({ results: newResults });
|
|
651
|
-
|
|
652
|
-
snackbarController.open({
|
|
653
|
-
type: "success",
|
|
654
|
-
message: t("studio_sql_row_updated")
|
|
655
|
-
});
|
|
656
|
-
}
|
|
657
|
-
} catch (e: unknown) {
|
|
658
|
-
snackbarController.open({
|
|
659
|
-
type: "error",
|
|
660
|
-
message: t("studio_sql_update_failed", { message: e instanceof Error ? e.message : String(e) })
|
|
661
|
-
});
|
|
662
|
-
}
|
|
663
|
-
}, [editingCell, schemas, activeTab.lastExecutedSql, activeTab.results, databaseAdmin, updateActiveTab, snackbarController, selectedDatabase, selectedRole]);
|
|
664
|
-
|
|
665
|
-
const [columnWidths, setColumnWidths] = useState<Record<string, Record<string, number>>>(() => {
|
|
666
|
-
const projectPrefixSync = client?.baseUrl ? client.baseUrl.replace(/^https?:\/\//, "").replace(/[^a-zA-Z0-9]/g, "_") : "default";
|
|
667
|
-
return readStoredJson<Record<string, Record<string, number>>>(
|
|
668
|
-
`rebase_sql_column_widths_${projectPrefixSync}`,
|
|
669
|
-
{ fallback: {}, accept: isRecordValue }
|
|
670
|
-
);
|
|
671
|
-
});
|
|
672
|
-
const [snippets, setSnippets] = useState<Snippet[]>([]);
|
|
673
|
-
const [history, setHistory] = useState<string[]>([]);
|
|
674
|
-
const [isSaveDialogOpen, setIsSaveDialogOpen] = useState(false);
|
|
675
|
-
const [newSnippetName, setNewSnippetName] = useState("");
|
|
676
|
-
|
|
677
|
-
// Load from local storage
|
|
678
|
-
useEffect(() => {
|
|
679
|
-
setSnippets(readStoredJson<Snippet[]>(
|
|
680
|
-
`rebase_sql_snippets_${projectPrefix}`,
|
|
681
|
-
{ fallback: [], accept: isArrayValue }
|
|
682
|
-
));
|
|
683
|
-
setHistory(readStoredJson<string[]>(
|
|
684
|
-
`rebase_sql_history_${projectPrefix}`,
|
|
685
|
-
{ fallback: [], accept: isArrayValue }
|
|
686
|
-
));
|
|
687
|
-
}, [projectPrefix]);
|
|
688
|
-
|
|
689
|
-
// Save tabs and active tab to local storage. Tab text is persisted on every
|
|
690
|
-
// edit, so this is the write that reaches the origin's quota first — and a
|
|
691
|
-
// `QuotaExceededError` thrown out of an effect is not something the view
|
|
692
|
-
// can do anything with.
|
|
693
|
-
useEffect(() => {
|
|
694
|
-
const sanitizedTabs = tabs.map(t => ({
|
|
695
|
-
id: t.id,
|
|
696
|
-
name: t.name,
|
|
697
|
-
sql: t.sql,
|
|
698
|
-
database: t.database,
|
|
699
|
-
role: t.role
|
|
700
|
-
}));
|
|
701
|
-
writeStoredJson(`rebase_sql_tabs_${projectPrefix}`, sanitizedTabs);
|
|
702
|
-
}, [tabs, projectPrefix]);
|
|
703
|
-
|
|
704
|
-
useEffect(() => {
|
|
705
|
-
writeStoredString(`rebase_sql_active_tab_${projectPrefix}`, activeTabId);
|
|
706
|
-
}, [activeTabId, projectPrefix]);
|
|
707
|
-
|
|
708
|
-
const saveSnippets = (newSnippets: Snippet[]) => {
|
|
709
|
-
setSnippets(newSnippets);
|
|
710
|
-
writeStoredJson(`rebase_sql_snippets_${projectPrefix}`, newSnippets);
|
|
711
|
-
};
|
|
712
|
-
|
|
713
|
-
const saveHistory = (newHistory: string[]) => {
|
|
714
|
-
setHistory(newHistory);
|
|
715
|
-
writeStoredJson(`rebase_sql_history_${projectPrefix}`, newHistory.slice(-50));
|
|
716
|
-
};
|
|
717
|
-
|
|
718
|
-
const handleDeleteSnippet = (id: string) => {
|
|
719
|
-
saveSnippets(snippets.filter(s => s.id !== id));
|
|
720
|
-
};
|
|
721
|
-
|
|
722
|
-
const handleAddTab = () => {
|
|
723
|
-
const newId = Math.random().toString(36).substring(2, 9);
|
|
724
|
-
|
|
725
|
-
// Find the next available query number
|
|
726
|
-
let maxNumber = 0;
|
|
727
|
-
tabs.forEach(tab => {
|
|
728
|
-
const match = tab.name.match(/^Query (\d+)$/);
|
|
729
|
-
if (match) {
|
|
730
|
-
const num = parseInt(match[1], 10);
|
|
731
|
-
if (num > maxNumber) maxNumber = num;
|
|
732
|
-
}
|
|
733
|
-
});
|
|
734
|
-
const name = `Query ${maxNumber + 1}`;
|
|
735
|
-
setTabs(prev => [...prev, {
|
|
736
|
-
id: newId,
|
|
737
|
-
name,
|
|
738
|
-
sql: "SELECT * FROM ",
|
|
739
|
-
database: selectedDatabase,
|
|
740
|
-
role: selectedRole,
|
|
741
|
-
results: null,
|
|
742
|
-
loading: false,
|
|
743
|
-
error: null,
|
|
744
|
-
execTime: null,
|
|
745
|
-
lastExecutedSql: null
|
|
746
|
-
}]);
|
|
747
|
-
setActiveTabId(newId);
|
|
748
|
-
};
|
|
749
|
-
|
|
750
|
-
const handleCloseTab = (id: string, e: React.MouseEvent) => {
|
|
751
|
-
e.stopPropagation();
|
|
752
|
-
if (tabs.length === 1) return;
|
|
753
|
-
|
|
754
|
-
const tabIndex = tabs.findIndex(t => t.id === id);
|
|
755
|
-
const newTabs = tabs.filter(t => t.id !== id);
|
|
756
|
-
setTabs(newTabs);
|
|
757
|
-
|
|
758
|
-
if (activeTabId === id) {
|
|
759
|
-
// Find a new active tab: the one at the same index, or the last one if we closed the last
|
|
760
|
-
const nextIndex = Math.min(tabIndex, newTabs.length - 1);
|
|
761
|
-
if (newTabs[nextIndex]) {
|
|
762
|
-
setActiveTabId(newTabs[nextIndex].id);
|
|
763
|
-
}
|
|
764
|
-
}
|
|
765
|
-
};
|
|
766
|
-
|
|
767
|
-
const handleColumnResize = useCallback(({ key, width }: { key: string, width: number }) => {
|
|
768
|
-
setColumnWidths(prev => {
|
|
769
|
-
const newWidths = {
|
|
770
|
-
...prev,
|
|
771
|
-
[activeTab.sql]: {
|
|
772
|
-
...(prev[activeTab.sql] || {}),
|
|
773
|
-
[key]: width
|
|
774
|
-
}
|
|
775
|
-
};
|
|
776
|
-
writeStoredJson(`rebase_sql_column_widths_${projectPrefix}`, newWidths);
|
|
777
|
-
return newWidths;
|
|
778
|
-
});
|
|
779
|
-
}, [activeTab.sql, projectPrefix]);
|
|
780
|
-
|
|
781
|
-
const handlePrettify = () => {
|
|
782
|
-
// Simple formatting for now
|
|
783
|
-
const formatted = activeTab.sql
|
|
784
|
-
.replace(/\s+/g, " ")
|
|
785
|
-
.replace(/\s?,\s?/g, ", ")
|
|
786
|
-
.replace(/\s?=\s?/g, " = ")
|
|
787
|
-
.trim();
|
|
788
|
-
setSql(formatted);
|
|
789
|
-
};
|
|
790
|
-
|
|
791
|
-
const handleExplain = async () => {
|
|
792
|
-
const explainSql = `EXPLAIN (FORMAT JSON, ANALYZE) ${activeTab.sql}`;
|
|
793
|
-
updateActiveTab({ loading: true,
|
|
794
|
-
error: null,
|
|
795
|
-
results: null });
|
|
796
|
-
const start = performance.now();
|
|
797
|
-
try {
|
|
798
|
-
if (databaseAdmin?.executeSql) {
|
|
799
|
-
const result = await databaseAdmin.executeSql(explainSql, { database: selectedDatabase,
|
|
800
|
-
role: selectedRole });
|
|
801
|
-
updateActiveTab({ results: result,
|
|
802
|
-
execTime: Math.round(performance.now() - start) });
|
|
803
|
-
}
|
|
804
|
-
} catch (e: unknown) {
|
|
805
|
-
const message = e instanceof Error ? e.message : String(e);
|
|
806
|
-
updateActiveTab({ error: message || t("studio_sql_error_explaining") });
|
|
807
|
-
} finally {
|
|
808
|
-
updateActiveTab({ loading: false });
|
|
809
|
-
}
|
|
810
|
-
};
|
|
811
|
-
|
|
812
|
-
const executeRun = useCallback(async (sqlOverride?: string) => {
|
|
813
|
-
let sqlToRun = sqlOverride || activeTab.sql;
|
|
814
|
-
const upperSql = sqlToRun.toUpperCase();
|
|
815
|
-
|
|
816
|
-
const isAggregate = /\b(COUNT|SUM|AVG|MIN|MAX)\s*\(/i.test(sqlToRun);
|
|
817
|
-
const isExplain = /\bEXPLAIN\b/i.test(sqlToRun);
|
|
818
|
-
|
|
819
|
-
if (autoLimit && upperSql.includes("SELECT") && !upperSql.includes("LIMIT") && !isAggregate && !isExplain) {
|
|
820
|
-
// Remove trailing semicolon if present to safely append LIMIT
|
|
821
|
-
sqlToRun = sqlToRun.trim().replace(/;$/, "");
|
|
822
|
-
sqlToRun = `${sqlToRun} LIMIT 1000;`;
|
|
823
|
-
}
|
|
824
|
-
|
|
825
|
-
updateActiveTab({ loading: true,
|
|
826
|
-
error: null,
|
|
827
|
-
results: null });
|
|
828
|
-
const start = performance.now();
|
|
829
|
-
|
|
830
|
-
try {
|
|
831
|
-
if (databaseAdmin?.executeSql) {
|
|
832
|
-
const result = await databaseAdmin.executeSql(sqlToRun, { database: selectedDatabase,
|
|
833
|
-
role: selectedRole });
|
|
834
|
-
updateActiveTab({
|
|
835
|
-
results: result,
|
|
836
|
-
execTime: Math.round(performance.now() - start),
|
|
837
|
-
lastExecutedSql: sqlToRun
|
|
838
|
-
});
|
|
839
|
-
|
|
840
|
-
if (history[history.length - 1] !== activeTab.sql) {
|
|
841
|
-
saveHistory([...history, activeTab.sql]);
|
|
842
|
-
}
|
|
843
|
-
} else {
|
|
844
|
-
updateActiveTab({ error: t("studio_sql_execution_not_supported") });
|
|
845
|
-
}
|
|
846
|
-
} catch (e: unknown) {
|
|
847
|
-
const message = e instanceof Error ? e.message : String(e);
|
|
848
|
-
updateActiveTab({ error: message || t("studio_sql_error_executing") });
|
|
849
|
-
} finally {
|
|
850
|
-
updateActiveTab({ loading: false });
|
|
851
|
-
}
|
|
852
|
-
}, [activeTab.sql, autoLimit, databaseAdmin, history, updateActiveTab, selectedDatabase, selectedRole]);
|
|
853
|
-
|
|
854
|
-
const handleRun = useCallback(async (selectedText?: string) => {
|
|
855
|
-
const sqlTarget = selectedText || activeTab.sql;
|
|
856
|
-
if (!sqlTarget.trim()) return;
|
|
857
|
-
|
|
858
|
-
// Destructive operation check
|
|
859
|
-
const destructiveKeywords = ["DELETE", "DROP", "TRUNCATE", "UPDATE"];
|
|
860
|
-
const hasDestructive = destructiveKeywords.some(kw => sqlTarget.toUpperCase().includes(kw));
|
|
861
|
-
const hasWhere = sqlTarget.toUpperCase().includes("WHERE");
|
|
862
|
-
|
|
863
|
-
if (hasDestructive && (!hasWhere || sqlTarget.toUpperCase().includes("DROP") || sqlTarget.toUpperCase().includes("TRUNCATE"))) {
|
|
864
|
-
setPendingAction(() => () => executeRun(selectedText));
|
|
865
|
-
setIsConfirmDialogOpen(true);
|
|
866
|
-
return;
|
|
867
|
-
}
|
|
868
|
-
|
|
869
|
-
executeRun(selectedText);
|
|
870
|
-
}, [activeTab.sql, executeRun]);
|
|
871
|
-
|
|
872
|
-
// Global keybindings
|
|
873
|
-
useEffect(() => {
|
|
874
|
-
const handleKeyDown = (e: KeyboardEvent) => {
|
|
875
|
-
if ((e.metaKey || e.ctrlKey) && e.key === "Enter") {
|
|
876
|
-
// If we are in an input or textarea (except the code editor which handles its own), we might not want to run
|
|
877
|
-
const activeElement = document.activeElement;
|
|
878
|
-
const isInput = activeElement?.tagName === "INPUT" || activeElement?.tagName === "TEXTAREA";
|
|
879
|
-
// If it's the monaco editor textarea, it's fine, let's trigger handleRun
|
|
880
|
-
// Actually the monaco editor already has its own action, so we don't need a global one IF focused in monaco.
|
|
881
|
-
// But wait, if we have both, it might run twice.
|
|
882
|
-
// Let's check if we're focused in monaco.
|
|
883
|
-
const isMonaco = activeElement?.className?.includes("monaco-mouse-cursor-text");
|
|
884
|
-
|
|
885
|
-
if (!isMonaco && !isInput) {
|
|
886
|
-
e.preventDefault();
|
|
887
|
-
handleRun();
|
|
888
|
-
}
|
|
889
|
-
}
|
|
890
|
-
};
|
|
891
|
-
window.addEventListener("keydown", handleKeyDown);
|
|
892
|
-
return () => window.removeEventListener("keydown", handleKeyDown);
|
|
893
|
-
}, [handleRun]);
|
|
894
|
-
|
|
895
|
-
const handleSaveSnippet = () => {
|
|
896
|
-
if (!newSnippetName.trim() || !sql.trim()) return;
|
|
897
|
-
|
|
898
|
-
const newSnippet: Snippet = {
|
|
899
|
-
id: Math.random().toString(36).substring(2, 9),
|
|
900
|
-
name: newSnippetName,
|
|
901
|
-
sql: sql,
|
|
902
|
-
createdAt: Date.now()
|
|
903
|
-
};
|
|
904
|
-
|
|
905
|
-
saveSnippets([...snippets, newSnippet]);
|
|
906
|
-
setNewSnippetName("");
|
|
907
|
-
setIsSaveDialogOpen(false);
|
|
908
|
-
snackbarController.open({
|
|
909
|
-
type: "success",
|
|
910
|
-
message: t("studio_sql_snippet_saved", { name: newSnippetName })
|
|
911
|
-
});
|
|
912
|
-
};
|
|
913
|
-
|
|
914
|
-
const handleExportCSV = () => {
|
|
915
|
-
if (!results || results.length === 0) return;
|
|
916
|
-
|
|
917
|
-
const headers = Object.keys(results[0]).join(",");
|
|
918
|
-
const rows = results.map(row =>
|
|
919
|
-
Object.values(row).map(val => {
|
|
920
|
-
const str = String(val);
|
|
921
|
-
return str.includes(",") ? `"${str}"` : str;
|
|
922
|
-
}).join(",")
|
|
923
|
-
);
|
|
924
|
-
const csv = [headers, ...rows].join("\n");
|
|
925
|
-
const blob = new Blob([csv], { type: "text/csv" });
|
|
926
|
-
const url = window.URL.createObjectURL(blob);
|
|
927
|
-
const a = document.createElement("a");
|
|
928
|
-
a.href = url;
|
|
929
|
-
a.download = `query_results_${new Date().toISOString().slice(0, 19)}.csv`;
|
|
930
|
-
a.click();
|
|
931
|
-
window.URL.revokeObjectURL(url);
|
|
932
|
-
};
|
|
933
|
-
|
|
934
|
-
const handleExportJSON = () => {
|
|
935
|
-
if (!results || results.length === 0) return;
|
|
936
|
-
|
|
937
|
-
const json = JSON.stringify(results, null, 2);
|
|
938
|
-
const blob = new Blob([json], { type: "application/json" });
|
|
939
|
-
const url = window.URL.createObjectURL(blob);
|
|
940
|
-
const a = document.createElement("a");
|
|
941
|
-
a.href = url;
|
|
942
|
-
a.download = `query_results_${new Date().toISOString().slice(0, 19)}.json`;
|
|
943
|
-
a.click();
|
|
944
|
-
window.URL.revokeObjectURL(url);
|
|
945
|
-
};
|
|
946
|
-
|
|
947
|
-
const handleExportMarkdown = () => {
|
|
948
|
-
if (!results || results.length === 0) return;
|
|
949
|
-
|
|
950
|
-
const headers = Object.keys(results[0]);
|
|
951
|
-
const headerRow = `| ${headers.join(" | ")} |`;
|
|
952
|
-
const dividerRow = `| ${headers.map(() => "---").join(" | ")} |`;
|
|
953
|
-
const dataRows = results.map(row =>
|
|
954
|
-
`| ${headers.map(header => {
|
|
955
|
-
const val = row[header];
|
|
956
|
-
if (val === null) return "null";
|
|
957
|
-
if (val === undefined) return "";
|
|
958
|
-
// Replace pipes and newlines to avoid breaking the markdown table
|
|
959
|
-
return String(val).replace(/\|/g, "\\|").replace(/\n/g, " ");
|
|
960
|
-
}).join(" | ")} |`
|
|
961
|
-
);
|
|
962
|
-
|
|
963
|
-
const markdown = [headerRow, dividerRow, ...dataRows].join("\n");
|
|
964
|
-
navigator.clipboard.writeText(markdown).then(() => {
|
|
965
|
-
snackbarController.open({
|
|
966
|
-
type: "success",
|
|
967
|
-
message: t("studio_sql_markdown_copied")
|
|
968
|
-
});
|
|
969
|
-
}).catch(() => {
|
|
970
|
-
snackbarController.open({
|
|
971
|
-
type: "error",
|
|
972
|
-
message: t("studio_sql_markdown_copy_failed")
|
|
973
|
-
});
|
|
974
|
-
});
|
|
975
|
-
};
|
|
976
|
-
|
|
977
|
-
const renderResults = () => {
|
|
978
|
-
if (loading) {
|
|
979
|
-
return (
|
|
980
|
-
<div className="flex-grow flex items-center justify-center">
|
|
981
|
-
<div className="text-center">
|
|
982
|
-
<CircularProgress size="medium"/>
|
|
983
|
-
<Typography variant="body2" className="mt-4 text-text-secondary dark:text-text-secondary-dark font-mono tracking-tight animate-pulse">{t("studio_sql_executing_query")}</Typography>
|
|
984
|
-
</div>
|
|
985
|
-
</div>
|
|
986
|
-
);
|
|
987
|
-
}
|
|
988
|
-
|
|
989
|
-
if (error) {
|
|
990
|
-
return (
|
|
991
|
-
<div className="flex-grow flex items-center justify-center p-6 overflow-auto">
|
|
992
|
-
<ErrorView title={t("studio_sql_query_error")} error={error}/>
|
|
993
|
-
</div>
|
|
994
|
-
);
|
|
995
|
-
}
|
|
996
|
-
|
|
997
|
-
if (!results) {
|
|
998
|
-
return (
|
|
999
|
-
<div className="flex-grow flex items-center justify-center text-text-disabled dark:text-text-disabled-dark">
|
|
1000
|
-
<div className="text-center">
|
|
1001
|
-
<svg className="w-12 h-12 mx-auto mb-4 opacity-50" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} d="M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4m0 5c0 2.21-3.582 4-8 4s-8-1.79-8-4"/></svg>
|
|
1002
|
-
<Typography variant="body2">{t("studio_sql_run_query_placeholder")}</Typography>
|
|
1003
|
-
</div>
|
|
1004
|
-
</div>
|
|
1005
|
-
);
|
|
1006
|
-
}
|
|
1007
|
-
|
|
1008
|
-
// Check for EXPLAIN (FORMAT JSON) response
|
|
1009
|
-
if (results.length === 1 && results[0]["QUERY PLAN"] && Array.isArray(results[0]["QUERY PLAN"])) {
|
|
1010
|
-
try {
|
|
1011
|
-
const plan = results[0]["QUERY PLAN"][0].Plan;
|
|
1012
|
-
if (plan) {
|
|
1013
|
-
return (
|
|
1014
|
-
<div className="flex-grow overflow-auto p-4 bg-surface-50 dark:bg-surface-900 flex flex-col items-start">
|
|
1015
|
-
<Typography variant="caption" className="font-semibold text-text-secondary mb-4 tracking-wider uppercase">{t("studio_sql_visual_execution_plan")}</Typography>
|
|
1016
|
-
<div className="pb-12">
|
|
1017
|
-
<ExplainVisualizer plan={plan}/>
|
|
1018
|
-
</div>
|
|
1019
|
-
</div>
|
|
1020
|
-
);
|
|
1021
|
-
}
|
|
1022
|
-
} catch (e) {
|
|
1023
|
-
console.warn("Failed to parse EXPLAIN JSON output:", e);
|
|
1024
|
-
}
|
|
1025
|
-
}
|
|
1026
|
-
|
|
1027
|
-
if (results.length === 0) {
|
|
1028
|
-
return (
|
|
1029
|
-
<div className="flex-grow p-6 flex flex-col items-center justify-center">
|
|
1030
|
-
<Typography variant="body2" className="text-text-secondary dark:text-text-secondary-dark font-mono border-b border-surface-200 dark:border-surface-950 pb-2 mb-2">{t("studio_sql_success")}</Typography>
|
|
1031
|
-
<Typography variant="caption" className="text-text-disabled dark:text-text-disabled-dark">{t("studio_sql_no_results")}</Typography>
|
|
1032
|
-
</div>
|
|
1033
|
-
);
|
|
1034
|
-
}
|
|
1035
|
-
|
|
1036
|
-
const savedWidths = columnWidths[activeTab.sql] || {};
|
|
1037
|
-
const resultColumnKeys = Object.keys(results[0]);
|
|
1038
|
-
|
|
1039
|
-
// Compute matched collections for this query, including PK column detection
|
|
1040
|
-
const matchedCollections: ResolvedQueryCollection[] = (() => {
|
|
1041
|
-
if (!activeTab.lastExecutedSql || !collectionRegistry.collections) return [];
|
|
1042
|
-
try {
|
|
1043
|
-
return resolveQueryCollections(activeTab.lastExecutedSql, schemas, collectionRegistry.collections, resultColumnKeys);
|
|
1044
|
-
} catch {
|
|
1045
|
-
return [];
|
|
1046
|
-
}
|
|
1047
|
-
})();
|
|
1048
|
-
|
|
1049
|
-
// Only collections that have a PK column in the result set can be opened
|
|
1050
|
-
const actionableCollections = matchedCollections.filter(mc => mc.pkColumn && resultColumnKeys.includes(mc.pkColumn));
|
|
1051
|
-
|
|
1052
|
-
// For each row, determine which entities can be opened
|
|
1053
|
-
const getRowEntityActions = (rowData: Record<string, unknown>): { collection: ResolvedQueryCollection, entityId: string | number }[] => {
|
|
1054
|
-
if (!rowData) return [];
|
|
1055
|
-
return actionableCollections
|
|
1056
|
-
.filter(mc => rowData[mc.pkColumn!] != null)
|
|
1057
|
-
.map(mc => ({
|
|
1058
|
-
collection: mc,
|
|
1059
|
-
entityId: rowData[mc.pkColumn!] as string | number
|
|
1060
|
-
}));
|
|
1061
|
-
};
|
|
1062
|
-
|
|
1063
|
-
// Build the columns array. If we have actionable collections, prepend a dedicated action column.
|
|
1064
|
-
const dataColumns: VirtualTableColumn[] = resultColumnKeys.map(key => ({
|
|
1065
|
-
key,
|
|
1066
|
-
title: key,
|
|
1067
|
-
width: savedWidths[key] ?? 150,
|
|
1068
|
-
sortable: false,
|
|
1069
|
-
resizable: true
|
|
1070
|
-
}));
|
|
1071
|
-
|
|
1072
|
-
const columns: VirtualTableColumn[] = actionableCollections.length > 0
|
|
1073
|
-
? [{ key: "__cms_action__",
|
|
1074
|
-
title: "",
|
|
1075
|
-
width: 36,
|
|
1076
|
-
sortable: false,
|
|
1077
|
-
resizable: false }, ...dataColumns]
|
|
1078
|
-
: dataColumns;
|
|
1079
|
-
|
|
1080
|
-
return (
|
|
1081
|
-
<div className="flex-grow flex flex-col overflow-hidden min-h-0">
|
|
1082
|
-
{/* Collection Badges Bar */}
|
|
1083
|
-
{actionableCollections.length > 0 && (
|
|
1084
|
-
<div className={cls("px-4 py-1.5 border-b flex items-center gap-2 shrink-0 bg-surface-50 dark:bg-surface-900", defaultBorderMixin)}>
|
|
1085
|
-
<Tooltip title={t("studio_sql_admin_collections_tooltip")}>
|
|
1086
|
-
<Typography variant="caption" className="text-[10px] font-semibold uppercase tracking-widest text-text-disabled dark:text-text-disabled-dark mr-1 shrink-0 cursor-help">{t("studio_sql_collections_label")}</Typography>
|
|
1087
|
-
</Tooltip>
|
|
1088
|
-
<div className="flex items-center gap-1.5 overflow-x-auto no-scrollbar">
|
|
1089
|
-
{actionableCollections.map(mc => (
|
|
1090
|
-
<Tooltip key={mc.tableName} title={`Table "${mc.tableName}" → ${mc.collection.name} (PK: ${mc.pkColumn})`}>
|
|
1091
|
-
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-medium bg-primary/10 dark:bg-primary-dark/15 text-primary dark:text-primary-dark whitespace-nowrap border border-primary/20 dark:border-primary-dark/20">
|
|
1092
|
-
{typeof mc.collection.icon === "string" && (
|
|
1093
|
-
<IconForView collectionOrView={mc.collection} className="text-[12px]"/>
|
|
1094
|
-
)}
|
|
1095
|
-
{mc.collection.name}
|
|
1096
|
-
</span>
|
|
1097
|
-
</Tooltip>
|
|
1098
|
-
))}
|
|
1099
|
-
</div>
|
|
1100
|
-
</div>
|
|
1101
|
-
)}
|
|
1102
|
-
<div className="flex-grow relative h-full min-h-0 min-w-0">
|
|
1103
|
-
<VirtualTable
|
|
1104
|
-
data={results}
|
|
1105
|
-
columns={columns}
|
|
1106
|
-
rowHeight={32}
|
|
1107
|
-
headerHeight={32}
|
|
1108
|
-
extraData={editingCell}
|
|
1109
|
-
onColumnResizeEnd={handleColumnResize}
|
|
1110
|
-
cellRenderer={({ rowData, column, rowIndex }) => {
|
|
1111
|
-
// Dedicated collection action column
|
|
1112
|
-
if (column.key === "__cms_action__") {
|
|
1113
|
-
const rowActions = getRowEntityActions(rowData ?? {});
|
|
1114
|
-
if (rowActions.length === 0) {
|
|
1115
|
-
return <div className="h-full w-full"/>;
|
|
1116
|
-
}
|
|
1117
|
-
if (rowActions.length === 1) {
|
|
1118
|
-
const ra = rowActions[0];
|
|
1119
|
-
return (
|
|
1120
|
-
<div className="h-full flex items-center justify-center">
|
|
1121
|
-
<Tooltip title={t("studio_sql_edit_entity", { name: ra.collection.collection.name,
|
|
1122
|
-
id: String(ra.entityId) })}>
|
|
1123
|
-
<IconButton
|
|
1124
|
-
size="small"
|
|
1125
|
-
className="text-surface-400 dark:text-surface-500 hover:text-surface-600 dark:hover:text-surface-300 transition-colors"
|
|
1126
|
-
onClick={(e) => {
|
|
1127
|
-
e.stopPropagation();
|
|
1128
|
-
sidePanelController?.open({
|
|
1129
|
-
path: ra.collection.collection.slug,
|
|
1130
|
-
entityId: ra.entityId,
|
|
1131
|
-
collection: ra.collection.collection,
|
|
1132
|
-
updateUrl: false
|
|
1133
|
-
});
|
|
1134
|
-
}}
|
|
1135
|
-
>
|
|
1136
|
-
<PencilIcon size={iconSize.smallest}/>
|
|
1137
|
-
</IconButton>
|
|
1138
|
-
</Tooltip>
|
|
1139
|
-
</div>
|
|
1140
|
-
);
|
|
1141
|
-
}
|
|
1142
|
-
// Multiple matched collections (JOIN) — show a dropdown
|
|
1143
|
-
return (
|
|
1144
|
-
<div className="h-full flex items-center justify-center">
|
|
1145
|
-
<Menu
|
|
1146
|
-
trigger={
|
|
1147
|
-
<IconButton
|
|
1148
|
-
size="small"
|
|
1149
|
-
className="text-surface-400 dark:text-surface-500 hover:text-surface-600 dark:hover:text-surface-300 transition-colors"
|
|
1150
|
-
onClick={(e) => e.stopPropagation()}
|
|
1151
|
-
>
|
|
1152
|
-
<MoreVerticalIcon size={iconSize.smallest}/>
|
|
1153
|
-
</IconButton>
|
|
1154
|
-
}
|
|
1155
|
-
>
|
|
1156
|
-
{rowActions.map(ra => (
|
|
1157
|
-
<MenuItem
|
|
1158
|
-
key={ra.collection.tableName}
|
|
1159
|
-
dense
|
|
1160
|
-
onClick={() => {
|
|
1161
|
-
sidePanelController?.open({
|
|
1162
|
-
path: ra.collection.collection.slug,
|
|
1163
|
-
entityId: ra.entityId,
|
|
1164
|
-
collection: ra.collection.collection,
|
|
1165
|
-
updateUrl: false
|
|
1166
|
-
});
|
|
1167
|
-
}}
|
|
1168
|
-
>
|
|
1169
|
-
{t("studio_sql_edit_entity", { name: ra.collection.collection.name,
|
|
1170
|
-
id: String(ra.entityId) })}
|
|
1171
|
-
</MenuItem>
|
|
1172
|
-
))}
|
|
1173
|
-
</Menu>
|
|
1174
|
-
</div>
|
|
1175
|
-
);
|
|
1176
|
-
}
|
|
1177
|
-
|
|
1178
|
-
// Regular data cell
|
|
1179
|
-
const isEditing = editingCell?.rowIndex === rowIndex && editingCell?.columnKey === column.key;
|
|
1180
|
-
const value = rowData ? rowData[column.key] : null;
|
|
1181
|
-
const displayValue = typeof value === "object" && value !== null ? JSON.stringify(value) : String(value ?? "");
|
|
1182
|
-
|
|
1183
|
-
if (isEditing) {
|
|
1184
|
-
return (
|
|
1185
|
-
<FixedEditorOverlay
|
|
1186
|
-
displayValue={displayValue}
|
|
1187
|
-
onSave={(val) => handleCellSave(val, rowData ?? {}, column.key, rowIndex)}
|
|
1188
|
-
onCancel={() => setEditingCell(null)}
|
|
1189
|
-
/>
|
|
1190
|
-
);
|
|
1191
|
-
}
|
|
1192
|
-
|
|
1193
|
-
return (
|
|
1194
|
-
<div
|
|
1195
|
-
className="px-4 py-1.5 h-full flex items-center whitespace-nowrap text-[13px] text-text-primary dark:text-text-primary-dark font-mono cursor-text group/cell"
|
|
1196
|
-
onDoubleClick={() => handleDoubleClick(rowIndex, column.key, displayValue, rowData ?? {})}
|
|
1197
|
-
>
|
|
1198
|
-
<div className="truncate flex-grow" title={displayValue}>
|
|
1199
|
-
{displayValue === "" ? <span className="text-text-disabled dark:text-text-disabled-dark italic text-[11px]">NULL</span> : displayValue}
|
|
1200
|
-
</div>
|
|
1201
|
-
</div>
|
|
1202
|
-
);
|
|
1203
|
-
}}
|
|
1204
|
-
/>
|
|
1205
|
-
</div>
|
|
1206
|
-
|
|
1207
|
-
<div className={cls("p-2 px-4 border-t bg-surface-50 dark:bg-surface-900 flex justify-between items-center shrink-0", defaultBorderMixin)}>
|
|
1208
|
-
<div className="flex space-x-4">
|
|
1209
|
-
<div className="flex items-center text-[11px]">
|
|
1210
|
-
<span className="font-semibold text-text-disabled dark:text-text-disabled-dark mr-2 uppercase tracking-tighter">{t("studio_sql_rows")}</span>
|
|
1211
|
-
<span className="font-mono text-text-secondary dark:text-text-secondary-dark">{results.length}</span>
|
|
1212
|
-
</div>
|
|
1213
|
-
<div className="flex items-center text-[11px]">
|
|
1214
|
-
<span className="font-semibold text-text-disabled dark:text-text-disabled-dark mr-2 uppercase tracking-tighter">{t("studio_sql_time")}</span>
|
|
1215
|
-
<span className="font-mono text-text-secondary dark:text-text-secondary-dark">{execTime}ms</span>
|
|
1216
|
-
</div>
|
|
1217
|
-
</div>
|
|
1218
|
-
<div className="flex gap-2 overflow-x-auto no-scrollbar items-center px-2">
|
|
1219
|
-
<Button
|
|
1220
|
-
size="small"
|
|
1221
|
-
variant="text"
|
|
1222
|
-
className="text-[10px] uppercase font-semibold text-text-secondary dark:text-text-secondary-dark whitespace-nowrap"
|
|
1223
|
-
onClick={handleExportMarkdown}
|
|
1224
|
-
>
|
|
1225
|
-
{t("studio_sql_copy_markdown")}
|
|
1226
|
-
</Button>
|
|
1227
|
-
<Button
|
|
1228
|
-
size="small"
|
|
1229
|
-
variant="text"
|
|
1230
|
-
className="text-[10px] uppercase font-semibold text-text-secondary dark:text-text-secondary-dark whitespace-nowrap"
|
|
1231
|
-
onClick={handleExportJSON}
|
|
1232
|
-
>
|
|
1233
|
-
{t("studio_sql_export_json")}
|
|
1234
|
-
</Button>
|
|
1235
|
-
<Button
|
|
1236
|
-
size="small"
|
|
1237
|
-
variant="text"
|
|
1238
|
-
className="text-[10px] uppercase font-semibold text-text-secondary dark:text-text-secondary-dark whitespace-nowrap"
|
|
1239
|
-
onClick={handleExportCSV}
|
|
1240
|
-
>
|
|
1241
|
-
{t("studio_sql_export_csv")}
|
|
1242
|
-
</Button>
|
|
1243
|
-
</div>
|
|
1244
|
-
</div>
|
|
1245
|
-
</div>
|
|
1246
|
-
);
|
|
1247
|
-
};
|
|
1248
|
-
|
|
1249
|
-
// `parseFloat` answers NaN for anything it cannot read, and a NaN pane size
|
|
1250
|
-
// lays the editor out to nothing — so the stored value has to be checked,
|
|
1251
|
-
// not just parsed.
|
|
1252
|
-
const readStoredSize = (key: string, fallback: number) => {
|
|
1253
|
-
const saved = readStoredString(`${key}_${getStoragePrefix(client?.baseUrl)}`);
|
|
1254
|
-
const parsed = saved === null ? NaN : parseFloat(saved);
|
|
1255
|
-
return Number.isFinite(parsed) ? parsed : fallback;
|
|
1256
|
-
};
|
|
1257
|
-
|
|
1258
|
-
const [sidebarSize, setSidebarSize] = useState(() => readStoredSize("rebase_sql_editor_sidebar_size", 20));
|
|
1259
|
-
const [editorHeight, setEditorHeight] = useState(() => readStoredSize("rebase_sql_editor_height", 50));
|
|
1260
|
-
|
|
1261
|
-
useEffect(() => {
|
|
1262
|
-
writeStoredString(`rebase_sql_editor_sidebar_size_${projectPrefix}`, sidebarSize.toString());
|
|
1263
|
-
}, [sidebarSize, projectPrefix]);
|
|
1264
|
-
|
|
1265
|
-
useEffect(() => {
|
|
1266
|
-
writeStoredString(`rebase_sql_editor_height_${projectPrefix}`, editorHeight.toString());
|
|
1267
|
-
}, [editorHeight, projectPrefix]);
|
|
1268
|
-
|
|
1269
|
-
const activeSnippet = snippets.find(s => s.sql === activeTab.sql);
|
|
1270
|
-
const isFavorite = activeSnippet?.isFavorite || false;
|
|
1271
|
-
|
|
1272
|
-
return (
|
|
1273
|
-
<div className="flex h-full w-full bg-white dark:bg-surface-950 overflow-hidden text-text-primary dark:text-text-primary-dark">
|
|
1274
|
-
<ResizablePanels
|
|
1275
|
-
orientation="horizontal"
|
|
1276
|
-
panelSizePercent={sidebarSize}
|
|
1277
|
-
onPanelSizeChange={setSidebarSize}
|
|
1278
|
-
minPanelSizePx={220}
|
|
1279
|
-
firstPanel={
|
|
1280
|
-
<SQLEditorSidebar
|
|
1281
|
-
snippets={snippets}
|
|
1282
|
-
history={history}
|
|
1283
|
-
onSelectSnippet={setSql}
|
|
1284
|
-
onTableClick={setSql}
|
|
1285
|
-
onDeleteSnippet={handleDeleteSnippet}
|
|
1286
|
-
schemas={schemas}
|
|
1287
|
-
isSchemaLoading={isSchemaLoading}
|
|
1288
|
-
schemaError={schemaError}
|
|
1289
|
-
onRetrySchema={fetchSchema}
|
|
1290
|
-
/>
|
|
1291
|
-
}
|
|
1292
|
-
secondPanel={
|
|
1293
|
-
<div className="flex-grow flex flex-col min-w-0 h-full w-full">
|
|
1294
|
-
{/* Toolbar */}
|
|
1295
|
-
<div className={cls("flex items-center justify-between pr-2 border-b bg-white dark:bg-surface-950", defaultBorderMixin)}>
|
|
1296
|
-
<div className="flex items-center flex-grow overflow-hidden mr-4">
|
|
1297
|
-
<div className="flex items-center no-scrollbar overflow-x-auto min-w-0">
|
|
1298
|
-
<Tabs value={activeTabId} onValueChange={handleTabChange} variant="boxy" className="w-[unset] flex-shrink-0" innerClassName="bg-white dark:bg-surface-950">
|
|
1299
|
-
{tabs.map(tab => (
|
|
1300
|
-
<Tab key={tab.id} value={tab.id} className="flex items-center justify-between group max-w-[200px]">
|
|
1301
|
-
<TerminalIcon size={iconSize.smallest} className="text-blue-500 mr-1.5 flex-shrink-0"/>
|
|
1302
|
-
<span className="truncate">{tab.name}</span>
|
|
1303
|
-
{tabs.length > 1 && (
|
|
1304
|
-
<IconButton
|
|
1305
|
-
size="smallest"
|
|
1306
|
-
onClick={(e) => handleCloseTab(tab.id, e)}
|
|
1307
|
-
className="ml-1 !p-0.5 opacity-0 group-hover:opacity-100 hover:text-red-500 transition-opacity"
|
|
1308
|
-
>
|
|
1309
|
-
<XIcon size={iconSize.smallest}/>
|
|
1310
|
-
</IconButton>
|
|
1311
|
-
)}
|
|
1312
|
-
</Tab>
|
|
1313
|
-
))}
|
|
1314
|
-
</Tabs>
|
|
1315
|
-
<IconButton
|
|
1316
|
-
size="small"
|
|
1317
|
-
onClick={handleAddTab}
|
|
1318
|
-
className="ml-2 flex-shrink-0"
|
|
1319
|
-
>
|
|
1320
|
-
<PlusIcon size={iconSize.smallest}/>
|
|
1321
|
-
</IconButton>
|
|
1322
|
-
</div>
|
|
1323
|
-
</div>
|
|
1324
|
-
<div className="flex shrink-0 items-center justify-end pr-2 gap-1.5">
|
|
1325
|
-
<Tooltip title={t("studio_sql_format_sql")}>
|
|
1326
|
-
<IconButton size="small" onClick={handlePrettify}>
|
|
1327
|
-
<MenuIcon size={iconSize.smallest}/>
|
|
1328
|
-
</IconButton>
|
|
1329
|
-
</Tooltip>
|
|
1330
|
-
|
|
1331
|
-
<Button
|
|
1332
|
-
variant="text"
|
|
1333
|
-
size="small"
|
|
1334
|
-
onClick={handleExplain}
|
|
1335
|
-
disabled={loading}
|
|
1336
|
-
>
|
|
1337
|
-
{t("studio_sql_explain")}
|
|
1338
|
-
</Button>
|
|
1339
|
-
|
|
1340
|
-
<div className="h-4 w-px bg-surface-200 dark:bg-surface-950 mx-1"></div>
|
|
1341
|
-
|
|
1342
|
-
<div className="flex items-center space-x-2 px-2" onClick={(e) => {
|
|
1343
|
-
setAutoLimit(!autoLimit);
|
|
1344
|
-
e.stopPropagation();
|
|
1345
|
-
}}>
|
|
1346
|
-
<Typography variant="caption" className="text-[11px] text-text-secondary cursor-pointer select-none">{t("studio_sql_limit_1000")}</Typography>
|
|
1347
|
-
<div onClick={(e) => e.stopPropagation()}>
|
|
1348
|
-
<Checkbox
|
|
1349
|
-
checked={autoLimit}
|
|
1350
|
-
onCheckedChange={setAutoLimit}
|
|
1351
|
-
size="smallest"
|
|
1352
|
-
padding={false}
|
|
1353
|
-
/>
|
|
1354
|
-
</div>
|
|
1355
|
-
</div>
|
|
1356
|
-
|
|
1357
|
-
<div className="h-4 w-px bg-surface-200 dark:bg-surface-950 mx-1"></div>
|
|
1358
|
-
|
|
1359
|
-
<Tooltip title={isFavorite ? t("studio_sql_remove_from_favorites") : t("studio_sql_add_to_favorites")}>
|
|
1360
|
-
<IconButton
|
|
1361
|
-
size="small"
|
|
1362
|
-
onClick={() => {
|
|
1363
|
-
if (!activeSnippet) {
|
|
1364
|
-
snackbarController.open({
|
|
1365
|
-
type: "info",
|
|
1366
|
-
message: t("studio_sql_save_first_to_favorite")
|
|
1367
|
-
});
|
|
1368
|
-
return;
|
|
1369
|
-
}
|
|
1370
|
-
saveSnippets(snippets.map(s => s.id === activeSnippet.id ? { ...s,
|
|
1371
|
-
isFavorite: !s.isFavorite } : s));
|
|
1372
|
-
}}
|
|
1373
|
-
>
|
|
1374
|
-
<svg className={`w-4 h-4 ${isFavorite ? "text-red-500 fill-current" : "text-text-disabled dark:text-text-disabled-dark hover:text-text-primary"}`} fill={isFavorite ? "currentColor" : "none"} stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"/></svg>
|
|
1375
|
-
</IconButton>
|
|
1376
|
-
</Tooltip>
|
|
1377
|
-
|
|
1378
|
-
<Button
|
|
1379
|
-
variant="text"
|
|
1380
|
-
size="small"
|
|
1381
|
-
onClick={() => setIsSaveDialogOpen(true)}
|
|
1382
|
-
>
|
|
1383
|
-
{t("studio_sql_save")}
|
|
1384
|
-
</Button>
|
|
1385
|
-
|
|
1386
|
-
<div className="h-4 w-px bg-surface-200 dark:bg-surface-950 mx-1"></div>
|
|
1387
|
-
|
|
1388
|
-
<Menu
|
|
1389
|
-
trigger={
|
|
1390
|
-
<Button
|
|
1391
|
-
size="small"
|
|
1392
|
-
variant="outlined"
|
|
1393
|
-
className="text-text-secondary dark:text-text-secondary-dark font-medium mr-2"
|
|
1394
|
-
>
|
|
1395
|
-
<DatabaseIcon size={iconSize.small} className="mr-1.5 text-text-disabled dark:text-text-disabled-dark"/>
|
|
1396
|
-
<span className="max-w-[160px] truncate">
|
|
1397
|
-
{isLoadingConfig
|
|
1398
|
-
? "..."
|
|
1399
|
-
: `${selectedDatabase || t("studio_sql_select_db")}${selectedRole ? ` (${selectedRole})` : ""}`}
|
|
1400
|
-
</span>
|
|
1401
|
-
</Button>
|
|
1402
|
-
}
|
|
1403
|
-
>
|
|
1404
|
-
<div className="max-h-64 overflow-y-auto">
|
|
1405
|
-
<div className="px-3 py-1.5 border-b border-surface-200 dark:border-surface-950 mb-1">
|
|
1406
|
-
<Typography variant="caption" className="font-semibold uppercase tracking-wider text-[9px] text-text-disabled dark:text-text-disabled-dark">{t("studio_sql_database")}</Typography>
|
|
1407
|
-
</div>
|
|
1408
|
-
{isLoadingConfig ? (
|
|
1409
|
-
<div className="flex items-center justify-center p-4">
|
|
1410
|
-
<CircularProgress size="small"/>
|
|
1411
|
-
</div>
|
|
1412
|
-
) : connectionConfigError ? (
|
|
1413
|
-
<div className="px-3 py-2 text-xs text-red-500 dark:text-red-400 max-w-[200px] break-words">
|
|
1414
|
-
{connectionConfigError}
|
|
1415
|
-
</div>
|
|
1416
|
-
) : (
|
|
1417
|
-
<>
|
|
1418
|
-
{availableDatabases.map(db => (
|
|
1419
|
-
<MenuItem key={db} dense onClick={() => handleDatabaseChange(db)} className={cls("text-xs", selectedDatabase === db && "text-primary dark:text-primary-dark")}>
|
|
1420
|
-
{db}
|
|
1421
|
-
</MenuItem>
|
|
1422
|
-
))}
|
|
1423
|
-
|
|
1424
|
-
<div className="px-3 py-1.5 border-y border-surface-200 dark:border-surface-950 mb-1 mt-1">
|
|
1425
|
-
<Typography variant="caption" className="font-semibold uppercase tracking-wider text-[9px] text-text-disabled dark:text-text-disabled-dark">{t("studio_sql_role")}</Typography>
|
|
1426
|
-
</div>
|
|
1427
|
-
{availableRoles.map(role => (
|
|
1428
|
-
<MenuItem key={role} dense onClick={() => handleRoleChange(role)} className={cls("text-xs", selectedRole === role && "text-primary dark:text-primary-dark")}>
|
|
1429
|
-
{role}{role === "postgres" ? " " + t("studio_sql_collections_label") : ""}
|
|
1430
|
-
</MenuItem>
|
|
1431
|
-
))}
|
|
1432
|
-
</>
|
|
1433
|
-
)}
|
|
1434
|
-
</div>
|
|
1435
|
-
</Menu>
|
|
1436
|
-
|
|
1437
|
-
<Button
|
|
1438
|
-
onClick={() => handleRun()}
|
|
1439
|
-
disabled={loading}
|
|
1440
|
-
size="small"
|
|
1441
|
-
color="primary"
|
|
1442
|
-
>
|
|
1443
|
-
{loading ? <CircularProgress size="smallest" className="mr-2"/> : <PlayIcon size={iconSize.smallest} className="mr-2"/>}
|
|
1444
|
-
{t("studio_sql_run")}
|
|
1445
|
-
</Button>
|
|
1446
|
-
</div>
|
|
1447
|
-
</div>
|
|
1448
|
-
|
|
1449
|
-
<ResizablePanels
|
|
1450
|
-
orientation="vertical"
|
|
1451
|
-
panelSizePercent={editorHeight}
|
|
1452
|
-
onPanelSizeChange={setEditorHeight}
|
|
1453
|
-
minPanelSizePx={100}
|
|
1454
|
-
firstPanel={
|
|
1455
|
-
<div className="h-full w-full relative flex flex-col min-h-0">
|
|
1456
|
-
<MonacoEditor
|
|
1457
|
-
value={sql}
|
|
1458
|
-
onChange={(v) => setSql(v || "")}
|
|
1459
|
-
onRun={handleRun}
|
|
1460
|
-
schemas={schemas}
|
|
1461
|
-
/>
|
|
1462
|
-
</div>
|
|
1463
|
-
}
|
|
1464
|
-
secondPanel={
|
|
1465
|
-
<div className="h-full w-full flex flex-col bg-surface-50 dark:bg-surface-950 overflow-hidden min-h-0">
|
|
1466
|
-
<div className={cls("p-2 px-4 bg-surface-100 dark:bg-surface-900 border-b shrink-0 flex items-center", defaultBorderMixin)}>
|
|
1467
|
-
<Typography variant="caption" className="font-semibold text-text-disabled dark:text-text-disabled-dark uppercase tracking-widest text-[10px]">{t("studio_sql_query_results")}</Typography>
|
|
1468
|
-
</div>
|
|
1469
|
-
<div className="flex-grow flex flex-col min-h-0 overflow-hidden">
|
|
1470
|
-
{renderResults()}
|
|
1471
|
-
</div>
|
|
1472
|
-
</div>
|
|
1473
|
-
}
|
|
1474
|
-
/>
|
|
1475
|
-
|
|
1476
|
-
</div>
|
|
1477
|
-
}
|
|
1478
|
-
/>
|
|
1479
|
-
|
|
1480
|
-
<Dialog open={isSaveDialogOpen} onOpenChange={setIsSaveDialogOpen}>
|
|
1481
|
-
<DialogTitle>{t("studio_sql_save_snippet")}</DialogTitle>
|
|
1482
|
-
<DialogContent>
|
|
1483
|
-
<div className="py-4 flex flex-col gap-4">
|
|
1484
|
-
<TextField
|
|
1485
|
-
label={t("studio_sql_snippet_name")}
|
|
1486
|
-
autoFocus
|
|
1487
|
-
placeholder={t("studio_sql_snippet_name_placeholder")}
|
|
1488
|
-
value={newSnippetName}
|
|
1489
|
-
onChange={(e) => setNewSnippetName(e.target.value)}
|
|
1490
|
-
onKeyDown={(e) => {
|
|
1491
|
-
if (e.key === "Enter") {
|
|
1492
|
-
e.preventDefault();
|
|
1493
|
-
handleSaveSnippet();
|
|
1494
|
-
}
|
|
1495
|
-
}}
|
|
1496
|
-
/>
|
|
1497
|
-
<Typography variant="caption" className="text-text-disabled dark:text-text-disabled-dark block">{t("studio_sql_snippet_saved_local")}</Typography>
|
|
1498
|
-
</div>
|
|
1499
|
-
</DialogContent>
|
|
1500
|
-
<DialogActions>
|
|
1501
|
-
<Button variant="text" onClick={() => setIsSaveDialogOpen(false)}>{t("studio_sql_cancel")}</Button>
|
|
1502
|
-
<Button onClick={handleSaveSnippet} color="primary" disabled={!newSnippetName.trim()}>{t("studio_sql_save")}</Button>
|
|
1503
|
-
</DialogActions>
|
|
1504
|
-
</Dialog>
|
|
1505
|
-
{/* Confirmation Dialog */}
|
|
1506
|
-
<ConfirmationDialog
|
|
1507
|
-
open={isConfirmDialogOpen}
|
|
1508
|
-
onCancel={() => setIsConfirmDialogOpen(false)}
|
|
1509
|
-
title={t("studio_sql_dangerous_operation")}
|
|
1510
|
-
body={t("studio_sql_dangerous_operation_body")}
|
|
1511
|
-
onAccept={() => {
|
|
1512
|
-
if (pendingAction) pendingAction();
|
|
1513
|
-
setIsConfirmDialogOpen(false);
|
|
1514
|
-
}}
|
|
1515
|
-
/>
|
|
1516
|
-
</div>
|
|
1517
|
-
);
|
|
1518
|
-
};
|