Files
supabase/apps/studio/components/interfaces/Explorer/QueryTab.tsx
T
Joshen Lim 097a105663 joshenlim/fe 4176 add role impersonation to explorerquerysourcemenu (#49101)
## Context

Stacked off from https://github.com/supabase/supabase/pull/49098 - adds
role impersonation for both Notebook Query cell + Explorer Query tab

Note that this refactors the role impersonation state a little to
decouple some stuffs to make this work, since the role impersonation
state is global and we need a local state to support this UX

Similarly to row limit, for query tab its intentional that for now that
the role impersonation isn't scoped to the query draft atm as I wanna
avoid making changes to explorer-query given there was a couple of PRs
in flux that adjusts that file - will handle that separately

<img width="1117" height="577" alt="image"
src="https://github.com/user-attachments/assets/9bfd6287-efff-418b-a1c0-934ee2c840cb"
/>

<img width="1917" height="436" alt="image"
src="https://github.com/user-attachments/assets/bfd1be82-8f77-4764-bd3a-4b9c63169b82"
/>


## To test
- [ ] Verify that role impersonation works in notebook query cell
- [ ] Verify that role impersonation works in notebook query tab

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
  * Added role impersonation support to SQL Explorer queries.
* Users can select an impersonated role directly from database query
menus.
  * Query execution now applies the selected role when configured.
* Added local role selection state for individual query tabs and cells.
* Improved reuse and consistency of role impersonation controls across
the interface.
* Role selections and impersonation details remain synchronized across
supported query components.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-08-17 14:22:50 +08:00

110 lines
3.7 KiB
TypeScript

import { useParams } from 'common'
import { Loader2, SquareCode } from 'lucide-react'
import { useRouter } from 'next/router'
import { useContext, useEffect, useState } from 'react'
import { Button } from 'ui'
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 { useLocalRoleImpersonationState } from '@/state/role-impersonation-state'
import { createTabId, TabsStateContext } from '@/state/tabs'
/** Query-tab lifecycle adapter around the shared QueryEditor. */
export const QueryTab = () => {
const { id, ref } = useParams()
const router = useRouter()
const tabs = useContext(TabsStateContext)
const querySnap = useExplorerQueryStateSnapshot()
const roleImpersonationState = useLocalRoleImpersonationState()
const [rowLimit, setRowLimit] = useState<number>(100)
const [restoredQueryKey, setRestoredQueryKey] = useState<string>()
const stateDraft = id ? querySnap.drafts[id] : undefined
const draft = stateDraft?.projectRef === ref ? stateDraft : undefined
const result = draft && id ? querySnap.results[id] : undefined
const queryKey = id && ref ? `${ref}:${id}` : undefined
useEffect(() => {
if (!id || !ref) return
const restored = explorerQueryState.restoreDraft({ id, projectRef: ref })
const restoredDraft = explorerQueryState.drafts[id]
if (restored && restoredDraft) {
tabs.addTab({
id: createTabId('query', { id }),
type: 'query',
label: restoredDraft.name,
metadata: { queryId: id },
isPreview: false,
})
}
setRestoredQueryKey(`${ref}:${id}`)
}, [id, ref, tabs])
if (!queryKey || restoredQueryKey !== queryKey) {
return (
<div
role="status"
aria-label="Loading query"
className="flex h-full items-center justify-center bg-surface-100"
>
<Loader2 className="animate-spin text-foreground-muted" size={18} />
</div>
)
}
if (!id || !draft) {
return (
<div className="flex h-full flex-col items-center justify-center gap-3 bg-surface-100">
<SquareCode className="text-foreground-muted" size={24} />
<div className="text-center">
<p className="text-sm font-medium">Query draft not found</p>
<p className="text-sm text-foreground-lighter">
This local draft may have been closed or cleared from this browser.
</p>
</div>
<Button onClick={() => router.push(`/project/${ref}/explorer`)}>Back to Explorer</Button>
</div>
)
}
const handleResultChange = (nextResult: QueryResult) => {
explorerQueryState.setResult({
id,
result: { ...nextResult, executedAt: Date.now() },
})
}
const query: ExplorerQueryModel =
draft._tag === 'logs'
? { ...toQuerySourceBinding(draft), uncheckedSql: draft.uncheckedSql }
: {
...toQuerySourceBinding(draft),
uncheckedSql: draft.uncheckedSql,
rowLimit,
}
return (
<QueryEditor
id={id}
variant="viewport"
title={draft.name}
query={query}
result={result}
roleImpersonationState={roleImpersonationState}
onTitleChange={(value) => {
const name = value.trim() || 'Untitled query'
explorerQueryState.updateDraft({ id, name })
tabs.updateTab(createTabId('query', { id }), { label: name })
}}
onSqlChange={(sql) => explorerQueryState.updateDraft({ id, sql })}
onSourceChange={(source) => explorerQueryState.updateDraft({ id, source })}
onResultChange={handleResultChange}
onRowLimitChange={setRowLimit}
/>
)
}