Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Joshenlim/fe 4401 re sql editor silently points to the primary instead of (#50513)

Joshen Lim71d58cba7f7a
diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts
index ae75a7edb62..f88a2558afb 100644
--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts
+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts
@@ -1271,8 +1271,8 @@ const makeEditor = ({
}): IStandaloneCodeEditor =>
({
getValue: () => value,
- getSelection: () => (hasSelection ? ({ startLineNumber: 1 } as any) : null),
- getModel: () => ({ getValueInRange: () => selectionValue }) as any,
+ getSelection: () => (hasSelection ? { startLineNumber: 1 } : null),
+ getModel: () => ({ getValueInRange: () => selectionValue }),
}) as unknown as IStandaloneCodeEditor
describe('SQLEditor.utils:getEditorSql', () => {
diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditorControllers.tsx b/apps/studio/components/interfaces/SQLEditor/SQLEditorControllers.tsx
index e73d167d803..a2b03739bb9 100644
--- a/apps/studio/components/interfaces/SQLEditor/SQLEditorControllers.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditorControllers.tsx
@@ -25,18 +25,16 @@ import { useRunSource } from './useRunSource'
import { useSnippetIdentity } from './useSnippetIdentity'
import { useSnippetTitleGenerator } from './useSnippetTitleGenerator'
import { useSqlEditorAi } from './useSqlEditorAi'
+import { useSqlEditorDatabaseSelection } from './useSqlEditorDatabaseSelection'
import { useSqlEditorExecution } from './useSqlEditorExecution'
import { useSqlEditorShortcuts } from './useSqlEditorShortcuts'
-import { isValidConnString } from '@/data/fetchers'
import {
untrustedLogSql,
type SafeLogSqlFragment,
type UntrustedLogSqlFragment,
} from '@/data/logs/safe-analytics-sql'
import { type QuerySourceBinding } from '@/data/query-sources/query-source-registry'
-import { useReadReplicasQuery } from '@/data/read-replicas/replicas-query'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
-import { useDatabaseSelectorStateSnapshot } from '@/state/database-selector'
import {
getSqlEditorV2StateSnapshot,
useSqlEditorV2StateSnapshot,
@@ -129,7 +127,6 @@ export const SQLEditorControllersProvider = ({ children }: PropsWithChildren) =>
const tabs = useTabsStateSnapshot()
const snapV2 = useSqlEditorV2StateSnapshot()
- const { setSelectedDatabaseId } = useDatabaseSelectorStateSnapshot()
const diff = useSqlEditorDiff()
const { isDiffOpen } = diff
@@ -146,12 +143,7 @@ export const SQLEditorControllersProvider = ({ children }: PropsWithChildren) =>
useAddDefinitions(id, monacoRef.current, { enabled: runSource._tag !== 'logs' })
- const { data: databases, isSuccess: isSuccessReadReplicas } = useReadReplicasQuery(
- {
- projectRef: ref,
- },
- { enabled: isValidConnString(project?.connectionString) }
- )
+ useSqlEditorDatabaseSelection({ ref, connectionString: project?.connectionString })
const { setAiTitle } = useSnippetTitleGenerator()
@@ -214,13 +206,6 @@ export const SQLEditorControllersProvider = ({ children }: PropsWithChildren) =>
return () => saveScrollPosition(id)
}, [id])
- useEffect(() => {
- if (isSuccessReadReplicas) {
- const primaryDatabase = databases.find((db) => db.identifier === ref)
- setSelectedDatabaseId(primaryDatabase?.identifier)
- }
- }, [isSuccessReadReplicas, databases, ref, setSelectedDatabaseId])
-
const snippetName =
urlId === 'new'
? generatedNewSnippetName
diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/QuerySourceMenu.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/QuerySourceMenu.tsx
index 2a812e30030..7d318f4053c 100644
--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/QuerySourceMenu.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/QuerySourceMenu.tsx
@@ -61,7 +61,8 @@ export const QuerySourceMenu = ({ id, runSource, canCreateLogsSnippet }: QuerySo
const snapV2 = useSqlEditorV2StateSnapshot()
const sessionSnap = useSqlEditorSessionSnapshot()
const databaseSelector = useDatabaseSelectorStateSnapshot()
- const [lastSelectedDatabase, setLastSelectedDatabase] = useLocalStorageQuery(
+
+ const [, setLastSelectedDatabase] = useLocalStorageQuery(
LOCAL_STORAGE_KEYS.SQL_EDITOR_LAST_SELECTED_DB(ref ?? ''),
''
)
@@ -79,10 +80,7 @@ export const QuerySourceMenu = ({ id, runSource, canCreateLogsSnippet }: QuerySo
// A snippet materializes in the store on its first keystroke; until then a
// `/sql/new` tab is a blank scaffold with nothing to preserve.
const isBlankNewTab = snapV2.snippets[id] === undefined
- const databaseIdentifier =
- lastSelectedDatabase.length > 0
- ? lastSelectedDatabase
- : (databaseSelector.selectedDatabaseId ?? ref)
+ const databaseIdentifier = databaseSelector.selectedDatabaseId ?? ref
const selectableSources = QUERY_SOURCES.filter(
(source) => source._tag !== 'logs' || canCreateLogsSnippet || isLogs
diff --git a/apps/studio/components/interfaces/SQLEditor/useSqlEditorDatabaseSelection.test.tsx b/apps/studio/components/interfaces/SQLEditor/useSqlEditorDatabaseSelection.test.tsx
new file mode 100644
index 00000000000..17a408955f7
--- /dev/null
+++ b/apps/studio/components/interfaces/SQLEditor/useSqlEditorDatabaseSelection.test.tsx
@@ -0,0 +1,153 @@
+import { QueryClient } from '@tanstack/react-query'
+import { act, waitFor } from '@testing-library/react'
+import { LOCAL_STORAGE_KEYS } from 'common'
+import { HttpResponse } from 'msw'
+import { subscribe } from 'valtio'
+import { beforeEach, describe, expect, it } from 'vitest'
+
+import { useSqlEditorDatabaseSelection } from './useSqlEditorDatabaseSelection'
+import { replicaKeys } from '@/data/read-replicas/keys'
+import { useReadReplicasQuery, type Database } from '@/data/read-replicas/replicas-query'
+import {
+ createDatabaseSelectorState,
+ useDatabaseSelectorStateSnapshot,
+} from '@/state/database-selector'
+import { addAPIMock } from '@/tests/lib/msw'
+import {
+ renderSqlEditorHook,
+ resetSqlEditorStores,
+ setupSqlEditorMocks,
+} from '@/tests/lib/sql-editor-test-utils'
+
+const REF = 'default'
+const CONNECTION_STRING = 'postgresql://postgres@localhost:5432/postgres'
+
+function useHarness() {
+ useSqlEditorDatabaseSelection({ ref: REF, connectionString: CONNECTION_STRING })
+ const { selectedDatabaseId } = useDatabaseSelectorStateSnapshot()
+ // Shares the query cache with the hook under test, purely so the test can
+ // observe when a refetch has actually reached this render (see below).
+ const { data: databases } = useReadReplicasQuery({ projectRef: REF })
+ return { selectedDatabaseId, databases }
+}
+
+function buildDatabase(identifier: string, requestCount = 1): Database {
+ return {
+ identifier,
+ connectionString: CONNECTION_STRING,
+ connection_string_read_only: CONNECTION_STRING,
+ cloud_provider: 'AWS',
+ db_host: `db.${identifier}.supabase.co`,
+ db_name: 'postgres',
+ db_port: 5432,
+ db_user: 'postgres',
+ inserted_at: `2024-01-01T00:00:${String(requestCount).padStart(2, '0')}Z`,
+ region: 'us-east-1',
+ restUrl: `https://${identifier}.supabase.co/rest/v1/`,
+ size: 'ci_micro',
+ status: 'ACTIVE_HEALTHY',
+ }
+}
+
+/**
+ * Overrides the default single-database mock from `setupSqlEditorMocks` with a
+ * primary + replica, and varies a field (as a real background poll would, e.g.
+ * timestamps) on every request so react-query's structural sharing can't reuse
+ * the previous array reference — otherwise the effect this hook guards would
+ * never even re-run, masking the clobbering bug regardless of the guard.
+ */
+function mockDatabasesWithReplica() {
+ let requestCount = 0
+ addAPIMock({
+ method: 'get',
+ path: '/platform/projects/:ref/databases',
+ response: () => {
+ requestCount += 1
+ return HttpResponse.json<Database[]>(
+ [REF, 'replica-1'].map((identifier) => buildDatabase(identifier, requestCount))
+ )
+ },
+ })
+}
+
+beforeEach(() => {
+ resetSqlEditorStores()
+ setupSqlEditorMocks({ ref: REF, connectionString: CONNECTION_STRING })
+ localStorage.clear()
+})
+
+describe('useSqlEditorDatabaseSelection', () => {
+ it('defaults to the primary database once read replicas load', async () => {
+ const { result } = renderSqlEditorHook(() => useHarness())
+
+ await waitFor(() => expect(result.current.selectedDatabaseId).toBe(REF))
+ })
+
+ it('does not clobber an existing selection when the databases list is refetched', async () => {
+ // This is the regression this hook exists to prevent: a background refetch
+ // of `databases` used to re-run the selection effect and silently swap the
+ // user's chosen replica back to the primary.
+ mockDatabasesWithReplica()
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const databaseSelectorState = createDatabaseSelectorState()
+
+ const { result } = renderSqlEditorHook(() => useHarness(), {
+ queryClient,
+ databaseSelectorState,
+ })
+
+ await waitFor(() => expect(result.current.selectedDatabaseId).toBe(REF))
+
+ await act(async () => {
+ databaseSelectorState.setSelectedDatabaseId('replica-1')
+ })
+ await waitFor(() => expect(result.current.selectedDatabaseId).toBe('replica-1'))
+
+ await act(async () => {
+ await queryClient.refetchQueries({ queryKey: replicaKeys.list(REF) })
+ })
+
+ // Wait until the refetched (differently-timestamped) data has actually
+ // reached this render, so the assertion below isn't just "too early" —
+ // if the guard were broken, this is the point at which it would clobber.
+ await waitFor(() => expect(result.current.databases?.[0].inserted_at).toMatch(/:02Z$/))
+
+ expect(result.current.selectedDatabaseId).toBe('replica-1')
+ })
+
+ it('waits for the persisted last-selected database to load before defaulting to the primary', async () => {
+ // Regression: if `databases` is already cached/fresh (isSuccess synchronously
+ // true) while the local-storage read is still in flight, the effect used to
+ // fire immediately, default to the primary, and then the "only once" guard
+ // blocked the persisted replica choice from ever being applied once it loaded.
+ localStorage.setItem(
+ LOCAL_STORAGE_KEYS.SQL_EDITOR_LAST_SELECTED_DB(REF),
+ JSON.stringify('replica-1')
+ )
+ // Also mock the endpoint (not just the cache) so a refetch-on-mount — triggered
+ // because seeded data via `setQueryData` is immediately stale — doesn't clobber
+ // the seeded replica with the default single-database response.
+ mockDatabasesWithReplica()
+
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ queryClient.setQueryData(replicaKeys.list(REF), [
+ buildDatabase(REF),
+ buildDatabase('replica-1'),
+ ])
+
+ const databaseSelectorState = createDatabaseSelectorState()
+ const selectionsSeen: (string | undefined)[] = []
+ subscribe(databaseSelectorState, () =>
+ selectionsSeen.push(databaseSelectorState.selectedDatabaseId)
+ )
+
+ const { result } = renderSqlEditorHook(() => useHarness(), {
+ queryClient,
+ databaseSelectorState,
+ })
+
+ await waitFor(() => expect(result.current.selectedDatabaseId).toBe('replica-1'))
+
+ expect(selectionsSeen).not.toContain(REF)
+ })
+})
diff --git a/apps/studio/components/interfaces/SQLEditor/useSqlEditorDatabaseSelection.ts b/apps/studio/components/interfaces/SQLEditor/useSqlEditorDatabaseSelection.ts
new file mode 100644
index 00000000000..19fce6a3636
--- /dev/null
+++ b/apps/studio/components/interfaces/SQLEditor/useSqlEditorDatabaseSelection.ts
@@ -0,0 +1,65 @@
+import { LOCAL_STORAGE_KEYS } from 'common'
+import { useEffect } from 'react'
+
+import { isValidConnString } from '@/data/fetchers'
+import { useReadReplicasQuery, type Database } from '@/data/read-replicas/replicas-query'
+import { useLocalStorageQuery } from '@/hooks/misc/useLocalStorage'
+import {
+ useDatabaseSelectorStateSnapshot,
+ useGetSelectedDatabaseId,
+} from '@/state/database-selector'
+
+export function getDefaultDatabaseId({
+ databases,
+ ref,
+ lastSelectedDatabase,
+}: {
+ databases: Pick<Database, 'identifier'>[]
+ ref: string | undefined
+ lastSelectedDatabase: string
+}): string | undefined {
+ const lastSelectedIsStillValid = databases.some((db) => db.identifier === lastSelectedDatabase)
+ if (lastSelectedIsStillValid) return lastSelectedDatabase
+
+ return databases.find((db) => db.identifier === ref)?.identifier
+}
+
+/**
+ * Defaults the SQL editor's selected database once read replicas load
+ */
+export function useSqlEditorDatabaseSelection({
+ ref,
+ connectionString,
+}: {
+ ref: string | undefined
+ connectionString: string | null | undefined
+}) {
+ const { setSelectedDatabaseId } = useDatabaseSelectorStateSnapshot()
+ const getSelectedDatabaseId = useGetSelectedDatabaseId()
+
+ const { data: databases, isSuccess: isSuccessReadReplicas } = useReadReplicasQuery(
+ { projectRef: ref },
+ { enabled: isValidConnString(connectionString) }
+ )
+ const [lastSelectedDatabase, , { isLoading: isLoadingLastSelectedDatabase }] =
+ useLocalStorageQuery(LOCAL_STORAGE_KEYS.SQL_EDITOR_LAST_SELECTED_DB(ref ?? ''), '')
+
+ useEffect(() => {
+ // Only set the initial selection once, when nothing has been selected yet.
+ if (
+ isSuccessReadReplicas &&
+ !isLoadingLastSelectedDatabase &&
+ getSelectedDatabaseId() === undefined
+ ) {
+ setSelectedDatabaseId(getDefaultDatabaseId({ databases, ref, lastSelectedDatabase }))
+ }
+ }, [
+ isSuccessReadReplicas,
+ isLoadingLastSelectedDatabase,
+ databases,
+ ref,
+ lastSelectedDatabase,
+ setSelectedDatabaseId,
+ getSelectedDatabaseId,
+ ])
+}
diff --git a/apps/studio/components/interfaces/SQLEditor/useSqlEditorExecution.ts b/apps/studio/components/interfaces/SQLEditor/useSqlEditorExecution.ts
index 5d9c7f45a8d..601e92aa5a9 100644
--- a/apps/studio/components/interfaces/SQLEditor/useSqlEditorExecution.ts
+++ b/apps/studio/components/interfaces/SQLEditor/useSqlEditorExecution.ts
@@ -72,7 +72,7 @@ export function useSqlEditorExecution({
queryClient.invalidateQueries({ queryKey: lintKeys.lint(ref) })
refocusEditorAfterRunIfNeeded()
},
- onError(error: any, vars) {
+ onError(error, vars) {
if (id) {
editor.highlightErrorLine(error, hasSelection)
sessionSnap.addResultError(id, error, vars.autoLimit)