@rebasepro/studio 0.35.1 → 0.36.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.
Files changed (91) hide show
  1. package/README.md +1 -1
  2. package/dist/{ApiExplorer-C61w8gCc.js → ApiExplorer-BVQHAjHB.js} +3 -2
  3. package/dist/{ApiExplorer-C61w8gCc.js.map → ApiExplorer-BVQHAjHB.js.map} +1 -1
  4. package/dist/{useRunAsUsers-CF7tkGzj.js → AuthSimulationSelector-XogpkeXC.js} +4 -68
  5. package/dist/AuthSimulationSelector-XogpkeXC.js.map +1 -0
  6. package/dist/{CronJobsView-DUuyzkJK.js → CronJobsView-DyX9MINh.js} +2 -2
  7. package/dist/{CronJobsView-DUuyzkJK.js.map → CronJobsView-DyX9MINh.js.map} +1 -1
  8. package/dist/DatabaseView-Bi0NZS90.js +1897 -0
  9. package/dist/DatabaseView-Bi0NZS90.js.map +1 -0
  10. package/dist/{JSEditor-Bi2Aol-Y.js → JSEditor-B4Lazm-z.js} +4 -3
  11. package/dist/{JSEditor-Bi2Aol-Y.js.map → JSEditor-B4Lazm-z.js.map} +1 -1
  12. package/dist/RLSEditor-CcHkWFNg.js +973 -0
  13. package/dist/RLSEditor-CcHkWFNg.js.map +1 -0
  14. package/dist/{SQLEditor-DRo5kW1h.js → SQLEditorRoute-f5j_ZKdj.js} +1472 -320
  15. package/dist/SQLEditorRoute-f5j_ZKdj.js.map +1 -0
  16. package/dist/SchemaDiagramView-CckQobIZ.js +98 -0
  17. package/dist/SchemaDiagramView-CckQobIZ.js.map +1 -0
  18. package/dist/{StorageView-D0D8z4lI.js → StorageView-B7QHjEGY.js} +2 -2
  19. package/dist/{StorageView-D0D8z4lI.js.map → StorageView-B7QHjEGY.js.map} +1 -1
  20. package/dist/TableEditorView-BRZNvD6U.js +3615 -0
  21. package/dist/TableEditorView-BRZNvD6U.js.map +1 -0
  22. package/dist/TablePolicies-C1-tbC8x.js +1740 -0
  23. package/dist/TablePolicies-C1-tbC8x.js.map +1 -0
  24. package/dist/{SchemaVisualizer-Dy4kWKT5.js → TablesDiagram-RTJfwVEN.js} +651 -489
  25. package/dist/TablesDiagram-RTJfwVEN.js.map +1 -0
  26. package/dist/{UsersAndRolesView-CKw4SJPj.js → UsersAndRolesView-Cx6xtMVH.js} +2 -2
  27. package/dist/{UsersAndRolesView-CKw4SJPj.js.map → UsersAndRolesView-Cx6xtMVH.js.map} +1 -1
  28. package/dist/{WebhooksView-CFPY-N9h.js → WebhooksView-Bn9KB7xG.js} +2 -2
  29. package/dist/{WebhooksView-CFPY-N9h.js.map → WebhooksView-Bn9KB7xG.js.map} +1 -1
  30. package/dist/{adminFetch-BfOnfRgU.js → adminFetch-C7Ra8rpP.js} +26 -1
  31. package/dist/{adminFetch-BfOnfRgU.js.map → adminFetch-C7Ra8rpP.js.map} +1 -1
  32. package/dist/components/Database/ActivitySection.d.ts +9 -0
  33. package/dist/components/Database/AdvisorsSection.d.ts +17 -0
  34. package/dist/components/Database/DatabaseView.d.ts +13 -0
  35. package/dist/components/Database/ExtensionsSection.d.ts +2 -0
  36. package/dist/components/Database/FunctionsSection.d.ts +2 -0
  37. package/dist/components/Database/QueriesSection.d.ts +3 -0
  38. package/dist/components/Database/TriggersSection.d.ts +2 -0
  39. package/dist/components/Database/TypesSection.d.ts +2 -0
  40. package/dist/components/Database/format.d.ts +6 -0
  41. package/dist/components/Database/links.d.ts +11 -0
  42. package/dist/components/Database/shared.d.ts +35 -0
  43. package/dist/components/Database/source.d.ts +12 -0
  44. package/dist/components/Database/useCatalogList.d.ts +13 -0
  45. package/dist/components/RLSEditor/RLSEditor.d.ts +2 -0
  46. package/dist/components/RLSEditor/TablePolicies.d.ts +54 -0
  47. package/dist/components/SQLEditor/ExplainVisualizer.d.ts +8 -20
  48. package/dist/components/SQLEditor/ResultChart.d.ts +18 -0
  49. package/dist/components/SQLEditor/SQLEditor.d.ts +13 -1
  50. package/dist/components/SQLEditor/SQLEditorRoute.d.ts +13 -0
  51. package/dist/components/SQLEditor/SQLEditorSidebar.d.ts +7 -1
  52. package/dist/components/SQLEditor/SqlParamsPanel.d.ts +16 -0
  53. package/dist/components/SQLEditor/useSqlSnippets.d.ts +47 -0
  54. package/dist/components/SchemaVisualizer/SchemaDiagramView.d.ts +12 -0
  55. package/dist/components/SchemaVisualizer/TablesDiagram.d.ts +23 -0
  56. package/dist/components/SchemaVisualizer/useSchemaGraph.d.ts +32 -1
  57. package/dist/components/TableEditor/CreateTableDialog.d.ts +8 -0
  58. package/dist/components/TableEditor/DdlConfirm.d.ts +23 -0
  59. package/dist/components/TableEditor/SqlBlock.d.ts +7 -0
  60. package/dist/components/TableEditor/TableDdlSheet.d.ts +9 -0
  61. package/dist/components/TableEditor/TableEditorView.d.ts +7 -0
  62. package/dist/components/TableEditor/tableModel.d.ts +210 -0
  63. package/dist/components/TableEditor/tabs/DataTab.d.ts +12 -0
  64. package/dist/components/TableEditor/tabs/PoliciesTab.d.ts +8 -0
  65. package/dist/components/TableEditor/tabs/RelationsTab.d.ts +8 -0
  66. package/dist/components/TableEditor/tabs/SettingsTab.d.ts +11 -0
  67. package/dist/components/TableEditor/tabs/StatsTab.d.ts +8 -0
  68. package/dist/components/TableEditor/tabs/StructureTab.d.ts +12 -0
  69. package/dist/index.es.js +29 -15
  70. package/dist/index.es.js.map +1 -1
  71. package/dist/{sql_utils-CYcgpgam.js → sql_utils-DkMYltfq.js} +27 -3
  72. package/dist/sql_utils-DkMYltfq.js.map +1 -0
  73. package/dist/useRunAsUsers-GPFCxcBC.js +69 -0
  74. package/dist/useRunAsUsers-GPFCxcBC.js.map +1 -0
  75. package/dist/utils/adminFetch.d.ts +1 -0
  76. package/dist/utils/csv_parse.d.ts +11 -0
  77. package/dist/utils/explain_plan.d.ts +70 -0
  78. package/dist/utils/sql_params.d.ts +51 -0
  79. package/dist/utils/sql_utils.d.ts +16 -0
  80. package/package.json +11 -9
  81. package/dist/RLSEditor-CTG3jLE7.js +0 -2572
  82. package/dist/RLSEditor-CTG3jLE7.js.map +0 -1
  83. package/dist/SQLEditor-DRo5kW1h.js.map +0 -1
  84. package/dist/SchemaVisualizer-Dy4kWKT5.js.map +0 -1
  85. package/dist/TableEditorView-BKhSBG-K.js +0 -1694
  86. package/dist/TableEditorView-BKhSBG-K.js.map +0 -1
  87. package/dist/components/SchemaVisualizer/SchemaVisualizer.d.ts +0 -3
  88. package/dist/policy-presets-CJKzAvQp.js +0 -167
  89. package/dist/policy-presets-CJKzAvQp.js.map +0 -1
  90. package/dist/sql_utils-CYcgpgam.js.map +0 -1
  91. package/dist/useRunAsUsers-CF7tkGzj.js.map +0 -1
@@ -1,10 +1,12 @@
1
- import { a as needsDestructiveConfirmation, c as rememberColumnWidth, d as resultsToCsv, f as tableStatementTemplates, h as withAutoLimit, i as keepLatestColumnWidths, l as resolveCellEdit, m as typedJsonRows, n as formatSql, o as quoteIdentifier, r as groupSchemaRows, s as quoteTableName, t as buildExplainSql, u as resolveQueryCollections } from "./sql_utils-CYcgpgam.js";
1
+ import { i as asString, o as isRecord$1, s as useAdminFetch, t as asBoolean } from "./adminFetch-C7Ra8rpP.js";
2
+ import { a as keepLatestColumnWidths, c as quoteTableName, d as resolveQueryCollections, f as resultsToCsv, g as withAutoLimit, h as typedJsonRows, i as groupSchemaRows, l as rememberColumnWidth, n as buildExplainSql, o as needsDestructiveConfirmation, p as tableStatementTemplates, r as formatSql, s as quoteIdentifier, t as buildExplainAnalyzeScript, u as resolveCellEdit } from "./sql_utils-DkMYltfq.js";
2
3
  import { t as MonacoEditor } from "./MonacoEditor-7IlHFZU5.js";
3
4
  import { t as FixedEditorOverlay } from "./FixedEditorOverlay-DtgPBSjq.js";
4
5
  import { ConfirmationDialog, ErrorView, IconForView, useApiBase, useApiConfig, useRebaseContext, useSnackbarController, useStudioCollectionRegistry, useStudioSidePanelController, useTableDescriptors, useTranslation } from "@rebasepro/app";
5
6
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
6
- import { Alert, Button, Checkbox, Chip, CircularProgress, Collapse, CopyIcon, DatabaseIcon, Dialog, DialogActions, DialogContent, DialogTitle, HeartIcon, IconButton, Menu, MenuIcon, MenuItem, MoreVerticalIcon, PencilIcon, PlayIcon, PlusIcon, RefreshCwIcon, ResizablePanels, SquareIcon, Tab, Tabs, TerminalIcon, TextField, Tooltip, Trash2Icon, Typography, VirtualTable, XIcon, cls, defaultBorderMixin, iconSize, isKeyHandled } from "@rebasepro/ui";
7
+ import { Alert, Button, Checkbox, ChevronDownIcon, Chip, CircularProgress, Collapse, CopyIcon, DatabaseIcon, Dialog, DialogActions, DialogContent, DialogTitle, HeartIcon, IconButton, Label, Menu, MenuIcon, MenuItem, MoreVerticalIcon, PencilIcon, PlayIcon, PlusIcon, RefreshCwIcon, ResizablePanels, SearchBar, Select, SelectItem, SquareIcon, Tab, Tabs, TerminalIcon, TextField, ToggleButtonGroup, Tooltip, Trash2Icon, Typography, VirtualTable, XIcon, cls, defaultBorderMixin, iconSize, isKeyHandled } from "@rebasepro/ui";
7
8
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
9
+ import { useSearchParams } from "react-router";
8
10
  import { isArrayValue, isRecordValue, readStoredJson, readStoredString, writeStoredJson, writeStoredString } from "@rebasepro/utils";
9
11
  //#region src/components/SQLEditor/SchemaBrowser.tsx
