ReportBlock.tsx219 lines · main
1import { acceptUntrustedSql } from '@supabase/pg-meta'
2import { useQuery } from '@tanstack/react-query'
3import { useParams } from 'common'
4import { X } from 'lucide-react'
5import { useEffect, useState } from 'react'
6import { toast } from 'sonner'
7
8import { DEPRECATED_REPORTS } from '../Reports.constants'
9import { ChartBlock } from './ChartBlock'
10import { DeprecatedChartBlock } from './DeprecatedChartBlock'
11import { ChartConfig } from '@/components/interfaces/SQLEditor/UtilityPanel/ChartConfig'
12import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
13import { DEFAULT_CHART_CONFIG, QueryBlock } from '@/components/ui/QueryBlock/QueryBlock'
14import { AnalyticsInterval } from '@/data/analytics/constants'
15import { useContentIdQuery } from '@/data/content/content-id-query'
16import { usePrimaryDatabase } from '@/data/read-replicas/replicas-query'
17import { executeSql } from '@/data/sql/execute-sql-query'
18import { sqlKeys } from '@/data/sql/keys'
19import { useDatabaseSelectorStateSnapshot } from '@/state/database-selector'
20import type { Dashboards, SqlSnippets } from '@/types'
21
22interface ReportBlockProps {
23 item: Dashboards.Chart
24 startDate: string
25 endDate: string
26 interval: AnalyticsInterval
27 disableUpdate: boolean
28 isRefreshing: boolean
29 onRemoveChart: ({ metric }: { metric: { key: string } }) => void
30 onUpdateChart: ({
31 chart,
32 chartConfig,
33 }: {
34 chart?: Partial<Dashboards.Chart>
35 chartConfig?: Partial<ChartConfig>
36 }) => void
37}
38
39export const ReportBlock = ({
40 item,
41 startDate,
42 endDate,
43 interval,
44 disableUpdate,
45 isRefreshing,
46 onRemoveChart,
47 onUpdateChart,
48}: ReportBlockProps) => {
49 const { ref: projectRef } = useParams()
50 const state = useDatabaseSelectorStateSnapshot()
51
52 const [isWriteQuery, setIsWriteQuery] = useState(false)
53
54 const isSnippet = item.attribute.startsWith('snippet_')
55
56 const {
57 data,
58 error: contentError,
59 isPending: isLoadingContent,
60 } = useContentIdQuery(
61 { projectRef, id: item.id },
62 {
63 enabled: isSnippet && !!item.id,
64 refetchOnWindowFocus: false,
65 refetchOnMount: false,
66 refetchIntervalInBackground: false,
67 retry: (failureCount: number, error) => {
68 if (error.code === 404 || failureCount >= 2) return false
69 return true
70 },
71 }
72 )
73
74 const sql = isSnippet ? (data?.content as SqlSnippets.Content)?.unchecked_sql : undefined
75 const chartConfig = { ...DEFAULT_CHART_CONFIG, ...(item.chartConfig ?? {}) }
76 const isDeprecatedChart = DEPRECATED_REPORTS.includes(item.attribute)
77 const snippetMissing = contentError?.message.includes('Content not found')
78
79 const { database: primaryDatabase } = usePrimaryDatabase({ projectRef })
80 const readOnlyConnectionString = primaryDatabase?.connection_string_read_only
81 const postgresConnectionString = primaryDatabase?.connectionString
82
83 const {
84 data: queryResult,
85 error: executeSqlError,
86 isPending: executeSqlLoading,
87 refetch,
88 } = useQuery({
89 queryKey: sqlKeys.query(projectRef, [
90 item.id,
91 sql,
92 readOnlyConnectionString,
93 postgresConnectionString,
94 ]),
95 queryFn: async () => {
96 if (!projectRef || !sql) return null
97
98 const connectionString = readOnlyConnectionString ?? postgresConnectionString
99
100 if (!connectionString) {
101 toast.error('Unable to establish a database connection for this project.')
102 return null
103 }
104
105 return executeSql({
106 projectRef,
107 connectionString,
108 // acceptUntrustedSql is usually not allowed in an auto-run position,
109 // but in this case we are explicitly allowing it because adding a block
110 // to a report is an explicit user action.
111 sql: acceptUntrustedSql(sql),
112 })
113 },
114 enabled: !isLoadingContent && contentError == null,
115 refetchOnWindowFocus: false,
116 })
117
118 const rows = queryResult?.result
119
120 useEffect(() => {
121 if (executeSqlError) {
122 const errorMessage = String(executeSqlError).toLowerCase()
123 const isReadOnlyError =
124 errorMessage.includes('read-only transaction') ||
125 errorMessage.includes('permission denied') ||
126 errorMessage.includes('must be owner')
127
128 if (isReadOnlyError) {
129 setIsWriteQuery(true)
130 }
131 }
132 }, [executeSqlError])
133
134 useEffect(() => {
135 if (isRefreshing) {
136 refetch()
137 }
138 }, [isRefreshing, refetch])
139
140 return (
141 <>
142 {isSnippet ? (
143 <QueryBlock
144 blockWriteQueries
145 id={item.id}
146 label={item.label}
147 chartConfig={chartConfig}
148 sql={sql}
149 results={rows}
150 initialHideSql={true}
151 errorText={
152 snippetMissing
153 ? 'SQL snippet not found'
154 : executeSqlError
155 ? String(executeSqlError)
156 : undefined
157 }
158 isExecuting={!contentError && executeSqlLoading}
159 isWriteQuery={isWriteQuery}
160 actions={
161 <ButtonTooltip
162 type="text"
163 icon={<X />}
164 className="w-7 h-7"
165 onClick={() => onRemoveChart({ metric: { key: item.attribute } })}
166 tooltip={{ content: { side: 'bottom', text: 'Remove chart' } }}
167 />
168 }
169 onExecute={(_queryType) => {
170 refetch()
171 }}
172 onUpdateChartConfig={onUpdateChart}
173 onRemoveChart={() => onRemoveChart({ metric: { key: item.attribute } })}
174 disabled={isLoadingContent || snippetMissing || !sql}
175 />
176 ) : isDeprecatedChart ? (
177 <DeprecatedChartBlock
178 attribute={item.attribute}
179 label={`${item.label}${projectRef !== state.selectedDatabaseId ? (item.provider === 'infra-monitoring' ? ' of replica' : ' on project') : ''}`}
180 actions={
181 !disableUpdate ? (
182 <ButtonTooltip
183 type="text"
184 icon={<X />}
185 className="w-7 h-7"
186 onClick={() => onRemoveChart({ metric: { key: item.attribute } })}
187 tooltip={{ content: { side: 'bottom', text: 'Remove chart' } }}
188 />
189 ) : null
190 }
191 />
192 ) : (
193 <ChartBlock
194 startDate={startDate}
195 endDate={endDate}
196 interval={interval}
197 attribute={item.attribute}
198 provider={item.provider}
199 defaultChartStyle={item.chart_type}
200 defaultLogScale={chartConfig?.logScale ?? false}
201 maxHeight={176}
202 label={`${item.label}${projectRef !== state.selectedDatabaseId ? (item.provider === 'infra-monitoring' ? ' of replica' : ' on project') : ''}`}
203 actions={
204 !disableUpdate ? (
205 <ButtonTooltip
206 type="text"
207 icon={<X />}
208 className="w-7 h-7"
209 onClick={() => onRemoveChart({ metric: { key: item.attribute } })}
210 tooltip={{ content: { side: 'bottom', text: 'Remove chart' } }}
211 />
212 ) : null
213 }
214 onUpdateChartConfig={onUpdateChart}
215 />
216 )}
217 </>
218 )
219}