The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
fix(studio): correlate a query's SQL brand with the backend it runs against (#49074)
Charisb5bfc70c06b5
diff --git a/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx b/apps/studio/components/interfaces/Explorer/QueryCell/index.tsxindex 0348eaf1942..462093ec2f2 100644--- a/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx+++ b/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx@@ -4,7 +4,7 @@ import { type Snapshot } from 'valtio'import { AddCellDropdown } from '../AddCellDropdown'import { MoveCellDropdownContent } from '../MoveCellDropdownContent'-import { QueryEditor } from '../QueryEditor'+import { QueryEditor, type ExplorerQueryModel } from '../QueryEditor'import { type QueryDisplay, type QueryResult } from '../types'import { SortableSection } from '@/components/ui/SortableSection'import {@@ -38,13 +38,19 @@ export const QueryCell = ({ cell }: QueryCellProps) => {const currentNotebook = useCurrentNotebook()const { id, title: cellTitle, view, chart, unchecked_sql } = cell- const rowLimit = 'row_limit' in cell ? cell.row_limit : undefined- const source = getQuerySourceBinding(cell)const [sql, setSql] = useState<string>(unchecked_sql)const [result, setResult] = useState<QueryResult>()const title = cellTitle ?? 'Untitled snippet'+ const query: ExplorerQueryModel =+ cell._tag === 'log_cell'+ ? { ...getQuerySourceBinding(cell), uncheckedSql: untrustedLogSql(sql) }+ : {+ ...getQuerySourceBinding(cell),+ uncheckedSql: untrustedSql(sql),+ rowLimit: cell.row_limit,+ }const display: QueryDisplay = {view: view ?? 'table',chart: chart ? { ...chart, y_columns: [...chart.y_columns] } : undefined,@@ -133,10 +139,8 @@ export const QueryCell = ({ cell }: QueryCellProps) => {id={id}variant="embedded"title={title}- sql={sql}- source={source}+ query={query}result={result}- rowLimit={rowLimit}display={cell._tag === 'database_cell' ? display : undefined}onTitleChange={(title) => handleUpdateCell({ title })}onSqlChange={setSql}diff --git a/apps/studio/components/interfaces/Explorer/QueryEditor.tsx b/apps/studio/components/interfaces/Explorer/QueryEditor.tsxindex fba1aaa5503..7d05434ecb2 100644--- a/apps/studio/components/interfaces/Explorer/QueryEditor.tsx+++ b/apps/studio/components/interfaces/Explorer/QueryEditor.tsx@@ -1,4 +1,4 @@-import { acceptUntrustedSql, untrustedSql } from '@supabase/pg-meta'+import { acceptUntrustedSql, untrustedSql, type UntrustedSqlFragment } from '@supabase/pg-meta'import { useFlag } from 'common'import { CodeSquare, Eye, EyeOff, Play } from 'lucide-react'import { useState, type ReactNode } from 'react'@@ -25,12 +25,20 @@ import { QueryResultChart } from './QueryCell/QueryResultChart'import { QueryResultTable } from './QueryResultTable'import { type QueryDisplay, type QueryResult } from './types'import { CodeEditor } from '@/components/ui/CodeEditor/CodeEditor'+import {+ type DatabaseSourceParameters,+ type LogsSourceParameters,+} from '@/data/content/notebooks/notebook-schema'import { isValidConnString } from '@/data/fetchers'import { useExecuteLogsSqlMutation } from '@/data/logs/execute-logs-sql-mutation'-import { acceptUntrustedLogsSql, untrustedLogSql } from '@/data/logs/safe-analytics-sql'import {- createDefaultSourceBinding,+ acceptUntrustedLogsSql,+ untrustedLogSql,+ type UntrustedLogSqlFragment,+} from '@/data/logs/safe-analytics-sql'+import {QUERY_SOURCE_REGISTRY,+ toQuerySourceBinding,type QuerySourceBinding,} from '@/data/query-sources/query-source-registry'import { useReadReplicasQuery } from '@/data/read-replicas/replicas-query'@@ -39,14 +47,29 @@ import { applyAutoLimit } from '@/data/sql/utils'import { useLatest } from '@/hooks/misc/useLatest'import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'+/**+ * The query this editor is showing, tagged by backend. The tag correlates the SQL's+ * dialect brand with that backend's parameters, so a single `_tag` check inside+ * `handleRunQuery` narrows both at once and there is no path that sends a query to the+ * wrong wire boundary.+ */+export type ExplorerQueryModel =+ | ({+ _tag: 'database'+ uncheckedSql: UntrustedSqlFragment+ rowLimit?: number+ } & DatabaseSourceParameters)+ | ({+ _tag: 'logs'+ uncheckedSql: UntrustedLogSqlFragment+ } & LogsSourceParameters)+export type QueryEditorProps = {id: stringvariant: 'embedded' | 'viewport'title: string- sql: string- source?: QuerySourceBinding+ query: ExplorerQueryModelresult?: QueryResult- rowLimit?: numberdisplay?: QueryDisplaytoolbarActions?: ReactNodeonTitleChange: (title: string) => void@@ -66,10 +89,8 @@ export const QueryEditor = ({id,variant,title,- sql,- source,+ query,result,- rowLimit,display,toolbarActions,onTitleChange,@@ -79,7 +100,8 @@ export const QueryEditor = ({onResultChange,onDisplayChange,}: QueryEditorProps) => {- const sqlRef = useLatest(sql)+ const sql = query.uncheckedSql+ const sqlRef = useLatest<string>(sql)const onSqlCommitRef = useLatest(onSqlCommit)const isOtelLogsEnabled = useFlag('otelLegacyLogs')@@ -87,13 +109,11 @@ export const QueryEditor = ({const view = display?.view ?? 'table'const columns = Object.keys(result?.rows?.[0] ?? {})- const sourceBinding = source ?? createDefaultSourceBinding('database')+ const rowLimit = query._tag === 'database' ? query.rowLimit : undefined+ const databaseIdentifier = query._tag === 'database' ? query.database_identifier : undefinedconst [showQuery, setShowQuery] = useState(true)- const databaseIdentifier =- sourceBinding._tag === 'database' ? sourceBinding.database_identifier : undefined-const { data: databases, isPending: isLoadingDatabases } = useReadReplicasQuery({ projectRef: project?.ref },{@@ -119,12 +139,19 @@ export const QueryEditor = ({const isExecuting = isExecutingSql || isExecutingLogsconst isBusy = isLoadingProject || isResolvingDatabase || isExecuting- const handleRunQuery = (sqlToRun: string = sql) => {- if (!project || isBusy || sqlToRun.trim().length === 0) return+ /**+ * The user's run gesture, and therefore the promotion point for this query's SQL. The+ * raw text comes straight off the editor, so it is (re)branded untrusted here — the+ * editor boundary — and promoted in the same handler. Which pair of helpers applies is+ * decided by `query._tag`, the same discriminant that picks the execution endpoint, so+ * Postgres SQL cannot reach the analytics wire or vice versa.+ */+ const handleRunQuery = (rawSql: string = sql) => {+ if (!project || isBusy || rawSql.trim().length === 0) return- onSqlCommit?.(sql)+ onSqlCommit?.(rawSql)- if (sourceBinding._tag === 'logs') {+ if (query._tag === 'logs') {if (!isOtelLogsEnabled) {onResultChange({error: { message: "Querying logs isn't available for this project yet." },@@ -134,14 +161,14 @@ export const QueryEditor = ({executeLogsSql({projectRef: project.ref,- sql: acceptUntrustedLogsSql(untrustedLogSql(sqlToRun)),- range: resolveLogTimeRange(sourceBinding.time_range),+ sql: acceptUntrustedLogsSql(untrustedLogSql(rawSql)),+ range: resolveLogTimeRange(query.time_range),endpoint: QUERY_SOURCE_REGISTRY.logs.endpoint,})return}- const safeSql = acceptUntrustedSql(untrustedSql(sqlToRun))+ const safeSql = acceptUntrustedSql(untrustedSql(rawSql))const limitedSql = applyAutoLimit(safeSql, rowLimit)const connectionString =databaseIdentifier === undefined || databaseIdentifier === project.ref@@ -175,8 +202,11 @@ export const QueryEditor = ({<ExplorerToolbarTitle onSaveTitle={onTitleChange}>{title}</ExplorerToolbarTitle><ExplorerToolbarActions>{toolbarActions}- {source && onSourceChange && (- <ExplorerQuerySourceMenu source={source} onSourceChange={onSourceChange} />+ {onSourceChange && (+ <ExplorerQuerySourceMenu+ source={toQuerySourceBinding(query)}+ onSourceChange={onSourceChange}+ />)}{display && onDisplayChange && (<DisplaySettingsButtondiff --git a/apps/studio/components/interfaces/Explorer/QueryTab.tsx b/apps/studio/components/interfaces/Explorer/QueryTab.tsxindex 0948b97a773..83f32f4aa5e 100644--- a/apps/studio/components/interfaces/Explorer/QueryTab.tsx+++ b/apps/studio/components/interfaces/Explorer/QueryTab.tsx@@ -4,8 +4,9 @@ import { useRouter } from 'next/router'import { useContext, useEffect, useState } from 'react'import { Button } from 'ui'-import { QueryEditor } from './QueryEditor'+import { QueryEditor, type ExplorerQueryModel } from './QueryEditor'import { type QueryResult } from './types'+import { toQuerySourceBinding } from '@/data/query-sources/query-source-registry'import { explorerQueryState, useExplorerQueryStateSnapshot } from '@/state/explorer-query'import { createTabId, TabsStateContext } from '@/state/tabs'@@ -74,15 +75,22 @@ export const QueryTab = () => {})}+ const query: ExplorerQueryModel =+ draft._tag === 'logs'+ ? { ...toQuerySourceBinding(draft), uncheckedSql: draft.uncheckedSql }+ : {+ ...toQuerySourceBinding(draft),+ uncheckedSql: draft.uncheckedSql,+ rowLimit: QUERY_ROW_LIMIT,+ }+return (<QueryEditorid={id}variant="viewport"title={draft.name}- sql={draft.uncheckedSql}- source={draft.source}+ query={query}result={result}- rowLimit={QUERY_ROW_LIMIT}onTitleChange={(value) => {const name = value.trim() || 'Untitled query'explorerQueryState.updateDraft({ id, name })diff --git a/apps/studio/state/explorer-query.test.ts b/apps/studio/state/explorer-query.test.tsindex de2ccae4f20..e23f7f9fbdb 100644--- a/apps/studio/state/explorer-query.test.ts+++ b/apps/studio/state/explorer-query.test.ts@@ -17,6 +17,11 @@ const createMemoryStorage = () => {}}+const LOGS_SOURCE = {+ _tag: 'logs',+ time_range: { _tag: 'relative_time_range', amount: 3, unit: 'hour' },+} as const+describe('explorer query drafts', () => {beforeEach(() => vi.useFakeTimers())afterEach(() => vi.useRealTimers())@@ -32,36 +37,59 @@ describe('explorer query drafts', () => {expect(secondState.restoreDraft({ id: 'query-1', projectRef: 'project-a' })).toBe(true)expect(secondState.drafts['query-1']).toMatchObject({+ _tag: 'database',name: 'Active users',- source: { _tag: 'database' },uncheckedSql: 'select * from users',projectRef: 'project-a',})expect(secondState.restoreDraft({ id: 'query-1', projectRef: 'project-b' })).toBe(false)})- it('persists source parameters and clears stale results when they change', () => {+ it('persists source parameters and clears stale results when the backend changes', () => {const storage = createMemoryStorage()const state = createExplorerQueryState(storage)state.createDraft({ id: 'query-1', projectRef: 'project-a', sql: 'select 1' })state.setResult({ id: 'query-1', result: { rows: [{ value: 1 }], executedAt: 1 } })- state.updateDraft({- id: 'query-1',- source: {- _tag: 'logs',- time_range: { _tag: 'relative_time_range', amount: 3, unit: 'hour' },- },- })+ state.updateDraft({ id: 'query-1', source: LOGS_SOURCE })expect(state.results['query-1']).toBeUndefined()const restored = createExplorerQueryState(storage)expect(restored.restoreDraft({ id: 'query-1', projectRef: 'project-a' })).toBe(true)- expect(restored.drafts['query-1'].source).toEqual({+ expect(restored.drafts['query-1']).toMatchObject(LOGS_SOURCE)+ })++ it('carries the query text over when the backend changes, rebranded for the new dialect', () => {+ const storage = createMemoryStorage()+ const state = createExplorerQueryState(storage)++ state.createDraft({ id: 'query-1', projectRef: 'project-a', sql: 'select * from users' })+ state.updateDraft({ id: 'query-1', source: LOGS_SOURCE })++ expect(state.drafts['query-1']).toMatchObject({_tag: 'logs',- time_range: { _tag: 'relative_time_range', amount: 3, unit: 'hour' },+ uncheckedSql: 'select * from users',+ })+ })++ it('keeps the query when only the parameters of the same backend change', () => {+ const storage = createMemoryStorage()+ const state = createExplorerQueryState(storage)++ state.createDraft({ id: 'query-1', projectRef: 'project-a', sql: 'select * from users' })+ state.setResult({ id: 'query-1', result: { rows: [{ value: 1 }], executedAt: 1 } })+ state.updateDraft({+ id: 'query-1',+ source: { _tag: 'database', database_identifier: 'replica-1' },+ })++ expect(state.drafts['query-1']).toMatchObject({+ _tag: 'database',+ database_identifier: 'replica-1',+ uncheckedSql: 'select * from users',})+ expect(state.results['query-1']).toBeDefined()})it('restores pre-source drafts as database queries', () => {@@ -75,7 +103,7 @@ describe('explorer query drafts', () => {const state = createExplorerQueryState(storage)expect(state.restoreDraft({ id: 'query-1', projectRef: 'project-a' })).toBe(true)- expect(state.drafts['query-1'].source).toEqual({ _tag: 'database' })+ expect(state.drafts['query-1']._tag).toBe('database')})it('ignores a malformed root value', () => {@@ -115,7 +143,10 @@ describe('explorer query drafts', () => {const state = createExplorerQueryState(storage)expect(state.restoreDraft({ id: 'query-1', projectRef: 'project-a' })).toBe(true)- expect(state.drafts['query-1'].source).toEqual({ _tag: 'database' })+ expect(state.drafts['query-1']).toMatchObject({+ _tag: 'database',+ uncheckedSql: 'select 1',+ })})it('debounces SQL persistence while updating in-memory state immediately', () => {diff --git a/apps/studio/state/explorer-query.ts b/apps/studio/state/explorer-query.tsindex 805e7efd8eb..ae1f1972c61 100644--- a/apps/studio/state/explorer-query.ts+++ b/apps/studio/state/explorer-query.ts@@ -4,25 +4,54 @@ import { proxy, ref, snapshot, useSnapshot } from 'valtio'import { z } from 'zod'import { type QueryResult } from '@/components/interfaces/Explorer/types'+import {+ type DatabaseSourceParameters,+ type LogsSourceParameters,+} from '@/data/content/notebooks/notebook-schema'+import { untrustedLogSql, type UntrustedLogSqlFragment } from '@/data/logs/safe-analytics-sql'import {createDefaultSourceBinding,querySourceBindingSchema,+ toQuerySourceBinding,type QuerySourceBinding,} from '@/data/query-sources/query-source-registry'-export type ExplorerQueryDraft = {+type ExplorerQueryDraftBase = {id: stringprojectRef: stringname: string- source: QuerySourceBinding- uncheckedSql: UntrustedSqlFragmentupdatedAt: number}+/**+ * A standalone Explorer query draft. Tagged by backend rather than carrying a separate+ * `source` object, mirroring how notebook cells store their binding: the tag narrows+ * `uncheckedSql` to that backend's brand, so a Postgres draft's text can never be handed+ * to the analytics wire boundary (or vice versa) without failing to compile.+ */+export type DatabaseQueryDraft = ExplorerQueryDraftBase &+ DatabaseSourceParameters & {+ _tag: 'database'+ uncheckedSql: UntrustedSqlFragment+ }++export type LogsQueryDraft = ExplorerQueryDraftBase &+ LogsSourceParameters & {+ _tag: 'logs'+ uncheckedSql: UntrustedLogSqlFragment+ }++export type ExplorerQueryDraft = DatabaseQueryDraft | LogsQueryDraft+export type ExplorerQueryResult = QueryResult & {executedAt: number}+/**+ * Drafts persist their binding under a single `source` key. This is browser-local storage,+ * not the notebook wire contract, so nesting costs nothing here and lets the whole binding+ * be validated in one `safeParse`.+ */type PersistedExplorerQueryDraft = {name: stringsource: QuerySourceBinding@@ -45,6 +74,39 @@ const persistedDraftSchema = z.object({source: z.unknown().optional(),})+/**+ * Rebuilds a draft from its persisted form, branding the SQL for the backend the binding+ * names. The single place a stored string re-enters the type system as untrusted SQL, which+ * is what keeps the brand correlated with the backend rather than assumed.+ */+const toDraft = ({+ id,+ projectRef,+ persisted,+}: {+ id: string+ projectRef: string+ persisted: PersistedExplorerQueryDraft+}): ExplorerQueryDraft => {+ const base = { id, projectRef, name: persisted.name, updatedAt: persisted.updatedAt }++ if (persisted.source._tag === 'logs') {+ return {+ ...base,+ _tag: 'logs',+ time_range: persisted.source.time_range,+ uncheckedSql: untrustedLogSql(persisted.sql),+ }+ }++ return {+ ...base,+ _tag: 'database',+ database_identifier: persisted.source.database_identifier,+ uncheckedSql: untrustedSql(persisted.sql),+ }+}+const readPersistedDrafts = (storage: StorageLike, projectRef: string) => {const raw = storage.getItem(LOCAL_STORAGE_KEYS.EXPLORER_QUERY_DRAFTS(projectRef))if (!raw) return {} as PersistedExplorerQueryDrafts@@ -103,6 +165,17 @@ export const createExplorerQueryState = (storage: StorageLike = safeLocalStorage{ timeout: ReturnType<typeof setTimeout>; persist: () => void }>()+ const persistDraft = (draft: ExplorerQueryDraft) => {+ const persisted = readPersistedDrafts(storage, draft.projectRef)+ persisted[draft.id] = {+ name: draft.name,+ source: toQuerySourceBinding(draft),+ sql: draft.uncheckedSql,+ updatedAt: draft.updatedAt,+ }+ writePersistedDrafts(storage, draft.projectRef, persisted)+ }+const state = proxy({drafts: {} as Record<string, ExplorerQueryDraft>,results: {} as Record<string, ExplorerQueryResult>,@@ -120,19 +193,19 @@ export const createExplorerQueryState = (storage: StorageLike = safeLocalStoragesql?: stringsource?: QuerySourceBinding}) => {- const draft: ExplorerQueryDraft = {+ const draft = toDraft({id,projectRef,- name,- source: querySourceBindingSchema.parse(source),- uncheckedSql: untrustedSql(sql),- updatedAt: Date.now(),- }- state.drafts[id] = draft+ persisted: {+ name,+ source: querySourceBindingSchema.parse(source),+ sql,+ updatedAt: Date.now(),+ },+ })- const persisted = readPersistedDrafts(storage, projectRef)- persisted[id] = { name, source: draft.source, sql, updatedAt: draft.updatedAt }- writePersistedDrafts(storage, projectRef, persisted)+ state.drafts[id] = draft+ persistDraft(draft)return id},@@ -143,17 +216,22 @@ export const createExplorerQueryState = (storage: StorageLike = safeLocalStorageconst persisted = readPersistedDrafts(storage, projectRef)[id]if (!persisted) return false- state.drafts[id] = {- id,- projectRef,- name: persisted.name,- source: persisted.source,- uncheckedSql: untrustedSql(persisted.sql),- updatedAt: persisted.updatedAt,- }+ state.drafts[id] = toDraft({ id, projectRef, persisted })return true},+ /**+ * Applies an edit to a draft. The draft is rebuilt rather than mutated in place, since+ * a backend change changes which brand its SQL carries; a stale result from the old+ * backend is dropped, because another engine returns unrelated columns.+ *+ * NOTE — see `changeCellSource`: keeping the query text across a backend change is very+ * likely not what the user wants, since the dialects differ, and is kept for now only+ * because it destroys nothing. Worth revisiting alongside the notebook-cell behavior.+ *+ * A rename or a source change is a discrete action, so it writes through immediately;+ * SQL keystrokes are debounced by `EXPLORER_QUERY_PERSIST_DELAY`.+ */updateDraft: ({id,name,@@ -168,29 +246,28 @@ export const createExplorerQueryState = (storage: StorageLike = safeLocalStorageconst draft = state.drafts[id]if (!draft) return- if (name !== undefined) draft.name = name- if (source !== undefined) {- draft.source = querySourceBindingSchema.parse(source)- delete state.results[id]- }- if (sql !== undefined) draft.uncheckedSql = untrustedSql(sql)- draft.updatedAt = Date.now()+ const nextSource = source === undefined ? undefined : querySourceBindingSchema.parse(source)+ if (nextSource !== undefined && nextSource._tag !== draft._tag) delete state.results[id]++ state.drafts[id] = toDraft({+ id,+ projectRef: draft.projectRef,+ persisted: {+ name: name ?? draft.name,+ source: nextSource ?? toQuerySourceBinding(draft),+ sql: sql ?? draft.uncheckedSql,+ updatedAt: Date.now(),+ },+ })const persist = () => {const pending = pendingPersistence.get(id)if (pending) clearTimeout(pending.timeout)pendingPersistence.delete(id)+const currentDraft = state.drafts[id]if (!currentDraft) return-- const persisted = readPersistedDrafts(storage, currentDraft.projectRef)- persisted[id] = {- name: currentDraft.name,- source: currentDraft.source,- sql: currentDraft.uncheckedSql,- updatedAt: currentDraft.updatedAt,- }- writePersistedDrafts(storage, currentDraft.projectRef, persisted)+ persistDraft(currentDraft)}const pending = pendingPersistence.get(id)