10
12
  var SchemaBrowser = ({ onTableClick, schemas, isSchemaLoading, schemaError, onRetrySchema }) => {
@@ -218,9 +220,68 @@ var SchemaBrowser = ({ onTableClick, schemas, isSchemaLoading, schemaError, onRe
218
220
  };
219
221
  //#endregion
220
222
  //#region src/components/SQLEditor/SQLEditorSidebar.tsx
221
- var SQLEditorSidebar = ({ onSelectSnippet, onTableClick, snippets, history, onDeleteSnippet, schemas, isSchemaLoading, schemaError, onRetrySchema }) => {
223
+ /** One saved snippet: its name and first line, opened on click, with its own favorite and delete controls. */
224
+ function SnippetCard({ snippet, onSelect, onDelete, onToggleFavorite }) {
225
+ const { t } = useTranslation();
226
+ return /* @__PURE__ */ jsxs("div", {
227
+ className: cls("group p-2 rounded-lg border bg-surface-card hover:bg-surface-card-hover transition-colors cursor-pointer flex items-start gap-1", defaultBorderMixin),
228
+ onClick: () => onSelect(snippet.sql),
229
+ children: [
230
+ /* @__PURE__ */ jsxs("div", {
231
+ className: "min-w-0 flex-grow",
232
+ children: [/* @__PURE__ */ jsxs("div", {
233
+ className: "flex items-center gap-1.5 min-w-0",
234
+ children: [/* @__PURE__ */ jsx(Typography, {
235
+ variant: "body2",
236
+ className: "font-medium text-[13px] truncate",
237
+ children: snippet.name
238
+ }), snippet.visibility === "team" && /* @__PURE__ */ jsx(Chip, {
239
+ size: "smallest",
240
+ className: "shrink-0",
241
+ children: t("studio_sql_snippet_team")
242
+ })]
243
+ }), /* @__PURE__ */ jsx(Typography, {
244
+ variant: "caption",
245
+ color: "secondary",
246
+ className: "text-xs block mt-1 truncate font-mono",
247
+ children: snippet.sql
248
+ })]
249
+ }),
250
+ onToggleFavorite && /* @__PURE__ */ jsx(IconButton, {
251
+ "aria-label": snippet.isFavorite ? t("studio_sql_remove_from_favorites") : t("studio_sql_add_to_favorites"),
252
+ size: "smallest",
253
+ onClick: (e) => {
254
+ e.stopPropagation();
255
+ onToggleFavorite(snippet);
256
+ },
257
+ children: /* @__PURE__ */ jsx(HeartIcon, {
258
+ size: iconSize.smallest,
259
+ fill: snippet.isFavorite ? "currentColor" : "none",
260
+ className: snippet.isFavorite ? "text-red-500" : "text-text-disabled dark:text-text-disabled-dark"
261
+ })
262
+ }),
263
+ /* @__PURE__ */ jsx(IconButton, {
264
+ "aria-label": t("studio_sql_sidebar_delete_snippet"),
265
+ size: "smallest",
266
+ className: "text-text-disabled dark:text-text-disabled-dark hover:text-red-500",
267
+ onClick: (e) => {
268
+ e.stopPropagation();
269
+ onDelete(snippet.id);
270
+ },
271
+ children: /* @__PURE__ */ jsx(Trash2Icon, { size: iconSize.smallest })
272
+ })
273
+ ]
274
+ });
275
+ }
276
+ var SQLEditorSidebar = ({ onSelectSnippet, onTableClick, snippets, history, onDeleteSnippet, onToggleFavorite, schemas, isSchemaLoading, schemaError, onRetrySchema }) => {
222
277
  const [activeTab, setActiveTab] = useState("schema");
278
+ const [historySearch, setHistorySearch] = useState("");
223
279
  const { t } = useTranslation();
280
+ const matchingHistory = useMemo(() => {
281
+ const needle = historySearch.trim().toLowerCase();
282
+ const newestFirst = [...history].reverse();
283
+ return needle ? newestFirst.filter((sql) => sql.toLowerCase().includes(needle)) : newestFirst;
284
+ }, [history, historySearch]);
224
285
  return /* @__PURE__ */ jsxs("div", {
225
286
  className: cls("flex flex-col h-full w-full bg-surface-card border-r", defaultBorderMixin),
226
287
  children: [/* @__PURE__ */ jsxs(Tabs, {
@@ -287,67 +348,27 @@ var SQLEditorSidebar = ({ onSelectSnippet, onTableClick, snippets, history, onDe
287
348
  d: "M3.172 5.172a4 4 0 015.656 0L10 6.343l1.172-1.171a4 4 0 115.656 5.656L10 17.657l-6.828-6.829a4 4 0 010-5.656z",
288
349
  clipRule: "evenodd"
289
350
  })
290
- }), "Favorites"]
351
+ }), t("studio_sql_sidebar_favorites")]
291
352
  }), /* @__PURE__ */ jsx("div", {
292
353
  className: "space-y-2",
293
- children: favorites.map((snippet) => /* @__PURE__ */ jsxs("div", {
294
- className: cls("group p-2 rounded border hover:border-hairline-strong bg-surface-card transition-all cursor-pointer relative", defaultBorderMixin),
295
- onClick: () => onSelectSnippet(snippet.sql),
296
- children: [
297
- /* @__PURE__ */ jsx(Typography, {
298
- variant: "body2",
299
- className: "text-text-primary dark:text-text-primary-dark font-medium text-[13px] truncate pr-6",
300
- children: snippet.name
301
- }),
302
- /* @__PURE__ */ jsx(Typography, {
303
- variant: "caption",
304
- className: "text-text-secondary dark:text-text-secondary-dark text-xs block mt-1 truncate",
305
- children: snippet.sql
306
- }),
307
- /* @__PURE__ */ jsx(IconButton, {
308
- "aria-label": t("studio_sql_sidebar_delete_snippet"),
309
- size: "smallest",
310
- className: "absolute right-1 top-1 opacity-0 group-hover:opacity-100 text-text-disabled hover:text-red-500 transition-opacity",
311
- onClick: (e) => {
312
- e.stopPropagation();
313
- onDeleteSnippet(snippet.id);
314
- },
315
- children: /* @__PURE__ */ jsx(Trash2Icon, { size: iconSize.smallest })
316
- })
317
- ]
354
+ children: favorites.map((snippet) => /* @__PURE__ */ jsx(SnippetCard, {
355
+ snippet,
356
+ onSelect: onSelectSnippet,
357
+ onDelete: onDeleteSnippet,
358
+ onToggleFavorite
318
359
  }, snippet.id))
319
360
  })]
320
361
  }), others.length > 0 && /* @__PURE__ */ jsxs("div", { children: [favorites.length > 0 && /* @__PURE__ */ jsx(Typography, {
321
362
  variant: "caption",
322
363
  className: "text-[10px] font-semibold uppercase tracking-wider text-text-disabled dark:text-text-disabled-dark mb-2 px-1 mt-4",
323
- children: "Others"
364
+ children: t("studio_sql_sidebar_other_snippets")
324
365
  }), /* @__PURE__ */ jsx("div", {
325
366
  className: "space-y-2",
326
- children: others.map((snippet) => /* @__PURE__ */ jsxs("div", {
327
- className: cls("group p-2 rounded border hover:border-hairline-strong bg-surface-card transition-all cursor-pointer relative", defaultBorderMixin),
328
- onClick: () => onSelectSnippet(snippet.sql),
329
- children: [
330
- /* @__PURE__ */ jsx(Typography, {
331
- variant: "body2",
332
- className: "text-text-primary dark:text-text-primary-dark font-medium text-[13px] truncate pr-6",
333
- children: snippet.name
334
- }),
335
- /* @__PURE__ */ jsx(Typography, {
336
- variant: "caption",
337
- className: "text-text-secondary dark:text-text-secondary-dark text-xs block mt-1 truncate",
338
- children: snippet.sql
339
- }),
340
- /* @__PURE__ */ jsx(IconButton, {
341
- "aria-label": t("studio_sql_sidebar_delete_snippet"),
342
- size: "smallest",
343
- className: "absolute right-1 top-1 opacity-0 group-hover:opacity-100 text-text-disabled hover:text-red-500 transition-opacity",
344
- onClick: (e) => {
345
- e.stopPropagation();
346
- onDeleteSnippet(snippet.id);
347
- },
348
- children: /* @__PURE__ */ jsx(Trash2Icon, { size: iconSize.smallest })
349
- })
350
- ]
367
+ children: others.map((snippet) => /* @__PURE__ */ jsx(SnippetCard, {
368
+ snippet,
369
+ onSelect: onSelectSnippet,
370
+ onDelete: onDeleteSnippet,
371
+ onToggleFavorite
351
372
  }, snippet.id))
352
373
  })] })] })
353
374
  })]
@@ -355,191 +376,1003 @@ var SQLEditorSidebar = ({ onSelectSnippet, onTableClick, snippets, history, onDe
355
376
  })(),
356
377
  activeTab === "history" && /* @__PURE__ */ jsxs("div", {
357
378
  className: "flex flex-col h-full",
358
- children: [/* @__PURE__ */ jsx("div", {
359
- className: cls("flex items-center justify-between px-3 py-2 border-b bg-surface-sheet h-10 shrink-0", defaultBorderMixin),
360
- children: /* @__PURE__ */ jsx(Typography, {
361
- variant: "caption",
362
- className: "font-semibold uppercase tracking-wider text-text-disabled dark:text-text-disabled-dark",
363
- children: t("studio_sql_sidebar_history")
364
- })
365
- }), /* @__PURE__ */ jsx("div", {
366
- className: "flex-grow overflow-y-auto p-1 space-y-1 no-scrollbar",
367
- children: history.length === 0 ? /* @__PURE__ */ jsx("div", {
368
- className: "p-4 text-center",
379
+ children: [
380
+ /* @__PURE__ */ jsx("div", {
381
+ className: cls("flex items-center justify-between px-3 py-2 border-b bg-surface-sheet h-10 shrink-0", defaultBorderMixin),
369
382
  children: /* @__PURE__ */ jsx(Typography, {
370
383
  variant: "caption",
371
- className: "text-text-disabled dark:text-text-disabled-dark",
372
- children: t("studio_sql_sidebar_no_history")
384
+ className: "font-semibold uppercase tracking-wider text-text-disabled dark:text-text-disabled-dark",
385
+ children: t("studio_sql_sidebar_history")
373
386
  })
374
- }) : [...history].reverse().map((sql, i) => /* @__PURE__ */ jsxs("div", {
375
- className: "p-2 py-1.5 rounded hover:bg-surface-hover cursor-pointer group transition-colors flex items-start",
376
- onClick: () => onSelectSnippet(sql),
377
- children: [/* @__PURE__ */ jsx("svg", {
378
- className: "w-3 h-3 mt-1 mr-2 text-text-disabled dark:text-text-disabled-dark group-hover:text-primary transition-colors flex-shrink-0",
379
- fill: "none",
380
- stroke: "currentColor",
381
- viewBox: "0 0 24 24",
382
- children: /* @__PURE__ */ jsx("path", {
383
- strokeLinecap: "round",
384
- strokeLinejoin: "round",
385
- strokeWidth: 2,
386
- d: "M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
387
+ }),
388
+ history.length > 0 && /* @__PURE__ */ jsx("div", {
389
+ className: "px-2 pt-2 shrink-0",
390
+ children: /* @__PURE__ */ jsx(SearchBar, {
391
+ size: "small",
392
+ placeholder: t("studio_sql_sidebar_search_history"),
393
+ onTextSearch: (value) => setHistorySearch(value ?? "")
394
+ })
395
+ }),
396
+ /* @__PURE__ */ jsx("div", {
397
+ className: "flex-grow overflow-y-auto p-1 space-y-1 no-scrollbar",
398
+ children: history.length === 0 ? /* @__PURE__ */ jsx("div", {
399
+ className: "p-4 text-center",
400
+ children: /* @__PURE__ */ jsx(Typography, {
401
+ variant: "caption",
402
+ className: "text-text-disabled dark:text-text-disabled-dark",
403
+ children: t("studio_sql_sidebar_no_history")
387
404
  })
388
- }), /* @__PURE__ */ jsx(Typography, {
389
- variant: "caption",
390
- className: "text-text-secondary dark:text-text-secondary-dark group-hover:text-text-primary dark:group-hover:text-text-primary-dark text-xs line-clamp-2 leading-tight flex-grow",
391
- children: sql
392
- })]
393
- }, i))
394
- })]
405
+ }) : matchingHistory.length === 0 ? /* @__PURE__ */ jsx("div", {
406
+ className: "p-4 text-center",
407
+ children: /* @__PURE__ */ jsx(Typography, {
408
+ variant: "caption",
409
+ className: "text-text-disabled dark:text-text-disabled-dark",
410
+ children: t("studio_sql_sidebar_no_history_match")
411
+ })
412
+ }) : matchingHistory.map((sql, i) => /* @__PURE__ */ jsxs("div", {
413
+ className: "p-2 py-1.5 rounded hover:bg-surface-hover cursor-pointer group transition-colors flex items-start",
414
+ onClick: () => onSelectSnippet(sql),
415
+ children: [/* @__PURE__ */ jsx("svg", {
416
+ className: "w-3 h-3 mt-1 mr-2 text-text-disabled dark:text-text-disabled-dark group-hover:text-primary transition-colors flex-shrink-0",
417
+ fill: "none",
418
+ stroke: "currentColor",
419
+ viewBox: "0 0 24 24",
420
+ children: /* @__PURE__ */ jsx("path", {
421
+ strokeLinecap: "round",
422
+ strokeLinejoin: "round",
423
+ strokeWidth: 2,
424
+ d: "M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
425
+ })
426
+ }), /* @__PURE__ */ jsx(Typography, {
427
+ variant: "caption",
428
+ className: "text-text-secondary dark:text-text-secondary-dark group-hover:text-text-primary dark:group-hover:text-text-primary-dark text-xs line-clamp-2 leading-tight flex-grow",
429
+ children: sql
430
+ })]
431
+ }, i))
432
+ })
433
+ ]
395
434
  })
396
435
  ]
397
436
  })]
398
437
  });
399
438
  };
400
439
  //#endregion
440
+ //#region src/utils/explain_plan.ts
441
+ function isRecord(value) {
442
+ return typeof value === "object" && value !== null && !Array.isArray(value);
443
+ }
444
+ function isPlanNode(value) {
445
+ return isRecord(value) && typeof value["Node Type"] === "string" && typeof value["Total Cost"] === "number" && typeof value["Startup Cost"] === "number";
446
+ }
447
+ /**
448
+ * The plan in a result's `QUERY PLAN` value — an array (an admin read parses
449
+ * json) or the JSON text the console's script door returns — or `null` when
450
+ * the value is not one.
451
+ */
452
+ function readExplainResult(value) {
453
+ let parsed = value;
454
+ if (typeof value === "string") try {
455
+ parsed = JSON.parse(value);
456
+ } catch {
457
+ return null;
458
+ }
459
+ const entry = Array.isArray(parsed) ? parsed[0] : void 0;
460
+ if (!isRecord(entry) || !isPlanNode(entry.Plan)) return null;
461
+ const plan = entry.Plan;
462
+ return {
463
+ plan,
464
+ planningTime: typeof entry["Planning Time"] === "number" ? entry["Planning Time"] : void 0,
465
+ executionTime: typeof entry["Execution Time"] === "number" ? entry["Execution Time"] : void 0,
466
+ analyzed: typeof plan["Actual Total Time"] === "number"
467
+ };
468
+ }
469
+ /** The `QUERY PLAN` cell of a result, when the rows are a single plan. */
470
+ function explainResultOfRows(rows) {
471
+ if (!rows || rows.length !== 1 || !("QUERY PLAN" in rows[0])) return null;
472
+ return readExplainResult(rows[0]["QUERY PLAN"]);
473
+ }
474
+ /**
475
+ * Milliseconds the node spent on its own, over all its loops: its total time
476
+ * less its children's. Postgres reports `Actual Total Time` per loop, so each
477
+ * is multiplied by its loops first. Never below zero — a parallel node's
478
+ * children can add up to more than it, timed on other workers.
479
+ */
480
+ function exclusiveTime(node) {
481
+ const total = (node["Actual Total Time"] ?? 0) * (node["Actual Loops"] ?? 1);
482
+ const children = (node.Plans ?? []).reduce((sum, child) => sum + (child["Actual Total Time"] ?? 0) * (child["Actual Loops"] ?? 1), 0);
483
+ return Math.max(0, total - children);
484
+ }
485
+ /**
486
+ * The nodes that took the most time of their own, slowest first: at most
487
+ * `count`, and only ones that took at least `minShare` of the whole run — a
488
+ * sort that took a fraction of a millisecond beside a 40 ms scan is not one of
489
+ * "the slowest" however few nodes there are. Empty for a plan that did not run.
490
+ */
491
+ function slowestNodes(plan, count = 3, minShare = .05) {
492
+ const nodes = [];
493
+ const visit = (node) => {
494
+ nodes.push(node);
495
+ node.Plans?.forEach(visit);
496
+ };
497
+ visit(plan);
498
+ const total = (plan["Actual Total Time"] ?? 0) * (plan["Actual Loops"] ?? 1);
499
+ return nodes.filter((node) => typeof node["Actual Total Time"] === "number" && exclusiveTime(node) > 0 && exclusiveTime(node) >= total * minShare).sort((a, b) => exclusiveTime(b) - exclusiveTime(a)).slice(0, count);
500
+ }
501
+ /** The shared and temp blocks a node touched, as `BUFFERS` reports them; `null` when it reported none. */
502
+ function nodeBuffers(node) {
503
+ if (![
504
+ "Shared Hit Blocks",
505
+ "Shared Read Blocks",
506
+ "Shared Dirtied Blocks",
507
+ "Shared Written Blocks",
508
+ "Temp Read Blocks",
509
+ "Temp Written Blocks"
510
+ ].some((field) => typeof node[field] === "number")) return null;
511
+ return {
512
+ hit: node["Shared Hit Blocks"] ?? 0,
513
+ read: node["Shared Read Blocks"] ?? 0,
514
+ dirtied: node["Shared Dirtied Blocks"] ?? 0,
515
+ written: node["Shared Written Blocks"] ?? 0,
516
+ temp: (node["Temp Read Blocks"] ?? 0) + (node["Temp Written Blocks"] ?? 0)
517
+ };
518
+ }
519
+ //#endregion
401
520
  //#region src/components/SQLEditor/ExplainVisualizer.tsx
