Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

ReportsV2 P2: Support adding SQL snippets to Reports (#32851)

Joshen Lim0129c94cf150
diff --git a/apps/studio/components/interfaces/Auth/EmailTemplates/TemplateEditor.tsx b/apps/studio/components/interfaces/Auth/EmailTemplates/TemplateEditor.tsx
index d109b86be04..23b202cc9ba 100644
--- a/apps/studio/components/interfaces/Auth/EmailTemplates/TemplateEditor.tsx
+++ b/apps/studio/components/interfaces/Auth/EmailTemplates/TemplateEditor.tsx
@@ -1,7 +1,6 @@
import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { debounce } from 'lodash'
import { Code, Monitor } from 'lucide-react'
-import { useCallback, useEffect, useMemo, useState } from 'react'
+import { useEffect, useMemo, useState } from 'react'
import ReactMarkdown from 'react-markdown'
import { toast } from 'sonner'
diff --git a/apps/studio/components/interfaces/Reports/GridResize.tsx b/apps/studio/components/interfaces/Reports/GridResize.tsx
index fd27d77e107..7e42f63e0b2 100644
--- a/apps/studio/components/interfaces/Reports/GridResize.tsx
+++ b/apps/studio/components/interfaces/Reports/GridResize.tsx
@@ -1,10 +1,10 @@
-import { X } from 'lucide-react'
import RGL, { WidthProvider } from 'react-grid-layout'
+import 'react-grid-layout/css/styles.css'
+import 'react-resizable/css/styles.css'
-import { useParams } from 'common'
-import ChartHandler from 'components/to-be-cleaned/Charts/ChartHandler'
-import { ButtonTooltip } from 'components/ui/ButtonTooltip'
-import { useDatabaseSelectorStateSnapshot } from 'state/database-selector'
+import { Dashboards } from 'types'
+import { ChartConfig } from '../SQLEditor/UtilityPanel/ChartConfig'
+import { ReportChartBlock } from './ReportChartBlock'
import { LAYOUT_COLUMN_COUNT } from './Reports.constants'
const ReactGridLayout = WidthProvider(RGL)
@@ -13,93 +13,76 @@ interface GridResizeProps {
startDate: string
endDate: string
interval: string
- editableReport: any
+ editableReport: Dashboards.Content
disableUpdate: boolean
onRemoveChart: ({ metric }: { metric: { key: string } }) => void
+ onUpdateChart: (id: string, config: Partial<ChartConfig>) => void
setEditableReport: (payload: any) => void
}
-const GridResize = ({
+export const GridResize = ({
startDate,
endDate,
interval,
editableReport,
disableUpdate,
onRemoveChart,
+ onUpdateChart,
setEditableReport,
}: GridResizeProps) => {
- const { ref } = useParams()
- const state = useDatabaseSelectorStateSnapshot()
+ const onUpdateLayout = (layout: RGL.Layout[]) => {
+ const updatedLayout = [...editableReport.layout]
- function onLayoutChange(layout: any) {
- let updatedLayout = editableReport.layout
- layout.map((item: any) => {
- const index = updatedLayout.findIndex((x: any) => x.id === item.i)
- updatedLayout[index].w = layout[index].w
- updatedLayout[index].h = layout[index].h
- updatedLayout[index].x = layout[index].x
- updatedLayout[index].y = layout[index].y
+ layout.forEach((chart) => {
+ const chartIdx = updatedLayout.findIndex((y) => chart.i === y.id)
+ if (chartIdx !== undefined && chartIdx >= 0) {
+ updatedLayout[chartIdx] = {
+ ...updatedLayout[chartIdx],
+ w: chart.w,
+ h: chart.h,
+ x: chart.x,
+ y: chart.y,
+ }
+ }
})
- const payload = {
- ...editableReport,
- layout: updatedLayout,
- }
- setEditableReport(payload)
+
+ setEditableReport({ ...editableReport, layout: updatedLayout })
}
if (!editableReport) return null
return (
- <>
- <ReactGridLayout
- autoSize={true}
- layout={editableReport}
- onLayoutChange={(layout) => onLayoutChange(layout)}
- rowHeight={60}
- cols={LAYOUT_COLUMN_COUNT}
- containerPadding={[0, 0]}
- compactType="horizontal"
- >
- {editableReport.layout.map((x: any) => {
- return (
- <div
- key={x.id}
- data-grid={{ ...x, minH: 4, maxH: 4, minW: 8 }}
- className="react-grid-layout__report-item bg-surface-100 border-overlay group relative rounded border px-6 py-4 shadow-sm hover:border-green-900"
- >
- <ChartHandler
- startDate={startDate}
- endDate={endDate}
- interval={interval}
- attribute={x.attribute}
- provider={x.provider}
- label={`${x.label}${ref !== state.selectedDatabaseId ? (x.provider === 'infra-monitoring' ? ' of replica' : ' on project') : ''}`}
- customDateFormat={'MMM D, YYYY'}
- >
- {!disableUpdate && (
- <ButtonTooltip
- type="text"
- icon={<X />}
- className="ml-2 px-1"
- onClick={() => onRemoveChart({ metric: { key: x.attribute } })}
- tooltip={{ content: { side: 'bottom', text: 'Remove chart' } }}
- />
- )}
- </ChartHandler>
-
- <div className="absolute inset-x-0 top-3 ">
- <div className="flex justify-around">
- <div className="flex h-3 w-24 cursor-move flex-col space-y-2">
- <div className="hidden h-3 w-full border-4 border-dotted border-green-900 opacity-50 transition-all hover:opacity-100 group-hover:block" />
- </div>
- </div>
- </div>
- </div>
- )
- })}
- </ReactGridLayout>
- </>
+ <ReactGridLayout
+ autoSize
+ isDraggable
+ isResizable
+ rowHeight={270}
+ cols={LAYOUT_COLUMN_COUNT}
+ containerPadding={[0, 0]}
+ resizeHandles={['sw', 'se']}
+ compactType="vertical"
+ onDragStop={onUpdateLayout}
+ onResizeStop={onUpdateLayout}
+ >
+ {editableReport.layout.map((item) => {
+ return (
+ <div
+ key={item.id}
+ data-grid={{ ...item, minH: 1, maxH: 1, minW: 1, maxW: LAYOUT_COLUMN_COUNT }}
+ >
+ <ReportChartBlock
+ key={item.id}
+ item={item}
+ startDate={startDate}
+ endDate={endDate}
+ interval={interval}
+ disableUpdate={disableUpdate}
+ onRemoveChart={onRemoveChart}
+ onUpdateChart={(config) => onUpdateChart(item.id, config)}
+ />
+ </div>
+ )
+ })}
+ </ReactGridLayout>
)
}
-
-export default GridResize
diff --git a/apps/studio/components/interfaces/Reports/MetricOptions.tsx b/apps/studio/components/interfaces/Reports/MetricOptions.tsx
index b179f960686..154c7421a7d 100644
--- a/apps/studio/components/interfaces/Reports/MetricOptions.tsx
+++ b/apps/studio/components/interfaces/Reports/MetricOptions.tsx
@@ -1,21 +1,44 @@
-import { Home } from 'lucide-react'
+import { useDebounce } from '@uidotdev/usehooks'
+import { Code, Home } from 'lucide-react'
+import { useState } from 'react'
+import { useParams } from 'common'
+import { useContentQuery } from 'data/content/content-query'
import { useIsFeatureEnabled } from 'hooks/misc/useIsFeatureEnabled'
-import { METRICS, METRIC_CATEGORIES } from 'lib/constants/metrics'
+import { useFlag } from 'hooks/ui/useFlag'
+import { Metric, METRIC_CATEGORIES, METRICS } from 'lib/constants/metrics'
+import { Dashboards } from 'types'
import {
+ Command_Shadcn_,
+ CommandEmpty_Shadcn_,
+ CommandGroup_Shadcn_,
+ CommandInput_Shadcn_,
+ CommandItem_Shadcn_,
+ CommandList_Shadcn_,
DropdownMenuCheckboxItem,
DropdownMenuPortal,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
} from 'ui'
+import ShimmeringLoader from 'ui-patterns/ShimmeringLoader'
interface MetricOptionsProps {
- config: any
- handleChartSelection: any
+ config?: Dashboards.Content
+ handleChartSelection: ({
+ metric,
+ isAddingChart,
+ }: {
+ metric: Metric
+ isAddingChart: boolean
+ }) => void
}
export const MetricOptions = ({ config, handleChartSelection }: MetricOptionsProps) => {
+ const { ref: projectRef } = useParams()
+ const supportSQLBlocks = useFlag('reportsV2')
+ const [search, setSearch] = useState('')
+
const { projectAuthAll: authEnabled, projectStorageAll: storageEnabled } = useIsFeatureEnabled([
'project_auth:all',
'project_storage:all',
@@ -27,31 +50,97 @@ export const MetricOptions = ({ config, handleChartSelection }: MetricOptionsPro
return true
})
- return metricCategories.map((cat) => {
- return (
- <DropdownMenuSub key={cat.key}>
- <DropdownMenuSubTrigger className="space-x-2">
- {cat.icon ? cat.icon : <Home size={14} />}
- <p>{cat.label}</p>
- </DropdownMenuSubTrigger>
- <DropdownMenuPortal>
- <DropdownMenuSubContent>
- {METRICS.filter((metric) => metric?.category?.key === cat.key).map((metric) => {
- return (
- <DropdownMenuCheckboxItem
- key={metric.key}
- checked={config.layout?.some((x: any) => x.attribute === metric.key)}
- onCheckedChange={(e) => handleChartSelection({ metric, value: e })}
- >
- <div className="flex flex-col space-y-0">
- <span>{metric.label}</span>
- </div>
- </DropdownMenuCheckboxItem>
- )
- })}
- </DropdownMenuSubContent>
- </DropdownMenuPortal>
- </DropdownMenuSub>
- )
+ const debouncedSearch = useDebounce(search, 300)
+ const { data, isLoading } = useContentQuery({
+ projectRef,
+ type: 'sql',
+ name: debouncedSearch.length === 0 ? undefined : debouncedSearch,
})
+ const snippets = data?.content
+
+ return (
+ <>
+ {metricCategories.map((cat) => {
+ return (
+ <DropdownMenuSub key={cat.key}>
+ <DropdownMenuSubTrigger className="space-x-2">
+ {cat.icon ? cat.icon : <Home size={14} />}
+ <p>{cat.label}</p>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuPortal>
+ <DropdownMenuSubContent>
+ {METRICS.filter((metric) => metric?.category?.key === cat.key).map((metric) => {
+ return (
+ <DropdownMenuCheckboxItem
+ key={metric.key}
+ className="cursor-pointer"
+ checked={config?.layout?.some((x: any) => x.attribute === metric.key)}
+ onCheckedChange={(e) => handleChartSelection({ metric, isAddingChart: e })}
+ >
+ <div className="flex flex-col space-y-0">
+ <span>{metric.label}</span>
+ </div>
+ </DropdownMenuCheckboxItem>
+ )
+ })}
+ </DropdownMenuSubContent>
+ </DropdownMenuPortal>
+ </DropdownMenuSub>
+ )
+ })}
+ {supportSQLBlocks && (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger className="space-x-2">
+ <Code size={14} />
+ <p>SQL Snippets</p>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuPortal>
+ <DropdownMenuSubContent className="p-0">
+ <Command_Shadcn_ shouldFilter={false}>
+ <CommandInput_Shadcn_
+ autoFocus
+ placeholder="Search snippets..."
+ value={search}
+ onValueChange={setSearch}
+ />
+ <CommandList_Shadcn_>
+ {isLoading ? (
+ <div className="flex flex-col p-1 gap-y-1">
+ <ShimmeringLoader />
+ <ShimmeringLoader className="w-3/4" />
+ </div>
+ ) : (
+ <CommandEmpty_Shadcn_>No snippets found</CommandEmpty_Shadcn_>
+ )}
+ <CommandGroup_Shadcn_>
+ {snippets?.map((snippet) => (
+ <CommandItem_Shadcn_
+ key={snippet.id}
+ value={snippet.id}
+ className="cursor-pointer"
+ onSelect={() => {
+ if (!config?.layout.find((x) => x.id === snippet.id)) {
+ handleChartSelection({
+ metric: {
+ id: snippet.id,
+ key: `snippet_${snippet.id}`,
+ label: snippet.name,
+ },
+ isAddingChart: true,
+ })
+ }
+ }}
+ >
+ {snippet.name}
+ </CommandItem_Shadcn_>
+ ))}
+ </CommandGroup_Shadcn_>
+ </CommandList_Shadcn_>
+ </Command_Shadcn_>
+ </DropdownMenuSubContent>
+ </DropdownMenuPortal>
+ </DropdownMenuSub>
+ )}
+ </>
+ )
}
diff --git a/apps/studio/components/interfaces/Reports/ReportChartBlock.tsx b/apps/studio/components/interfaces/Reports/ReportChartBlock.tsx
new file mode 100644
index 00000000000..9af11482f5b
--- /dev/null
+++ b/apps/studio/components/interfaces/Reports/ReportChartBlock.tsx
@@ -0,0 +1,122 @@
+import { X } from 'lucide-react'
+
+import { useParams } from 'common'
+import ChartHandler from 'components/to-be-cleaned/Charts/ChartHandler'
+import { isReadOnlySelect } from 'components/ui/AIAssistantPanel/AIAssistant.utils'
+import { ButtonTooltip } from 'components/ui/ButtonTooltip'
+import { DEFAULT_CHART_CONFIG, QueryBlock } from 'components/ui/QueryBlock/QueryBlock'
+import { useContentIdQuery } from 'data/content/content-id-query'
+import { useDatabaseSelectorStateSnapshot } from 'state/database-selector'
+import { Dashboards, SqlSnippets } from 'types'
+import { ChartConfig } from '../SQLEditor/UtilityPanel/ChartConfig'
+
+const ChartGrip = () => (
+ <div className="absolute inset-x-0 top-3 grid-item-drag-handle ">
+ <div className="flex justify-around">
+ <div className="flex h-3 w-24 cursor-move flex-col space-y-2">
+ <div className="hidden h-3 w-full border-4 border-dotted border-green-900 opacity-50 transition-all hover:opacity-100 group-hover:block" />
+ </div>
+ </div>
+ </div>
+)
+
+interface ReportChartBlockProps {
+ item: Dashboards.Chart
+ startDate: string
+ endDate: string
+ interval: string
+ disableUpdate: boolean
+ onRemoveChart: ({ metric }: { metric: { key: string } }) => void
+ onUpdateChart: (config: Partial<ChartConfig>) => void
+}
+
+export const ReportChartBlock = ({
+ item,
+ startDate,
+ endDate,
+ interval,
+ disableUpdate,
+ onRemoveChart,
+ onUpdateChart,
+}: ReportChartBlockProps) => {
+ const { ref: projectRef } = useParams()
+ const state = useDatabaseSelectorStateSnapshot()
+
+ const isSnippet = item.attribute.startsWith('snippet_')
+
+ const { data } = useContentIdQuery(
+ { projectRef, id: item.id },
+ { enabled: isSnippet && !!item.id }
+ )
+ const sql = isSnippet ? (data?.content as SqlSnippets.Content)?.sql : undefined
+ const chartConfig = { ...DEFAULT_CHART_CONFIG, ...(item.chartConfig ?? {}) }
+ const isReadOnlySQL = isReadOnlySelect(sql ?? '')
+
+ return (
+ <>
+ {isSnippet ? (
+ <QueryBlock
+ runQuery
+ isChart
+ disableRunIfMutation
+ id={item.id}
+ label={item.label}
+ chartConfig={chartConfig}
+ sql={sql}
+ maxHeight={232}
+ queryHeight={232}
+ actions={
+ <ButtonTooltip
+ type="text"
+ icon={<X />}
+ className="w-7 h-7"
+ onClick={() => onRemoveChart({ metric: { key: item.attribute } })}
+ tooltip={{ content: { side: 'bottom', text: 'Remove chart' } }}
+ />
+ }
+ onUpdateChartConfig={onUpdateChart}
+ noResultPlaceholder={
+ isReadOnlySQL ? (
+ <div className="border-t flex flex-col gap-y-1 items-center justify-center h-full">
+ <p className="text-xs text-foreground-light">SQL query is not readonly</p>
+ <p className="text-xs text-foreground-lighter">
+ Queries that involve any mutation will not be run or rendered in reports
+ </p>
+ </div>
+ ) : (
+ <div className="border-t flex flex-col gap-y-1 items-center justify-center h-full">
+ <p className="text-xs text-foreground-light">No results returned from query</p>
+ <p className="text-xs text-foreground-lighter">
+ Results from the SQL query can be viewed as a table or chart here
+ </p>
+ </div>
+ )
+ }
+ />
+ ) : (
+ <div className="h-full bg-surface-100 border-overlay group relative rounded border px-6 py-4 shadow-sm hover:border-green-900">
+ <ChartHandler
+ startDate={startDate}
+ endDate={endDate}
+ interval={interval}
+ attribute={item.attribute}
+ provider={item.provider}
+ label={`${item.label}${projectRef !== state.selectedDatabaseId ? (item.provider === 'infra-monitoring' ? ' of replica' : ' on project') : ''}`}
+ customDateFormat={'MMM D, YYYY'}
+ >
+ {!disableUpdate && (
+ <ButtonTooltip
+ type="text"
+ icon={<X />}
+ className="ml-2 px-1"
+ onClick={() => onRemoveChart({ metric: { key: item.attribute } })}
+ tooltip={{ content: { side: 'bottom', text: 'Remove chart' } }}
+ />
+ )}
+ </ChartHandler>
+ <ChartGrip />
+ </div>
+ )}
+ </>
+ )
+}
diff --git a/apps/studio/components/interfaces/Reports/Reports.constants.ts b/apps/studio/components/interfaces/Reports/Reports.constants.ts
index 383de377907..cad3f68307a 100644
--- a/apps/studio/components/interfaces/Reports/Reports.constants.ts
+++ b/apps/studio/components/interfaces/Reports/Reports.constants.ts
@@ -3,7 +3,7 @@ import dayjs from 'dayjs'
import type { DatetimeHelper } from '../Settings/Logs/Logs.types'
import { PresetConfig, Presets, ReportFilterItem } from './Reports.types'
-export const LAYOUT_COLUMN_COUNT = 24
+export const LAYOUT_COLUMN_COUNT = 2
export const REPORTS_DATEPICKER_HELPERS: DatetimeHelper[] = [
{
diff --git a/apps/studio/components/interfaces/Reports/Reports.tsx b/apps/studio/components/interfaces/Reports/Reports.tsx
index ead38cc7277..f851283d515 100644
--- a/apps/studio/components/interfaces/Reports/Reports.tsx
+++ b/apps/studio/components/interfaces/Reports/Reports.tsx
@@ -1,6 +1,7 @@
import { PermissionAction } from '@supabase/shared-types/out/constants'
import dayjs from 'dayjs'
-import { groupBy, isNull } from 'lodash'
+import { groupBy, isEqual, isNull } from 'lodash'
+import { ArrowRight, Plus, Save } from 'lucide-react'
import { useEffect, useState } from 'react'
import { toast } from 'sonner'
@@ -10,31 +11,37 @@ import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import DatabaseSelector from 'components/ui/DatabaseSelector'
import { Loading } from 'components/ui/Loading'
import NoPermission from 'components/ui/NoPermission'
+import { DEFAULT_CHART_CONFIG } from 'components/ui/QueryBlock/QueryBlock'
import { useContentQuery } from 'data/content/content-query'
import { useContentUpdateMutation } from 'data/content/content-update-mutation'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { TIME_PERIODS_REPORTS } from 'lib/constants/metrics'
+import { Metric, TIME_PERIODS_REPORTS } from 'lib/constants/metrics'
import { uuidv4 } from 'lib/helpers'
import { useProfile } from 'lib/profile'
-import { ArrowRight, Plus, Save, Settings } from 'lucide-react'
-import { Button, DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from 'ui'
-import GridResize from './GridResize'
+import { Dashboards } from 'types'
+import { Button, cn, DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from 'ui'
+import { ChartConfig } from '../SQLEditor/UtilityPanel/ChartConfig'
+import { GridResize } from './GridResize'
import { MetricOptions } from './MetricOptions'
import { LAYOUT_COLUMN_COUNT } from './Reports.constants'
-const DEFAULT_CHART_COLUMN_COUNT = 12
-const DEFAULT_CHART_ROW_COUNT = 4
+const DEFAULT_CHART_COLUMN_COUNT = 1
+const DEFAULT_CHART_ROW_COUNT = 1
const Reports = () => {
const { id, ref } = useParams()
const { profile } = useProfile()
- const [config, setConfig] = useState<any>(undefined)
- const [startDate, setStartDate] = useState<any>(null)
- const [endDate, setEndDate] = useState<any>(null)
- const [hasEdits, setHasEdits] = useState<any>(false)
+ const [config, setConfig] = useState<Dashboards.Content>()
+ const [startDate, setStartDate] = useState<string | null>(null)
+ const [endDate, setEndDate] = useState<string | null>(null)
+ const [hasEdits, setHasEdits] = useState<boolean>(false)
- const { data: userContents, isLoading } = useContentQuery({
+ const {
+ data: userContents,
+ isLoading,
+ isSuccess,
+ } = useContentQuery({
projectRef: ref,
type: 'report',
})
@@ -47,7 +54,12 @@ const Reports = () => {
toast.error(`Failed to update report: ${error.message}`)
},
})
+
const currentReport = userContents?.content.find((report) => report.id === id)
+ const currentReportContent = currentReport?.content as Dashboards.Content
+ const showDatePicker = !!config?.layout.some(
+ (x) => x.provider === 'daily-stats' || x.provider === 'infra-monitoring'
+ )
const canReadReport = useCheckPermissions(PermissionAction.READ, 'user_content', {
resource: {
@@ -82,7 +94,7 @@ const Reports = () => {
* want to compare fixed dates as possible differences from saved and edited versions of report.
*/
let _config = JSON.parse(JSON.stringify(config))
- let _original = JSON.parse(JSON.stringify(currentReport?.content))
+ let _original = JSON.parse(JSON.stringify(currentReportContent))
if (!_original || !_config) return
@@ -94,8 +106,8 @@ const Reports = () => {
* the below would not need to be run
*/
if (
- _config.period_start.time_period != 'custom' ||
- _config.period_end.time_period != 'custom'
+ _config.period_start.time_period !== 'custom' ||
+ _config.period_end.time_period !== 'custom'
) {
_original.period_start.date = ''
_config.period_start.date = ''
@@ -104,25 +116,26 @@ const Reports = () => {
}
// Runs comparison
- if (JSON.stringify(_config) == JSON.stringify(_original)) {
+ if (isEqual(_config, _original)) {
setHasEdits(false)
} else {
setHasEdits(true)
}
}
- // Updates the report and reloads the report again
- const onSaveReport = async () => {
- if (ref === undefined) return console.error('Project ref is required')
- if (id === undefined) return console.error('Report ID is required')
- saveReport({ projectRef: ref, id, type: 'report', content: config })
- }
- function handleChartSelection({ metric, value }: any) {
- if (value) pushChart({ metric })
+ const handleChartSelection = ({
+ metric,
+ isAddingChart,
+ }: {
+ metric: Metric
+ isAddingChart: boolean
+ }) => {
+ if (isAddingChart) pushChart({ metric })
else popChart({ metric })
}
- function pushChart({ metric }: any) {
+ const pushChart = ({ metric }: { metric: Metric }) => {
+ if (!config) return
const current = [...config.layout]
let x = 0
@@ -130,6 +143,7 @@ const Reports = () => {
const chartsByY = groupBy(config.layout, 'y')
const yValues = Object.keys(chartsByY)
+ const isSnippet = metric.key?.startsWith('snippet_')
if (yValues.length === 0) {
y = 0
@@ -158,10 +172,12 @@ const Reports = () => {
y,
w: DEFAULT_CHART_COLUMN_COUNT,
h: DEFAULT_CHART_ROW_COUNT,
- id: uuidv4(),
- attribute: metric.key,
+ id: metric?.id ?? uuidv4(),
label: metric.label,
- provider: metric.provider,
+ attribute: metric.key as Dashboards.ChartType,
+ provider: metric.provider as any,
+ chart_type: 'bar',
+ ...(isSnippet ? { chartConfig: DEFAULT_CHART_CONFIG } : {}),
})
setConfig({
@@ -170,25 +186,46 @@ const Reports = () => {
})
}
- function popChart({ metric }: any) {
- const { key } = metric
+ const popChart = ({ metric }: { metric: Partial<Metric> }) => {
+ if (!config) return
+
+ const { key, id } = metric
const current = [...config.layout]
- const foundIndex = current.findIndex((x: any, i: number) => {
- if (x.attribute === key) {
- return x
- }
+ const foundIndex = current.findIndex((x) => {
+ if (x.attribute === key || x.id === id) return x
})
current.splice(foundIndex, 1)
- setConfig({
- ...config,
- layout: [...current],
- })
+ setConfig({ ...config, layout: [...current] })
+ }
+
+ const updateChart = (id: string, chartConfig: Partial<ChartConfig>) => {
+ const currentChart = config?.layout.find((x) => x.id === id)
+ if (currentChart) {
+ const updatedChart: Dashboards.Chart = {
+ ...currentChart,
+ chartConfig: { ...(currentChart?.chartConfig ?? {}), ...chartConfig },
+ }
+
+ const foundIndex = config?.layout.findIndex((x) => x.id === id)
+ if (config && foundIndex !== undefined && foundIndex >= 0) {
+ const updatedLayouts = [...config.layout]
+ updatedLayouts[foundIndex] = updatedChart
+ setConfig({ ...config, layout: updatedLayouts })
+ }
+ }
+ }
+
+ // Updates the report and reloads the report again
+ const onSaveReport = async () => {
+ if (ref === undefined) return console.error('Project ref is required')
+ if (id === undefined) return console.error('Report ID is required')
+ saveReport({ projectRef: ref, id, type: 'report', content: config })
}
useEffect(() => {
- if (currentReport !== undefined) setConfig(currentReport?.content)
- }, [currentReport])
+ if (isSuccess && currentReportContent !== undefined) setConfig(currentReportContent)
+ }, [isSuccess, currentReportContent])
useEffect(() => {
checkEditState()
@@ -213,7 +250,7 @@ const Reports = () => {
<div className="flex items-center gap-x-2">
<Button
type="default"
- onClick={() => setConfig(currentReport?.content)}
+ onClick={() => setConfig(currentReportContent)}
disabled={isSaving}
>
Cancel
@@ -229,39 +266,46 @@ const Reports = () => {
</div>
)}
</div>
- <div className="mb-4 flex items-center justify-between space-x-3">
- <div className="flex items-center space-x-3">
- <DateRangePicker
- onChange={handleDateRangePicker}
- value="7d"
- options={TIME_PERIODS_REPORTS}
- loading={isLoading}
- />
-
- {startDate && endDate && (
- <div className="hidden items-center space-x-1 lg:flex ">
- <span className="text-sm text-foreground-light">
- {dayjs(startDate).format('MMM D, YYYY')}
- </span>
- <span className="text-foreground-lighter">
- <ArrowRight size={12} />
- </span>
- <span className="text-sm text-foreground-light">
- {dayjs(endDate).format('MMM D, YYYY')}
- </span>
- </div>
- )}
- </div>
+ <div
+ className={cn(
+ 'mb-4 flex items-center gap-x-3',
+ showDatePicker ? 'justify-between' : 'justify-end'
+ )}
+ >
+ {showDatePicker && (
+ <div className="flex items-center gap-x-3">
+ <DateRangePicker
+ onChange={handleDateRangePicker}
+ value="7d"
+ options={TIME_PERIODS_REPORTS}
+ loading={isLoading}
+ />
+
+ {startDate && endDate && (
+ <div className="hidden items-center space-x-1 lg:flex ">
+ <span className="text-sm text-foreground-light">
+ {dayjs(startDate).format('MMM D, YYYY')}
+ </span>
+ <span className="text-foreground-lighter">
+ <ArrowRight size={12} />
+ </span>
+ <span className="text-sm text-foreground-light">
+ {dayjs(endDate).format('MMM D, YYYY')}
+ </span>
+ </div>
+ )}
+ </div>
+ )}
<div className="flex items-center gap-x-2">
{canUpdateReport ? (
<DropdownMenu>
<DropdownMenuTrigger asChild>
- <Button type="default" iconRight={<Settings size={14} />}>
- <span>Add / Remove charts</span>
+ <Button type="default" icon={<Plus />}>
+ <span>Add block</span>
</Button>
</DropdownMenuTrigger>
- <DropdownMenuContent side="bottom" align="end">
+ <DropdownMenuContent side="bottom" align="center" className="w-44">
<MetricOptions config={config} handleChartSelection={handleChartSelection} />
</DropdownMenuContent>
</DropdownMenu>
@@ -269,7 +313,7 @@ const Reports = () => {
<ButtonTooltip
disabled
type="default"
- iconRight={<Settings size={14} />}
+ icon={<Plus />}
tooltip={{
content: {
side: 'bottom',
@@ -278,7 +322,7 @@ const Reports = () => {
},
}}
>
- Add / Remove charts
+ Add block
</ButtonTooltip>
)}
<DatabaseSelector />
@@ -314,6 +358,7 @@ const Reports = () => {
editableReport={config}
disableUpdate={!canUpdateReport}
onRemoveChart={popChart}
+ onUpdateChart={updateChart}
setEditableReport={setConfig}
/>
)}
diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/ChartConfig.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/ChartConfig.tsx
index bb21c0f4d6a..8358e7efe28 100644
--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/ChartConfig.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/ChartConfig.tsx
@@ -21,6 +21,7 @@ import {
type Results = { rows: readonly any[] }
export type ChartConfig = {
+ view?: 'table' | 'chart'
type: 'bar'
cumulative: boolean
xKey: string
diff --git a/apps/studio/components/layouts/ReportsLayout/ReportsMenu.tsx b/apps/studio/components/layouts/ReportsLayout/ReportsMenu.tsx
index 684eefb283e..188f2962a91 100644
--- a/apps/studio/components/layouts/ReportsLayout/ReportsMenu.tsx
+++ b/apps/studio/components/layouts/ReportsLayout/ReportsMenu.tsx
@@ -15,7 +15,7 @@ import { Content, useContentQuery } from 'data/content/content-query'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { useIsFeatureEnabled } from 'hooks/misc/useIsFeatureEnabled'
import { useProfile } from 'lib/profile'
-import { AlertDescription_Shadcn_, AlertTitle_Shadcn_, Alert_Shadcn_, Button, Menu, cn } from 'ui'
+import { Menu, cn } from 'ui'
import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
import { ReportMenuItem } from './ReportMenuItem'
diff --git a/apps/studio/components/to-be-cleaned/Charts/ChartHandler.tsx b/apps/studio/components/to-be-cleaned/Charts/ChartHandler.tsx
index 5248759b69e..b72c397cfc2 100644
--- a/apps/studio/components/to-be-cleaned/Charts/ChartHandler.tsx
+++ b/apps/studio/components/to-be-cleaned/Charts/ChartHandler.tsx
@@ -33,7 +33,6 @@ interface ChartHandlerProps {
isLoading?: boolean
format?: string
highlightedValue?: string | number
- onBarClick?: (v: any) => void
}
/**
@@ -60,7 +59,6 @@ const ChartHandler = ({
isLoading,
format,
highlightedValue,
- onBarClick,
}: PropsWithChildren<ChartHandlerProps>) => {
const router = useRouter()
const { ref } = router.query
diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.types.ts b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.types.ts
index 38fb580b306..c587434a402 100644
--- a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.types.ts
+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.types.ts
@@ -1,2 +1,10 @@
export type SupportedAssistantEntities = 'rls-policies' | 'functions'
export type SupportedAssistantQuickPromptTypes = 'suggest' | 'examples' | 'ask'
+
+export type AssistantSnippetProps = {
+ title: string
+ runQuery: 'true' | 'false'
+ isChart?: 'true' | 'false'
+ xAxis?: string
+ yAxis?: string
+}
diff --git a/apps/studio/components/ui/AIAssistantPanel/Message.tsx b/apps/studio/components/ui/AIAssistantPanel/Message.tsx
index 509fc5f88b1..4ae075b24ca 100644
--- a/apps/studio/components/ui/AIAssistantPanel/Message.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/Message.tsx
@@ -1,180 +1,17 @@
import { User } from 'lucide-react'
-import {
- PropsWithChildren,
- memo,
- useMemo,
- useEffect,
- createContext,
- useContext,
- ReactNode,
-} from 'react'
+import { createContext, PropsWithChildren, useMemo } from 'react'
import ReactMarkdown from 'react-markdown'
-import remarkGfm from 'remark-gfm'
import { Components } from 'react-markdown/lib/ast-to-react'
+import remarkGfm from 'remark-gfm'
-import {
- AiIconAnimation,
- cn,
- CodeBlock,
- markdownComponents,
- WarningIcon,
- type CodeBlockLang,
-} from 'ui'
-import { QueryBlock } from '../QueryBlock/QueryBlock'
-import CollapsibleCodeBlock from './CollapsibleCodeBlock'
-import { DebouncedComponent } from '../DebouncedComponent'
-
-interface MessageProps {
- role: 'function' | 'system' | 'user' | 'assistant' | 'data' | 'tool'
- content?: string
- isLoading: boolean
- readOnly?: boolean
- action?: React.ReactNode
- variant?: 'default' | 'warning'
-}
-
-type AssistantSnippetProps = {
- title: string
- runQuery: 'true' | 'false'
- isChart?: 'true' | 'false'
- xAxis?: string
- yAxis?: string
-}
+import { AiIconAnimation, cn, markdownComponents, WarningIcon } from 'ui'
+import { Heading3, InlineCode, Link, ListItem, MarkdownPre, OrderedList } from './MessageMarkdown'
interface MessageContextType {
isLoading: boolean
readOnly?: boolean
}
-
-const MessageContext = createContext<MessageContextType>({ isLoading: false })
-
-const MemoizedQueryBlock = memo(
- ({
- sql,
- title,
- xAxis,
- yAxis,
- isChart,
- isLoading,
- runQuery,
- }: {
- sql: string
- title: string
- xAxis?: string
- yAxis?: string
- isChart: boolean
- isLoading: boolean
- runQuery: boolean
- }) => (
- <DebouncedComponent
- delay={500}
- value={sql}
- fallback={
- <div className="bg-surface-100 border-overlay rounded border shadow-sm px-3 py-2 text-xs">
- Writing SQL...
- </div>
- }
- >
- <QueryBlock
- lockColumns
- label={title}
- sql={sql}
- chartConfig={{
- type: 'bar',
- cumulative: false,
- xKey: xAxis ?? '',
- yKey: yAxis ?? '',
- }}
- isChart={isChart}
- isLoading={isLoading}
- runQuery={runQuery}
- />
- </DebouncedComponent>
- )
-)
-MemoizedQueryBlock.displayName = 'MemoizedQueryBlock'
-
-const MarkdownPre = ({ children }: any) => {
- const { isLoading, readOnly } = useContext(MessageContext)
-
- const language = children[0].props.className?.replace('language-', '') || 'sql'
- const rawSql = language === 'sql' ? children[0].props.children : undefined
- const formatted = (rawSql || [''])[0]
- const propsMatch = formatted.match(/--\s*props:\s*(\{[^}]+\})/)
-
- const snippetProps: AssistantSnippetProps = propsMatch ? JSON.parse(propsMatch[1]) : {}
- const { xAxis, yAxis } = snippetProps
- const title = snippetProps.title || 'SQL Query'
- const isChart = snippetProps.isChart === 'true'
- const runQuery = snippetProps.runQuery === 'true'
- const sql = formatted?.replace(/--\s*props:\s*\{[^}]+\}/, '').trim()
-
- return (
- <div className="w-auto -ml-[36px] overflow-x-hidden">
- {language === 'sql' ? (
- readOnly ? (
- <CollapsibleCodeBlock
- value={children[0].props.children[0]}
- language="sql"
- hideLineNumbers
- />
- ) : (
- <MemoizedQueryBlock
- sql={sql}
- title={title}
- xAxis={xAxis}
- yAxis={yAxis}
- isChart={isChart}
- isLoading={isLoading}
- runQuery={runQuery}
- />
- )
- ) : (
- <CodeBlock
- hideLineNumbers
- value={children[0].props.children[0]}
- language={language as CodeBlockLang}
- className={cn(
- 'max-h-96 max-w-none block border rounded !bg-transparent !py-3 !px-3.5 prose dark:prose-dark text-foreground',
- '[&>code]:m-0 [&>code>span]:flex [&>code>span]:flex-wrap [&>code]:block [&>code>span]:text-foreground'
- )}
- />
- )}
- </div>
- )
-}
-
-const OrderedList = memo(({ children }: { children: ReactNode }) => (
- <ol className="flex flex-col gap-y-4">{children}</ol>
-))
-OrderedList.displayName = 'OrderedList'
-
-const ListItem = memo(({ children }: { children: ReactNode }) => (
- <li className="[&>pre]:mt-2">{children}</li>
-))
-ListItem.displayName = 'ListItem'
-
-const Heading3 = memo(({ children }: { children: ReactNode }) => (
- <h3 className="underline">{children}</h3>
-))
-Heading3.displayName = 'Heading3'
-
-const InlineCode = memo(({ className, children }: { className?: string; children: ReactNode }) => (
- <code className={cn('text-xs', className)}>{children}</code>
-))
-InlineCode.displayName = 'InlineCode'
-
-const Link = memo(({ href, children }: { href?: string; children: ReactNode }) => (
- <a
- target="_blank"
- rel="noopener noreferrer"
- href={href}
- className="underline transition underline-offset-2 decoration-foreground-lighter hover:decoration-foreground text-foreground"
- >
- {children}
- </a>
-))
-Link.displayName = 'Link'
+export const MessageContext = createContext<MessageContextType>({ isLoading: false })
const baseMarkdownComponents: Partial<Components> = {
ol: OrderedList,
@@ -185,6 +22,15 @@ const baseMarkdownComponents: Partial<Components> = {
pre: MarkdownPre,
}
+interface MessageProps {
+ role: 'function' | 'system' | 'user' | 'assistant' | 'data' | 'tool'
+ content?: string
+ isLoading: boolean
+ readOnly?: boolean
+ action?: React.ReactNode
+ variant?: 'default' | 'warning'
+}
+
export const Message = function Message({
role,
content,
@@ -194,19 +40,9 @@ export const Message = function Message({
action = null,
variant = 'default',
}: PropsWithChildren<MessageProps>) {
- useEffect(() => {
- return () => {
- console.log('unmounting parent')
- }
- }, [])
-
const isUser = role === 'user'
-
const allMarkdownComponents = useMemo(
- () => ({
- ...markdownComponents,
- ...baseMarkdownComponents,
- }),
+ () => ({ ...markdownComponents, ...baseMarkdownComponents }),
[]
)
diff --git a/apps/studio/components/ui/AIAssistantPanel/MessageMarkdown.tsx b/apps/studio/components/ui/AIAssistantPanel/MessageMarkdown.tsx
new file mode 100644
index 00000000000..ebc9dd09942
--- /dev/null
+++ b/apps/studio/components/ui/AIAssistantPanel/MessageMarkdown.tsx
@@ -0,0 +1,158 @@
+import { memo, ReactNode, useContext } from 'react'
+
+import { useSendEventMutation } from 'data/telemetry/send-event-mutation'
+import { TelemetryActions } from 'lib/constants/telemetry'
+import { cn, CodeBlock, CodeBlockLang } from 'ui'
+import { DebouncedComponent } from '../DebouncedComponent'
+import { QueryBlock } from '../QueryBlock/QueryBlock'
+import { AssistantSnippetProps } from './AIAssistant.types'
+import { identifyQueryType } from './AIAssistant.utils'
+import CollapsibleCodeBlock from './CollapsibleCodeBlock'
+import { MessageContext } from './Message'
+
+export const OrderedList = memo(({ children }: { children: ReactNode }) => (
+ <ol className="flex flex-col gap-y-4">{children}</ol>
+))
+OrderedList.displayName = 'OrderedList'
+
+export const ListItem = memo(({ children }: { children: ReactNode }) => (
+ <li className="[&>pre]:mt-2">{children}</li>
+))
+ListItem.displayName = 'ListItem'
+
+export const Heading3 = memo(({ children }: { children: ReactNode }) => (
+ <h3 className="underline">{children}</h3>
+))
+Heading3.displayName = 'Heading3'
+
+export const InlineCode = memo(
+ ({ className, children }: { className?: string; children: ReactNode }) => (
+ <code className={cn('text-xs', className)}>{children}</code>
+ )
+)
+InlineCode.displayName = 'InlineCode'
+
+export const Link = memo(({ href, children }: { href?: string; children: ReactNode }) => (
+ <a
+ target="_blank"
+ rel="noopener noreferrer"
+ href={href}
+ className="underline transition underline-offset-2 decoration-foreground-lighter hover:decoration-foreground text-foreground"
+ >
+ {children}
+ </a>
+))
+Link.displayName = 'Link'
+
+const MemoizedQueryBlock = memo(
+ ({
+ sql,
+ title,
+ xAxis,
+ yAxis,
+ isChart,
+ isLoading,
+ runQuery,
+ onRunQuery,
+ }: {
+ sql: string
+ title: string
+ xAxis?: string
+ yAxis?: string
+ isChart: boolean
+ isLoading: boolean
+ runQuery: boolean
+ onRunQuery: (queryType: 'select' | 'mutation') => void
+ }) => (
+ <DebouncedComponent
+ delay={500}
+ value={sql}
+ fallback={
+ <div className="bg-surface-100 border-overlay rounded border shadow-sm px-3 py-2 text-xs">
+ Writing SQL...
+ </div>
+ }
+ >
+ <QueryBlock
+ lockColumns
+ label={title}
+ sql={sql}
+ chartConfig={{
+ type: 'bar',
+ cumulative: false,
+ xKey: xAxis ?? '',
+ yKey: yAxis ?? '',
+ view: isChart ? 'chart' : 'table',
+ }}
+ showSql={!isChart}
+ isChart={isChart}
+ isLoading={isLoading}
+ runQuery={runQuery}
+ onRunQuery={onRunQuery}
+ />
+ </DebouncedComponent>
+ )
+)
+MemoizedQueryBlock.displayName = 'MemoizedQueryBlock'
+
+export const MarkdownPre = ({ children }: { children: any }) => {
+ const { isLoading, readOnly } = useContext(MessageContext)
+ const { mutate: sendEvent } = useSendEventMutation()
+
+ const language = children[0].props.className?.replace('language-', '') || 'sql'
+ const rawSql = language === 'sql' ? children[0].props.children : undefined
+ const formatted = (rawSql || [''])[0]
+ const propsMatch = formatted.match(/--\s*props:\s*(\{[^}]+\})/)
+
+ const snippetProps: AssistantSnippetProps = propsMatch ? JSON.parse(propsMatch[1]) : {}
+ const { xAxis, yAxis } = snippetProps
+ const title = snippetProps.title || 'SQL Query'
+ const isChart = snippetProps.isChart === 'true'
+ const runQuery = snippetProps.runQuery === 'true'
+ const sql = formatted?.replace(/--\s*props:\s*\{[^}]+\}/, '').trim()
+
+ const onRunQuery = async (queryType: 'select' | 'mutation') => {
+ sendEvent({
+ action: TelemetryActions.ASSISTANT_SUGGESTION_RUN_QUERY_CLICKED,
+ properties: {
+ queryType,
+ ...(queryType === 'mutation' ? { category: identifyQueryType(sql) ?? 'unknown' } : {}),
+ },
+ })
+ }
+
+ return (
+ <div className="w-auto -ml-[36px] overflow-x-hidden">
+ {language === 'sql' ? (
+ readOnly ? (
+ <CollapsibleCodeBlock
+ value={children[0].props.children[0]}
+ language="sql"
+ hideLineNumbers
+ />
+ ) : (
+ <MemoizedQueryBlock
+ sql={sql}
+ title={title}
+ xAxis={xAxis}
+ yAxis={yAxis}
+ isChart={isChart}
+ isLoading={isLoading}
+ runQuery={runQuery}
+ onRunQuery={onRunQuery}
+ />
+ )
+ ) : (
+ <CodeBlock
+ hideLineNumbers
+ value={children[0].props.children[0]}
+ language={language as CodeBlockLang}
+ className={cn(
+ 'max-h-96 max-w-none block border rounded !bg-transparent !py-3 !px-3.5 prose dark:prose-dark text-foreground',
+ '[&>code]:m-0 [&>code>span]:flex [&>code>span]:flex-wrap [&>code]:block [&>code>span]:text-foreground'
+ )}
+ />
+ )}
+ </div>
+ )
+}
diff --git a/apps/studio/components/ui/QueryBlock/EditQueryButton.tsx b/apps/studio/components/ui/QueryBlock/EditQueryButton.tsx
index 590e430db25..89e56aaf371 100644
--- a/apps/studio/components/ui/QueryBlock/EditQueryButton.tsx
+++ b/apps/studio/components/ui/QueryBlock/EditQueryButton.tsx
@@ -1,37 +1,68 @@
import { Edit } from 'lucide-react'
import { useRouter } from 'next/router'
+import { useParams } from 'common'
import { DiffType } from 'components/interfaces/SQLEditor/SQLEditor.types'
import useNewQuery from 'components/interfaces/SQLEditor/hooks'
import { useSendEventMutation } from 'data/telemetry/send-event-mutation'
import { TelemetryActions } from 'lib/constants/telemetry'
+import Link from 'next/link'
+import { ComponentProps } from 'react'
import { useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'
-import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from 'ui'
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ TooltipContent_Shadcn_,
+} from 'ui'
import { ButtonTooltip } from '../ButtonTooltip'
interface EditQueryButtonProps {
+ id?: string
title: string
- sql: string
+ sql?: string
}
-export const EditQueryButton = ({ sql, title }: EditQueryButtonProps) => {
+export const EditQueryButton = ({ id, sql, title }: EditQueryButtonProps) => {
const router = useRouter()
+ const { ref } = useParams()
const { newQuery } = useNewQuery()
const sqlEditorSnap = useSqlEditorV2StateSnapshot()
const isInSQLEditor = router.pathname.includes('/sql')
const isInNewSnippet = router.pathname.endsWith('/sql')
+ const tooltip: { content: ComponentProps<typeof TooltipContent_Shadcn_> & { text: string } } = {
+ content: { side: 'bottom', text: 'Edit in SQL Editor' },
+ }
const { mutate: sendEvent } = useSendEventMutation()
const handleEditInSQLEditor = () => {
- if (isInSQLEditor) {
- sqlEditorSnap.setDiffContent(sql, DiffType.Addition)
- } else {
- newQuery(sql, title)
+ if (sql) {
+ if (isInSQLEditor) {
+ sqlEditorSnap.setDiffContent(sql, DiffType.Addition)
+ } else {
+ newQuery(sql, title)
+ }
}
}
+ if (id !== undefined) {
+ return (
+ <ButtonTooltip
+ asChild
+ type="text"
+ size="tiny"
+ className="w-7 h-7"
+ icon={<Edit size={14} />}
+ tooltip={tooltip}
+ >
+ <Link href={`/project/${ref}/sql/${id}`} />
+ </ButtonTooltip>
+ )
+ }
+
return !isInSQLEditor || isInNewSnippet ? (
<ButtonTooltip
type="text"
@@ -48,7 +79,7 @@ export const EditQueryButton = ({ sql, title }: EditQueryButtonProps) => {
},
})
}}
- tooltip={{ content: { side: 'bottom', text: 'Edit in SQL Editor' } }}
+ tooltip={tooltip}
/>
) : (
<DropdownMenu>
@@ -56,22 +87,27 @@ export const EditQueryButton = ({ sql, title }: EditQueryButtonProps) => {
<ButtonTooltip
type="text"
size="tiny"
+ disabled={!sql}
className="w-7 h-7"
icon={<Edit size={14} />}
- tooltip={{ content: { side: 'bottom', text: 'Edit in SQL Editor' } }}
+ tooltip={!!sql ? tooltip : { content: { side: 'bottom', text: undefined } }}
/>
</DropdownMenuTrigger>
- <DropdownMenuContent className="w-36">
- <DropdownMenuItem onClick={() => sqlEditorSnap.setDiffContent(sql, DiffType.Addition)}>
- Insert code
- </DropdownMenuItem>
- <DropdownMenuItem onClick={() => sqlEditorSnap.setDiffContent(sql, DiffType.Modification)}>
- Replace code
- </DropdownMenuItem>
- <DropdownMenuItem onClick={() => sqlEditorSnap.setDiffContent(sql, DiffType.NewSnippet)}>
- Create new snippet
- </DropdownMenuItem>
- </DropdownMenuContent>
+ {!!sql && (
+ <DropdownMenuContent className="w-36">
+ <DropdownMenuItem onClick={() => sqlEditorSnap.setDiffContent(sql, DiffType.Addition)}>
+ Insert code
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => sqlEditorSnap.setDiffContent(sql, DiffType.Modification)}
+ >
+ Replace code
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => sqlEditorSnap.setDiffContent(sql, DiffType.NewSnippet)}>
+ Create new snippet
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ )}
</DropdownMenu>
)
}
diff --git a/apps/studio/components/ui/QueryBlock/QueryBlock.tsx b/apps/studio/components/ui/QueryBlock/QueryBlock.tsx
index 40db5cf35a0..b4b0a88caba 100644
--- a/apps/studio/components/ui/QueryBlock/QueryBlock.tsx
+++ b/apps/studio/components/ui/QueryBlock/QueryBlock.tsx
@@ -8,7 +8,7 @@ import { ChartConfig } from 'components/interfaces/SQLEditor/UtilityPanel/ChartC
import Results from 'components/interfaces/SQLEditor/UtilityPanel/Results'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { useExecuteSqlMutation } from 'data/sql/execute-sql-mutation'
-import { Parameter, parseParameters, processParameterizedSql } from 'lib/sql-parameters'
+import { Parameter, parseParameters } from 'lib/sql-parameters'
import {
Button,
ChartContainer,
@@ -27,29 +27,55 @@ import { EditQueryButton } from './EditQueryButton'
import { ParametersPopover } from './ParametersPopover'
import { getCumulativeResults } from './QueryBlock.utils'
-const DEFAULT_CHART_CONFIG: ChartConfig = {
+export const DEFAULT_CHART_CONFIG: ChartConfig = {
type: 'bar',
cumulative: false,
xKey: '',
yKey: '',
showLabels: false,
showGrid: false,
+ view: 'table',
}
interface QueryBlockProps {
+ /** Applicable if SQL is a snippet that's already saved (Used in Reports) */
id?: string
+ /** Title of the QueryBlock */
label: string
- sql: string
+ /** SQL query to render/run in the QueryBlock */
+ sql?: string
+ /** Configuration of the output chart based on the query result */
chartConfig?: ChartConfig
- maxHeight?: number
+ /** Not implemented yet: Will be the next part of ReportsV2 */
parameterValues?: Record<string, string>
- actions?: ReactNode // Any other actions specific to the parent to be rendered in the header
+ /** Any other actions specific to the parent to be rendered in the header */
+ actions?: ReactNode
+ /** Toggle visiblity of SQL query on render */
+ showSql?: boolean
+ /** Indicate if SQL query can be rendered as a chart */
isChart?: boolean
+ /** For Assistant as QueryBlock is rendered while streaming response */
isLoading?: boolean
+ /** Override to prevent running the SQL query provided */
runQuery?: boolean
+ /** Prevent updating of columns for X and Y axes in the chart view */
lockColumns?: boolean
+ /** Max height set to render results / charts (Defaults to 250) */
+ maxHeight?: number
+ /** Not implemented yet: Will be the next part of ReportsV2 */
onSetParameter?: (params: Parameter[]) => void
- onUpdateChartConfig?: (config: ChartConfig) => void
+ /** Optional callback the SQL query is run */
+ onRunQuery?: (queryType: 'select' | 'mutation') => void
+
+ // [Joshen] Params below are currently only used by ReportsV2 (Might revisit to see how to improve these)
+ /** Optional height set to render the SQL query (Used in Reports) */
+ queryHeight?: number
+ /** Override hiding Run Query button if SQL query is NOT readonly (Used in Reports) */
+ disableRunIfMutation?: boolean
+ /** UI to render if there's no query results (Used in Reports) */
+ noResultPlaceholder?: ReactNode
+ /** Optional callback whenever a chart configuration is updated (Used in Reports) */
+ onUpdateChartConfig?: (config: Partial<ChartConfig>) => void
}
// [Joshen ReportsV2] JFYI we may adjust this in subsequent PRs when we implement this into Reports V2
@@ -60,35 +86,38 @@ export const QueryBlock = ({
sql,
chartConfig = DEFAULT_CHART_CONFIG,
maxHeight = 250,
+ queryHeight,
parameterValues: extParameterValues,
actions,
+ showSql: _showSql = false,
isChart = false,
isLoading = false,
runQuery = false,
lockColumns = false,
+ disableRunIfMutation = false,
+ noResultPlaceholder = null,
+ onRunQuery,
onSetParameter,
onUpdateChartConfig,
}: QueryBlockProps) => {
const { ref } = useParams()
const { project } = useProjectContext()
- const [showSql, setShowSql] = useState(!isChart)
- const [view, setView] = useState<'table' | 'chart'>(isChart ? 'chart' : 'table')
- // [Joshen] Thinking cumulative could just be a UI state here to prevent unnecessary re-rendering
- const [cumulative, setCumulative] = useState(false)
+ const [chartSettings, setChartSettings] = useState<ChartConfig>(chartConfig)
+ const { xKey, yKey, view = 'table' } = chartSettings
+
+ const [showSql, setShowSql] = useState(_showSql)
const [queryResult, setQueryResult] = useState<any[]>()
const [parameterValues, setParameterValues] = useState<Record<string, string>>({})
const [showWarning, setShowWarning] = useState<'hasWriteOperation' | 'hasUnknownFunctions'>()
- const { xKey, yKey } = chartConfig
- const showChart =
- isChart && (queryResult ?? []).length > 0 && !!xKey && !!yKey && view === 'chart'
-
const parameters = useMemo(() => {
if (!sql) return []
return parseParameters(sql)
}, [sql])
- const combinedParameterValues = { ...extParameterValues, ...parameterValues }
+ // [Joshen] This is for when we introduced the concept of parameters into our reports
+ // const combinedParameterValues = { ...extParameterValues, ...parameterValues }
+ const isReadOnlySelectSQL = isReadOnlySelect(sql ?? '')
const { mutate: execute, isLoading: isExecuting } = useExecuteSqlMutation({
onSuccess: (data) => setQueryResult(data.result),
@@ -97,17 +126,18 @@ export const QueryBlock = ({
const handleExecute = () => {
if (!sql || isLoading) return
- if (!isReadOnlySelect(sql)) {
+ if (!isReadOnlySelectSQL) {
const hasUnknownFunctions = containsUnknownFunction(sql)
return setShowWarning(hasUnknownFunctions ? 'hasUnknownFunctions' : 'hasWriteOperation')
}
try {
- const processedSql = processParameterizedSql(sql, combinedParameterValues)
+ // [Joshen] This is for when we introduced the concept of parameters into our reports
+ // const processedSql = processParameterizedSql(sql, combinedParameterValues)
execute({
projectRef: ref,
connectionString: project?.connectionString,
- sql: processedSql,
+ sql,
})
} catch (error: any) {
toast.error(`Failed to execute query: ${error.message}`)
@@ -171,40 +201,48 @@ export const QueryBlock = ({
view={view}
isChart={isChart}
lockColumns={lockColumns}
- chartConfig={{ ...chartConfig, cumulative }}
+ chartConfig={chartSettings}
columns={Object.keys(queryResult[0] || {})}
- changeView={setView}
+ changeView={(view) => {
+ if (onUpdateChartConfig) onUpdateChartConfig({ view })
+ setChartSettings({ ...chartSettings, view })
+ }}
updateChartConfig={(config) => {
if (onUpdateChartConfig) onUpdateChartConfig(config)
- setCumulative(config.cumulative)
+ setChartSettings(config)
}}
/>
)}
</>
)}
- <EditQueryButton title={label} sql={sql} />
+ <EditQueryButton id={id} title={label} sql={sql} />
- <ButtonTooltip
- type="text"
- size="tiny"
- className="w-7 h-7"
- icon={<Play size={14} />}
- loading={isExecuting || isLoading}
- disabled={isLoading}
- onClick={handleExecute}
- tooltip={{
- content: {
- side: 'bottom',
- className: 'max-w-56 text-center',
- text: isExecuting ? (
- <p>{`Query is running. You may cancel ongoing queries via the [SQL Editor](/project/${ref}/sql?viewOngoingQueries=true).`}</p>
- ) : (
- 'Run query'
- ),
- },
- }}
- />
+ {(isReadOnlySelectSQL || (!isReadOnlySelectSQL && !disableRunIfMutation)) && (
+ <ButtonTooltip
+ type="text"
+ size="tiny"
+ className="w-7 h-7"
+ icon={<Play size={14} />}
+ loading={isExecuting || isLoading}
+ disabled={isLoading}
+ onClick={() => {
+ handleExecute()
+ if (!!sql && isReadOnlySelect(sql)) onRunQuery?.('select')
+ }}
+ tooltip={{
+ content: {
+ side: 'bottom',
+ className: 'max-w-56 text-center',
+ text: isExecuting ? (
+ <p>{`Query is running. You may cancel ongoing queries via the [SQL Editor](/project/${ref}/sql?viewOngoingQueries=true).`}</p>
+ ) : (
+ 'Run query'
+ ),
+ },
+ }}
+ />
+ )}
{actions}
</div>
@@ -236,17 +274,20 @@ export const QueryBlock = ({
<Button
type="danger"
size="tiny"
+ disabled={!sql}
className="w-full flex-1"
onClick={() => {
// [Joshen] This is for when we introduced the concept of parameters into our reports
// const processedSql = processParameterizedSql(sql!, combinedParameterValues)
-
- setShowWarning(undefined)
- execute({
- projectRef: ref,
- connectionString: project?.connectionString,
- sql,
- })
+ if (sql) {
+ setShowWarning(undefined)
+ execute({
+ projectRef: ref,
+ connectionString: project?.connectionString,
+ sql,
+ })
+ onRunQuery?.('mutation')
+ }
}}
>
Run
@@ -256,8 +297,17 @@ export const QueryBlock = ({
)}
{/* QueryBlock output */}
+ {isExecuting && queryResult === undefined && (
+ <div className="border-t p-3">
+ <ShimmeringLoader />
+ </div>
+ )}
+
{showSql && (
- <div className="shrink-0 max-h-96 overflow-y-auto border-t">
+ <div
+ className="shrink-0 max-h-96 overflow-y-auto border-t"
+ style={{ height: !!queryHeight ? `${queryHeight}px` : undefined }}
+ >
<CodeBlock
hideLineNumbers
wrapLines={false}
@@ -271,54 +321,62 @@ export const QueryBlock = ({
</div>
)}
- {isExecuting && queryResult === undefined && (
- <div className="border-t p-3">
- <ShimmeringLoader />
- </div>
- )}
-
- {showChart ? (
- <div className={cn('border-t flex-1 shrink-0')}>
- <ChartContainer
- className="aspect-auto p-3"
- config={{}}
- style={{
- height: maxHeight ? `${maxHeight}px` : undefined,
- minHeight: maxHeight ? `${maxHeight}px` : undefined,
- }}
- >
- <BarChart
- accessibilityLayer
- margin={{ left: 0, right: 0 }}
- data={
- cumulative
- ? getCumulativeResults({ rows: queryResult ?? [] }, chartConfig)
- : queryResult
- }
- >
- <CartesianGrid vertical={false} />
- <XAxis
- dataKey={xKey}
- tickLine={false}
- axisLine={false}
- tickMargin={8}
- minTickGap={32}
- />
- <ChartTooltip content={<ChartTooltipContent className="w-[150px]" />} />
- <Bar dataKey={yKey} fill="var(--chart-1)" radius={4} />
- </BarChart>
- </ChartContainer>
- </div>
+ {view === 'chart' && queryResult !== undefined ? (
+ <>
+ {(queryResult ?? []).length === 0 ? (
+ <div className="flex h-full items-center justify-center">
+ <p className="text-foreground-light text-xs">No results returned from query</p>
+ </div>
+ ) : !xKey || !yKey ? (
+ <div className="flex h-full items-center justify-center">
+ <p className="text-foreground-light text-xs">Select columns for the X and Y axes</p>
+ </div>
+ ) : (
+ <div className={cn('flex-1 border-t')}>
+ <ChartContainer
+ className="aspect-auto px-3 pb-2"
+ config={{}}
+ style={{
+ height: maxHeight ? `${maxHeight}px` : undefined,
+ minHeight: maxHeight ? `${maxHeight}px` : undefined,
+ }}
+ >
+ <BarChart
+ accessibilityLayer
+ margin={{ left: 0, right: 0 }}
+ data={
+ chartSettings.cumulative
+ ? getCumulativeResults({ rows: queryResult ?? [] }, chartSettings)
+ : queryResult
+ }
+ >
+ <CartesianGrid vertical={false} />
+ <XAxis
+ dataKey={xKey}
+ tickLine={false}
+ axisLine={false}
+ tickMargin={8}
+ minTickGap={32}
+ />
+ <ChartTooltip content={<ChartTooltipContent className="w-[150px]" />} />
+ <Bar dataKey={yKey} fill="var(--chart-1)" radius={4} />
+ </BarChart>
+ </ChartContainer>
+ </div>
+ )}
+ </>
) : (
<>
- {queryResult && (
+ {queryResult ? (
<div
className={cn('flex-1 overflow-auto relative border-t')}
style={{ maxHeight: maxHeight ? `${maxHeight}px` : undefined }}
>
<Results rows={queryResult} />
</div>
- )}
+ ) : !isExecuting ? (
+ noResultPlaceholder
+ ) : null}
</>
)}
</div>
diff --git a/apps/studio/components/ui/QueryBlock/QueryBlockWrapper.tsx b/apps/studio/components/ui/QueryBlock/QueryBlockWrapper.tsx
deleted file mode 100644
index 79bac51df5d..00000000000
--- a/apps/studio/components/ui/QueryBlock/QueryBlockWrapper.tsx
+++ /dev/null
@@ -1,68 +0,0 @@
-import { useState } from 'react'
-
-import { useParams } from 'common'
-import { ChartConfig } from 'components/interfaces/SQLEditor/UtilityPanel/ChartConfig'
-import { useContentIdQuery } from 'data/content/content-id-query'
-import { Parameter } from 'lib/sql-parameters'
-import { SqlSnippets } from 'types'
-import { QueryBlock } from './QueryBlock'
-
-interface QueryBlockWrapperProps {
- item: {
- label: string
- id?: string
- sql?: string
- isSnippet?: boolean
- isChart?: boolean
- chartConfig?: ChartConfig
- results?: any
- }
- maxHeight?: number
- lockColumns?: boolean
- runQuery?: boolean
- isLoading?: boolean
- parameterValues?: Record<string, string>
- onUpdateChartConfig: (config: ChartConfig) => void
- onSetParameter?: (params: Parameter[]) => void
-}
-
-// [Joshen ReportsV2] I'm actually not sure if this wrapper but keeping for now till it becomes clearer
-// when we progress on with the work for ReportsV2. Currently the only logic here is just fetching data for QueryBlock
-export const QueryBlockWrapper = ({
- item,
- maxHeight,
- lockColumns = false,
- runQuery = false,
- isLoading = false,
- parameterValues,
- onUpdateChartConfig,
- onSetParameter,
-}: QueryBlockWrapperProps) => {
- const { ref: projectRef } = useParams()
- const [sql, setSql] = useState(item.sql || '')
-
- useContentIdQuery(
- { projectRef, id: item.id },
- {
- enabled: item.isSnippet && !!item.id,
- onSuccess: (data) => setSql((data.content as SqlSnippets.Content).sql),
- }
- )
-
- return (
- <QueryBlock
- id={''}
- label={item.label}
- sql={sql}
- maxHeight={maxHeight}
- chartConfig={item.chartConfig}
- isChart={item.isChart}
- isLoading={isLoading}
- runQuery={runQuery}
- lockColumns={lockColumns}
- parameterValues={parameterValues}
- onUpdateChartConfig={onUpdateChartConfig}
- onSetParameter={onSetParameter}
- />
- )
-}
diff --git a/apps/studio/data/content/content-query.ts b/apps/studio/data/content/content-query.ts
index efcda7d5d66..fbde6e51fd5 100644
--- a/apps/studio/data/content/content-query.ts
+++ b/apps/studio/data/content/content-query.ts
@@ -28,15 +28,19 @@ export type ContentType = Content['type']
interface GetContentVariables {
projectRef?: string
type: ContentType
+ name?: string
}
-export async function getContent({ projectRef, type }: GetContentVariables, signal?: AbortSignal) {
+export async function getContent(
+ { projectRef, type, name }: GetContentVariables,
+ signal?: AbortSignal
+) {
if (typeof projectRef === 'undefined') {
throw new Error('projectRef is required for getContent')
}
const { data, error } = await get('/platform/projects/{ref}/content', {
- params: { path: { ref: projectRef }, query: { type } },
+ params: { path: { ref: projectRef }, query: { type, name } },
signal,
})
@@ -54,11 +58,11 @@ export type ContentData = Awaited<ReturnType<typeof getContent>>
export type ContentError = unknown
export const useContentQuery = <TData = ContentData>(
- { projectRef, type }: GetContentVariables,
+ { projectRef, type, name }: GetContentVariables,
{ enabled = true, ...options }: UseQueryOptions<ContentData, ContentError, TData> = {}
) =>
useQuery<ContentData, ContentError, TData>(
- contentKeys.list(projectRef, type),
- ({ signal }) => getContent({ projectRef, type }, signal),
+ contentKeys.list(projectRef, { type, name }),
+ ({ signal }) => getContent({ projectRef, type, name }, signal),
{ enabled: enabled && typeof projectRef !== 'undefined', ...options }
)
diff --git a/apps/studio/data/content/keys.ts b/apps/studio/data/content/keys.ts
index 3e9317d4356..7078bf75f73 100644
--- a/apps/studio/data/content/keys.ts
+++ b/apps/studio/data/content/keys.ts
@@ -3,8 +3,10 @@ import type { SqlSnippet } from './sql-snippets-query'
export const contentKeys = {
allContentLists: (projectRef: string | undefined) => ['projects', projectRef, 'content'] as const,
- list: (projectRef: string | undefined, type: ContentType | undefined) =>
- ['projects', projectRef, 'content', type] as const,
+ list: (
+ projectRef: string | undefined,
+ options: { type: ContentType | undefined; name: string | undefined }
+ ) => ['projects', projectRef, 'content', options] as const,
sqlSnippets: (
projectRef: string | undefined,
options?: {
diff --git a/apps/studio/lib/constants/metrics.tsx b/apps/studio/lib/constants/metrics.tsx
index 2b6fd2fb41a..062d48255f7 100644
--- a/apps/studio/lib/constants/metrics.tsx
+++ b/apps/studio/lib/constants/metrics.tsx
@@ -1,5 +1,20 @@
import { Auth, Realtime, Storage } from 'icons'
-import { ActivityIcon, DatabaseIcon, ServerIcon, HeartIcon } from 'lucide-react'
+import { ActivityIcon, DatabaseIcon, HeartIcon, ServerIcon } from 'lucide-react'
+import { ReactNode } from 'react'
+
+export type Metric = {
+ key: string
+ label: string
+ provider?: string
+ category?: MetricCategory
+ id?: string
+}
+
+type MetricCategory = {
+ label: string
+ icon: ReactNode
+ key: string
+}
export const METRIC_CATEGORIES = {
API: {
@@ -39,7 +54,7 @@ export const METRIC_CATEGORIES = {
},
}
-export const METRICS = [
+export const METRICS: Metric[] = [
{
key: 'avg_cpu_usage',
label: 'Average CPU % usage',
diff --git a/apps/studio/styles/main.scss b/apps/studio/styles/main.scss
index f71742f907d..8dd672ab4a1 100644
--- a/apps/studio/styles/main.scss
+++ b/apps/studio/styles/main.scss
@@ -269,3 +269,17 @@ div[data-radix-portal]:not(.portal--toast) {
.settings-container {
@apply mx-auto max-w-4xl xl:max-w-6xl;
}
+
+.react-grid-item.react-grid-placeholder {
+ @apply bg-brand-500 #{!important};
+}
+
+.react-grid-item > .react-resizable-handle::after {
+ content: "";
+ position: absolute;
+ right: 3px !important;
+ bottom: 3px !important;
+ width: 6px !important;
+ height: 6px !important;
+ @apply dark:border-r-2 dark:border-b-2 dark:border-overlay #{!important};
+}
\ No newline at end of file
diff --git a/apps/studio/types/userContent.ts b/apps/studio/types/userContent.ts
index 1f7da48d0a0..fb9405ca1e1 100644
--- a/apps/studio/types/userContent.ts
+++ b/apps/studio/types/userContent.ts
@@ -1,3 +1,5 @@
+import { ChartConfig } from 'components/interfaces/SQLEditor/UtilityPanel/ChartConfig'
+
export interface UserContent<
T = Dashboards.Content | SqlSnippets.Content | LogSqlSnippets.Content,
> {
@@ -67,7 +69,6 @@ export namespace Dashboards {
*/
export interface Content {
schema_version: 1 // we can add some versioning to this schema in case we need to change the format.
-
period_start: {
time_period?: string // "0m", "1m", "5m", "1h", "1d", "1w", "1M", "1y"
date?: string // "2017-01-01T00:00:00.000Z"
@@ -104,10 +105,11 @@ export namespace Dashboards {
y: number
w: number
h: number
+ label: string
attribute: ChartType
- provider: 'daily-stats' | 'prometheus'
+ provider: 'daily-stats' | 'infra-monitoring'
chart_type: 'bar' | 'line' | 'area'
- // title: string // Eventually we might need this "per chart" right?
+ chartConfig?: Partial<ChartConfig>
}
}