The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat: store sql editor charts (#21990)
Jordi Enricaa01f780ea34
diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/ChartConfig.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/ChartConfig.tsxindex 431a42ca8dc..b996596a834 100644--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/ChartConfig.tsx+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/ChartConfig.tsx@@ -20,7 +20,7 @@ import {type Results = { rows: readonly any[] }export type ChartConfig = {- type: 'bar' | 'line'+ type: 'bar'cumulative: booleanxKey: stringyKey: string@@ -87,7 +87,7 @@ export function ChartConfig({ results = { rows: [] }, config, onConfigChange }:return (<ResizablePanelGroup direction="horizontal" className="flex-grow h-full"><>- <ResizablePanel className="p-4 h-full" defaultSize={85}>+ <ResizablePanel className="p-4 h-full" defaultSize={75}>{config.type === 'bar' && (<BarChartshowLegend@@ -101,7 +101,7 @@ export function ChartConfig({ results = { rows: [] }, config, onConfigChange }:)}</ResizablePanel><ResizableHandle withHandle />- <ResizablePanel defaultSize={15} minSize={15} className="px-3 py-3 space-y-4">+ <ResizablePanel defaultSize={25} minSize={15} className="px-3 py-3 space-y-4"><><div className="flex justify-between items-center h-5"><h2 className="text-sm text-foreground-lighter">Chart options</h2>diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsxindex ae96a7e4f5d..9c5187afc6d 100644--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsx+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsx@@ -1,12 +1,17 @@-import { useState } from 'react'+import { useMemo, useState } from 'react'import ResultsDropdown from './ResultsDropdown'import UtilityActions from './UtilityActions'import UtilityTabResults from './UtilityTabResults'import { useSqlEditorStateSnapshot } from 'state/sql-editor'-import { TabsContent_Shadcn_, TabsList_Shadcn_, TabsTrigger_Shadcn_, Tabs_Shadcn_ } from 'ui'import { ChartConfig } from './ChartConfig'-import { useFlag } from 'hooks'+import { useContentUpsertMutation } from 'data/content/content-upsert-mutation'+import { useContentQuery } from 'data/content/content-query'+import { useParams } from 'common'+import { useQueryClient } from '@tanstack/react-query'+import toast from 'react-hot-toast'+import { contentKeys } from 'data/content/keys'+import { SqlSnippets } from 'types'export type UtilityPanelProps = {id: string@@ -17,6 +22,13 @@ export type UtilityPanelProps = {executeQuery: () => void}+const DEFAULT_CHART_CONFIG = {+ type: 'bar',+ cumulative: false,+ xKey: '',+ yKey: '',+} as const+const UtilityPanel = ({id,isExecuting,@@ -26,14 +38,77 @@ const UtilityPanel = ({executeQuery,}: UtilityPanelProps) => {const snap = useSqlEditorStateSnapshot()- const result = snap.results[id]?.[0]+ const { ref } = useParams()+ const { data } = useContentQuery(ref)+ const snippet = snap.snippets[id]?.snippet++ const queryKeys = contentKeys.list(ref)++ const upsertContent = useContentUpsertMutation({+ invalidateQueriesOnSuccess: false,+ // Optimistic update to the cache+ onMutate: async (newContentSnippet) => {+ const { payload } = newContentSnippet- const [config, setConfig] = useState<ChartConfig>({- type: 'bar',- cumulative: false,- xKey: '',- yKey: '',+ // No need to update the cache for non-SQL content+ if (payload.type !== 'sql') return+ if (!('chart' in payload.content)) return++ // Cancel any existing queries so that the new content is fetched+ await queryClient.cancelQueries(queryKeys)++ const newSnippet = {+ ...snippet,+ content: {+ ...snippet.content,+ chart: payload.content.chart,+ },+ }++ snap.updateSnippet(id, newSnippet)+ },+ onError: async (err, newContent, context) => {+ toast.error(`Failed to update chart. Please try again.`)+ },})+ const queryClient = useQueryClient()++ function getChartConfig() {+ if (!snippet || snippet.type !== 'sql') {+ return DEFAULT_CHART_CONFIG+ }++ if (!snippet.content.chart) {+ return DEFAULT_CHART_CONFIG+ }++ return snippet.content.chart+ }++ const chartConfig = getChartConfig()++ const result = snap.results[id]?.[0]++ function onConfigChange(config: ChartConfig) {+ if (!ref || !snippet.id) {+ return+ }++ upsertContent.mutateAsync({+ projectRef: ref,+ payload: {+ ...snippet,+ id: snippet.id,+ description: snippet.description || '',+ project_id: snippet.project_id || 0,+ content: {+ ...snippet.content,+ content_id: id,+ chart: config,+ },+ },+ })+ }return (<Tabs_Shadcn_ defaultValue="results" className="w-full h-full">@@ -65,9 +140,8 @@ const UtilityPanel = ({<TabsContent_Shadcn_ className="mt-0 h-full" value="results"><UtilityTabResults id={id} isExecuting={isExecuting} /></TabsContent_Shadcn_>-<TabsContent_Shadcn_ className="mt-0 h-full" value="chart">- <ChartConfig results={result} config={config} onConfigChange={setConfig} />+ <ChartConfig results={result} config={chartConfig} onConfigChange={onConfigChange} /></TabsContent_Shadcn_></Tabs_Shadcn_>)diff --git a/apps/studio/data/content/content-upsert-mutation.ts b/apps/studio/data/content/content-upsert-mutation.tsindex a3fe29ef1cd..06cf8f8f176 100644--- a/apps/studio/data/content/content-upsert-mutation.ts+++ b/apps/studio/data/content/content-upsert-mutation.ts@@ -45,11 +45,14 @@ export type UpsertContentData = Awaited<ReturnType<typeof upsertContent>>export const useContentUpsertMutation = ({onError,onSuccess,+ invalidateQueriesOnSuccess = true,...options}: Omit<UseMutationOptions<UpsertContentData, ResponseError, UpsertContentVariables>,'mutationFn'-> = {}) => {+> & {+ invalidateQueriesOnSuccess?: boolean+} = {}) => {const queryClient = useQueryClient()return useMutation<UpsertContentData, ResponseError, UpsertContentVariables>(@@ -57,7 +60,9 @@ export const useContentUpsertMutation = ({{async onSuccess(data, variables, context) {const { projectRef } = variables- await queryClient.invalidateQueries(contentKeys.list(projectRef))+ if (invalidateQueriesOnSuccess) {+ await queryClient.invalidateQueries(contentKeys.list(projectRef))+ }await onSuccess?.(data, variables, context)},async onError(data, variables, context) {diff --git a/apps/studio/state/sql-editor.ts b/apps/studio/state/sql-editor.tsindex 4f234c0863b..d32b62f2a12 100644--- a/apps/studio/state/sql-editor.ts+++ b/apps/studio/state/sql-editor.ts@@ -95,6 +95,12 @@ export const sqlEditorState = proxy({sqlEditorState.needsSaving.delete(id)},+ updateSnippet: (id: string, snippet: SqlSnippet) => {+ if (sqlEditorState.snippets[id]) {+ sqlEditorState.snippets[id].snippet = snippet+ sqlEditorState.needsSaving.add(id)+ }+ },setSplitSizes: (id: string, splitSizes: number[]) => {if (sqlEditorState.snippets[id]) {sqlEditorState.snippets[id].splitSizes = splitSizesdiff --git a/apps/studio/types/userContent.ts b/apps/studio/types/userContent.tsindex 83ea9647e77..bb652467872 100644--- a/apps/studio/types/userContent.ts+++ b/apps/studio/types/userContent.ts@@ -39,6 +39,13 @@ export namespace SqlSnippets {// show sql snippet as a favorite.// this could be problematic if sql snippets have visibility that is != 'user'favorite: boolean++ chart?: {+ type: 'bar'+ cumulative: boolean+ xKey: string+ yKey: string+ }}}