The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
ReportsV2 P1: Add Query block component (#32738)
Joshen Lim0710d62665b6
diff --git a/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationPopover.tsx b/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationPopover.tsxindex e22fc1fcb54..8c978d87539 100644--- a/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationPopover.tsx+++ b/apps/studio/components/interfaces/RoleImpersonationSelector/RoleImpersonationPopover.tsx@@ -4,8 +4,8 @@ import { Button, PopoverContent_Shadcn_, PopoverTrigger_Shadcn_, Popover_Shadcn_import type { User } from 'data/auth/users-infinite-query'import { ChevronDown, User as IconUser } from 'lucide-react'import { useRoleImpersonationStateSnapshot } from 'state/role-impersonation-state'-import RoleImpersonationSelector from './RoleImpersonationSelector'import { getAvatarUrl, getDisplayName } from '../Auth/Users/Users.utils'+import RoleImpersonationSelector from './RoleImpersonationSelector'export interface RoleImpersonationPopoverProps {serviceRoleLabel?: string@@ -38,7 +38,7 @@ const RoleImpersonationPopover = ({)}><div className="flex items-center gap-1">- <span className="text-foreground-muted">role</span>+ <span className="text-foreground-muted">Role</span><span>{currentRole}</span>{state.role?.type === 'postgrest' && state.role.role === 'authenticated' && (<>diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsxindex 07db5ddc1b7..39ef8d43683 100644--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsx+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsx@@ -3,7 +3,6 @@ import { toast } from 'sonner'import { useParams } from 'common'import { useContentUpsertMutation } from 'data/content/content-upsert-mutation'-import { contentKeys } from 'data/content/keys'import { Snippet } from 'data/content/sql-folders-query'import { useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'import { TabsContent_Shadcn_, TabsList_Shadcn_, TabsTrigger_Shadcn_, Tabs_Shadcn_ } from 'ui'diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsxindex 508da8bc13a..5fd65dea4df 100644--- a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx@@ -51,7 +51,6 @@ const MemoizedMessage = memo(return (<Messagekey={message.id}- id={message.id}role={message.role}content={message.content}readOnly={message.role === 'user'}@@ -86,7 +85,7 @@ export const AIAssistant = ({const disablePrompts = useFlag('disableAssistantPrompts')const { snippets } = useSqlEditorV2StateSnapshot()- const { aiAssistantPanel, setAiAssistantPanel } = useAppStateSnapshot()+ const { aiAssistantPanel, setAiAssistantPanel, saveLatestMessage } = useAppStateSnapshot()const { open, initialInput, sqlSnippets, suggestions } = aiAssistantPanelconst inputRef = useRef<HTMLTextAreaElement>(null)@@ -96,7 +95,6 @@ export const AIAssistant = ({const [assistantError, setAssistantError] = useState<string>()const [lastSentMessage, setLastSentMessage] = useState<MessageType>()const [isConfirmOptInModalOpen, setIsConfirmOptInModalOpen] = useState(false)- const [showFade, setShowFade] = useState(false)const { data: check } = useCheckOpenAIKeyQuery()const isApiKeySet = IS_PLATFORM || !!check?.hasKey@@ -136,11 +134,7 @@ export const AIAssistant = ({schema: currentSchema,table: currentTable?.name,},- onFinish: (message) => {- setAiAssistantPanel({- messages: [...chatMessages, message],- })- },+ onFinish: (message) => saveLatestMessage(message),})const canUpdateOrganization = useCheckPermissions(PermissionAction.UPDATE, 'organizations')diff --git a/apps/studio/components/ui/AIAssistantPanel/AiAssistant.constants.ts b/apps/studio/components/ui/AIAssistantPanel/AiAssistant.constants.tsindex 7762e28bd27..69f453c0f5f 100644--- a/apps/studio/components/ui/AIAssistantPanel/AiAssistant.constants.ts+++ b/apps/studio/components/ui/AIAssistantPanel/AiAssistant.constants.ts@@ -27,6 +27,8 @@ export const SAFE_FUNCTIONS = ['to_char(','to_date(','extract(',+ 'date(','date_trunc(','string_agg(',+ 'in (',]diff --git a/apps/studio/components/ui/AIAssistantPanel/Message.tsx b/apps/studio/components/ui/AIAssistantPanel/Message.tsxindex 9cada1b99f5..1eb5ed6410e 100644--- a/apps/studio/components/ui/AIAssistantPanel/Message.tsx+++ b/apps/studio/components/ui/AIAssistantPanel/Message.tsx@@ -5,11 +5,10 @@ import ReactMarkdown from 'react-markdown'import remarkGfm from 'remark-gfm'import { AiIconAnimation, cn, CodeBlock, markdownComponents, WarningIcon } from 'ui'+import { QueryBlock } from '../QueryBlock/QueryBlock'import CollapsibleCodeBlock from './CollapsibleCodeBlock'-import { SqlSnippet } from './SqlSnippet'interface MessageProps {- id: stringrole: 'function' | 'system' | 'user' | 'assistant' | 'data' | 'tool'content?: stringisLoading: boolean@@ -18,8 +17,15 @@ interface MessageProps {variant?: 'default' | 'warning'}+type AssistantSnippetProps = {+ title: string+ runQuery: 'true' | 'false'+ isChart?: 'true' | 'false'+ xAxis?: string+ yAxis?: string+}+export const Message = function Message({- id,role,content,isLoading,@@ -65,6 +71,19 @@ export const Message = function Message({pre: (props: any) => {const language = props.children[0].props.className?.replace('language-', '') || 'sql'+ const rawSql = language === 'sql' ? props.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' ? (@@ -75,10 +94,19 @@ export const Message = function Message({hideLineNumbers/>) : (- <SqlSnippet- readOnly={readOnly}+ <QueryBlock+ lockColumns+ label={title}+ sql={sql}+ chartConfig={{+ type: 'bar',+ cumulative: false,+ xKey: xAxis ?? '',+ yKey: yAxis ?? '',+ }}+ isChart={isChart}isLoading={isLoading}- sql={props.children[0].props.children}+ runQuery={runQuery}/>)) : (diff --git a/apps/studio/components/ui/AIAssistantPanel/SqlSnippet.tsx b/apps/studio/components/ui/AIAssistantPanel/SqlSnippet.tsxdeleted file mode 100644index 0c66f91f7ac..00000000000--- a/apps/studio/components/ui/AIAssistantPanel/SqlSnippet.tsx+++ /dev/null@@ -1,455 +0,0 @@-import { Code, Edit, Play } from 'lucide-react'-import { useRouter } from 'next/router'-import { useCallback, useEffect, useState } from 'react'-import { Bar, BarChart, CartesianGrid, XAxis } from 'recharts'--import { useQueryClient } from '@tanstack/react-query'-import { useParams } from 'common'-import { Markdown } from 'components/interfaces/Markdown'-import useNewQuery from 'components/interfaces/SQLEditor/hooks'-import { DiffType } from 'components/interfaces/SQLEditor/SQLEditor.types'-import { suffixWithLimit } from 'components/interfaces/SQLEditor/SQLEditor.utils'-import Results from 'components/interfaces/SQLEditor/UtilityPanel/Results'-import { QueryResponseError, useExecuteSqlMutation } from 'data/sql/execute-sql-mutation'-import { useSendEventMutation } from 'data/telemetry/send-event-mutation'-import { useSelectedProject } from 'hooks/misc/useSelectedProject'-import { TelemetryActions } from 'lib/constants/telemetry'-import { useAppStateSnapshot } from 'state/app-state'-import { useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'-import {- Button,- ChartContainer,- ChartTooltip,- ChartTooltipContent,- CodeBlock,- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,- SQL_ICON,- cn,-} from 'ui'-import { Admonition } from 'ui-patterns'-import { ButtonTooltip } from '../ButtonTooltip'-import {- containsUnknownFunction,- getContextualInvalidationKeys,- identifyQueryType,- isReadOnlySelect,-} from './AIAssistant.utils'--interface SqlSnippetWrapperProps {- sql: string- isLoading?: boolean- readOnly?: boolean-}--const SqlSnippetWrapper = ({- sql,- isLoading = false,- readOnly = false,-}: SqlSnippetWrapperProps) => {- const formatted = (sql || [''])[0]- const propsMatch = formatted.match(/--\s*props:\s*(\{[^}]+\})/)- const props = propsMatch ? JSON.parse(propsMatch[1]) : {}- const title = props.title || 'SQL Query'- const updatedFormatted = formatted?.replace(/--\s*props:\s*\{[^}]+\}/, '').trim()-- return (- <div className="overflow-hidden">- <SqlCard- sql={updatedFormatted}- isChart={props.isChart === 'true'}- xAxis={props.xAxis}- yAxis={props.yAxis}- runQuery={props.runQuery === 'true'}- title={title}- readOnly={readOnly}- isLoading={isLoading}- />- </div>- )-}--interface ParsedSqlProps {- sql: string- title: string- isLoading?: boolean- readOnly?: boolean- isChart: boolean- runQuery?: boolean- xAxis: string- yAxis: string-}--export const SqlCard = ({- sql,- isChart,- runQuery = false,- xAxis,- yAxis,- title,- readOnly = false,- isLoading = false,-}: ParsedSqlProps) => {- const router = useRouter()- const { ref } = useParams()- const queryClient = useQueryClient()- const project = useSelectedProject()- const snapV2 = useSqlEditorV2StateSnapshot()- const { setAiAssistantPanel } = useAppStateSnapshot()- const { newQuery } = useNewQuery()-- const isInSQLEditor = router.pathname.includes('/sql')- const isInNewSnippet = router.pathname.endsWith('/sql')-- const [showCode, setShowCode] = useState(readOnly || !runQuery || !isReadOnlySelect(sql))- const [showResults, setShowResults] = useState(false)- const [results, setResults] = useState<any[]>()- const [error, setError] = useState<QueryResponseError>()- const [showWarning, setShowWarning] = useState<'hasWriteOperation' | 'hasUnknownFunctions'>()-- const { mutate: sendEvent } = useSendEventMutation()-- const { mutate: executeSql, isLoading: isExecuting } = useExecuteSqlMutation({- onSuccess: async (res) => {- // [Joshen] Only do contextual invalidation within a project context- if (!!ref) {- const invalidationKeys = getContextualInvalidationKeys({ ref, pathname: router.pathname })- await Promise.all(invalidationKeys?.map((x) => queryClient.invalidateQueries(x)))- }-- setShowResults(true)- setResults(res.result)- setShowWarning(undefined)- },- onError: (error) => {- setError(error)- setResults([])- setShowWarning(undefined)- },- })-- const handleExecute = useCallback(() => {- if (!project?.ref || !sql || readOnly) return-- if (!isReadOnlySelect(sql)) {- const hasUnknownFunctions = containsUnknownFunction(sql)-- setShowCode(true)- setShowWarning(hasUnknownFunctions ? 'hasUnknownFunctions' : 'hasWriteOperation')- return- }-- setError(undefined)- executeSql({- sql: suffixWithLimit(sql, 100),- projectRef: project?.ref,- connectionString: project?.connectionString,- handleError: (error: any) => {- setError(error)- setResults([])- return { result: [] }- },- })- }, [project?.ref, project?.connectionString, sql, executeSql, readOnly])-- const handleEditInSQLEditor = () => {- if (isInSQLEditor) {- snapV2.setDiffContent(sql, DiffType.Addition)- } else {- newQuery(sql, title)- }- }-- const [errorHeader, ...errorContent] =- (error?.formattedError?.split('\n') ?? [])?.filter((x: string) => x.length > 0) ?? []-- useEffect(() => {- if (runQuery && isReadOnlySelect(sql) && !results && !readOnly && !isLoading) {- handleExecute()- }- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [sql, readOnly, isLoading, runQuery])-- return (- <div className="overflow-hidden rounded border w-auto bg-surface-100">- <div className={cn('flex items-center gap-2', showWarning ? '' : 'px-3 pr-1 py-1')}>- {!!showWarning ? (- <Admonition type="warning" className="mb-0 rounded-none border-0">- <p>- {showWarning === 'hasWriteOperation'- ? 'This query contains write operations.'- : 'This query involves running a function.'}{' '}- Are you sure you want to execute it?- </p>- <p className="text-foreground-light">- Make sure you are not accidentally removing something important.- </p>- <div className="flex justify-stretch mt-2 gap-2">- <Button- type="outline"- size="tiny"- className="w-full flex-1"- onClick={() => setShowWarning(undefined)}- >- Cancel- </Button>- <Button- type="danger"- size="tiny"- className="w-full flex-1"- onClick={() => {- setShowWarning(undefined)- executeSql({- sql: suffixWithLimit(sql, 100),- projectRef: project?.ref,- connectionString: project?.connectionString,- handleError: (error: any) => {- setError(error)- setResults([])- return { result: [] }- },- })-- sendEvent({- action: TelemetryActions.ASSISTANT_SUGGESTION_RUN_QUERY_CLICKED,- properties: {- queryType: 'mutation',- category: identifyQueryType(sql) ?? 'unknown',- },- })- }}- >- Run- </Button>- </div>- </Admonition>- ) : (- <>- <SQL_ICON- className={cn(- 'transition-colors',- 'fill-foreground-muted',- 'group-aria-selected:fill-foreground',- 'w-5 h-5 shrink-0',- '-ml-0.5'- )}- size={16}- strokeWidth={1.5}- />- <h3 className="text-xs font-medium flex-1">{title}</h3>-- {!readOnly && (- <div className="flex">- <ButtonTooltip- type="text"- size="tiny"- className="w-7 h-7"- icon={<Code size={14} />}- onClick={() => setShowCode(!showCode)}- tooltip={{- content: { side: 'bottom', text: showCode ? 'Hide query' : 'Show query' },- }}- />-- {!isInSQLEditor || isInNewSnippet ? (- <ButtonTooltip- type="text"- size="tiny"- className="w-7 h-7"- icon={<Edit size={14} />}- onClick={() => {- handleEditInSQLEditor()- sendEvent({- action: TelemetryActions.ASSISTANT_EDIT_IN_SQL_EDITOR_CLICKED,- properties: {- isInSQLEditor,- isInNewSnippet,- },- })- }}- tooltip={{ content: { side: 'bottom', text: 'Edit in SQL Editor' } }}- />- ) : (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <ButtonTooltip- type="text"- size="tiny"- className="w-7 h-7"- icon={<Edit size={14} />}- tooltip={{ content: { side: 'bottom', text: 'Edit in SQL Editor' } }}- />- </DropdownMenuTrigger>- <DropdownMenuContent className="w-36">- <DropdownMenuItem- onClick={() => snapV2.setDiffContent(sql, DiffType.Addition)}- >- Insert code- </DropdownMenuItem>- <DropdownMenuItem- onClick={() => snapV2.setDiffContent(sql, DiffType.Modification)}- >- Replace code- </DropdownMenuItem>- <DropdownMenuItem- onClick={() => snapV2.setDiffContent(sql, DiffType.NewSnippet)}- >- Create new snippet- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- )}-- <ButtonTooltip- type="text"- size="tiny"- className="w-7 h-7"- icon={<Play size={14} />}- loading={isExecuting}- onClick={() => {- handleExecute()- if (isReadOnlySelect(sql)) {- sendEvent({- action: TelemetryActions.ASSISTANT_SUGGESTION_RUN_QUERY_CLICKED,- properties: { queryType: 'select' },- })- }- }}- tooltip={{- content: {- side: 'bottom',- className: 'max-w-56 text-center',- text: isExecuting ? (- <Markdown- className="[&>p]:text-xs text-foreground"- content={`Query is running. You may cancel ongoing queries via the [SQL Editor](/project/${ref}/sql?viewOngoingQueries=true).`}- />- ) : (- 'Run query'- ),- },- }}- />- </div>- )}- </>- )}- </div>-- {showCode && (- <CodeBlock- hideLineNumbers- wrapLines={false}- value={sql}- language="sql"- className={cn(- 'max-h-96 max-w-none block !bg-transparent !py-3 !px-3.5 prose dark:prose-dark border-0 border-t text-foreground !rounded-none w-full',- '[&>code]:m-0 [&>code>span]:text-foreground'- )}- />- )}-- {/* Results Section */}- {results !== undefined && results.length > 0 && isChart && xAxis && yAxis ? (- <div className="p-3 border-t">- <ChartContainer config={{}} className="aspect-auto h-[250px] w-full">- <BarChart- data={results}- margin={{- left: 12,- right: 12,- }}- >- <CartesianGrid vertical={false} />- <XAxis- dataKey={xAxis}- tickLine={false}- axisLine={false}- tickMargin={8}- minTickGap={32}- />- <ChartTooltip content={<ChartTooltipContent className="w-[150px]" />} />- <Bar dataKey={yAxis} fill="hsl(var(--chart-2))" />- </BarChart>- </ChartContainer>- </div>- ) : (- <div>- {error !== undefined ? (- <Admonition- type="warning"- className="m-0 rounded-none border-x-0 border-b-0 [&>div>div>pre]:text-sm [&>div]:flex [&>div]:flex-col [&>div]:gap-y-2"- title={errorHeader || 'Error running SQL query'}- description={- <>- <div>- {errorContent.length > 0 ? (- <div>- {errorContent.map((errorText: string, i: number) => (- <pre key={`err-${i}`} className="font-mono text-xs whitespace-pre-wrap">- {errorText}- </pre>- ))}- <Button- type="default"- className="mt-2"- onClick={() => {- setAiAssistantPanel({- sqlSnippets: [sql],- initialInput: `Help me to debug the attached sql snippet which gives the following error: \n\n${errorHeader}\n${errorContent.join('\n')}`,- })- }}- >- Debug- </Button>- </div>- ) : (- <>- <p className="font-mono text-xs">{error.error}</p>- <Button- type="default"- className="mt-2"- onClick={() => {- setAiAssistantPanel({- sqlSnippets: [sql],- initialInput: `Help me to debug the attached sql snippet which gives the following error: \n\n${error.error}`,- })- }}- >- Debug- </Button>- </>- )}- </div>- </>- }- />- ) : results !== undefined && results.length > 0 ? (- <>- <div className={cn(showResults ? 'h-auto max-h-64 overflow-auto border-t' : 'h-0')}>- <Results rows={results} />- </div>- <div className="flex items-center justify-between border-t bg-background-muted py-2 pl-2 pr-5">- <p className="text-xs text-foreground-light">- {results.length} rows- {results.length >= 100 && ` (Limited to only 100 rows)`}- </p>- </div>- </>- ) : (- results !== undefined &&- results.length === 0 && (- <div className="flex items-center justify-between border-t bg-surface-100 h-[43px] pl-2 pr-5">- <p className="text-xs text-foreground-light">Success. No rows returned.</p>- </div>- )- )}- </div>- )}- </div>- )-}--export { SqlSnippetWrapper as SqlSnippet }diff --git a/apps/studio/components/ui/QueryBlock/BlockViewConfiguration.tsx b/apps/studio/components/ui/QueryBlock/BlockViewConfiguration.tsxnew file mode 100644index 00000000000..ef3819933e8--- /dev/null+++ b/apps/studio/components/ui/QueryBlock/BlockViewConfiguration.tsx@@ -0,0 +1,124 @@+import { BarChart2, Settings2, Table } from 'lucide-react'++import { ChartConfig } from 'components/interfaces/SQLEditor/UtilityPanel/ChartConfig'+import {+ Checkbox_Shadcn_,+ Label_Shadcn_,+ Popover_Shadcn_,+ PopoverContent_Shadcn_,+ PopoverTrigger_Shadcn_,+ Select_Shadcn_,+ SelectContent_Shadcn_,+ SelectGroup_Shadcn_,+ SelectItem_Shadcn_,+ SelectTrigger_Shadcn_,+ ToggleGroup,+ ToggleGroupItem,+} from 'ui'+import { ButtonTooltip } from '../ButtonTooltip'++interface BlockViewConfigurationProps {+ columns: string[]+ view: 'chart' | 'table'+ isChart: boolean+ lockColumns?: boolean+ chartConfig?: ChartConfig+ changeView: (value: 'chart' | 'table') => void+ updateChartConfig: (config: ChartConfig) => void+}++export const BlockViewConfiguration = ({+ columns,+ view,+ isChart,+ lockColumns = false,+ chartConfig,+ changeView,+ updateChartConfig,+}: BlockViewConfigurationProps) => {+ return (+ <Popover_Shadcn_ modal={false}>+ <PopoverTrigger_Shadcn_ asChild>+ <ButtonTooltip+ id="help-popover-button"+ type="text"+ className="px-1"+ icon={<Settings2 size={14} />}+ tooltip={{ content: { side: 'bottom', text: 'View data' } }}+ />+ </PopoverTrigger_Shadcn_>+ <PopoverContent_Shadcn_ side="bottom" align="center" className="w-[240px] p-3">+ <form className="grid gap-2">+ <ToggleGroup type="single" value={view} className="w-full" onValueChange={changeView}>+ <ToggleGroupItem className="w-full" value="table" aria-label="Show as table">+ <Table className="h-4 w-4" />+ <p className="text-xs ml-2">As table</p>+ </ToggleGroupItem>+ <ToggleGroupItem className="w-full" value="chart" aria-label="Show as chart">+ <BarChart2 className="h-4 w-4" />+ <p className="text-xs ml-2">As chart</p>+ </ToggleGroupItem>+ </ToggleGroup>++ {isChart && chartConfig && (+ <>+ <Select_Shadcn_+ disabled={lockColumns}+ value={chartConfig?.xKey}+ onValueChange={(value) => updateChartConfig({ ...chartConfig, xKey: value })}+ >+ <SelectTrigger_Shadcn_ className="text-left">+ X Axis {chartConfig?.xKey && `- ${chartConfig.xKey}`}+ </SelectTrigger_Shadcn_>+ <SelectContent_Shadcn_>+ <SelectGroup_Shadcn_>+ {columns.map((key) => (+ <SelectItem_Shadcn_ value={key} key={key}>+ {key}+ </SelectItem_Shadcn_>+ ))}+ </SelectGroup_Shadcn_>+ </SelectContent_Shadcn_>+ </Select_Shadcn_>++ <Select_Shadcn_+ disabled={lockColumns}+ value={chartConfig?.yKey}+ onValueChange={(value) => updateChartConfig({ ...chartConfig, yKey: value })}+ >+ <SelectTrigger_Shadcn_ className="text-left">+ Y Axis {chartConfig?.yKey && `- ${chartConfig.yKey}`}+ </SelectTrigger_Shadcn_>+ <SelectContent_Shadcn_>+ <SelectGroup_Shadcn_>+ {columns.map((key) => (+ <SelectItem_Shadcn_ value={key} key={key}>+ {key}+ </SelectItem_Shadcn_>+ ))}+ </SelectGroup_Shadcn_>+ </SelectContent_Shadcn_>+ </Select_Shadcn_>++ <div className="*:flex *:gap-2 *:items-center grid gap-2 *:text-foreground-light *:p-1.5 *:pl-0">+ <Label_Shadcn_ htmlFor="cumulative">+ <Checkbox_Shadcn_+ id="cumulative"+ checked={chartConfig?.cumulative}+ onClick={() =>+ updateChartConfig({+ ...chartConfig,+ cumulative: !chartConfig?.cumulative,+ })+ }+ />+ Cumulative+ </Label_Shadcn_>+ </div>+ </>+ )}+ </form>+ </PopoverContent_Shadcn_>+ </Popover_Shadcn_>+ )+}diff --git a/apps/studio/components/ui/QueryBlock/EditQueryButton.tsx b/apps/studio/components/ui/QueryBlock/EditQueryButton.tsxnew file mode 100644index 00000000000..590e430db25--- /dev/null+++ b/apps/studio/components/ui/QueryBlock/EditQueryButton.tsx@@ -0,0 +1,77 @@+import { Edit } from 'lucide-react'+import { useRouter } from 'next/router'++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 { useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from 'ui'+import { ButtonTooltip } from '../ButtonTooltip'++interface EditQueryButtonProps {+ title: string+ sql: string+}++export const EditQueryButton = ({ sql, title }: EditQueryButtonProps) => {+ const router = useRouter()+ const { newQuery } = useNewQuery()+ const sqlEditorSnap = useSqlEditorV2StateSnapshot()++ const isInSQLEditor = router.pathname.includes('/sql')+ const isInNewSnippet = router.pathname.endsWith('/sql')++ const { mutate: sendEvent } = useSendEventMutation()++ const handleEditInSQLEditor = () => {+ if (isInSQLEditor) {+ sqlEditorSnap.setDiffContent(sql, DiffType.Addition)+ } else {+ newQuery(sql, title)+ }+ }++ return !isInSQLEditor || isInNewSnippet ? (+ <ButtonTooltip+ type="text"+ size="tiny"+ className="w-7 h-7"+ icon={<Edit size={14} />}+ onClick={() => {+ handleEditInSQLEditor()+ sendEvent({+ action: TelemetryActions.ASSISTANT_EDIT_IN_SQL_EDITOR_CLICKED,+ properties: {+ isInSQLEditor,+ isInNewSnippet,+ },+ })+ }}+ tooltip={{ content: { side: 'bottom', text: 'Edit in SQL Editor' } }}+ />+ ) : (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <ButtonTooltip+ type="text"+ size="tiny"+ className="w-7 h-7"+ icon={<Edit size={14} />}+ tooltip={{ content: { side: 'bottom', text: 'Edit in SQL Editor' } }}+ />+ </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>+ </DropdownMenu>+ )+}diff --git a/apps/studio/components/ui/QueryBlock/ParametersPopover.tsx b/apps/studio/components/ui/QueryBlock/ParametersPopover.tsxnew file mode 100644index 00000000000..a314fead4e1--- /dev/null+++ b/apps/studio/components/ui/QueryBlock/ParametersPopover.tsx@@ -0,0 +1,164 @@+import { format } from 'date-fns'+import { ArrowUpDown } from 'lucide-react'+import { useEffect, useState } from 'react'++import { DatePicker } from 'components/ui/DatePicker'+import { Parameter } from 'lib/sql-parameters'+import {+ Button,+ Input_Shadcn_,+ Label_Shadcn_,+ Popover_Shadcn_,+ PopoverContent_Shadcn_,+ PopoverTrigger_Shadcn_,+ Select_Shadcn_,+ SelectContent_Shadcn_,+ SelectItem_Shadcn_,+ SelectTrigger_Shadcn_,+ SelectValue_Shadcn_,+} from 'ui'++interface ParametersPopoverProps {+ parameters: Parameter[]+ parameterValues?: Record<string, string>+ onSubmit?: (parameters: Record<string, string>) => void+ onChange?: (parameters: Record<string, string>) => void+}++export const ParametersPopover = ({+ parameters,+ parameterValues = {},+ onSubmit,+ onChange,+}: ParametersPopoverProps) => {+ const [tempParameters, setTempParameters] = useState<Record<string, string>>(+ parameters.reduce(+ (acc, param) => ({+ ...acc,+ [param.name]: parameterValues[param.name] ?? param.defaultValue ?? '',+ }),+ {}+ )+ )++ // Update temp parameters when external parameters or values change+ useEffect(() => {+ setTempParameters(+ parameters.reduce(+ (acc, param) => ({+ ...acc,+ [param.name]: parameterValues[param.name] ?? param.defaultValue ?? '',+ }),+ {}+ )+ )+ }, [parameters, parameterValues])++ const handleParameterChange = (name: string, value: string) => {+ const newParameters = {+ ...tempParameters,+ [name]: value,+ }+ setTempParameters(newParameters)+ onChange?.(newParameters)+ }++ const renderInput = (param: Parameter) => {+ const currentValue = tempParameters[param.name] ?? parameterValues[param.name] ?? ''++ if (param.type === 'date') {+ // Check if the current value is a valid date+ const isValidDate = currentValue && !isNaN(new Date(currentValue).getTime())++ if (isValidDate) {+ return (+ <DatePicker+ selectsRange={false}+ from={currentValue}+ to={currentValue}+ onChange={(date) => {+ if (date && date.to) {+ handleParameterChange(param.name, date.to)+ } else {+ handleParameterChange(param.name, '')+ }+ }}+ >+ <span>{currentValue ? format(new Date(currentValue), 'dd MMM') : 'Pick a date'}</span>+ </DatePicker>+ )+ }++ // Fallback to regular input if date is invalid+ return (+ <Input_Shadcn_+ size="tiny"+ value={currentValue}+ onChange={(e) => handleParameterChange(param.name, e.target.value)}+ />+ )+ }++ if (param.type === 'enum' && param.possibleValues) {+ return (+ <Select_Shadcn_+ value={currentValue}+ onValueChange={(value) => handleParameterChange(param.name, value)}+ >+ <SelectTrigger_Shadcn_ className="h-8">+ <SelectValue_Shadcn_ placeholder="Select value" />+ </SelectTrigger_Shadcn_>+ <SelectContent_Shadcn_>+ {param.possibleValues.map((value) => (+ <SelectItem_Shadcn_ key={value} value={value}>+ {value}+ </SelectItem_Shadcn_>+ ))}+ </SelectContent_Shadcn_>+ </Select_Shadcn_>+ )+ }++ return (+ <Input_Shadcn_+ size="tiny"+ value={currentValue}+ onChange={(e) => handleParameterChange(param.name, e.target.value)}+ />+ )+ }++ return (+ <Popover_Shadcn_ modal={false}>+ <PopoverTrigger_Shadcn_ asChild>+ <Button icon={<ArrowUpDown size={14} />} type="text" size="tiny" className="w-7 h-7" />+ </PopoverTrigger_Shadcn_>+ <PopoverContent_Shadcn_ side="bottom" align="end" className="w-[300px] p-4">+ <div className="space-y-4">+ <div className="space-y-2">+ {parameters.map((param) => (+ <div key={param.name} className="grid gap-2">+ <Label_Shadcn_ className="flex items-center gap-2">+ {param.name}+ {param.occurrences > 1 && (+ <span className="text-xs text-foreground-light">+ (used {param.occurrences} times)+ </span>+ )}+ </Label_Shadcn_>+ {renderInput(param)}+ </div>+ ))}+ </div>+ {onSubmit && (+ <div className="flex justify-end">+ <Button type="primary" size="tiny" onClick={() => onSubmit(tempParameters)}>+ Apply changes+ </Button>+ </div>+ )}+ </div>+ </PopoverContent_Shadcn_>+ </Popover_Shadcn_>+ )+}diff --git a/apps/studio/components/ui/QueryBlock/QueryBlock.tsx b/apps/studio/components/ui/QueryBlock/QueryBlock.tsxnew file mode 100644index 00000000000..40db5cf35a0--- /dev/null+++ b/apps/studio/components/ui/QueryBlock/QueryBlock.tsx@@ -0,0 +1,326 @@+import { Code, Play } from 'lucide-react'+import { ReactNode, useEffect, useMemo, useState } from 'react'+import { Bar, BarChart, CartesianGrid, XAxis } from 'recharts'+import { toast } from 'sonner'++import { useParams } from 'common'+import { ChartConfig } from 'components/interfaces/SQLEditor/UtilityPanel/ChartConfig'+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 {+ Button,+ ChartContainer,+ ChartTooltip,+ ChartTooltipContent,+ cn,+ CodeBlock,+ SQL_ICON,+} from 'ui'+import { Admonition } from 'ui-patterns'+import ShimmeringLoader from 'ui-patterns/ShimmeringLoader'+import { containsUnknownFunction, isReadOnlySelect } from '../AIAssistantPanel/AIAssistant.utils'+import { ButtonTooltip } from '../ButtonTooltip'+import { BlockViewConfiguration } from './BlockViewConfiguration'+import { EditQueryButton } from './EditQueryButton'+import { ParametersPopover } from './ParametersPopover'+import { getCumulativeResults } from './QueryBlock.utils'++const DEFAULT_CHART_CONFIG: ChartConfig = {+ type: 'bar',+ cumulative: false,+ xKey: '',+ yKey: '',+ showLabels: false,+ showGrid: false,+}++interface QueryBlockProps {+ id?: string+ label: string+ sql: string+ chartConfig?: ChartConfig+ maxHeight?: number+ parameterValues?: Record<string, string>+ actions?: ReactNode // Any other actions specific to the parent to be rendered in the header+ isChart?: boolean+ isLoading?: boolean+ runQuery?: boolean+ lockColumns?: boolean+ onSetParameter?: (params: Parameter[]) => void+ onUpdateChartConfig?: (config: ChartConfig) => void+}++// [Joshen ReportsV2] JFYI we may adjust this in subsequent PRs when we implement this into Reports V2+// First iteration here is just to make this work with the AI Assistant first+export const QueryBlock = ({+ id,+ label,+ sql,+ chartConfig = DEFAULT_CHART_CONFIG,+ maxHeight = 250,+ parameterValues: extParameterValues,+ actions,+ isChart = false,+ isLoading = false,+ runQuery = false,+ lockColumns = false,+ 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 [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 }++ const { mutate: execute, isLoading: isExecuting } = useExecuteSqlMutation({+ onSuccess: (data) => setQueryResult(data.result),+ })++ const handleExecute = () => {+ if (!sql || isLoading) return++ if (!isReadOnlySelect(sql)) {+ const hasUnknownFunctions = containsUnknownFunction(sql)+ return setShowWarning(hasUnknownFunctions ? 'hasUnknownFunctions' : 'hasWriteOperation')+ }++ try {+ const processedSql = processParameterizedSql(sql, combinedParameterValues)+ execute({+ projectRef: ref,+ connectionString: project?.connectionString,+ sql: processedSql,+ })+ } catch (error: any) {+ toast.error(`Failed to execute query: ${error.message}`)+ }+ }++ // Run once on mount to parse parameters and notify parent+ useEffect(() => {+ if (!!sql && onSetParameter) {+ const params = parseParameters(sql)+ onSetParameter(params)+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [sql])++ useEffect(() => {+ if (!!sql && !isLoading && runQuery && isReadOnlySelect(sql) && !!project) {+ handleExecute()+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [sql, isLoading, runQuery, project])++ return (+ <div className="h-full flex flex-col overflow-hidden bg-surface-100 border-overlay rounded border shadow-sm">+ <div className="flex py-1 pl-3 pr-1 items-center gap-2 z-10 shrink-0">+ <SQL_ICON+ className={cn(+ 'transition-colors fill-foreground-muted group-aria-selected:fill-foreground',+ 'w-5 h-5 shrink-0 grow-0 -ml-0.5'+ )}+ size={16}+ strokeWidth={1.5}+ />+ <h3 className="text-xs font-medium text-foreground-light flex-1">{label}</h3>++ {/* QueryBlock actions */}+ <div className="flex items-center">+ <ButtonTooltip+ type="text"+ size="tiny"+ className="w-7 h-7"+ icon={<Code size={14} />}+ onClick={() => setShowSql(!showSql)}+ tooltip={{+ content: { side: 'bottom', text: showSql ? 'Hide query' : 'Show query' },+ }}+ />++ {queryResult && (+ <>+ {/* [Joshen ReportsV2] Won't see this just yet as this is intended for Reports V2 */}+ {parameters.length > 0 && (+ <ParametersPopover+ parameters={parameters}+ parameterValues={parameterValues}+ onSubmit={setParameterValues}+ />+ )}+ {isChart && (+ <BlockViewConfiguration+ view={view}+ isChart={isChart}+ lockColumns={lockColumns}+ chartConfig={{ ...chartConfig, cumulative }}+ columns={Object.keys(queryResult[0] || {})}+ changeView={setView}+ updateChartConfig={(config) => {+ if (onUpdateChartConfig) onUpdateChartConfig(config)+ setCumulative(config.cumulative)+ }}+ />+ )}+ </>+ )}++ <EditQueryButton 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'+ ),+ },+ }}+ />++ {actions}+ </div>+ </div>++ {showWarning && (+ <Admonition+ type="warning"+ className="mb-0 rounded-none border-0 shrink-0 bg-background-100 border-t"+ >+ <p>+ {showWarning === 'hasWriteOperation'+ ? 'This query contains write operations.'+ : 'This query involves running a function.'}{' '}+ Are you sure you want to execute it?+ </p>+ <p className="text-foreground-light">+ Make sure you are not accidentally removing something important.+ </p>+ <div className="flex justify-stretch mt-2 gap-2">+ <Button+ type="outline"+ size="tiny"+ className="w-full flex-1"+ onClick={() => setShowWarning(undefined)}+ >+ Cancel+ </Button>+ <Button+ type="danger"+ size="tiny"+ 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,+ })+ }}+ >+ Run+ </Button>+ </div>+ </Admonition>+ )}++ {/* QueryBlock output */}+ {showSql && (+ <div className="shrink-0 max-h-96 overflow-y-auto border-t">+ <CodeBlock+ hideLineNumbers+ wrapLines={false}+ value={sql}+ language="sql"+ className={cn(+ 'max-w-none block !bg-transparent !py-3 !px-3.5 prose dark:prose-dark border-0 text-foreground !rounded-none w-full',+ '[&>code]:m-0 [&>code>span]:text-foreground'+ )}+ />+ </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>+ ) : (+ <>+ {queryResult && (+ <div+ className={cn('flex-1 overflow-auto relative border-t')}+ style={{ maxHeight: maxHeight ? `${maxHeight}px` : undefined }}+ >+ <Results rows={queryResult} />+ </div>+ )}+ </>+ )}+ </div>+ )+}diff --git a/apps/studio/components/ui/QueryBlock/QueryBlock.utils.ts b/apps/studio/components/ui/QueryBlock/QueryBlock.utils.tsnew file mode 100644index 00000000000..f3310842cc0--- /dev/null+++ b/apps/studio/components/ui/QueryBlock/QueryBlock.utils.ts@@ -0,0 +1,19 @@+import { ChartConfig } from 'components/interfaces/SQLEditor/UtilityPanel/ChartConfig'++// Add helper function for cumulative results+export const getCumulativeResults = (results: { rows: any[] }, config: ChartConfig) => {+ if (!results?.rows?.length) {+ return []+ }++ const cumulativeResults = results.rows.reduce((acc, row) => {+ const prev = acc[acc.length - 1] || {}+ const next = {+ ...row,+ [config.yKey]: (prev[config.yKey] || 0) + row[config.yKey],+ }+ return [...acc, next]+ }, [])++ return cumulativeResults+}diff --git a/apps/studio/components/ui/QueryBlock/QueryBlockWrapper.tsx b/apps/studio/components/ui/QueryBlock/QueryBlockWrapper.tsxnew file mode 100644index 00000000000..79bac51df5d--- /dev/null+++ b/apps/studio/components/ui/QueryBlock/QueryBlockWrapper.tsx@@ -0,0 +1,68 @@+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/lib/sql-parameters.ts b/apps/studio/lib/sql-parameters.tsnew file mode 100644index 00000000000..2311e0f5dda--- /dev/null+++ b/apps/studio/lib/sql-parameters.ts@@ -0,0 +1,114 @@+export interface Parameter {+ name: string+ value: string+ defaultValue?: string+ type?: string+ possibleValues?: string[]+ occurrences: number+}++// [Joshen TODO] We'll want tests for this to ensure that this runs properly++export const parseParameters = (sql: string | undefined) => {+ if (!sql) return []++ // Parse @set parameter defaults with optional type information+ const setParamRegex = /@set\s+(\w+)(?::([^=]+))?\s*=\s*([^;\n]+)/g+ const paramDefaults: Record<string, { value: string; type?: string; possibleValues?: string[] }> =+ {}+ let match++ while ((match = setParamRegex.exec(sql)) !== null) {+ const [_, paramName, paramType, paramValue] = match+ if (!paramName || !paramValue?.trim()) continue++ const typeInfo = paramType?.trim()++ let type: string | undefined+ let possibleValues: string[] | undefined++ if (typeInfo) {+ // Handle union types (value1 | value2 | value3)+ if (typeInfo.includes('|')) {+ possibleValues = typeInfo.split('|').map((v) => v.trim())+ type = 'enum'+ } else {+ type = typeInfo.trim()+ }+ }++ paramDefaults[paramName] = {+ value: paramValue.trim(),+ type,+ possibleValues,+ }+ }++ // Find all :parameter occurrences and count them+ const paramRegex = /:(\w+)/g+ const paramOccurrences: Record<string, number> = {}+ const uniqueParams = new Set<string>()++ while ((match = paramRegex.exec(sql)) !== null) {+ const [_, paramName] = match+ paramOccurrences[paramName] = (paramOccurrences[paramName] || 0) + 1+ uniqueParams.add(paramName)+ }++ // Create parameter objects for unique parameters+ return Array.from(uniqueParams).map((paramName) => ({+ name: paramName,+ value: paramDefaults[paramName]?.value || '',+ defaultValue: paramDefaults[paramName]?.value,+ type: paramDefaults[paramName]?.type,+ possibleValues: paramDefaults[paramName]?.possibleValues,+ occurrences: paramOccurrences[paramName],+ }))+}++export const processParameterizedSql = (sql: string, parameters: Record<string, string>) => {+ // Parse @set parameter defaults with type information from SQL+ const setParamRegex = /@set\s+(\w+)(?::([^=]+))?\s*=\s*([^;\n]+)/g+ const paramDefaults: Record<string, { value: string; type?: string; possibleValues?: string[] }> =+ {}+ let match++ while ((match = setParamRegex.exec(sql)) !== null) {+ const [_, paramName, paramType, paramValue] = match+ if (!paramName || !paramValue?.trim()) continue++ const typeInfo = paramType?.trim()+ let type: string | undefined+ let possibleValues: string[] | undefined++ if (typeInfo) {+ if (typeInfo.includes('|')) {+ possibleValues = typeInfo.split('|').map((v) => v.trim())+ type = 'enum'+ } else {+ type = typeInfo.trim()+ }+ }++ paramDefaults[paramName] = {+ value: paramValue.trim(),+ type,+ possibleValues,+ }+ }++ // Remove @set lines from SQL+ let processedSql = sql.replace(/@set\s+\w+(?:\s*:\s*[^=]+)?\s*=\s*[^;\n]+[\n;]*/g, '')++ // Replace :parameters with values+ const paramRegex = /:(\w+)/g+ processedSql = processedSql.replace(paramRegex, (match, paramName) => {+ const value = parameters[paramName] ?? paramDefaults[paramName]?.value+ if (value === undefined) {+ throw new Error(`Missing value for parameter: ${paramName}`)+ }+ return value+ })++ return processedSql+}diff --git a/apps/studio/state/app-state.ts b/apps/studio/state/app-state.tsindex 40acb74d84f..5b411b4e16f 100644--- a/apps/studio/state/app-state.ts+++ b/apps/studio/state/app-state.ts@@ -210,6 +210,13 @@ export const appState = proxy({...value,}},++ saveLatestMessage: (message: any) => {+ appState.aiAssistantPanel = {+ ...appState.aiAssistantPanel,+ messages: [...appState.aiAssistantPanel.messages, message],+ }+ },})// Set up localStorage subscriptiondiff --git a/apps/studio/styles/main.scss b/apps/studio/styles/main.scssindex a4ed805f793..f71742f907d 100644--- a/apps/studio/styles/main.scss+++ b/apps/studio/styles/main.scss@@ -8,7 +8,7 @@@import '~ui/build/css/themes/classic-dark.css';:root {- --chart-1: 12 76% 61%;+ --chart-1: hsl(var(--brand-default));--chart-2: 173 58% 39%;--chart-3: 197 37% 24%;--chart-4: 43 74% 66%;@@ -16,7 +16,7 @@}.dark {- --chart-1: 220 70% 50%;+ --chart-1: hsl(var(--brand-default));--chart-2: 160 60% 45%;--chart-3: 30 80% 55%;--chart-4: 280 65% 60%;