The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Explorer home to run query in query tab if input in chat form is a sql query (#50204)
Joshen Lim7c681da0d213
diff --git a/apps/studio/components/interfaces/Explorer/ExplorerHomeTab.tsx b/apps/studio/components/interfaces/Explorer/ExplorerHomeTab.tsxindex 5deb147d84c..3e811df3720 100644--- a/apps/studio/components/interfaces/Explorer/ExplorerHomeTab.tsx+++ b/apps/studio/components/interfaces/Explorer/ExplorerHomeTab.tsx@@ -2,6 +2,7 @@ import { NotebookText, SquareCode } from 'lucide-react'import { useState } from 'react'import { cn } from 'ui'+import { isSqlStatement } from './ExplorerHomeTab.utils'import { useCreateChat, useCreateNotebook, useCreateQuery } from './hooks'import { NOTEBOOK_TEMPLATES } from './templates'import { ActionCard } from '@/components/layouts/Tabs/ActionCard'@@ -35,7 +36,11 @@ export const ExplorerHomeTab = () => {placeholder="Explore your data, check project health, create a notebook..."value={value}onValueChange={(e) => setValue(e.target.value)}- onSubmit={(message) => createChat({ initialMessage: message })}+ onSubmit={(message) =>+ isSqlStatement(message)+ ? createQuery({ sql: message, autoRun: true })+ : createChat({ initialMessage: message })+ }/><AssistantAgentHarnessFooter />diff --git a/apps/studio/components/interfaces/Explorer/ExplorerHomeTab.utils.test.ts b/apps/studio/components/interfaces/Explorer/ExplorerHomeTab.utils.test.tsnew file mode 100644index 00000000000..805bdc73e97--- /dev/null+++ b/apps/studio/components/interfaces/Explorer/ExplorerHomeTab.utils.test.ts@@ -0,0 +1,40 @@+import { describe, expect, it } from 'vitest'++import { isSqlStatement } from './ExplorerHomeTab.utils'++describe('isSqlStatement', () => {+ it.each([+ 'select * from profiles',+ 'SELECT id FROM profiles WHERE id = 1;',+ "insert into logs (msg) values ('hi')",+ 'update profiles set name = null',+ 'delete from profiles where id = 1',+ 'with recent as (select 1) select * from recent',+ ' \n select 1',+ '-- get everyone\nselect * from profiles',+ 'create table users (id serial primary key)',+ 'CREATE OR REPLACE FUNCTION foo() RETURNS void AS $$ BEGIN END; $$ LANGUAGE plpgsql',+ 'create policy my_policy on profiles for select using (true)',+ 'show search_path',+ 'SHOW ALL;',+ 'set search_path to public',+ "SET TIME ZONE 'UTC'",+ ])('returns true for %s', (message) => {+ expect(isSqlStatement(message)).toBe(true)+ })++ it.each([+ '',+ ' ',+ 'How do I add a new column to my table?',+ 'What indexes exist on my users table?',+ 'Explain how RLS works',+ 'Can you help me select the right plan for my project?',+ 'Create a new table for storing user profiles',+ 'Show me my tables',+ 'Set up RLS on my users table',+ 'With my current schema, what tables should I add?',+ ])('returns false for %s', (message) => {+ expect(isSqlStatement(message)).toBe(false)+ })+})diff --git a/apps/studio/components/interfaces/Explorer/ExplorerHomeTab.utils.ts b/apps/studio/components/interfaces/Explorer/ExplorerHomeTab.utils.tsnew file mode 100644index 00000000000..37358997ce4--- /dev/null+++ b/apps/studio/components/interfaces/Explorer/ExplorerHomeTab.utils.ts@@ -0,0 +1,33 @@+import { removeCommentsFromSql } from '@/lib/helpers'++// [Joshen] `explain` is deliberately excluded even though it's a real SQL keyword - "Explain+// how RLS works" is a common natural-language prompt, and colliding with it would misroute+// a normal chat question into a query tab.+const UNAMBIGUOUS_SQL_STATEMENT_REGEX =+ /^\s*(select|insert|update|delete|alter|drop|truncate|grant|revoke|begin|vacuum|analyze|merge|call|copy|lock|reindex|refresh|execute|prepare|deallocate|comment)\b/i++// `create`, `show`, `set`, and `with` are also common natural-language sentence openers+// ("Create a table for me", "Show me my indexes", "Set up RLS", "With my current schema...").+// Matching the bare keyword alone would misroute those into a query tab, so each requires+// syntax that only shows up in the real SQL statement.+const CREATE_STATEMENT_REGEX =+ /^\s*create\s+(or\s+replace\s+)?(table|unique\s+index|index|view|materialized\s+view|function|procedure|trigger|schema|extension|role|user|policy|type|sequence|database|domain|rule|publication|foreign\s+table)\b/i+const SHOW_STATEMENT_REGEX = /^\s*show\s+(all|[a-zA-Z_][a-zA-Z0-9_.]*)\s*;?\s*$/i+const SET_STATEMENT_REGEX =+ /^\s*set\s+(session\s+|local\s+)?(time\s+zone\b|[a-zA-Z_][a-zA-Z0-9_.]*\s*(=|to)\s*\S)/i+const WITH_STATEMENT_REGEX = /^\s*with\s+(recursive\s+)?[a-zA-Z_][a-zA-Z0-9_]*\s+as\s*\(/i++/**+ * Whether `message` looks like a SQL statement rather than a natural-language chat prompt,+ * so the Explorer home tab can route it to a query tab instead of creating an AI chat.+ */+export function isSqlStatement(message: string): boolean {+ const sql = removeCommentsFromSql(message)+ return (+ UNAMBIGUOUS_SQL_STATEMENT_REGEX.test(sql) ||+ CREATE_STATEMENT_REGEX.test(sql) ||+ SHOW_STATEMENT_REGEX.test(sql) ||+ SET_STATEMENT_REGEX.test(sql) ||+ WITH_STATEMENT_REGEX.test(sql)+ )+}diff --git a/apps/studio/components/interfaces/Explorer/ExplorerQueryTab.tsx b/apps/studio/components/interfaces/Explorer/ExplorerQueryTab.tsxindex 9033c482856..9195aac3199 100644--- a/apps/studio/components/interfaces/Explorer/ExplorerQueryTab.tsx+++ b/apps/studio/components/interfaces/Explorer/ExplorerQueryTab.tsx@@ -80,6 +80,7 @@ export const ExplorerQueryTab = () => {const draft = stateDraft?.projectRef === ref ? stateDraft : undefinedconst result = draft && id ? querySnap.results[id] : undefinedconst queryKey = id && ref ? `${ref}:${id}` : undefined+ const isDraftReady = !!queryKey && restoredQueryKey === queryKeyconst roleImpersonationState = useControlledRoleImpersonationState(draft?._tag === 'database' ? draft.role : undefined,@@ -99,6 +100,13 @@ export const ExplorerQueryTab = () => {setRestoredQueryKey(`${ref}:${id}`)}, [id, ref])+ useEffect(() => {+ if (!id || !isDraftReady || !draft?.pendingAutoRun) return++ queryEditorRef.current?.run()+ explorerQueryState.clearPendingAutoRun({ id })+ }, [id, isDraftReady, draft?.pendingAutoRun])+if (!queryKey || restoredQueryKey !== queryKey) {return (<divdiff --git a/apps/studio/components/interfaces/Explorer/__tests__/QueryTab.test.tsx b/apps/studio/components/interfaces/Explorer/__tests__/QueryTab.test.tsxindex fc3e46d707d..ce0e88143bb 100644--- a/apps/studio/components/interfaces/Explorer/__tests__/QueryTab.test.tsx+++ b/apps/studio/components/interfaces/Explorer/__tests__/QueryTab.test.tsx@@ -1,3 +1,4 @@+import { QueryClient } from '@tanstack/react-query'import { act, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { HttpResponse } from 'msw'@@ -5,6 +6,7 @@ import { useEffect, useRef, type ReactNode } from 'react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { ExplorerQueryTab } from '../ExplorerQueryTab'+import { projectKeys } from '@/data/projects/keys'import type { ReadReplicasData } from '@/data/read-replicas/replicas-query'import { explorerQueryState } from '@/state/explorer-query'import { createTabId, createTabsState, TabsStateContext } from '@/state/tabs'@@ -155,13 +157,46 @@ vi.mock('../QueryEditor/QueryResultChart', () => ({QueryResultChart: () => <div>Chart results</div>,}))-const renderQueryTab = (tabsState = createTabsState('default')) =>+const renderQueryTab = (tabsState = createTabsState('default'), queryClient?: QueryClient) =>customRender(<TabsStateContext.Provider value={tabsState}><ExplorerQueryTab />- </TabsStateContext.Provider>+ </TabsStateContext.Provider>,+ { queryClient })+/**+ * By the time a query tab can auto-run, its project is already cached - the Explorer home tab+ * that created the draft required the same project data to do so. Priming the cache here+ * mirrors that instead of racing this test against a cold fetch of `/platform/projects/:ref`.+ */+const createWarmProjectQueryClient = (ref: string = 'default') => {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ })+ queryClient.setQueryData(projectKeys.detail(ref), {+ id: 1,+ ref,+ organization_id: 1,+ name: 'Test Project',+ status: 'ACTIVE_HEALTHY',+ cloud_provider: 'AWS',+ region: 'us-east-1',+ db_host: `db.${ref}.supabase.co`,+ restUrl: `https://${ref}.supabase.co/rest/v1/`,+ inserted_at: '2024-01-01T00:00:00Z',+ updated_at: '2024-01-01T00:00:00Z',+ subscription_id: 'sub_123',+ is_branch_enabled: false,+ is_physical_backups_enabled: false,+ high_availability: false,+ integration_source: null,+ connectionString: 'postgresql://postgres@localhost:5432/postgres',+ is_hibernating: false,+ })+ return queryClient+}+const createDraft = (source:| { _tag: 'database'; database_identifier?: string }@@ -169,7 +204,8 @@ const createDraft = (_tag: 'logs'time_range: { _tag: 'relative_time_range'; amount: number; unit: 'hour' }},- sql: string = 'select 1'+ sql: string = 'select 1',+ { autoRun = false }: { autoRun?: boolean } = {}) => {explorerQueryState.removeDraft({ id: 'query-test', projectRef: 'default' })explorerQueryState.createDraft({@@ -177,6 +213,7 @@ const createDraft = (projectRef: 'default',sql,source,+ autoRun,})}@@ -200,6 +237,29 @@ describe('QueryTab execution', () => {expect(screen.queryByText('Query draft not found')).not.toBeInTheDocument()})+ it('auto-runs a draft created with autoRun, then clears the flag', async () => {+ // `/platform/pg-meta/:ref/query` is also hit by unrelated background metadata fetches+ // (autocomplete definitions, event triggers, ...), so the run is asserted via the stored+ // result it produces rather than by counting requests to that shared endpoint.+ createDraft({ _tag: 'database' }, 'select 1', { autoRun: true })++ renderQueryTab(createTabsState('default'), createWarmProjectQueryClient())++ await waitFor(() => expect(explorerQueryState.results['query-test']).toBeDefined())+ expect(explorerQueryState.results['query-test']).toMatchObject({ rows: [] })+ expect(explorerQueryState.drafts['query-test']?.pendingAutoRun).toBe(false)+ })++ it('does not auto-run a draft created without autoRun', async () => {+ createDraft({ _tag: 'database' })++ renderQueryTab()+ await screen.findByRole('button', { name: 'Run' })++ await new Promise((resolve) => setTimeout(resolve, 50))+ expect(explorerQueryState.results['query-test']).toBeUndefined()+ })+it('records an unavailable error and skips the logs endpoint when the flag is off', async () => {testContext.flags.otelLegacyLogs = falsecreateDraft({diff --git a/apps/studio/components/interfaces/Explorer/__tests__/hooks.test.tsx b/apps/studio/components/interfaces/Explorer/__tests__/hooks.test.tsxindex 23824ccfe80..1d4f5662b1d 100644--- a/apps/studio/components/interfaces/Explorer/__tests__/hooks.test.tsx+++ b/apps/studio/components/interfaces/Explorer/__tests__/hooks.test.tsx@@ -137,4 +137,17 @@ describe('useCreateQuery', () => {name: undefined,})})++ it('forwards autoRun to the draft so its query tab can run itself once mounted', () => {+ const { result } = renderHook(() => useCreateQuery())++ result.current.createQuery({ sql: 'select 1', autoRun: true })+ expect(mockCreateDraft).toHaveBeenCalledWith({+ id: 'query-new',+ projectRef: 'default',+ sql: 'select 1',+ name: undefined,+ autoRun: true,+ })+ })})diff --git a/apps/studio/components/interfaces/Explorer/hooks.ts b/apps/studio/components/interfaces/Explorer/hooks.tsindex 77791bf9cf5..dd3c2d59fcb 100644--- a/apps/studio/components/interfaces/Explorer/hooks.ts+++ b/apps/studio/components/interfaces/Explorer/hooks.ts@@ -187,11 +187,15 @@ export const useCreateQuery = () => {const { data: project } = useSelectedProjectQuery()const querySnap = useExplorerQueryStateSnapshot()- const createQuery = ({ sql, name }: { sql?: string; name?: string } = {}) => {+ const createQuery = ({+ sql,+ name,+ autoRun,+ }: { sql?: string; name?: string; autoRun?: boolean } = {}) => {if (!project) return console.error('Project is required')const id = generateUuid()- querySnap.createDraft({ id, projectRef: project.ref, sql, name })+ querySnap.createDraft({ id, projectRef: project.ref, sql, name, autoRun })router.push(`/project/${project.ref}/explorer/query/${id}`)diff --git a/apps/studio/state/explorer-query.ts b/apps/studio/state/explorer-query.tsindex cc2faddbbfd..48927462b78 100644--- a/apps/studio/state/explorer-query.ts+++ b/apps/studio/state/explorer-query.ts@@ -27,6 +27,7 @@ type ExplorerQueryDraftBase = {updatedAt: numberview: QueryDisplay['view']chart?: QueryDisplay['chart']+ pendingAutoRun?: boolean}/**@@ -241,6 +242,7 @@ export const createExplorerQueryState = (storage: StorageLike = safeLocalStoragesql = '',source = createDefaultSourceBinding('database'),rowLimit = DEFAULT_CELL_ROW_LIMIT,+ autoRun = false,}: {id: stringprojectRef: string@@ -248,6 +250,7 @@ export const createExplorerQueryState = (storage: StorageLike = safeLocalStoragesql?: stringsource?: QuerySourceBindingrowLimit?: number+ autoRun?: boolean}) => {const draft = toDraft({id,@@ -261,6 +264,7 @@ export const createExplorerQueryState = (storage: StorageLike = safeLocalStorageview: 'table',},})+ draft.pendingAutoRun = autoRunstate.drafts[id] = draftpersistDraft(draft)@@ -268,6 +272,11 @@ export const createExplorerQueryState = (storage: StorageLike = safeLocalStoragereturn id},+ clearPendingAutoRun: ({ id }: { id: string }) => {+ const draft = state.drafts[id]+ if (draft) draft.pendingAutoRun = false+ },+restoreDraft: ({ id, projectRef }: { id: string; projectRef: string }) => {if (state.drafts[id]?.projectRef === projectRef) return true