402
- var ExplainVisualizer = ({ plan, isRoot = true }) => {
521
+ /** Milliseconds as the plan view prints them: three significant places below ten. */
522
+ function formatMs(ms) {
523
+ return `${ms < 10 ? ms.toFixed(3) : ms.toFixed(1)} ms`;
524
+ }
525
+ /**
526
+ * A plan, node by node. For a plan that ran (`ANALYZE`) each node says its
527
+ * actual time, rows and loops and the buffers it touched, and the nodes that
528
+ * took the most time of their own are marked, slowest first.
529
+ */
530
+ var ExplainVisualizer = ({ result }) => {
531
+ const { t } = useTranslation();
532
+ const slowest = useMemo(() => new Map(slowestNodes(result.plan).map((node, index) => [node, index + 1])), [result.plan]);
533
+ const timed = result.executionTime ?? result.plan["Actual Total Time"];
534
+ return /* @__PURE__ */ jsxs("div", {
535
+ className: "flex flex-col gap-3 p-4",
536
+ children: [result.analyzed && /* @__PURE__ */ jsxs("div", {
537
+ className: "flex flex-wrap items-center gap-4",
538
+ children: [
539
+ result.planningTime !== void 0 && /* @__PURE__ */ jsx(Metric, {
540
+ label: t("studio_sql_explain_planning_time"),
541
+ value: formatMs(result.planningTime)
542
+ }),
543
+ result.executionTime !== void 0 && /* @__PURE__ */ jsx(Metric, {
544
+ label: t("studio_sql_explain_execution_time"),
545
+ value: formatMs(result.executionTime)
546
+ }),
547
+ slowest.size > 0 && /* @__PURE__ */ jsx(Typography, {
548
+ variant: "caption",
549
+ color: "secondary",
550
+ children: t("studio_sql_explain_slowest_hint")
551
+ })
552
+ ]
553
+ }), /* @__PURE__ */ jsx(PlanNode, {
554
+ node: result.plan,
555
+ isRoot: true,
556
+ slowest,
557
+ totalTime: timed
558
+ })]
559
+ });
560
+ };
561
+ function Metric({ label, value, emphasis }) {
562
+ return /* @__PURE__ */ jsxs("div", {
563
+ className: "flex flex-col text-right",
564
+ children: [/* @__PURE__ */ jsx(Typography, {
565
+ variant: "caption",
566
+ color: "disabled",
567
+ className: "leading-tight",
568
+ children: label
569
+ }), /* @__PURE__ */ jsx(Typography, {
570
+ variant: "mono",
571
+ className: cls("text-[13px] leading-tight", emphasis && "font-medium"),
572
+ children: value
573
+ })]
574
+ });
575
+ }
576
+ function Detail({ label, children }) {
577
+ return /* @__PURE__ */ jsxs("div", {
578
+ className: "flex items-center gap-2",
579
+ children: [/* @__PURE__ */ jsx(Typography, {
580
+ variant: "caption",
581
+ color: "disabled",
582
+ children: label
583
+ }), /* @__PURE__ */ jsx(Typography, {
584
+ variant: "mono",
585
+ className: "text-[12px]",
586
+ children
587
+ })]
588
+ });
589
+ }
590
+ function Condition({ label, text }) {
591
+ return /* @__PURE__ */ jsxs("div", {
592
+ className: "flex flex-col gap-1",
593
+ children: [/* @__PURE__ */ jsx(Typography, {
594
+ variant: "caption",
595
+ color: "disabled",
596
+ children: label
597
+ }), /* @__PURE__ */ jsx(Typography, {
598
+ variant: "mono",
599
+ className: "block w-full p-2 bg-surface-field rounded-md text-[12px] truncate",
600
+ title: text,
601
+ children: text
602
+ })]
603
+ });
604
+ }
605
+ var PlanNode = ({ node, isRoot = false, slowest, totalTime }) => {
606
+ const { t } = useTranslation();
403
607
  const [expanded, setExpanded] = useState(true);
404
- const hasChildren = plan.Plans && plan.Plans.length > 0;
405
- const cost = plan["Total Cost"];
406
- let costColor = "text-green-500 dark:text-green-400";
407
- if (cost > 1e3) costColor = "text-red-500 dark:text-red-400";
408
- else if (cost > 100) costColor = "text-orange-500 dark:text-orange-400";
608
+ const hasChildren = (node.Plans?.length ?? 0) > 0;
609
+ const analyzed = typeof node["Actual Total Time"] === "number";
610
+ const rank = slowest.get(node);
611
+ const own = analyzed ? exclusiveTime(node) : void 0;
612
+ const share = own !== void 0 && totalTime ? Math.min(100, own / totalTime * 100) : void 0;
613
+ const buffers = nodeBuffers(node);
614
+ const loops = node["Actual Loops"] ?? 1;
615
+ const actualRows = node["Actual Rows"];
616
+ const misestimate = actualRows !== void 0 && node["Plan Rows"] > 0 ? Math.max(actualRows, 1) / Math.max(node["Plan Rows"], 1) : void 0;
617
+ const badEstimate = misestimate !== void 0 && (misestimate > 10 || misestimate < .1);
409
618
  return /* @__PURE__ */ jsxs("div", {
410
- className: cls("flex flex-col", isRoot ? "p-4" : "pl-6 mt-2 relative"),
619
+ className: cls("flex flex-col", !isRoot && "pl-6 mt-2 relative"),
411
620
  children: [
412
- !isRoot && /* @__PURE__ */ jsx("div", { className: "absolute left-2.5 top-0 bottom-0 w-px bg-hairline -z-10" }),
413
- !isRoot && /* @__PURE__ */ jsx("div", { className: "absolute left-2.5 top-5 w-3 h-px bg-hairline -z-10" }),
621
+ !isRoot && /* @__PURE__ */ jsx("div", { className: "absolute left-2.5 top-0 bottom-0 w-px bg-hairline" }),
622
+ !isRoot && /* @__PURE__ */ jsx("div", { className: "absolute left-2.5 top-5 w-3 h-px bg-hairline" }),
414
623
  /* @__PURE__ */ jsxs("div", {
415
- className: cls("border rounded-md bg-surface-card text-text-primary dark:text-text-primary-dark shadow-xs relative z-10 w-[420px] max-w-full", defaultBorderMixin),
416
- children: [/* @__PURE__ */ jsxs("div", {
417
- className: cls("px-4 py-3 flex justify-between items-center cursor-pointer select-none"),
624
+ className: cls("border rounded-xl bg-surface-card relative w-[480px] max-w-full", defaultBorderMixin, rank !== void 0 && "ring-1 ring-orange-500/60"),
625
+ children: [/* @__PURE__ */ jsxs("button", {
626
+ type: "button",
627
+ className: "w-full px-4 py-3 flex justify-between items-center gap-3 text-left select-none",
628
+ "aria-expanded": expanded,
418
629
  onClick: () => setExpanded(!expanded),
419
630
  children: [/* @__PURE__ */ jsxs("div", {
420
- className: "flex items-center space-x-2",
631
+ className: "flex items-center gap-2 min-w-0",
421
632
  children: [
422
- hasChildren ? /* @__PURE__ */ jsx("svg", {
423
- className: cls("w-4 h-4 text-text-secondary transition-transform", !expanded ? "-rotate-90" : ""),
424
- fill: "none",
425
- stroke: "currentColor",
426
- viewBox: "0 0 24 24",
427
- children: /* @__PURE__ */ jsx("path", {
428
- strokeLinecap: "round",
429
- strokeLinejoin: "round",
430
- strokeWidth: 2,
431
- d: "M19 9l-7 7-7-7"
432
- })
433
- }) : /* @__PURE__ */ jsx("div", { className: "w-4 h-4" }),
633
+ hasChildren ? /* @__PURE__ */ jsx(ChevronDownIcon, {
634
+ size: iconSize.smallest,
635
+ className: cls("text-text-secondary transition-transform shrink-0", !expanded && "-rotate-90")
636
+ }) : /* @__PURE__ */ jsx("span", { className: "w-4 shrink-0" }),
434
637
  /* @__PURE__ */ jsx(Typography, {
435
- variant: "body1",
436
- className: "flex items-center",
437
- children: plan["Node Type"]
638
+ variant: "body2",
639
+ className: "font-medium shrink-0",
640
+ children: node["Node Type"]
438
641
  }),
439
- plan["Relation Name"] && /* @__PURE__ */ jsxs("span", {
440
- className: "font-mono text-xs text-text-secondary dark:text-text-secondary-dark px-2 py-0.5 rounded bg-hairline ml-2",
441
- children: [
442
- "on ",
443
- plan["Relation Name"],
444
- " ",
445
- plan.Alias && plan.Alias !== plan["Relation Name"] ? `(${plan.Alias})` : ""
446
- ]
642
+ node["Relation Name"] && /* @__PURE__ */ jsx(Typography, {
643
+ variant: "caption",
644
+ color: "secondary",
645
+ className: "font-mono truncate",
646
+ children: t("studio_sql_explain_on_relation", { relation: node.Alias && node.Alias !== node["Relation Name"] ? `${node["Relation Name"]} (${node.Alias})` : node["Relation Name"] })
647
+ }),
648
+ rank !== void 0 && /* @__PURE__ */ jsx(Chip, {
649
+ size: "smallest",
650
+ colorScheme: "orangeLighter",
651
+ className: "shrink-0",
652
+ children: t("studio_sql_explain_slowest_rank", { rank })
447
653
  })
448
654
  ]
449
655
  }), /* @__PURE__ */ jsxs("div", {
450
- className: "flex space-x-6 items-center",
451
- children: [/* @__PURE__ */ jsxs("div", {
452
- className: "flex flex-col text-right",
453
- children: [/* @__PURE__ */ jsx("span", {
454
- className: "text-[10px] uppercase text-text-disabled dark:text-text-disabled-dark font-semibold tracking-wide leading-tight mb-0.5",
455
- children: "Cost"
456
- }), /* @__PURE__ */ jsx("span", {
457
- className: cls("font-mono font-medium text-[13px] leading-none", costColor),
458
- children: cost.toFixed(2)
459
- })]
460
- }), /* @__PURE__ */ jsxs("div", {
461
- className: "flex flex-col text-right",
462
- children: [/* @__PURE__ */ jsx("span", {
463
- className: "text-[10px] uppercase text-text-disabled dark:text-text-disabled-dark font-semibold tracking-wide leading-tight mb-0.5",
464
- children: "Rows"
465
- }), /* @__PURE__ */ jsx("span", {
466
- className: "font-mono text-[13px] text-text-secondary dark:text-text-secondary-dark leading-none",
467
- children: plan["Plan Rows"]
468
- })]
656
+ className: "flex gap-5 items-center shrink-0",
657
+ children: [analyzed && own !== void 0 ? /* @__PURE__ */ jsx(Metric, {
658
+ label: t("studio_sql_explain_own_time"),
659
+ value: `${formatMs(own)}${share !== void 0 ? ` · ${share.toFixed(0)}%` : ""}`,
660
+ emphasis: rank !== void 0
661
+ }) : /* @__PURE__ */ jsx(Metric, {
662
+ label: t("studio_sql_explain_cost"),
663
+ value: node["Total Cost"].toFixed(2)
664
+ }), /* @__PURE__ */ jsx(Metric, {
665
+ label: t("studio_sql_explain_rows"),
666
+ value: actualRows !== void 0 ? `${actualRows} / ${node["Plan Rows"]}` : String(node["Plan Rows"])
469
667
  })]
470
668
  })]
471
669
  }), /* @__PURE__ */ jsx(Collapse, {
472
670
  in: expanded,
473
671
  children: /* @__PURE__ */ jsxs("div", {
474
- className: "px-4 py-3 border-t border-hairline text-[13px] flex flex-col gap-2",
672
+ className: "px-4 py-3 border-t border-hairline flex flex-col gap-2",
475
673
  children: [
476
674
  /* @__PURE__ */ jsxs("div", {
477
- className: "flex items-center space-x-6",
478
- children: [/* @__PURE__ */ jsxs("div", {
479
- className: "flex items-center space-x-2",
480
- children: [/* @__PURE__ */ jsx("span", {
481
- className: "text-text-disabled dark:text-text-disabled-dark",
482
- children: "Startup Cost:"
483
- }), /* @__PURE__ */ jsx("span", {
484
- className: "font-mono font-medium",
485
- children: plan["Startup Cost"].toFixed(2)
486
- })]
487
- }), /* @__PURE__ */ jsxs("div", {
488
- className: "flex items-center space-x-2",
489
- children: [/* @__PURE__ */ jsx("span", {
490
- className: "text-text-disabled dark:text-text-disabled-dark",
491
- children: "Width:"
492
- }), /* @__PURE__ */ jsxs("span", {
493
- className: "font-mono font-medium",
494
- children: [plan["Plan Width"], " bytes"]
495
- })]
496
- })]
675
+ className: "flex flex-wrap items-center gap-x-5 gap-y-1",
676
+ children: [
677
+ /* @__PURE__ */ jsx(Detail, {
678
+ label: t("studio_sql_explain_cost"),
679
+ children: `${node["Startup Cost"].toFixed(2)}..${node["Total Cost"].toFixed(2)}`
680
+ }),
681
+ /* @__PURE__ */ jsx(Detail, {
682
+ label: t("studio_sql_explain_width"),
683
+ children: `${node["Plan Width"]} B`
684
+ }),
685
+ analyzed && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Detail, {
686
+ label: t("studio_sql_explain_actual_time"),
687
+ children: `${node["Actual Startup Time"]?.toFixed(3) ?? "0"}..${node["Actual Total Time"]?.toFixed(3)} ms`
688
+ }), /* @__PURE__ */ jsx(Detail, {
689
+ label: t("studio_sql_explain_loops"),
690
+ children: loops
691
+ })] }),
692
+ node["Rows Removed by Filter"] !== void 0 && /* @__PURE__ */ jsx(Detail, {
693
+ label: t("studio_sql_explain_rows_removed"),
694
+ children: node["Rows Removed by Filter"]
695
+ })
696
+ ]
497
697
  }),
498
- plan.Filter && /* @__PURE__ */ jsxs("div", {
499
- className: "mt-1",
500
- children: [/* @__PURE__ */ jsx("span", {
501
- className: "text-text-disabled dark:text-text-disabled-dark block mb-1",
502
- children: "Filter:"
503
- }), /* @__PURE__ */ jsx("code", {
504
- className: "block w-full p-2 bg-surface-well border border-hairline rounded font-mono text-[12px] truncate",
505
- children: plan.Filter
506
- })]
698
+ badEstimate && actualRows !== void 0 && /* @__PURE__ */ jsx(Typography, {
699
+ variant: "caption",
700
+ color: "secondary",
701
+ children: t("studio_sql_explain_misestimate", {
702
+ planned: node["Plan Rows"],
703
+ actual: actualRows
704
+ })
507
705
  }),
508
- plan["Index Cond"] && /* @__PURE__ */ jsxs("div", {
509
- className: "mt-1",
510
- children: [/* @__PURE__ */ jsx("span", {
511
- className: "text-text-disabled dark:text-text-disabled-dark block mb-1",
512
- children: "Index Cond:"
513
- }), /* @__PURE__ */ jsx("code", {
514
- className: "block w-full p-2 bg-surface-well border border-hairline rounded font-mono text-[12px] truncate",
515
- children: plan["Index Cond"]
516
- })]
706
+ buffers && /* @__PURE__ */ jsxs("div", {
707
+ className: "flex flex-wrap items-center gap-x-5 gap-y-1",
708
+ children: [
709
+ /* @__PURE__ */ jsx(Detail, {
710
+ label: t("studio_sql_explain_buffers_hit"),
711
+ children: buffers.hit
712
+ }),
713
+ /* @__PURE__ */ jsx(Detail, {
714
+ label: t("studio_sql_explain_buffers_read"),
715
+ children: buffers.read
716
+ }),
717
+ buffers.dirtied > 0 && /* @__PURE__ */ jsx(Detail, {
718
+ label: t("studio_sql_explain_buffers_dirtied"),
719
+ children: buffers.dirtied
720
+ }),
721
+ buffers.written > 0 && /* @__PURE__ */ jsx(Detail, {
722
+ label: t("studio_sql_explain_buffers_written"),
723
+ children: buffers.written
724
+ }),
725
+ buffers.temp > 0 && /* @__PURE__ */ jsx(Detail, {
726
+ label: t("studio_sql_explain_buffers_temp"),
727
+ children: buffers.temp
728
+ })
729
+ ]
517
730
  }),
518
- plan["Hash Cond"] && /* @__PURE__ */ jsxs("div", {
519
- className: "mt-1",
520
- children: [/* @__PURE__ */ jsx("span", {
521
- className: "text-text-disabled dark:text-text-disabled-dark block mb-1",
522
- children: "Hash Cond:"
523
- }), /* @__PURE__ */ jsx("code", {
524
- className: "block w-full p-2 bg-surface-well border border-hairline rounded font-mono text-[12px] truncate",
525
- children: plan["Hash Cond"]
526
- })]
731
+ node.Filter && /* @__PURE__ */ jsx(Condition, {
732
+ label: t("studio_sql_explain_filter"),
733
+ text: node.Filter
734
+ }),
735
+ node["Index Cond"] && /* @__PURE__ */ jsx(Condition, {
736
+ label: t("studio_sql_explain_index_cond"),
737
+ text: node["Index Cond"]
738
+ }),
739
+ node["Hash Cond"] && /* @__PURE__ */ jsx(Condition, {
740
+ label: t("studio_sql_explain_hash_cond"),
741
+ text: node["Hash Cond"]
527
742
  })
528
743
  ]
529
744
  })
530
745
  })]
531
746
  }),
532
747
  expanded && hasChildren && /* @__PURE__ */ jsx("div", {
533
- className: "flex flex-col space-y-2 mt-[-4px]",
534
- children: plan.Plans.map((childPlan, idx) => /* @__PURE__ */ jsx(ExplainVisualizer, {
535
- plan: childPlan,
536
- isRoot: false
537
- }, idx))
748
+ className: "flex flex-col",
749
+ children: node.Plans.map((child, index) => /* @__PURE__ */ jsx(PlanNode, {
750
+ node: child,
751
+ slowest,
752
+ totalTime
753
+ }, index))
538
754
  })
539
755
  ]
540
756
  });
541
757
  };
542
758
  //#endregion
759
+ //#region src/components/SQLEditor/SqlParamsPanel.tsx
760
+ var EMPTY = {
761
+ mode: "text",
762
+ value: ""
763
+ };
764
+ /**
765
+ * The values the editor's `:name` placeholders are filled in with when the
766
+ * SQL runs: a value quoted as a string literal, the value as written (a
767
+ * number, an expression), or NULL.
768
+ */
769
+ var SqlParamsPanel = ({ names, values, onChange, missing }) => {
770
+ const { t } = useTranslation();
771
+ if (names.length === 0) return null;
772
+ return /* @__PURE__ */ jsxs("div", {
773
+ className: "px-3 py-2 bg-surface-sheet shrink-0 flex flex-col gap-2 max-h-48 overflow-y-auto",
774
+ children: [/* @__PURE__ */ jsx(Typography, {
775
+ variant: "caption",
776
+ color: "secondary",
777
+ children: t("studio_sql_params_title")
778
+ }), /* @__PURE__ */ jsx("div", {
779
+ className: "flex flex-wrap gap-x-4 gap-y-2",
780
+ children: names.map((name) => {
781
+ const value = values[name] ?? EMPTY;
782
+ const isMissing = missing.includes(name);
783
+ return /* @__PURE__ */ jsxs("div", {
784
+ className: "flex items-center gap-2 min-w-0",
785
+ children: [
786
+ /* @__PURE__ */ jsx(Typography, {
787
+ variant: "mono",
788
+ className: cls("text-[13px] shrink-0", isMissing && "text-red-500 dark:text-red-400"),
789
+ children: `:${name}`
790
+ }),
791
+ /* @__PURE__ */ jsx(TextField, {
792
+ size: "small",
793
+ className: "w-44",
794
+ "aria-label": t("studio_sql_params_value_for", { name }),
795
+ placeholder: value.mode === "raw" ? t("studio_sql_params_raw_placeholder") : t("studio_sql_params_text_placeholder"),
796
+ disabled: value.mode === "null",
797
+ error: isMissing,
798
+ value: value.mode === "null" ? "" : value.value,
799
+ onChange: (event) => onChange(name, {
800
+ ...value,
801
+ value: event.target.value
802
+ })
803
+ }),
804
+ /* @__PURE__ */ jsx(ToggleButtonGroup, {
805
+ "aria-label": t("studio_sql_params_mode_for", { name }),
806
+ value: value.mode,
807
+ onValueChange: (mode) => onChange(name, {
808
+ ...value,
809
+ mode
810
+ }),
811
+ options: [
812
+ {
813
+ value: "text",
814
+ label: t("studio_sql_params_mode_text")
815
+ },
816
+ {
817
+ value: "raw",
818
+ label: t("studio_sql_params_mode_raw")
819
+ },
820
+ {
821
+ value: "null",
822
+ label: "NULL"
823
+ }
824
+ ]
825
+ })
826
+ ]
827
+ }, name);
828
+ })
829
+ })]
830
+ });
831
+ };
832
+ //#endregion
833
+ //#region src/components/SQLEditor/ResultChart.tsx
834
+ /** The most points one chart draws; a result past it is drawn by its first rows. */
835
+ var MAX_CHART_POINTS = {
836
+ bar: 200,
837
+ line: 2e3
838
+ };
839
+ var NUMERIC_TYPES = /^(smallint|integer|bigint|numeric|real|double precision|money|decimal)/;
840
+ function asNumber(value) {
841
+ if (typeof value === "number") return Number.isFinite(value) ? value : null;
842
+ if (typeof value !== "string" || value.trim() === "") return null;
843
+ const parsed = Number(value);
844
+ return Number.isFinite(parsed) ? parsed : null;
845
+ }
846
+ /**
847
+ * The columns a y axis can take: numeric by the type the database said, or,
848
+ * when it said none, every non-empty value of the first rows reads as a number.
849
+ */
850
+ function numericColumns(rows, columns, provenance) {
851
+ const typed = new Map((provenance?.columns ?? []).map((column) => [column.name, column.type]));
852
+ return columns.filter((column) => {
853
+ const type = typed.get(column);
854
+ if (type) return NUMERIC_TYPES.test(type);
855
+ const sample = rows.slice(0, 50).map((row) => row[column]).filter((value) => value !== null && value !== void 0);
856
+ return sample.length > 0 && sample.every((value) => asNumber(value) !== null);
857
+ });
858
+ }
859
+ /** About `count` round tick values from at or below `min` to at or above `max`, so the axis ends on a labelled line. */
860
+ function ticks(min, max, count = 5) {
861
+ if (min === max) return [min];
862
+ const span = max - min;
863
+ const raw = span / count;
864
+ const magnitude = 10 ** Math.floor(Math.log10(raw));
865
+ const step = [
866
+ 1,
867
+ 2,
868
+ 2.5,
869
+ 5,
870
+ 10
871
+ ].map((factor) => factor * magnitude).find((candidate) => span / candidate <= count) ?? raw;
872
+ const out = [];
873
+ const last = Math.ceil(max / step - 1e-9) * step;
874
+ for (let value = Math.floor(min / step + 1e-9) * step; value <= last + step * 1e-9; value += step) out.push(Number(value.toPrecision(12)));
875
+ return out;
876
+ }
877
+ function formatTick(value) {
878
+ const abs = Math.abs(value);
879
+ if (abs >= 1e9) return `${(value / 1e9).toFixed(1)}B`;
880
+ if (abs >= 1e6) return `${(value / 1e6).toFixed(1)}M`;
881
+ if (abs >= 1e4) return `${(value / 1e3).toFixed(0)}k`;
882
+ return Number.isInteger(value) ? String(value) : value.toFixed(2);
883
+ }
884
+ var MARGIN = {
885
+ top: 16,
886
+ right: 16,
887
+ bottom: 48,
888
+ left: 56
889
+ };
890
+ /**
891
+ * A bar or line chart of one result: one column along the x axis, one
892
+ * numeric column up the y axis. Drawn as SVG sized to its container.
893
+ */
894
+ var ResultChart = ({ rows, columns, provenance }) => {
895
+ const { t } = useTranslation();
896
+ const numeric = useMemo(() => numericColumns(rows, columns, provenance), [
897
+ rows,
898
+ columns,
899
+ provenance
900
+ ]);
901
+ const [kind, setKind] = useState("bar");
902
+ const [xColumn, setXColumn] = useState(() => columns.find((column) => !numeric.includes(column)) ?? columns[0] ?? "");
903
+ const [yColumn, setYColumn] = useState(() => numeric.find((column) => column !== xColumn) ?? numeric[0] ?? "");
904
+ const containerRef = useRef(null);
905
+ const [size, setSize] = useState({
906
+ width: 0,
907
+ height: 0
908
+ });
909
+ useEffect(() => {
910
+ const element = containerRef.current;
911
+ if (!element) return;
912
+ const observer = new ResizeObserver(([entry]) => {
913
+ setSize({
914
+ width: entry.contentRect.width,
915
+ height: entry.contentRect.height
916
+ });
917
+ });
918
+ observer.observe(element);
919
+ return () => observer.disconnect();
920
+ }, []);
921
+ const points = useMemo(() => rows.slice(0, MAX_CHART_POINTS[kind]).map((row) => ({
922
+ label: row[xColumn] === null || row[xColumn] === void 0 ? "NULL" : String(row[xColumn]),
923
+ value: asNumber(row[yColumn])
924
+ })).filter((point) => point.value !== null), [
925
+ rows,
926
+ kind,
927
+ xColumn,
928
+ yColumn
929
+ ]);
930
+ const width = Math.max(size.width, 0);
931
+ const height = Math.max(size.height, 0);
932
+ const plotWidth = Math.max(width - MARGIN.left - MARGIN.right, 0);
933
+ const plotHeight = Math.max(height - MARGIN.top - MARGIN.bottom, 0);
934
+ const values = points.map((point) => point.value);
935
+ const yMin = Math.min(0, ...values);
936
+ const yMax = Math.max(0, ...values);
937
+ const yTicks = ticks(yMin, yMax);
938
+ const top = Math.max(yMax, yTicks[yTicks.length - 1] ?? yMax);
939
+ const bottom = Math.min(yMin, yTicks[0] ?? yMin);
940
+ const y = (value) => MARGIN.top + (top === bottom ? plotHeight / 2 : (1 - (value - bottom) / (top - bottom)) * plotHeight);
941
+ const band = points.length > 0 ? plotWidth / points.length : 0;
942
+ const x = (index) => MARGIN.left + band * index + band / 2;
943
+ const labelEvery = Math.max(1, Math.ceil(points.length / Math.max(1, Math.floor(plotWidth / 64))));
944
+ return /* @__PURE__ */ jsxs("div", {
945
+ className: "h-full w-full flex flex-col min-h-0",
946
+ children: [/* @__PURE__ */ jsxs("div", {
947
+ className: "flex flex-wrap items-center gap-3 px-4 py-2 shrink-0",
948
+ children: [
949
+ /* @__PURE__ */ jsx(ToggleButtonGroup, {
950
+ "aria-label": t("studio_sql_chart_kind"),
951
+ value: kind,
952
+ onValueChange: setKind,
953
+ options: [{
954
+ value: "bar",
955
+ label: t("studio_sql_chart_bar")
956
+ }, {
957
+ value: "line",
958
+ label: t("studio_sql_chart_line")
959
+ }]
960
+ }),
961
+ /* @__PURE__ */ jsx(Select, {
962
+ size: "small",
963
+ className: "w-48",
964
+ label: t("studio_sql_chart_x"),
965
+ value: xColumn,
966
+ onValueChange: setXColumn,
967
+ children: columns.map((column) => /* @__PURE__ */ jsx(SelectItem, {
968
+ value: column,
969
+ children: column
970
+ }, column))
971
+ }),
972
+ /* @__PURE__ */ jsx(Select, {
973
+ size: "small",
974
+ className: "w-48",
975
+ label: t("studio_sql_chart_y"),
976
+ value: yColumn,
977
+ onValueChange: setYColumn,
978
+ disabled: numeric.length === 0,
979
+ children: numeric.map((column) => /* @__PURE__ */ jsx(SelectItem, {
980
+ value: column,
981
+ children: column
982
+ }, column))
983
+ }),
984
+ rows.length > MAX_CHART_POINTS[kind] && /* @__PURE__ */ jsx(Typography, {
985
+ variant: "caption",
986
+ color: "secondary",
987
+ children: t("studio_sql_chart_first_rows", { count: MAX_CHART_POINTS[kind] })
988
+ })
989
+ ]
990
+ }), /* @__PURE__ */ jsx("div", {
991
+ ref: containerRef,
992
+ className: "flex-grow min-h-0 relative",
993
+ children: numeric.length === 0 || points.length === 0 ? /* @__PURE__ */ jsx("div", {
994
+ className: "absolute inset-0 flex items-center justify-center",
995
+ children: /* @__PURE__ */ jsx(Typography, {
996
+ variant: "body2",
997
+ color: "secondary",
998
+ children: t("studio_sql_chart_no_numbers")
999
+ })
1000
+ }) : width > 0 && height > 0 && /* @__PURE__ */ jsxs("svg", {
1001
+ width,
1002
+ height,
1003
+ role: "img",
1004
+ "aria-label": t("studio_sql_chart_label", {
1005
+ y: yColumn,
1006
+ x: xColumn
1007
+ }),
1008
+ className: "block",
1009
+ children: [
1010
+ yTicks.map((tick) => /* @__PURE__ */ jsxs("g", { children: [/* @__PURE__ */ jsx("line", {
1011
+ x1: MARGIN.left,
1012
+ x2: MARGIN.left + plotWidth,
1013
+ y1: y(tick),
1014
+ y2: y(tick),
1015
+ className: "stroke-hairline",
1016
+ strokeWidth: 1
1017
+ }), /* @__PURE__ */ jsx("text", {
1018
+ x: MARGIN.left - 8,
1019
+ y: y(tick),
1020
+ dy: "0.32em",
1021
+ textAnchor: "end",
1022
+ className: "fill-text-secondary dark:fill-text-secondary-dark text-[11px] font-mono",
1023
+ children: formatTick(tick)
1024
+ })] }, tick)),
1025
+ /* @__PURE__ */ jsx("g", {
1026
+ className: "text-primary dark:text-primary-dark",
1027
+ children: kind === "bar" ? points.map((point, index) => {
1028
+ const barTop = y(Math.max(point.value, 0));
1029
+ const barHeight = Math.abs(y(point.value) - y(0));
1030
+ return /* @__PURE__ */ jsx("rect", {
1031
+ x: MARGIN.left + band * index + band * .15,
1032
+ y: barTop,
1033
+ width: Math.max(band * .7, 1),
1034
+ height: Math.max(barHeight, 1),
1035
+ rx: Math.min(3, band * .2),
1036
+ fill: "currentColor",
1037
+ fillOpacity: .85,
1038
+ children: /* @__PURE__ */ jsx("title", { children: `${point.label}: ${point.value}` })
1039
+ }, index);
1040
+ }) : /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("polyline", {
1041
+ points: points.map((point, index) => `${x(index)},${y(point.value)}`).join(" "),
1042
+ fill: "none",
1043
+ stroke: "currentColor",
1044
+ strokeWidth: 2,
1045
+ strokeLinejoin: "round"
1046
+ }), points.length <= 100 && points.map((point, index) => /* @__PURE__ */ jsx("circle", {
1047
+ cx: x(index),
1048
+ cy: y(point.value),
1049
+ r: 3,
1050
+ fill: "currentColor",
1051
+ children: /* @__PURE__ */ jsx("title", { children: `${point.label}: ${point.value}` })
1052
+ }, index))] })
1053
+ }),
1054
+ /* @__PURE__ */ jsx("line", {
1055
+ x1: MARGIN.left,
1056
+ x2: MARGIN.left + plotWidth,
1057
+ y1: y(0),
1058
+ y2: y(0),
1059
+ className: "stroke-hairline-strong",
1060
+ strokeWidth: 1
1061
+ }),
1062
+ points.map((point, index) => index % labelEvery === 0 && /* @__PURE__ */ jsx("text", {
1063
+ x: x(index),
1064
+ y: MARGIN.top + plotHeight + 16,
1065
+ textAnchor: "middle",
1066
+ className: "fill-text-secondary dark:fill-text-secondary-dark text-[11px]",
1067
+ children: point.label.length > 10 ? `${point.label.slice(0, 9)}…` : point.label
1068
+ }, index)),
1069
+ /* @__PURE__ */ jsx("text", {
1070
+ x: MARGIN.left + plotWidth / 2,
1071
+ y: height - 8,
1072
+ textAnchor: "middle",
1073
+ className: "fill-text-disabled dark:fill-text-disabled-dark text-[11px] font-mono",
1074
+ children: xColumn
1075
+ })
1076
+ ]
1077
+ })
1078
+ })]
1079
+ });
1080
+ };
1081
+ //#endregion
1082
+ //#region src/components/SQLEditor/useSqlSnippets.ts
1083
+ function isStoredSnippet(value) {
1084
+ if (typeof value !== "object" || value === null) return false;
1085
+ return "id" in value && typeof value.id === "string" && "name" in value && typeof value.name === "string" && "sql" in value && typeof value.sql === "string";
1086
+ }
1087
+ /**
1088
+ * The console's saved snippets, from the project's store when it has one.
1089
+ *
1090
+ * Snippets this browser kept before the project could are uploaded once,
1091
+ * each removed from local storage only when the server has confirmed it: an
1092
+ * upload cut short leaves the rest local, shown beside the server's and
1093
+ * uploaded on the next visit.
1094
+ */
1095
+ function useSqlSnippets(projectPrefix, remote) {
1096
+ const storageKey = `rebase_sql_snippets_${projectPrefix}`;
1097
+ const [serverSnippets, setServerSnippets] = useState([]);
1098
+ const [localSnippets, setLocalSnippets] = useState([]);
1099
+ const [storage, setStorage] = useState(remote ? "loading" : "local");
1100
+ const readLocal = useCallback(() => readStoredJson(storageKey, {
1101
+ fallback: [],
1102
+ accept: isArrayValue
1103
+ }).filter(isStoredSnippet), [storageKey]);
1104
+ const writeLocal = useCallback((snippets) => {
1105
+ setLocalSnippets(snippets);
1106
+ writeStoredJson(storageKey, snippets);
1107
+ }, [storageKey]);
1108
+ const generationRef = useRef(0);
1109
+ useEffect(() => {
1110
+ const generation = ++generationRef.current;
1111
+ const current = () => generation === generationRef.current;
1112
+ const local = readLocal();
1113
+ setLocalSnippets(local);
1114
+ setServerSnippets([]);
1115
+ if (!remote) {
1116
+ setStorage("local");
1117
+ return;
1118
+ }
1119
+ setStorage("loading");
1120
+ (async () => {
1121
+ let listed;
1122
+ try {
1123
+ listed = await remote.list();
1124
+ } catch {
1125
+ if (current()) setStorage("local");
1126
+ return;
1127
+ }
1128
+ if (!current()) return;
1129
+ setServerSnippets(listed);
1130
+ setStorage("server");
1131
+ let pending = local;
1132
+ for (const snippet of local) try {
1133
+ const created = await remote.create({
1134
+ name: snippet.name,
1135
+ sql: snippet.sql,
1136
+ visibility: "personal",
1137
+ favorite: snippet.isFavorite === true
1138
+ });
1139
+ if (!current()) return;
1140
+ pending = pending.filter((entry) => entry.id !== snippet.id);
1141
+ writeStoredJson(storageKey, pending);
1142
+ setLocalSnippets(pending);
1143
+ setServerSnippets((previous) => [...previous, created]);
1144
+ } catch {
1145
+ return;
1146
+ }
1147
+ })();
1148
+ }, [
1149
+ remote,
1150
+ readLocal,
1151
+ storageKey
1152
+ ]);
1153
+ const isLocal = useCallback((id) => localSnippets.some((snippet) => snippet.id === id), [localSnippets]);
1154
+ const createSnippet = useCallback(async (input) => {
1155
+ if (storage === "server" && remote) {
1156
+ const created = await remote.create({
1157
+ ...input,
1158
+ favorite: false
1159
+ });
1160
+ setServerSnippets((previous) => [created, ...previous]);
1161
+ return;
1162
+ }
1163
+ writeLocal([...localSnippets, {
1164
+ id: Math.random().toString(36).substring(2, 9),
1165
+ name: input.name,
1166
+ sql: input.sql,
1167
+ createdAt: Date.now()
1168
+ }]);
1169
+ }, [
1170
+ storage,
1171
+ remote,
1172
+ localSnippets,
1173
+ writeLocal
1174
+ ]);
1175
+ const setFavorite = useCallback(async (id, favorite) => {
1176
+ if (isLocal(id) || !remote) {
1177
+ writeLocal(localSnippets.map((snippet) => snippet.id === id ? {
1178
+ ...snippet,
1179
+ isFavorite: favorite
1180
+ } : snippet));
1181
+ return;
1182
+ }
1183
+ const updated = await remote.update(id, { favorite });
1184
+ setServerSnippets((previous) => previous.map((snippet) => snippet.id === id ? updated : snippet));
1185
+ }, [
1186
+ isLocal,
1187
+ remote,
1188
+ localSnippets,
1189
+ writeLocal
1190
+ ]);
1191
+ const deleteSnippet = useCallback(async (id) => {
1192
+ if (isLocal(id) || !remote) {
1193
+ writeLocal(localSnippets.filter((snippet) => snippet.id !== id));
1194
+ return;
1195
+ }
1196
+ await remote.remove(id);
1197
+ setServerSnippets((previous) => previous.filter((snippet) => snippet.id !== id));
1198
+ }, [
1199
+ isLocal,
1200
+ remote,
1201
+ localSnippets,
1202
+ writeLocal
1203
+ ]);
1204
+ return {
1205
+ snippets: [...serverSnippets, ...localSnippets],
1206
+ storage,
1207
+ createSnippet,
1208
+ setFavorite,
1209
+ deleteSnippet
1210
+ };
1211
+ }
1212
+ //#endregion
1213
+ //#region src/utils/sql_params.ts
1214
+ var IDENTIFIER_START = /[A-Za-z_\u0080-￿]/;
1215
+ var IDENTIFIER_PART = /[A-Za-z0-9_$\u0080-￿]/;
1216
+ /**
1217
+ * Where the dollar quote opening at `start` ends its tag (`$$`, `$body$`), or
1218
+ * -1 when the `$` there opens none — `$1` is a positional parameter.
1219
+ */
1220
+ function dollarTagEnd(sql, start) {
1221
+ let index = start + 1;
1222
+ if (sql[index] === "$") return index + 1;
1223
+ if (!IDENTIFIER_START.test(sql[index] ?? "") || sql[index] === "$") return -1;
1224
+ while (index < sql.length && /[A-Za-z0-9_\u0080-￿]/.test(sql[index])) index++;
1225
+ return sql[index] === "$" ? index + 1 : -1;
1226
+ }
1227
+ /** Every `:name` placeholder in `sql`, in order. */
1228
+ function findSqlParameters(sql) {
1229
+ const found = [];
1230
+ let bracketDepth = 0;
1231
+ let index = 0;
1232
+ while (index < sql.length) {
1233
+ const char = sql[index];
1234
+ const next = sql[index + 1];
1235
+ if (char === "-" && next === "-") {
1236
+ const end = sql.indexOf("\n", index + 2);
1237
+ index = end === -1 ? sql.length : end + 1;
1238
+ continue;
1239
+ }
1240
+ if (char === "/" && next === "*") {
1241
+ let depth = 1;
1242
+ index += 2;
1243
+ while (index < sql.length && depth > 0) if (sql[index] === "/" && sql[index + 1] === "*") {
1244
+ depth++;
1245
+ index += 2;
1246
+ } else if (sql[index] === "*" && sql[index + 1] === "/") {
1247
+ depth--;
1248
+ index += 2;
1249
+ } else index++;
1250
+ continue;
1251
+ }
1252
+ if (char === "'") {
1253
+ const escapes = index > 0 && /[eE]/.test(sql[index - 1]) && !IDENTIFIER_PART.test(sql[index - 2] ?? "");
1254
+ index++;
1255
+ while (index < sql.length) {
1256
+ if (escapes && sql[index] === "\\") {
1257
+ index += 2;
1258
+ continue;
1259
+ }
1260
+ if (sql[index] === "'") {
1261
+ if (sql[index + 1] === "'") {
1262
+ index += 2;
1263
+ continue;
1264
+ }
1265
+ index++;
1266
+ break;
1267
+ }
1268
+ index++;
1269
+ }
1270
+ continue;
1271
+ }
1272
+ if (char === "\"") {
1273
+ index++;
1274
+ while (index < sql.length) {
1275
+ if (sql[index] === "\"") {
1276
+ if (sql[index + 1] === "\"") {
1277
+ index += 2;
1278
+ continue;
1279
+ }
1280
+ index++;
1281
+ break;
1282
+ }
1283
+ index++;
1284
+ }
1285
+ continue;
1286
+ }
1287
+ if (char === "$" && !IDENTIFIER_PART.test(sql[index - 1] ?? "")) {
1288
+ const tagEnd = dollarTagEnd(sql, index);
1289
+ if (tagEnd !== -1) {
1290
+ const tag = sql.slice(index, tagEnd);
1291
+ const close = sql.indexOf(tag, tagEnd);
1292
+ index = close === -1 ? sql.length : close + tag.length;
1293
+ continue;
1294
+ }
1295
+ }
1296
+ if (char === "[") {
1297
+ bracketDepth++;
1298
+ index++;
1299
+ continue;
1300
+ }
1301
+ if (char === "]") {
1302
+ bracketDepth = Math.max(0, bracketDepth - 1);
1303
+ index++;
1304
+ continue;
1305
+ }
1306
+ if (char === ":") {
1307
+ if (next === ":") {
1308
+ index += 2;
1309
+ continue;
1310
+ }
1311
+ if (bracketDepth === 0 && IDENTIFIER_START.test(next ?? "") && !IDENTIFIER_PART.test(sql[index - 1] ?? "")) {
1312
+ let end = index + 1;
1313
+ while (end < sql.length && IDENTIFIER_PART.test(sql[end]) && sql[end] !== "$") end++;
1314
+ found.push({
1315
+ name: sql.slice(index + 1, end),
1316
+ start: index,
1317
+ end
1318
+ });
1319
+ index = end;
1320
+ continue;
1321
+ }
1322
+ }
1323
+ index++;
1324
+ }
1325
+ return found;
1326
+ }
1327
+ /** The distinct parameter names of `sql`, in the order they first appear. */
1328
+ function sqlParameterNames(sql) {
1329
+ return [...new Set(findSqlParameters(sql).map((occurrence) => occurrence.name))];
1330
+ }
1331
+ /**
1332
+ * `value` as a SQL string literal: single quotes doubled, and an `E''`
1333
+ * literal with its backslashes doubled when it holds one, so the database
1334
+ * reads the same characters whatever `standard_conforming_strings` says.
1335
+ */
1336
+ function quoteSqlLiteral(value) {
1337
+ const quoted = value.replace(/'/g, "''");
1338
+ return value.includes("\\") ? `E'${quoted.replace(/\\/g, "\\\\")}'` : `'${quoted}'`;
1339
+ }
1340
+ /** What `parameter` is written as in the SQL that runs. */
1341
+ function sqlParameterText(parameter) {
1342
+ switch (parameter.mode) {
1343
+ case "null": return "NULL";
1344
+ case "raw": return parameter.value;
1345
+ case "text": return quoteSqlLiteral(parameter.value);
1346
+ }
1347
+ }
1348
+ /**
1349
+ * `sql` with every placeholder replaced by its value's text. A placeholder
1350
+ * with no value is a mistake the caller asks about first —
1351
+ * {@link missingSqlParameters} — and is left as written here.
1352
+ */
1353
+ function substituteSqlParameters(sql, values) {
1354
+ let out = "";
1355
+ let last = 0;
1356
+ for (const occurrence of findSqlParameters(sql)) {
1357
+ const value = values[occurrence.name];
1358
+ if (!value) continue;
1359
+ out += sql.slice(last, occurrence.start) + sqlParameterText(value);
1360
+ last = occurrence.end;
1361
+ }
1362
+ return out + sql.slice(last);
1363
+ }
1364
+ /**
1365
+ * The placeholders of `sql` that `values` gives nothing for: no entry, or an
1366
+ * empty one that is not NULL. An empty string is written as the raw `''`, so
1367
+ * a field left blank is never run as one by accident.
1368
+ */
1369
+ function missingSqlParameters(sql, values) {
1370
+ return sqlParameterNames(sql).filter((name) => {
1371
+ const value = values[name];
1372
+ return !value || value.mode !== "null" && value.value === "";
1373
+ });
1374
+ }
1375
+ //#endregion
543
1376
  //#region src/components/SQLEditor/SQLEditor.tsx
544
1377
  var getStoragePrefix = (baseUrl) => {
545
1378
  if (!baseUrl) return "default";
@@ -555,7 +1388,38 @@ function isStoredTab(value) {
555
1388
  const tab = value;
556
1389
  return typeof tab.id === "string" && typeof tab.name === "string" && typeof tab.sql === "string";
557
1390
  }
558
- var SQLEditor = () => {
1391
+ /** The statements of a run, when it reported more than one; `null` for a run of one. */
1392
+ function resultSetsOf(run) {
1393
+ if (!run?.statements || run.statements.length < 2) return null;
1394
+ return run.statements.map((statement) => ({
1395
+ rows: statement.rows,
1396
+ provenance: {
1397
+ columns: statement.columns,
1398
+ tables: statement.tables
1399
+ },
1400
+ command: statement.command,
1401
+ rowCount: statement.rowCount,
1402
+ truncatedFrom: statement.truncated ? statement.rowCount ?? null : null
1403
+ }));
1404
+ }
1405
+ /** What a tab holds of its runs: nothing yet. */
1406
+ var noRun = () => ({
1407
+ results: null,
1408
+ loading: false,
1409
+ error: null,
1410
+ execTime: null,
1411
+ lastExecutedSql: null,
1412
+ lastExecutedConnection: null,
1413
+ ranAs: null,
1414
+ lastProvenance: null,
1415
+ notices: [],
1416
+ truncatedFrom: null,
1417
+ resultSets: null,
1418
+ activeResultIndex: 0,
1419
+ planAnalyzed: false,
1420
+ paramValues: {}
1421
+ });
1422
+ var SQLEditor = ({ incomingDraft, onDraftConsumed, snippetRemote } = {}) => {
559
1423
  const { databaseAdmin, client } = useRebaseContext();
560
1424
  const sidePanelController = useStudioSidePanelController();
561
1425
  const snackbarController = useSnackbarController();
@@ -596,16 +1460,7 @@ var SQLEditor = () => {
596
1460
  accept: isArrayValue
597
1461
  }).filter(isStoredTab).map((t) => ({
598
1462
  ...t,
599
- results: null,
600
- loading: false,
601
- error: null,
602
- execTime: null,
603
- lastExecutedSql: null,
604
- lastExecutedConnection: null,
605
- ranAs: null,
606
- lastProvenance: null,
607
- notices: [],
608
- truncatedFrom: null
1463
+ ...noRun()
609
1464
  }));
610
1465
  if (restored.length > 0) return restored;
611
1466
  return [{
@@ -614,16 +1469,7 @@ var SQLEditor = () => {
614
1469
  sql: "SELECT * FROM ",
615
1470
  database: readStoredString(`rebase_sql_selected_db_${projectPrefixSync}`) || void 0,
616
1471
  role: readStoredString(`rebase_sql_selected_role_${projectPrefixSync}`) || void 0,
617
- results: null,
618
- loading: false,
619
- error: null,
620
- execTime: null,
621
- lastExecutedSql: null,
622
- lastExecutedConnection: null,
623
- ranAs: null,
624
- lastProvenance: null,
625
- notices: [],
626
- truncatedFrom: null
1472
+ ...noRun()
627
1473
  }];
628
1474
  });
629
1475
  const [activeTabId, setActiveTabId] = useState(() => {
@@ -976,15 +1822,12 @@ var SQLEditor = () => {
976
1822
  accept: isRecordValue
977
1823
  }));
978
1824
  });
979
- const [snippets, setSnippets] = useState([]);
1825
+ const { snippets, storage: snippetStorage, createSnippet, setFavorite, deleteSnippet } = useSqlSnippets(projectPrefix, snippetRemote);
980
1826
  const [history, setHistory] = useState([]);
981
1827
  const [isSaveDialogOpen, setIsSaveDialogOpen] = useState(false);
982
1828
  const [newSnippetName, setNewSnippetName] = useState("");
1829
+ const [shareSnippetWithTeam, setShareSnippetWithTeam] = useState(false);
983
1830
  useEffect(() => {
984
- setSnippets(readStoredJson(`rebase_sql_snippets_${projectPrefix}`, {
985
- fallback: [],
986
- accept: isArrayValue
987
- }));
988
1831
  setHistory(readStoredJson(`rebase_sql_history_${projectPrefix}`, {
989
1832
  fallback: [],
990
1833
  accept: isArrayValue
@@ -1003,18 +1846,22 @@ var SQLEditor = () => {
1003
1846
  useEffect(() => {
1004
1847
  writeStoredString(`rebase_sql_active_tab_${projectPrefix}`, activeTabId);
1005
1848
  }, [activeTabId, projectPrefix]);
1006
- const saveSnippets = (newSnippets) => {
1007
- setSnippets(newSnippets);
1008
- writeStoredJson(`rebase_sql_snippets_${projectPrefix}`, newSnippets);
1009
- };
1010
1849
  const saveHistory = (newHistory) => {
1011
1850
  setHistory(newHistory);
1012
1851
  writeStoredJson(`rebase_sql_history_${projectPrefix}`, newHistory.slice(-50));
1013
1852
  };
1853
+ /** A snippet store's refusal, said rather than lost. */
1854
+ const reportSnippetFailure = (e) => snackbarController.open({
1855
+ type: "error",
1856
+ message: t("studio_sql_snippet_failed", { message: e instanceof Error ? e.message : String(e) })
1857
+ });
1014
1858
  const handleDeleteSnippet = (id) => {
1015
- saveSnippets(snippets.filter((s) => s.id !== id));
1859
+ deleteSnippet(id).catch(reportSnippetFailure);
1860
+ };
1861
+ const handleToggleFavorite = (snippet) => {
1862
+ setFavorite(snippet.id, !snippet.isFavorite).catch(reportSnippetFailure);
1016
1863
  };
1017
- const handleAddTab = () => {
1864
+ const handleAddTab = useCallback((initialSql = "SELECT * FROM ") => {
1018
1865
  const newId = Math.random().toString(36).substring(2, 9);
1019
1866
  let maxNumber = 0;
1020
1867
  tabs.forEach((tab) => {
@@ -1028,22 +1875,32 @@ var SQLEditor = () => {
1028
1875
  setTabs((prev) => [...prev, {
1029
1876
  id: newId,
1030
1877
  name,
1031
- sql: "SELECT * FROM ",
1878
+ sql: initialSql,
1032
1879
  database: selectedDatabase,
1033
1880
  role: selectedRole,
1034
- results: null,
1035
- loading: false,
1036
- error: null,
1037
- execTime: null,
1038
- lastExecutedSql: null,
1039
- lastExecutedConnection: null,
1040
- ranAs: null,
1041
- lastProvenance: null,
1042
- notices: [],
1043
- truncatedFrom: null
1881
+ ...noRun()
1044
1882
  }]);
1045
1883
  setActiveTabId(newId);
1046
- };
1884
+ }, [
1885
+ tabs,
1886
+ selectedDatabase,
1887
+ selectedRole
1888
+ ]);
1889
+ const consumedDraftRef = useRef(null);
1890
+ useEffect(() => {
1891
+ if (!incomingDraft) {
1892
+ consumedDraftRef.current = null;
1893
+ return;
1894
+ }
1895
+ if (consumedDraftRef.current === incomingDraft) return;
1896
+ consumedDraftRef.current = incomingDraft;
1897
+ handleAddTab(incomingDraft);
1898
+ onDraftConsumed?.();
1899
+ }, [
1900
+ incomingDraft,
1901
+ onDraftConsumed,
1902
+ handleAddTab
1903
+ ]);
1047
1904
  const handleCloseTab = (id, e) => {
1048
1905
  e.stopPropagation();
1049
1906
  if (tabs.length === 1) return;
@@ -1104,8 +1961,34 @@ var SQLEditor = () => {
1104
1961
  tabsRunningRef.current.delete(tabId);
1105
1962
  }
1106
1963
  };
1107
- const handleExplain = async () => {
1108
- const explainSql = buildExplainSql(editorHandle.current?.getSelectedText() ?? currentEditorText());
1964
+ /** The placeholders the last run or explain was refused for, marked in the params panel. */
1965
+ const [missingParams, setMissingParams] = useState([]);
1966
+ /**
1967
+ * `text` with its `:name` placeholders filled in from the tab's values,
1968
+ * or `null` — the run refused, and the empty ones marked — when one has
1969
+ * no value.
1970
+ */
1971
+ const paramValues = activeTab.paramValues;
1972
+ const withParameters = useCallback((text) => {
1973
+ const missing = missingSqlParameters(text, paramValues);
1974
+ setMissingParams(missing);
1975
+ if (missing.length > 0) {
1976
+ updateActiveTab({
1977
+ results: null,
1978
+ error: t("studio_sql_params_missing", { names: missing.map((name) => `:${name}`).join(", ") })
1979
+ });
1980
+ return null;
1981
+ }
1982
+ return substituteSqlParameters(text, paramValues);
1983
+ }, [
1984
+ paramValues,
1985
+ updateActiveTab,
1986
+ t
1987
+ ]);
1988
+ const handleExplain = async (analyze = false) => {
1989
+ const text = withParameters(editorHandle.current?.getSelectedText() ?? currentEditorText());
1990
+ if (text === null) return;
1991
+ const explainSql = analyze ? buildExplainAnalyzeScript(text) : buildExplainSql(text);
1109
1992
  if (!explainSql) {
1110
1993
  updateActiveTab({
1111
1994
  results: null,
@@ -1113,19 +1996,26 @@ var SQLEditor = () => {
1113
1996
  });
1114
1997
  return;
1115
1998
  }
1116
- await runOnce(activeTab.id, () => explain(explainSql));
1999
+ await runOnce(activeTab.id, () => analyze ? explainAnalyze(explainSql) : explain(explainSql));
2000
+ };
2001
+ /** What a plan replaces on screen: nothing left there is a row an edit could write back. */
2002
+ const planStarted = {
2003
+ loading: true,
2004
+ error: null,
2005
+ results: null,
2006
+ lastExecutedSql: null,
2007
+ lastExecutedConnection: null,
2008
+ ranAs: null,
2009
+ lastProvenance: null,
2010
+ notices: [],
2011
+ truncatedFrom: null,
2012
+ resultSets: null,
2013
+ activeResultIndex: 0
1117
2014
  };
1118
2015
  const explain = async (explainSql) => {
1119
2016
  updateActiveTab({
1120
- loading: true,
1121
- error: null,
1122
- results: null,
1123
- lastExecutedSql: null,
1124
- lastExecutedConnection: null,
1125
- ranAs: null,
1126
- lastProvenance: null,
1127
- notices: [],
1128
- truncatedFrom: null
2017
+ ...planStarted,
2018
+ planAnalyzed: false
1129
2019
  });
1130
2020
  const start = performance.now();
1131
2021
  try {
@@ -1147,6 +2037,54 @@ var SQLEditor = () => {
1147
2037
  }
1148
2038
  };
1149
2039
  /**
2040
+ * Time the statement for real, in a transaction the script rolls back —
2041
+ * through the script door, so it can be cancelled like any run.
2042
+ */
2043
+ const explainAnalyze = async (script) => {
2044
+ const tabId = activeTab.id;
2045
+ if (!databaseAdmin?.runSqlScript) {
2046
+ updateActiveTab({
2047
+ results: null,
2048
+ error: t("studio_sql_explain_analyze_unsupported")
2049
+ });
2050
+ return;
2051
+ }
2052
+ updateActiveTab({
2053
+ ...planStarted,
2054
+ planAnalyzed: true
2055
+ });
2056
+ const start = performance.now();
2057
+ const abort = new AbortController();
2058
+ runAbortRef.current.set(tabId, abort);
2059
+ setCancellable(tabId, true);
2060
+ try {
2061
+ const run = await databaseAdmin.runSqlScript(script, {
2062
+ database: selectedDatabase,
2063
+ role: selectedRole,
2064
+ signal: abort.signal
2065
+ });
2066
+ const explained = run.statements?.find((statement) => statement.command === "EXPLAIN");
2067
+ if (!explained) {
2068
+ updateActiveTab({ error: t("studio_sql_explain_analyze_unsupported") });
2069
+ return;
2070
+ }
2071
+ updateActiveTab({
2072
+ results: explained.rows,
2073
+ execTime: Math.round(performance.now() - start),
2074
+ notices: run.notices
2075
+ });
2076
+ } catch (e) {
2077
+ const message = e instanceof Error ? e.message : String(e);
2078
+ updateActiveTab({ error: abort.signal.aborted ? t("studio_sql_run_cancelled") : message || t("studio_sql_error_explaining") });
2079
+ } finally {
2080
+ if (runAbortRef.current.get(tabId) === abort) {
2081
+ runAbortRef.current.delete(tabId);
2082
+ setCancellable(tabId, false);
2083
+ }
2084
+ updateActiveTab({ loading: false });
2085
+ }
2086
+ };
2087
+ /**
1150
2088
  * Run `statement` — exactly the text the person ran, the selection or the
1151
2089
  * whole of `buffer` — and keep `buffer` in the history.
1152
2090
  */
@@ -1157,7 +2095,10 @@ var SQLEditor = () => {
1157
2095
  error: null,
1158
2096
  results: null,
1159
2097
  notices: [],
1160
- truncatedFrom: null
2098
+ truncatedFrom: null,
2099
+ resultSets: null,
2100
+ activeResultIndex: 0,
2101
+ planAnalyzed: false
1161
2102
  });
1162
2103
  const start = performance.now();
1163
2104
  const tabId = activeTab.id;
@@ -1177,7 +2118,10 @@ var SQLEditor = () => {
1177
2118
  signal: abort?.signal
1178
2119
  }) : void 0;
1179
2120
  const rows = run ? run.rows : await databaseAdmin.executeSql(sqlToRun, connection);
2121
+ const resultSets = resultSetsOf(run);
1180
2122
  updateActiveTab({
2123
+ resultSets,
2124
+ activeResultIndex: resultSets ? resultSets.length - 1 : 0,
1181
2125
  results: rows,
1182
2126
  execTime: Math.round(performance.now() - start),
1183
2127
  lastExecutedSql: sqlToRun,
@@ -1223,15 +2167,21 @@ var SQLEditor = () => {
1223
2167
  */
1224
2168
  const handleRun = useCallback(async (selectedText) => {
1225
2169
  const buffer = currentEditorText();
1226
- const statement = selectedText || buffer;
1227
- if (!statement.trim()) return;
2170
+ const typed = selectedText || buffer;
2171
+ if (!typed.trim()) return;
2172
+ const statement = withParameters(typed);
2173
+ if (statement === null) return;
1228
2174
  if (needsDestructiveConfirmation(statement)) {
1229
2175
  setPendingAction(() => () => executeRun(statement, buffer));
1230
2176
  setIsConfirmDialogOpen(true);
1231
2177
  return;
1232
2178
  }
1233
2179
  executeRun(statement, buffer);
1234
- }, [currentEditorText, executeRun]);
2180
+ }, [
2181
+ currentEditorText,
2182
+ executeRun,
2183
+ withParameters
2184
+ ]);
1235
2185
  useEffect(() => {
1236
2186
  const handleKeyDown = (e) => {
1237
2187
  if (isKeyHandled(e)) return;
@@ -1247,20 +2197,26 @@ var SQLEditor = () => {
1247
2197
  window.addEventListener("keydown", handleKeyDown);
1248
2198
  return () => window.removeEventListener("keydown", handleKeyDown);
1249
2199
  }, [handleRun]);
1250
- const handleSaveSnippet = () => {
1251
- if (!newSnippetName.trim() || !sql.trim()) return;
1252
- const newSnippet = {
1253
- id: Math.random().toString(36).substring(2, 9),
1254
- name: newSnippetName,
1255
- sql,
1256
- createdAt: Date.now()
1257
- };
1258
- saveSnippets([...snippets, newSnippet]);
2200
+ const handleSaveSnippet = async () => {
2201
+ const name = newSnippetName.trim();
2202
+ const text = currentEditorText();
2203
+ if (!name || !text.trim()) return;
2204
+ try {
2205
+ await createSnippet({
2206
+ name,
2207
+ sql: text,
2208
+ visibility: shareSnippetWithTeam ? "team" : "personal"
2209
+ });
2210
+ } catch (e) {
2211
+ reportSnippetFailure(e);
2212
+ return;
2213
+ }
1259
2214
  setNewSnippetName("");
2215
+ setShareSnippetWithTeam(false);
1260
2216
  setIsSaveDialogOpen(false);
1261
2217
  snackbarController.open({
1262
2218
  type: "success",
1263
- message: t("studio_sql_snippet_saved", { name: newSnippetName })
2219
+ message: t("studio_sql_snippet_saved", { name })
1264
2220
  });
1265
2221
  };
1266
2222
  const handleExportCSV = () => {
@@ -1500,6 +2456,31 @@ var SQLEditor = () => {
1500
2456
  sidePanelController,
1501
2457
  t
1502
2458
  ]);
2459
+ /** The grid or a chart of the rows on screen; back to the grid with every new result. */
2460
+ const [resultView, setResultView] = useState("grid");
2461
+ useEffect(() => setResultView("grid"), [results]);
2462
+ const resultSets = activeTab.resultSets;
2463
+ const activeResultSet = resultSets?.[activeTab.activeResultIndex] ?? null;
2464
+ /** "SELECT · 3 rows", "CREATE TABLE": what a statement's result tab says. */
2465
+ const resultSetLabel = (set) => {
2466
+ const command = set.command ?? t("studio_sql_statement");
2467
+ return set.rowCount !== void 0 ? t("studio_sql_statement_rows", {
2468
+ command,
2469
+ count: set.rowCount
2470
+ }) : command;
2471
+ };
2472
+ /** Show statement `index` of the last run: its rows, columns and truncation take the grid. */
2473
+ const selectResultSet = (index) => {
2474
+ const set = resultSets?.[Number(index)];
2475
+ if (!set) return;
2476
+ setEditingCell(null);
2477
+ updateActiveTab({
2478
+ activeResultIndex: Number(index),
2479
+ results: set.rows,
2480
+ lastProvenance: set.provenance,
2481
+ truncatedFrom: set.truncatedFrom
2482
+ });
2483
+ };
1503
2484
  const renderResults = () => {
1504
2485
  if (loading) return /* @__PURE__ */ jsx("div", {
1505
2486
  className: "flex-grow flex items-center justify-center",
@@ -1533,23 +2514,26 @@ var SQLEditor = () => {
1533
2514
  })]
1534
2515
  })
1535
2516
  });
1536
- if (results.length === 1 && results[0]["QUERY PLAN"] && Array.isArray(results[0]["QUERY PLAN"])) try {
1537
- const plan = results[0]["QUERY PLAN"][0].Plan;
1538
- if (plan) return /* @__PURE__ */ jsxs("div", {
1539
- className: "flex-grow overflow-auto p-4 bg-surface-sheet flex flex-col items-start",
1540
- children: [/* @__PURE__ */ jsx(Typography, {
2517
+ const explained = explainResultOfRows(results);
2518
+ if (explained) return /* @__PURE__ */ jsxs("div", {
2519
+ className: "flex-grow overflow-auto p-4 bg-surface-sheet flex flex-col items-start gap-2",
2520
+ children: [
2521
+ /* @__PURE__ */ jsx(Typography, {
1541
2522
  variant: "label",
1542
2523
  color: "secondary",
1543
- className: "mb-4",
1544
- children: t("studio_sql_visual_execution_plan")
1545
- }), /* @__PURE__ */ jsx("div", {
2524
+ children: explained.analyzed ? t("studio_sql_visual_execution_plan_analyzed") : t("studio_sql_visual_execution_plan")
2525
+ }),
2526
+ activeTab.planAnalyzed && /* @__PURE__ */ jsx(Alert, {
2527
+ color: "info",
2528
+ size: "small",
2529
+ children: t("studio_sql_explain_analyze_note")
2530
+ }),
2531
+ /* @__PURE__ */ jsx("div", {
1546
2532
  className: "pb-12",
1547
- children: /* @__PURE__ */ jsx(ExplainVisualizer, { plan })
1548
- })]
1549
- });
1550
- } catch (e) {
1551
- console.warn("Failed to parse EXPLAIN JSON output:", e);
1552
- }
2533
+ children: /* @__PURE__ */ jsx(ExplainVisualizer, { result: explained })
2534
+ })
2535
+ ]
2536
+ });
1553
2537
  if (results.length === 0) return /* @__PURE__ */ jsxs("div", {
1554
2538
  className: "flex-grow p-6 flex flex-col items-center justify-center",
1555
2539
  children: [/* @__PURE__ */ jsx(Typography, {
@@ -1559,7 +2543,7 @@ var SQLEditor = () => {
1559
2543
  }), /* @__PURE__ */ jsx(Typography, {
1560
2544
  variant: "caption",
1561
2545
  className: "text-text-disabled dark:text-text-disabled-dark",
1562
- children: t("studio_sql_no_results")
2546
+ children: activeResultSet?.command ? resultSetLabel(activeResultSet) : t("studio_sql_no_results")
1563
2547
  })]
1564
2548
  });
1565
2549
  return /* @__PURE__ */ jsxs("div", {
@@ -1597,7 +2581,11 @@ var SQLEditor = () => {
1597
2581
  }),
1598
2582
  /* @__PURE__ */ jsx("div", {
1599
2583
  className: "flex-grow relative h-full min-h-0 min-w-0",
1600
- children: /* @__PURE__ */ jsx(VirtualTable, {
2584
+ children: resultView === "chart" ? /* @__PURE__ */ jsx(ResultChart, {
2585
+ rows: results,
2586
+ columns: resultColumnKeys,
2587
+ provenance: activeTab.lastProvenance
2588
+ }) : /* @__PURE__ */ jsx(VirtualTable, {
1601
2589
  data: results,
1602
2590
  columns: resultColumns,
1603
2591
  rowHeight: 32,
@@ -1637,6 +2625,18 @@ var SQLEditor = () => {
1637
2625
  }), /* @__PURE__ */ jsxs("div", {
1638
2626
  className: "flex gap-2 overflow-x-auto no-scrollbar items-center px-2",
1639
2627
  children: [
2628
+ /* @__PURE__ */ jsx(ToggleButtonGroup, {
2629
+ "aria-label": t("studio_sql_result_view"),
2630
+ value: resultView,
2631
+ onValueChange: setResultView,
2632
+ options: [{
2633
+ value: "grid",
2634
+ label: t("studio_sql_result_view_grid")
2635
+ }, {
2636
+ value: "chart",
2637
+ label: t("studio_sql_result_view_chart")
2638
+ }]
2639
+ }),
1640
2640
  /* @__PURE__ */ jsx(Button, {
1641
2641
  size: "small",
1642
2642
  variant: "text",
@@ -1684,6 +2684,17 @@ var SQLEditor = () => {
1684
2684
  useEffect(() => {
1685
2685
  writeStoredString(`rebase_sql_editor_height_${projectPrefix}`, editorHeight.toString());
1686
2686
  }, [editorHeight, projectPrefix]);
2687
+ const parameterNames = useMemo(() => sqlParameterNames(sql), [sql]);
2688
+ const handleParamChange = useCallback((name, value) => {
2689
+ setMissingParams((previous) => previous.filter((entry) => entry !== name));
2690
+ setTabs((previous) => previous.map((tab) => tab.id === activeTabId ? {
2691
+ ...tab,
2692
+ paramValues: {
2693
+ ...tab.paramValues,
2694
+ [name]: value
2695
+ }
2696
+ } : tab));
2697
+ }, [activeTabId]);
1687
2698
  const activeSnippet = snippets.find((s) => s.sql === activeTab.sql);
1688
2699
  const isFavorite = activeSnippet?.isFavorite || false;
1689
2700
  return /* @__PURE__ */ jsxs("div", {
@@ -1701,6 +2712,7 @@ var SQLEditor = () => {
1701
2712
  onSelectSnippet: setSql,
1702
2713
  onTableClick: setSql,
1703
2714
  onDeleteSnippet: handleDeleteSnippet,
2715
+ onToggleFavorite: handleToggleFavorite,
1704
2716
  schemas,
1705
2717
  isSchemaLoading,
1706
2718
  schemaError,
@@ -1744,7 +2756,7 @@ var SQLEditor = () => {
1744
2756
  }, tab.id))
1745
2757
  }), /* @__PURE__ */ jsx(IconButton, {
1746
2758
  size: "small",
1747
- onClick: handleAddTab,
2759
+ onClick: () => handleAddTab(),
1748
2760
  "aria-label": t("studio_sql_new_tab"),
1749
2761
  title: t("studio_sql_new_tab"),
1750
2762
  className: "ml-2 flex-shrink-0",
@@ -1763,12 +2775,52 @@ var SQLEditor = () => {
1763
2775
  children: /* @__PURE__ */ jsx(MenuIcon, { size: iconSize.smallest })
1764
2776
  })
1765
2777
  }),
1766
- /* @__PURE__ */ jsx(Button, {
1767
- variant: "text",
1768
- size: "small",
1769
- onClick: handleExplain,
1770
- disabled: loading,
1771
- children: t("studio_sql_explain")
2778
+ /* @__PURE__ */ jsxs("div", {
2779
+ className: "flex items-center",
2780
+ children: [/* @__PURE__ */ jsx(Button, {
2781
+ variant: "text",
2782
+ size: "small",
2783
+ onClick: () => handleExplain(),
2784
+ disabled: loading,
2785
+ children: t("studio_sql_explain")
2786
+ }), /* @__PURE__ */ jsxs(Menu, {
2787
+ trigger: /* @__PURE__ */ jsx(IconButton, {
2788
+ size: "small",
2789
+ disabled: loading,
2790
+ "aria-label": t("studio_sql_explain_options"),
2791
+ children: /* @__PURE__ */ jsx(ChevronDownIcon, { size: iconSize.smallest })
2792
+ }),
2793
+ children: [/* @__PURE__ */ jsx(MenuItem, {
2794
+ dense: true,
2795
+ onClick: () => handleExplain(),
2796
+ children: /* @__PURE__ */ jsxs("div", {
2797
+ className: "flex flex-col",
2798
+ children: [/* @__PURE__ */ jsx(Typography, {
2799
+ variant: "body2",
2800
+ children: t("studio_sql_explain_plan_only")
2801
+ }), /* @__PURE__ */ jsx(Typography, {
2802
+ variant: "caption",
2803
+ color: "secondary",
2804
+ children: t("studio_sql_explain_plan_only_hint")
2805
+ })]
2806
+ })
2807
+ }), /* @__PURE__ */ jsx(MenuItem, {
2808
+ dense: true,
2809
+ onClick: () => handleExplain(true),
2810
+ children: /* @__PURE__ */ jsxs("div", {
2811
+ className: "flex flex-col max-w-[280px]",
2812
+ children: [/* @__PURE__ */ jsx(Typography, {
2813
+ variant: "body2",
2814
+ children: t("studio_sql_explain_analyze")
2815
+ }), /* @__PURE__ */ jsx(Typography, {
2816
+ variant: "caption",
2817
+ color: "secondary",
2818
+ className: "whitespace-normal",
2819
+ children: t("studio_sql_explain_analyze_hint")
2820
+ })]
2821
+ })
2822
+ })]
2823
+ })]
1772
2824
  }),
1773
2825
  /* @__PURE__ */ jsx("div", { className: "h-4 w-px bg-hairline mx-1" }),
1774
2826
  /* @__PURE__ */ jsxs("div", {
@@ -1804,10 +2856,7 @@ var SQLEditor = () => {
1804
2856
  });
1805
2857
  return;
1806
2858
  }
1807
- saveSnippets(snippets.map((s) => s.id === activeSnippet.id ? {
1808
- ...s,
1809
- isFavorite: !s.isFavorite
1810
- } : s));
2859
+ handleToggleFavorite(activeSnippet);
1811
2860
  },
1812
2861
  children: /* @__PURE__ */ jsx(HeartIcon, {
1813
2862
  size: iconSize.smallest,
@@ -1910,26 +2959,55 @@ var SQLEditor = () => {
1910
2959
  panelSizePercent: editorHeight,
1911
2960
  onPanelSizeChange: setEditorHeight,
1912
2961
  minPanelSizePx: 100,
1913
- firstPanel: /* @__PURE__ */ jsx("div", {
2962
+ firstPanel: /* @__PURE__ */ jsxs("div", {
1914
2963
  className: "h-full w-full relative flex flex-col min-h-0",
1915
- children: /* @__PURE__ */ jsx(MonacoEditor, {
2964
+ children: [/* @__PURE__ */ jsx(SqlParamsPanel, {
2965
+ names: parameterNames,
2966
+ values: activeTab.paramValues,
2967
+ missing: missingParams,
2968
+ onChange: handleParamChange
2969
+ }), /* @__PURE__ */ jsx(MonacoEditor, {
1916
2970
  ref: editorHandle,
1917
2971
  value: sql,
1918
2972
  onChange: (v) => setSql(v || ""),
1919
2973
  onRun: handleRun,
1920
2974
  schemas
1921
- })
2975
+ })]
1922
2976
  }),
1923
2977
  secondPanel: /* @__PURE__ */ jsxs("div", {
1924
2978
  className: "h-full w-full flex flex-col bg-surface-well overflow-hidden min-h-0",
1925
2979
  children: [
1926
- /* @__PURE__ */ jsx("div", {
1927
- className: cls("p-2 px-4 bg-surface-raised border-b shrink-0 flex items-center", defaultBorderMixin),
1928
- children: /* @__PURE__ */ jsx(Typography, {
2980
+ /* @__PURE__ */ jsxs("div", {
2981
+ className: cls("px-4 bg-surface-raised border-b shrink-0 flex items-center gap-3 min-h-[37px]", defaultBorderMixin),
2982
+ children: [/* @__PURE__ */ jsx(Typography, {
1929
2983
  variant: "caption",
1930
- className: "font-semibold text-text-disabled dark:text-text-disabled-dark uppercase tracking-widest text-[10px]",
2984
+ className: "font-semibold text-text-disabled dark:text-text-disabled-dark uppercase tracking-widest text-[10px] shrink-0",
1931
2985
  children: t("studio_sql_query_results")
1932
- })
2986
+ }), !loading && resultSets && /* @__PURE__ */ jsx("div", {
2987
+ className: "flex items-center no-scrollbar overflow-x-auto min-w-0",
2988
+ children: /* @__PURE__ */ jsx(Tabs, {
2989
+ value: String(activeTab.activeResultIndex),
2990
+ onValueChange: selectResultSet,
2991
+ variant: "boxy",
2992
+ className: "w-[unset] flex-shrink-0",
2993
+ "aria-label": t("studio_sql_statement_results"),
2994
+ children: resultSets.map((set, index) => /* @__PURE__ */ jsxs(Tab, {
2995
+ value: String(index),
2996
+ className: "whitespace-nowrap",
2997
+ children: [
2998
+ /* @__PURE__ */ jsx("span", {
2999
+ className: "text-text-disabled dark:text-text-disabled-dark mr-1.5 font-mono",
3000
+ children: index + 1
3001
+ }),
3002
+ resultSetLabel(set),
3003
+ set.truncatedFrom !== null && /* @__PURE__ */ jsx("span", {
3004
+ className: "ml-1 text-text-disabled dark:text-text-disabled-dark",
3005
+ children: "*"
3006
+ })
3007
+ ]
3008
+ }, index))
3009
+ })
3010
+ })]
1933
3011
  }),
1934
3012
  !loading && results && activeTab.ranAs && activeTab.lastExecutedConnection?.role && activeTab.ranAs !== activeTab.lastExecutedConnection.role && /* @__PURE__ */ jsx("div", {
1935
3013
  className: "px-4 pt-2 shrink-0",
@@ -1947,7 +3025,7 @@ var SQLEditor = () => {
1947
3025
  children: /* @__PURE__ */ jsx(Alert, {
1948
3026
  color: "info",
1949
3027
  size: "small",
1950
- action: activeTab.lastExecutedSql && apiBase ? /* @__PURE__ */ jsx(Button, {
3028
+ action: activeTab.lastExecutedSql && apiBase && !resultSets ? /* @__PURE__ */ jsx(Button, {
1951
3029
  size: "small",
1952
3030
  variant: "text",
1953
3031
  disabled: downloadingFullResult,
@@ -1984,23 +3062,33 @@ var SQLEditor = () => {
1984
3062
  /* @__PURE__ */ jsx(DialogTitle, { children: t("studio_sql_save_snippet") }),
1985
3063
  /* @__PURE__ */ jsx(DialogContent, { children: /* @__PURE__ */ jsxs("div", {
1986
3064
  className: "py-4 flex flex-col gap-4",
1987
- children: [/* @__PURE__ */ jsx(TextField, {
1988
- label: t("studio_sql_snippet_name"),
1989
- autoFocus: true,
1990
- placeholder: t("studio_sql_snippet_name_placeholder"),
1991
- value: newSnippetName,
1992
- onChange: (e) => setNewSnippetName(e.target.value),
1993
- onKeyDown: (e) => {
1994
- if (e.key === "Enter") {
1995
- e.preventDefault();
1996
- handleSaveSnippet();
3065
+ children: [
3066
+ /* @__PURE__ */ jsx(TextField, {
3067
+ label: t("studio_sql_snippet_name"),
3068
+ autoFocus: true,
3069
+ placeholder: t("studio_sql_snippet_name_placeholder"),
3070
+ value: newSnippetName,
3071
+ onChange: (e) => setNewSnippetName(e.target.value),
3072
+ onKeyDown: (e) => {
3073
+ if (e.key === "Enter") {
3074
+ e.preventDefault();
3075
+ handleSaveSnippet();
3076
+ }
1997
3077
  }
1998
- }
1999
- }), /* @__PURE__ */ jsx(Typography, {
2000
- variant: "caption",
2001
- className: "text-text-disabled dark:text-text-disabled-dark block",
2002
- children: t("studio_sql_snippet_saved_local")
2003
- })]
3078
+ }),
3079
+ snippetStorage === "server" && /* @__PURE__ */ jsxs(Label, {
3080
+ className: "flex items-center gap-2 cursor-pointer",
3081
+ children: [/* @__PURE__ */ jsx(Checkbox, {
3082
+ checked: shareSnippetWithTeam,
3083
+ onCheckedChange: setShareSnippetWithTeam
3084
+ }), t("studio_sql_snippet_share_team")]
3085
+ }),
3086
+ /* @__PURE__ */ jsx(Typography, {
3087
+ variant: "caption",
3088
+ className: "text-text-disabled dark:text-text-disabled-dark block",
3089
+ children: snippetStorage === "server" ? t("studio_sql_snippet_saved_project") : t("studio_sql_snippet_saved_local")
3090
+ })
3091
+ ]
2004
3092
  }) }),
2005
3093
  /* @__PURE__ */ jsxs(DialogActions, { children: [/* @__PURE__ */ jsx(Button, {
2006
3094
  variant: "text",
@@ -2028,6 +3116,70 @@ var SQLEditor = () => {
2028
3116
  });
2029
3117
  };
2030
3118
  //#endregion
2031
- export { SQLEditor };
3119
+ //#region src/components/SQLEditor/SQLEditorRoute.tsx
3120
+ /**
3121
+ * The query parameter other Studio views open the console with:
3122
+ * `/sql?sqlDraft=<encodeURIComponent(sql)>` opens that SQL in a new tab.
3123
+ * Namespaced, and removed on its own once read: the hosted console keeps its
3124
+ * open tab in `?tab=`, and a host app may use any other name.
3125
+ */
3126
+ var SQL_DRAFT_PARAM = "sqlDraft";
3127
+ function snippetOf(value) {
3128
+ const record = isRecord$1(value) ? value : {};
3129
+ const createdAt = Date.parse(asString(record.createdAt));
3130
+ return {
3131
+ id: asString(record.id),
3132
+ name: asString(record.name),
3133
+ sql: asString(record.sql),
3134
+ createdAt: Number.isNaN(createdAt) ? Date.now() : createdAt,
3135
+ isFavorite: asBoolean(record.favorite),
3136
+ visibility: record.visibility === "team" ? "team" : "personal",
3137
+ ownerId: asString(record.ownerId)
3138
+ };
3139
+ }
3140
+ /**
3141
+ * The SQL console as Studio routes it: the draft another view sent in the
3142
+ * URL, and the project's snippet store at `/api/admin/sql/snippets`.
3143
+ */
3144
+ var SQLEditorRoute = () => {
3145
+ const [searchParams, setSearchParams] = useSearchParams();
3146
+ const draft = searchParams.get(SQL_DRAFT_PARAM);
3147
+ const { requestJson } = useAdminFetch();
3148
+ return /* @__PURE__ */ jsx(SQLEditor, {
3149
+ incomingDraft: draft,
3150
+ onDraftConsumed: useCallback(() => {
3151
+ setSearchParams((previous) => {
3152
+ const next = new URLSearchParams(previous);
3153
+ next.delete(SQL_DRAFT_PARAM);
3154
+ return next;
3155
+ }, { replace: true });
3156
+ }, [setSearchParams]),
3157
+ snippetRemote: useMemo(() => ({
3158
+ async list() {
3159
+ const answer = await requestJson("/admin/sql/snippets");
3160
+ return (isRecord$1(answer) && Array.isArray(answer.snippets) ? answer.snippets : []).map(snippetOf);
3161
+ },
3162
+ async create(input) {
3163
+ const answer = await requestJson("/admin/sql/snippets", {
3164
+ method: "POST",
3165
+ body: input
3166
+ });
3167
+ return snippetOf(isRecord$1(answer) ? answer.snippet : void 0);
3168
+ },
3169
+ async update(id, patch) {
3170
+ const answer = await requestJson(`/admin/sql/snippets/${encodeURIComponent(id)}`, {
3171
+ method: "PATCH",
3172
+ body: patch
3173
+ });
3174
+ return snippetOf(isRecord$1(answer) ? answer.snippet : void 0);
3175
+ },
3176
+ async remove(id) {
3177
+ await requestJson(`/admin/sql/snippets/${encodeURIComponent(id)}`, { method: "DELETE" });
3178
+ }
3179
+ }), [requestJson])
3180
+ });
3181
+ };
3182
+ //#endregion
3183
+ export { SQLEditorRoute };
2032
3184
 
2033
- //# sourceMappingURL=SQLEditor-DRo5kW1h.js.map
3185
+ //# sourceMappingURL=SQLEditorRoute-f5j_ZKdj.js.map