Skip to content

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

Joshen/fe 3778 rls tester to support insert queries (#47554)

Joshen Lim3521ff06e1a7
diff --git a/apps/studio/components/interfaces/App/FeaturePreview/useFeaturePreviews.ts b/apps/studio/components/interfaces/App/FeaturePreview/useFeaturePreviews.ts
index 79d6a6059dc..1cdb5b0c3b0 100644
--- a/apps/studio/components/interfaces/App/FeaturePreview/useFeaturePreviews.ts
+++ b/apps/studio/components/interfaces/App/FeaturePreview/useFeaturePreviews.ts
@@ -37,7 +37,7 @@ export const useFeaturePreviews = (): FeaturePreview[] => {
isNew: true,
isPlatformOnly: false,
isDefaultOptIn: false,
- getRoute: (ref?: string) => `/project/${ref}/auth/policies`,
+ getRoute: (ref?: string) => `/project/${ref}/database/policies`,
},
{
key: LOCAL_STORAGE_KEYS.UI_PREVIEW_UNIFIED_LOGS,
diff --git a/apps/studio/components/interfaces/Database/RLSTester/RLSTableCard.tsx b/apps/studio/components/interfaces/Database/RLSTester/RLSTableCard.tsx
index 8dd31f87109..724f8b57cf2 100644
--- a/apps/studio/components/interfaces/Database/RLSTester/RLSTableCard.tsx
+++ b/apps/studio/components/interfaces/Database/RLSTester/RLSTableCard.tsx
@@ -4,18 +4,23 @@ import { cn, Collapsible, CollapsibleContent, CollapsibleTrigger, WarningIcon }
import type { Policy } from '@/components/interfaces/Database/Policies/PolicyTableRow/PolicyTableRow.utils'
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
+import { type ParseSQLQueryOperations } from '@/data/misc/parse-query-mutation'
interface RLSTableCardProps {
table: { schema: string; name: string; isRLSEnabled: boolean }
+ operation: ParseSQLQueryOperations
role?: string
policies: Policy[]
+ hasError: boolean
handleSelectEditPolicy: (policy: Policy) => void
}
export const RLSTableCard = ({
table,
+ operation,
role,
policies,
+ hasError,
handleSelectEditPolicy,
}: RLSTableCardProps) => {
const { schema, name, isRLSEnabled } = table
@@ -37,8 +42,11 @@ export const RLSTableCard = ({
return (
<p>
RLS is enabled but no policies exist for the{' '}
- <code className="text-code-inline">{role}</code> role on this table - no data will be
- returned.
+ <code className="text-code-inline">{role}</code> role on this table -{' '}
+ {operation === 'SELECT'
+ ? 'no data will be returned'
+ : `no data will be ${operation?.toLowerCase()}${operation?.toLowerCase().endsWith('e') ? 'd' : 'ed'}`}
+ .
</p>
)
}
@@ -54,6 +62,7 @@ export const RLSTableCard = ({
</p>
<TableAccessPolicySummary
policies={policies}
+ operation={operation}
handleSelectEditPolicy={handleSelectEditPolicy}
/>
</>
@@ -71,6 +80,7 @@ export const RLSTableCard = ({
</p>
<TableAccessPolicySummary
policies={policies}
+ operation={operation}
handleSelectEditPolicy={handleSelectEditPolicy}
/>
</>
@@ -81,11 +91,14 @@ export const RLSTableCard = ({
<>
<p>
{policies.length} {policies.length > 1 ? 'policies apply' : 'policy applies'} for the{' '}
- <code className="text-code-inline">{role}</code> role on this table. Only rows that match{' '}
- {policies.length > 1 ? 'these conditions' : 'this condition'} are returned.
+ <code className="text-code-inline">{role}</code> role on this table.{' '}
+ {operation === 'SELECT'
+ ? `Only rows that match ${policies.length > 1 ? 'these conditions' : 'this condition'} are returned.`
+ : `The ${operation} operation will only be successful if the conditions are matched.`}
</p>
<TableAccessPolicySummary
policies={policies}
+ operation={operation}
handleSelectEditPolicy={handleSelectEditPolicy}
/>
</>
@@ -97,6 +110,7 @@ export const RLSTableCard = ({
falseOnlyPolicy,
policies,
role,
+ operation,
handleSelectEditPolicy,
])
@@ -109,7 +123,7 @@ export const RLSTableCard = ({
<div className="flex items-center gap-x-2">
{!isRLSEnabled ? (
<WarningIcon />
- ) : noPolicies || falseOnlyPolicy ? (
+ ) : (hasError && operation === 'INSERT') || noPolicies || falseOnlyPolicy ? (
<X size={16} className="text-destructive" />
) : (
<Check size={16} className="text-brand" />
@@ -120,18 +134,20 @@ export const RLSTableCard = ({
</div>
</div>
<div className="flex items-center gap-x-2">
- <p
- className={cn(
- 'text-xs text-foreground-light w-max',
- !isRLSEnabled && 'text-foreground'
- )}
- >
- {noPolicies || falseOnlyPolicy
- ? 'Returns no rows'
- : !isRLSEnabled || !!trueOnlyPolicy
- ? 'Returns all rows'
- : null}
- </p>
+ {operation === 'SELECT' && (
+ <p
+ className={cn(
+ 'text-xs text-foreground-light w-max',
+ !isRLSEnabled && 'text-foreground'
+ )}
+ >
+ {noPolicies || falseOnlyPolicy
+ ? 'Returns no rows'
+ : !isRLSEnabled || !!trueOnlyPolicy
+ ? 'Returns all rows'
+ : null}
+ </p>
+ )}
<ChevronDown className="transition-transform duration-200" strokeWidth={1.5} size={14} />
</div>
</CollapsibleTrigger>
@@ -149,9 +165,11 @@ export const RLSTableCard = ({
const TableAccessPolicySummary = ({
policies,
+ operation,
handleSelectEditPolicy,
}: {
policies: Policy[]
+ operation: ParseSQLQueryOperations
handleSelectEditPolicy: (policy: Policy) => void
}) => {
return (
@@ -165,8 +183,11 @@ const TableAccessPolicySummary = ({
<div>
<p>{policy.name}</p>
<p className="text-foreground-lighter">
- Show rows where:{' '}
- <code className="text-code-inline text-foreground">{policy.definition}</code>
+ {operation === 'SELECT' ? 'Show rows' : `Allow ${operation?.toLocaleLowerCase()}s`}{' '}
+ where:{' '}
+ <code className="text-code-inline text-foreground">
+ {policy.definition ?? policy.check}
+ </code>
</p>
</div>
<ButtonTooltip
diff --git a/apps/studio/components/interfaces/Database/RLSTester/RLSTesterResults.tsx b/apps/studio/components/interfaces/Database/RLSTester/RLSTesterResults.tsx
index f8bdb5b4179..12d2a2b8f22 100644
--- a/apps/studio/components/interfaces/Database/RLSTester/RLSTesterResults.tsx
+++ b/apps/studio/components/interfaces/Database/RLSTester/RLSTesterResults.tsx
@@ -14,11 +14,13 @@ import { ParseQueryResults } from './RLSTester.types'
import { deriveRLSTestState } from './RLSTesterResults.utils'
import { useTestQueryRLS } from './useTestQueryRLS'
import type { Policy } from '@/components/interfaces/Database/Policies/PolicyTableRow/PolicyTableRow.utils'
+import { type QueryResponseError } from '@/data/sql/execute-sql-mutation'
interface RLSTesterResultsProps {
results: Object[]
autoLimit: boolean
parseQueryResults: ParseQueryResults
+ executeSqlError: Error | QueryResponseError | null | undefined
handleSelectEditPolicy: (policy: Policy) => void
}
@@ -26,6 +28,7 @@ export const RLSTesterResults = ({
results,
autoLimit,
parseQueryResults,
+ executeSqlError,
handleSelectEditPolicy,
}: RLSTesterResultsProps) => {
const { limit } = useTestQueryRLS()
@@ -34,14 +37,19 @@ export const RLSTesterResults = ({
isServiceRole,
tableWithRLSEnabledButNoPolicies,
tableWithRLSEnabledWithPolicyFalse,
+ tableWithRLSEnabledWithPoliciesDontApply,
noAccessToData,
} = deriveRLSTestState(parseQueryResults)
+ const { operation, role } = parseQueryResults
+ const rlsBlockInsert = executeSqlError && operation === 'INSERT'
+ const noAccess = noAccessToData || rlsBlockInsert
+
return (
<div className="p-5 pt-4">
<div className="flex items-center gap-x-2 mb-2">
<p className="text-sm">Summary</p>
- {noAccessToData ? (
+ {noAccess ? (
<Badge variant="destructive">No access</Badge>
) : (
<Badge variant="success">{results.length > 0 ? 'Can access' : 'Has access'}</Badge>
@@ -53,7 +61,7 @@ export const RLSTesterResults = ({
<TabsTrigger_Shadcn_ value="policies" className="px-2">
Policies applied
</TabsTrigger_Shadcn_>
- <TabsTrigger_Shadcn_ value="data" className="px-2">
+ <TabsTrigger_Shadcn_ value="data" className="px-2" disabled={operation !== 'SELECT'}>
Data preview
</TabsTrigger_Shadcn_>
</TabsList_Shadcn_>
@@ -84,7 +92,13 @@ export const RLSTesterResults = ({
{!isServiceRole &&
(!!tableWithRLSEnabledButNoPolicies ? (
<Admonition showIcon={false} type="default" className="rounded-sm mt-2">
- <p className="mb-0.5!">This user has no access to any rows from this query</p>
+ <p className="mb-0.5! text-foreground">
+ This user{' '}
+ {operation === 'SELECT'
+ ? 'has no access to any rows'
+ : `is unable to ${operation?.toLowerCase()} any rows`}{' '}
+ from this query
+ </p>
<p className="text-foreground-light">
The table{' '}
<code className="text-code-inline">
@@ -98,7 +112,9 @@ export const RLSTesterResults = ({
</Admonition>
) : tableWithRLSEnabledWithPolicyFalse ? (
<Admonition showIcon={false} type="default" className="rounded-sm mt-2">
- <p className="mb-0.5!">This user has no access to any rows from this query</p>
+ <p className="mb-0.5! text-foreground">
+ This user has no access to any rows from this query
+ </p>
<p className="text-foreground-light">
The table{' '}
<code className="text-code-inline">
@@ -111,11 +127,29 @@ export const RLSTesterResults = ({
role.
</p>
</Admonition>
+ ) : rlsBlockInsert &&
+ parseQueryResults.user &&
+ tableWithRLSEnabledWithPoliciesDontApply ? (
+ <Admonition showIcon={false} type="default" className="rounded-sm mt-2">
+ <p className="mb-0.5! text-foreground">
+ This user is unable to {operation?.toLowerCase()} any rows from this query
+ </p>
+ <p className="text-foreground-light">
+ The table{' '}
+ <code className="text-code-inline">
+ {tableWithRLSEnabledWithPoliciesDontApply.schema}.
+ {tableWithRLSEnabledWithPoliciesDontApply.table}
+ </code>{' '}
+ has a policy for the{' '}
+ <code className="text-code-inline break-keep!">{parseQueryResults.role}</code>{' '}
+ role, but its condition wasn't satisfied for this specific request.
+ </p>
+ </Admonition>
) : null)}
{isServiceRole && (
<Admonition showIcon={false} type="default" className="rounded-sm mt-2">
- <p className="mb-0.5!">
+ <p className="mb-0.5! text-foreground">
The <code className="text-code-inline">postgres</code> role has access to all rows
for this query
</p>
@@ -136,8 +170,10 @@ export const RLSTesterResults = ({
<RLSTableCard
key={`${schema}.${table}`}
table={{ schema, name: table, isRLSEnabled }}
- role={parseQueryResults.role}
+ role={role}
+ operation={operation}
policies={tablePolicies}
+ hasError={!!executeSqlError}
handleSelectEditPolicy={handleSelectEditPolicy}
/>
)
diff --git a/apps/studio/components/interfaces/Database/RLSTester/RLSTesterResults.utils.ts b/apps/studio/components/interfaces/Database/RLSTester/RLSTesterResults.utils.ts
index 05977e58eb5..5f0e43025c6 100644
--- a/apps/studio/components/interfaces/Database/RLSTester/RLSTesterResults.utils.ts
+++ b/apps/studio/components/interfaces/Database/RLSTester/RLSTesterResults.utils.ts
@@ -8,6 +8,10 @@ export function deriveRLSTestState(parseQueryResults: ParseQueryResults | undefi
const tableWithRLSEnabledWithPolicyFalse = parseQueryResults?.tables.find(
(x) => x.isRLSEnabled && x.tablePolicies.some((y) => y.definition === 'false')
)
+ const tableWithRLSEnabledWithPoliciesDontApply = parseQueryResults?.tables.find(
+ (x) => x.isRLSEnabled && x.tablePolicies.length !== 0
+ )
+
const noAccessToData =
!isServiceRole && (!!tableWithRLSEnabledButNoPolicies || !!tableWithRLSEnabledWithPolicyFalse)
@@ -15,6 +19,7 @@ export function deriveRLSTestState(parseQueryResults: ParseQueryResults | undefi
isServiceRole,
tableWithRLSEnabledButNoPolicies,
tableWithRLSEnabledWithPolicyFalse,
+ tableWithRLSEnabledWithPoliciesDontApply,
noAccessToData,
}
}
diff --git a/apps/studio/components/interfaces/Database/RLSTester/RLSTesterSheet.tsx b/apps/studio/components/interfaces/Database/RLSTester/RLSTesterSheet.tsx
index afa2bd82912..d5bcc5ed0b7 100644
--- a/apps/studio/components/interfaces/Database/RLSTester/RLSTesterSheet.tsx
+++ b/apps/studio/components/interfaces/Database/RLSTester/RLSTesterSheet.tsx
@@ -29,6 +29,8 @@ import {
SheetTrigger,
} from 'ui'
import { Admonition } from 'ui-patterns/admonition'
+import { ConfirmationModal } from 'ui-patterns/Dialogs/ConfirmationModal'
+import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'
import { InferredSQLViewer } from './InferredSQLViewer'
import { type ParseQueryResults } from './RLSTester.types'
@@ -38,14 +40,14 @@ import { RoleSelector } from './RoleSelector'
import { SandboxManagement } from './SandboxManagement'
import { UserSelector } from './UserSelector'
import { UserSqlEditor } from './UserSqlEditor'
-import { useTestQueryRLS } from './useTestQueryRLS'
+import { useTestQueryRLS, type TestQueryBlockedReason } from './useTestQueryRLS'
import type { Policy } from '@/components/interfaces/Database/Policies/PolicyTableRow/PolicyTableRow.utils'
import { SIDEBAR_KEYS } from '@/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
import { AiAssistantDropdown } from '@/components/ui/AiAssistantDropdown'
import { FeaturePreviewBadge } from '@/components/ui/FeaturePreviewBadge'
import { useTrack } from '@/lib/telemetry/track'
import { useAiAssistantStateSnapshot } from '@/state/ai-assistant-state'
-import { PostgresSandboxProvider } from '@/state/postgres-sandbox/sandbox'
+import { PostgresSandboxProvider, usePostgresSandbox } from '@/state/postgres-sandbox/sandbox'
import { useRoleImpersonationStateSnapshot } from '@/state/role-impersonation-state'
import { useSidebarManagerSnapshot } from '@/state/sidebar-manager-state'
@@ -66,10 +68,14 @@ const RLSTesterSheetContents = ({ handleSelectEditPolicy }: RLSTesterSheetProps)
const aiSnap = useAiAssistantStateSnapshot()
const { openSidebar } = useSidebarManagerSnapshot()
const { setRole } = useRoleImpersonationStateSnapshot()
+ const { startSandbox, status, isSyncing } = usePostgresSandbox()
+
const sandboxEnabled = useFlag('rlsTesterSandbox')
+ const sandboxIsStarting = status === 'loading'
const [open, setOpen] = useState(false)
const [selectedOption, setSelectedOption] = useState<'anon' | 'authenticated'>('anon')
+ const [blockedReason, setBlockedReason] = useState<TestQueryBlockedReason>()
const [format, setFormat] = useState<'sql' | 'lib'>('sql')
const [inferredSQL, setInferredSQL] = useState<UntrustedSqlFragment>()
@@ -88,6 +94,9 @@ const RLSTesterSheetContents = ({ handleSelectEditPolicy }: RLSTesterSheetProps)
parseQueryError,
parseClientCodeError,
} = useTestQueryRLS()
+ const isErrorDueToRLS =
+ executeSqlError?.message.includes('violates row-level security policy') ?? false
+ const mutationOperation = blockedReason?.type === 'mutation' ? blockedReason.operation : undefined
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
@@ -98,28 +107,33 @@ const RLSTesterSheetContents = ({ handleSelectEditPolicy }: RLSTesterSheetProps)
if (debounceRef.current !== null) clearTimeout(debounceRef.current)
if (!sql) return
- debounceRef.current = setTimeout(() => {
- inferSQLFromLib(sql, setInferredSQL)
- }, 1500)
+ debounceRef.current = setTimeout(() => inferSQLFromLib(sql, setInferredSQL), 1500)
}
const executionCallbacks = {
option: selectedOption,
+ acknowledgeMutation: blockedReason?.type === 'mutation',
onExecuteSQL: ({ result, isAutoLimit }: { result: Object[] | null; isAutoLimit: boolean }) => {
setResults(result)
setAutoLimit(isAutoLimit)
},
onParseQuery: setParseQueryResults,
+ onValidationBlocked: setBlockedReason,
}
const onRunQuery = async () => {
+ setBlockedReason(undefined)
+
if (format === 'lib') {
if (!inferredSQL) return
- await testQuery({ value: acceptUntrustedSql(inferredSQL), ...executionCallbacks })
- track('rls_tester_run_query_clicked', { type: 'inferred' })
+ const blocked = await testQuery({
+ value: acceptUntrustedSql(inferredSQL),
+ ...executionCallbacks,
+ })
+ if (!blocked) track('rls_tester_run_query_clicked', { type: 'inferred' })
} else {
- await testQuery({ value, ...executionCallbacks })
- track('rls_tester_run_query_clicked', { type: 'raw' })
+ const blocked = await testQuery({ value, ...executionCallbacks })
+ if (!blocked) track('rls_tester_run_query_clicked', { type: 'raw' })
}
}
@@ -143,121 +157,138 @@ const RLSTesterSheetContents = ({ handleSelectEditPolicy }: RLSTesterSheetProps)
}
useEffect(() => {
- if (open) {
- setRole({ type: 'postgrest', role: 'anon' })
- } else {
+ setRole({ type: 'postgrest', role: 'anon' })
+ return () => {
// Flip back to service role
setRole(undefined)
}
- }, [open, setRole])
+ // [Joshen] Intentional - to only reset back to service role when navigating away
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [])
return (
- <Sheet open={open} onOpenChange={setOpen}>
- <SheetTrigger asChild>
- <Button variant="default" icon={<Code />}>
- Test
- </Button>
- </SheetTrigger>
-
- <SheetContent className="w-[600px]! flex flex-col gap-y-0">
- <SheetHeader>
- <SheetTitle className="flex items-center gap-x-4">
- <span>What data can my users see?</span>
- <FeaturePreviewBadge featureKey={LOCAL_STORAGE_KEYS.UI_PREVIEW_RLS_TESTER} />
- </SheetTitle>
- <SheetDescription>
- See what data a user is allowed to read based on your RLS policies
- </SheetDescription>
- </SheetHeader>
-
- <div className="grow overflow-y-auto flex flex-col">
- {sandboxEnabled && <SandboxManagement />}
-
- <SheetSection className="px-0 py-0 border-t">
- <div className="flex flex-col p-5 pt-4 gap-y-4">
- <RoleSelector onSelectRole={setSelectedOption} />
- {selectedOption === 'authenticated' && <UserSelector />}
- </div>
+ <>
+ <Sheet open={open} onOpenChange={setOpen}>
+ <SheetTrigger asChild>
+ <Button variant="default" icon={<Code />}>
+ Test
+ </Button>
+ </SheetTrigger>
- <DialogSectionSeparator />
+ <SheetContent className="w-[600px]! flex flex-col gap-y-0">
+ <SheetHeader>
+ <SheetTitle className="flex items-center gap-x-4">
+ <span>What data can my users access?</span>
+ <FeaturePreviewBadge featureKey={LOCAL_STORAGE_KEYS.UI_PREVIEW_RLS_TESTER} />
+ </SheetTitle>
+ <SheetDescription>
+ See what data a user is allowed to read or modify based on your RLS policies
+ </SheetDescription>
+ </SheetHeader>
- <div className="flex items-center justify-between px-5 py-2">
- <p className="text-sm">Query</p>
- <div className="flex items-center gap-x-2">
- <Select
- value={format}
- onValueChange={(x) => {
- const newFormat = x as 'sql' | 'lib'
- setFormat(newFormat)
- if (newFormat !== 'lib') {
- setInferredSQL(undefined)
- if (debounceRef.current !== null) clearTimeout(debounceRef.current)
- }
- }}
- >
- <SelectTrigger size="tiny">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectGroup>
- <SelectLabel>Query format</SelectLabel>
- <SelectItem value="sql">SQL</SelectItem>
- <SelectItem value="lib">Client library</SelectItem>
- </SelectGroup>
- </SelectContent>
- </Select>
+ <div className="grow overflow-y-auto flex flex-col">
+ {sandboxEnabled && <SandboxManagement />}
+
+ <SheetSection className="px-0 py-0 border-t">
+ <div className="flex flex-col p-5 pt-4 gap-y-4">
+ <RoleSelector onSelectRole={setSelectedOption} />
+ {selectedOption === 'authenticated' && <UserSelector />}
</div>
- </div>
- <div className="h-40 relative">
- <UserSqlEditor
- id="rls-tester"
- value={value}
- placeholder={
- format === 'sql'
- ? safeSql`select * from table;`
- : safeSql`SQL will be inferred from client library code`
- }
- onChange={handleValueChange}
- actions={{
- runQuery: {
- enabled: open,
- callback: () => {
- if (!isInferring && !isLoading) onRunQuery()
+ <DialogSectionSeparator />
+
+ <div className="flex items-center justify-between px-5 py-2">
+ <p className="text-sm">Query</p>
+ <div className="flex items-center gap-x-2">
+ <Select
+ value={format}
+ onValueChange={(x) => {
+ const newFormat = x as 'sql' | 'lib'
+ setFormat(newFormat)
+ if (newFormat !== 'lib') {
+ setInferredSQL(undefined)
+ if (debounceRef.current !== null) clearTimeout(debounceRef.current)
+ }
+ }}
+ >
+ <SelectTrigger size="tiny">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ <SelectLabel>Query format</SelectLabel>
+ <SelectItem value="sql">SQL</SelectItem>
+ <SelectItem value="lib">Client library</SelectItem>
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+
+ <div className="h-40 relative">
+ <UserSqlEditor
+ id="rls-tester"
+ value={value}
+ placeholder={
+ format === 'sql'
+ ? safeSql`select * from table;`
+ : safeSql`SQL will be inferred from client library code`
+ }
+ onChange={handleValueChange}
+ actions={{
+ runQuery: {
+ enabled: open,
+ callback: () => {
+ if (!isInferring && !isLoading) onRunQuery()
+ },
},
- },
- }}
- />
- </div>
- </SheetSection>
+ }}
+ />
+ </div>
+ </SheetSection>
- {format === 'lib' && (
- <div>
- <DialogSectionSeparator />
- <InferredSQLViewer sql={inferredSQL} isLoading={isInferring} />
- </div>
- )}
+ {format === 'lib' && (
+ <div>
+ <DialogSectionSeparator />
+ <InferredSQLViewer sql={inferredSQL} isLoading={isInferring} />
+ </div>
+ )}
- <DialogSectionSeparator />
+ <DialogSectionSeparator />
- {parseQueryError ? (
- <div className="p-4">
- <Admonition
- type="warning"
- title="Error parsing query"
- description={parseQueryError.message}
- />
- </div>
- ) : parseClientCodeError ? (
- <div className="p-4">
- <Admonition
- type="warning"
- title="Error parsing client code"
- description={parseClientCodeError.message}
- />
- </div>
- ) : (
- executeSqlError && (
+ {blockedReason?.type === 'multiple-statements' ? (
+ <div className="p-4">
+ <Admonition
+ type="warning"
+ title="Only a single SQL statement is supported"
+ description="Remove any additional statements and run the query again."
+ />
+ </div>
+ ) : blockedReason?.type === 'unsupported-operation' ? (
+ <div className="p-4">
+ <Admonition
+ type="warning"
+ title={`${blockedReason.operation} queries are not supported by the RLS Tester yet`}
+ description="Support for testing UPDATE and DELETE statements will be available soon."
+ />
+ </div>
+ ) : parseQueryError ? (
+ <div className="p-4">
+ <Admonition
+ type="warning"
+ title="Error parsing query"
+ description={parseQueryError.message}
+ />
+ </div>
+ ) : parseClientCodeError ? (
+ <div className="p-4">
+ <Admonition
+ type="warning"
+ title="Error parsing client code"
+ description={parseClientCodeError.message}
+ />
+ </div>
+ ) : executeSqlError && !isErrorDueToRLS ? (
<div className="p-4">
<Admonition
type="warning"
@@ -274,46 +305,83 @@ const RLSTesterSheetContents = ({ handleSelectEditPolicy }: RLSTesterSheetProps)
]}
/>
</div>
- )
- )}
-
- {results === null ? (
- !parseQueryError && !parseClientCodeError && !executeSqlError && <RLSTesterEmptyState />
- ) : !!parseQueryResults ? (
- <RLSTesterResults
- results={results}
- parseQueryResults={parseQueryResults}
- autoLimit={autoLimit}
- handleSelectEditPolicy={handleSelectEditPolicy}
- />
- ) : null}
- </div>
-
- <SheetFooter className="sm:justify-between">
- <Button asChild variant="default" icon={<ExternalLink />}>
- <a
- target="_blank"
- rel="noopener noreferrer"
- href="https://github.com/orgs/supabase/discussions/45233"
- >
- Give feedback
- </a>
- </Button>
- <div className="flex items-center gap-x-2">
- <Button variant="default" disabled={isLoading} onClick={() => setOpen(false)}>
- Cancel
+ ) : isLoading ? (
+ <div className="p-4">
+ <GenericSkeletonLoader />
+ </div>
+ ) : results === null && !isErrorDueToRLS ? (
+ <RLSTesterEmptyState />
+ ) : !!parseQueryResults ? (
+ <RLSTesterResults
+ results={results ?? []}
+ parseQueryResults={parseQueryResults}
+ autoLimit={autoLimit}
+ executeSqlError={executeSqlError}
+ handleSelectEditPolicy={handleSelectEditPolicy}
+ />
+ ) : null}
+ </div>
+
+ <SheetFooter className="sm:justify-between">
+ <Button asChild variant="default" icon={<ExternalLink />}>
+ <a
+ target="_blank"
+ rel="noopener noreferrer"
+ href="https://github.com/orgs/supabase/discussions/45233"
+ >
+ Give feedback
+ </a>
</Button>
+ <div className="flex items-center gap-x-2">
+ <Button variant="default" disabled={isLoading} onClick={() => setOpen(false)}>
+ Cancel
+ </Button>
+ <Button
+ variant="primary"
+ loading={isInferring || isLoading}
+ disabled={(format === 'lib' && !inferredSQL) || sandboxIsStarting || isSyncing}
+ onClick={onRunQuery}
+ >
+ Run query
+ </Button>
+ </div>
+ </SheetFooter>
+ </SheetContent>
+ </Sheet>
+
+ <ConfirmationModal
+ visible={!!mutationOperation}
+ variant="warning"
+ size="medium"
+ loading={isLoading}
+ title="Confirm to run this query"
+ confirmLabel="Run query"
+ onConfirm={onRunQuery}
+ onCancel={() => setBlockedReason(undefined)}
+ alert={{
+ title: `This ${mutationOperation} query will run against your actual database`,
+ description: 'Your database may be directly modified as a result. Are you sure?',
+ }}
+ >
+ {sandboxEnabled && (
+ <>
+ <p className="text-sm">
+ We highly recommend using the sandbox to set up an ephemeral database environment for
+ testing insert, update, or delete queries.
+ </p>
<Button
- variant="primary"
- loading={isInferring || isLoading}
- disabled={format === 'lib' && !inferredSQL}
- onClick={onRunQuery}
+ variant="default"
+ className="mt-2"
+ onClick={() => {
+ startSandbox()
+ setBlockedReason(undefined)
+ }}
>
- Run query
+ Set up sandbox
</Button>
- </div>
- </SheetFooter>
- </SheetContent>
- </Sheet>
+ </>
+ )}
+ </ConfirmationModal>
+ </>
)
}
diff --git a/apps/studio/components/interfaces/Database/RLSTester/RoleSelector.tsx b/apps/studio/components/interfaces/Database/RLSTester/RoleSelector.tsx
index b25aab9d137..0d23453b36b 100644
--- a/apps/studio/components/interfaces/Database/RLSTester/RoleSelector.tsx
+++ b/apps/studio/components/interfaces/Database/RLSTester/RoleSelector.tsx
@@ -11,7 +11,7 @@ export const RoleSelector = ({ onSelectRole }: RoleSelectorProps) => {
const { role, setRole } = useRoleImpersonationStateSnapshot()
return (
- <FormItemLayout isReactForm={false} label="Test as">
+ <FormItemLayout isReactForm={false} label="Test query as" layout="horizontal">
<RadioGroupStacked defaultValue={role?.role ?? 'anon'}>
<RadioGroupStackedItem
value="anon"
@@ -27,7 +27,7 @@ export const RoleSelector = ({ onSelectRole }: RoleSelectorProps) => {
value="authenticated"
id="authenticated"
label="Authenticated user"
- description="A specific logged in user"
+ description="A logged in user"
onClick={() => {
onSelectRole('authenticated')
}}
diff --git a/apps/studio/components/interfaces/Database/RLSTester/SandboxManagement.tsx b/apps/studio/components/interfaces/Database/RLSTester/SandboxManagement.tsx
index b99b907e02f..1200d4d361e 100644
--- a/apps/studio/components/interfaces/Database/RLSTester/SandboxManagement.tsx
+++ b/apps/studio/components/interfaces/Database/RLSTester/SandboxManagement.tsx
@@ -14,15 +14,15 @@ export const SandboxManagement = () => {
<Admonition
type="default"
layout="horizontal"
- className="min-h-min border-none [&>div>div>div>div>p]:!mb-0"
+ className="min-h-min border-none [&>div>div>div>div>p]:!mb-0 [&>div>div]:gap-x-2"
actions={[
- <Button key="set-up" variant="default" onClick={() => startSandbox()}>
+ <Button key="sandbox" variant="default" onClick={() => startSandbox()}>
Set up sandbox
</Button>,
]}
>
<div className="flex items-center gap-x-2">
- <p className="text-foreground !m-0">Set up sandbox for testing</p>
+ <p className="text-foreground !m-0">Run queries in a sandbox</p>
<Badge variant="success">Recommended</Badge>
</div>
<p className="text-foreground-light !m-0">
diff --git a/apps/studio/components/interfaces/Database/RLSTester/UserSelector.tsx b/apps/studio/components/interfaces/Database/RLSTester/UserSelector.tsx
index 81d2a4dadad..c949c2f3fe0 100644
--- a/apps/studio/components/interfaces/Database/RLSTester/UserSelector.tsx
+++ b/apps/studio/components/interfaces/Database/RLSTester/UserSelector.tsx
@@ -12,6 +12,7 @@ import {
CommandInput,
CommandItem,
CommandList,
+ copyToClipboard,
Popover,
PopoverContent,
PopoverTrigger,
@@ -67,7 +68,27 @@ export const UserSelector = () => {
}
return (
- <FormItemLayout isReactForm={false} label="Select which user to test as">
+ <FormItemLayout
+ isReactForm={false}
+ layout="horizontal"
+ label="Select which user to test as"
+ description={
+ impersonatingUser ? (
+ <p>
+ ID:{' '}
+ <code
+ className="text-code-inline cursor-pointer"
+ onClick={() => {
+ copyToClipboard(impersonatingUser?.id ?? '')
+ toast('Copied ID to clipboard')
+ }}
+ >
+ {impersonatingUser.id}
+ </code>
+ </p>
+ ) : undefined
+ }
+ >
<Popover open={open} onOpenChange={setOpen} modal>
<PopoverTrigger asChild>
<Button
diff --git a/apps/studio/components/interfaces/Database/RLSTester/__tests__/RLSTesterResults.test.tsx b/apps/studio/components/interfaces/Database/RLSTester/__tests__/RLSTesterResults.test.tsx
index ec30e1e41a6..8ee7cda9bc8 100644
--- a/apps/studio/components/interfaces/Database/RLSTester/__tests__/RLSTesterResults.test.tsx
+++ b/apps/studio/components/interfaces/Database/RLSTester/__tests__/RLSTesterResults.test.tsx
@@ -37,6 +37,7 @@ const makeTable = (
const defaultProps = {
results: [],
autoLimit: false,
+ executeSqlError: undefined,
handleSelectEditPolicy: vi.fn(),
}
diff --git a/apps/studio/components/interfaces/Database/RLSTester/__tests__/useTestQueryRLS.utils.test.ts b/apps/studio/components/interfaces/Database/RLSTester/__tests__/useTestQueryRLS.utils.test.ts
index 0803c5191c8..a5ccadf1c6d 100644
--- a/apps/studio/components/interfaces/Database/RLSTester/__tests__/useTestQueryRLS.utils.test.ts
+++ b/apps/studio/components/interfaces/Database/RLSTester/__tests__/useTestQueryRLS.utils.test.ts
@@ -1,7 +1,10 @@
import { describe, expect, it } from 'vitest'
import type { Policy } from '@/components/interfaces/Database/Policies/PolicyTableRow/PolicyTableRow.utils'
-import { filterTablePolicies } from '@/components/interfaces/Database/RLSTester/useTestQueryRLS.utils'
+import {
+ filterTablePolicies,
+ getTestQueryBlockedReason,
+} from '@/components/interfaces/Database/RLSTester/useTestQueryRLS.utils'
const makePolicy = (overrides: Partial<Policy>): Policy =>
({
@@ -145,3 +148,118 @@ describe('filterTablePolicies', () => {
})
})
})
+
+describe('getTestQueryBlockedReason', () => {
+ const blockedBase = {
+ statementCount: 1,
+ operation: 'SELECT' as const,
+ hasSandbox: false,
+ acknowledgeMutation: false,
+ }
+
+ describe('multiple statements', () => {
+ it('blocks when statementCount is greater than 1', () => {
+ expect(getTestQueryBlockedReason({ ...blockedBase, statementCount: 2 })).toStrictEqual({
+ type: 'multiple-statements',
+ })
+ })
+
+ it('takes priority over an unsupported operation', () => {
+ expect(
+ getTestQueryBlockedReason({ ...blockedBase, statementCount: 2, operation: 'DELETE' })
+ ).toStrictEqual({ type: 'multiple-statements' })
+ })
+
+ it('takes priority over an unacknowledged mutation', () => {
+ expect(
+ getTestQueryBlockedReason({ ...blockedBase, statementCount: 2, operation: 'INSERT' })
+ ).toStrictEqual({ type: 'multiple-statements' })
+ })
+
+ it('does not block when statementCount is exactly 1', () => {
+ expect(getTestQueryBlockedReason({ ...blockedBase, statementCount: 1 })).toBeUndefined()
+ })
+
+ it('does not block when statementCount is 0', () => {
+ expect(getTestQueryBlockedReason({ ...blockedBase, statementCount: 0 })).toBeUndefined()
+ })
+ })
+
+ describe('unsupported operations', () => {
+ it('blocks UPDATE', () => {
+ expect(getTestQueryBlockedReason({ ...blockedBase, operation: 'UPDATE' })).toStrictEqual({
+ type: 'unsupported-operation',
+ operation: 'UPDATE',
+ })
+ })
+
+ it('blocks DELETE', () => {
+ expect(getTestQueryBlockedReason({ ...blockedBase, operation: 'DELETE' })).toStrictEqual({
+ type: 'unsupported-operation',
+ operation: 'DELETE',
+ })
+ })
+
+ it('blocks UPDATE even with a sandbox available', () => {
+ expect(
+ getTestQueryBlockedReason({ ...blockedBase, operation: 'UPDATE', hasSandbox: true })
+ ).toStrictEqual({ type: 'unsupported-operation', operation: 'UPDATE' })
+ })
+
+ it('blocks DELETE even when already acknowledged', () => {
+ expect(
+ getTestQueryBlockedReason({
+ ...blockedBase,
+ operation: 'DELETE',
+ acknowledgeMutation: true,
+ })
+ ).toStrictEqual({ type: 'unsupported-operation', operation: 'DELETE' })
+ })
+ })
+
+ describe('INSERT mutation warning', () => {
+ it('blocks an unacknowledged INSERT with no sandbox', () => {
+ expect(getTestQueryBlockedReason({ ...blockedBase, operation: 'INSERT' })).toStrictEqual({
+ type: 'mutation',
+ operation: 'INSERT',
+ })
+ })
+
+ it('does not block an INSERT when a sandbox is available', () => {
+ expect(
+ getTestQueryBlockedReason({ ...blockedBase, operation: 'INSERT', hasSandbox: true })
+ ).toBeUndefined()
+ })
+
+ it('does not block an INSERT once acknowledged', () => {
+ expect(
+ getTestQueryBlockedReason({
+ ...blockedBase,
+ operation: 'INSERT',
+ acknowledgeMutation: true,
+ })
+ ).toBeUndefined()
+ })
+
+ it('does not require acknowledgement when a sandbox is available', () => {
+ expect(
+ getTestQueryBlockedReason({
+ ...blockedBase,
+ operation: 'INSERT',
+ hasSandbox: true,
+ acknowledgeMutation: false,
+ })
+ ).toBeUndefined()
+ })
+ })
+
+ describe('unblocked operations', () => {
+ it('does not block SELECT', () => {
+ expect(getTestQueryBlockedReason({ ...blockedBase, operation: 'SELECT' })).toBeUndefined()
+ })
+
+ it('does not block when operation is undefined', () => {
+ expect(getTestQueryBlockedReason({ ...blockedBase, operation: undefined })).toBeUndefined()
+ })
+ })
+})
diff --git a/apps/studio/components/interfaces/Database/RLSTester/useTestQueryRLS.ts b/apps/studio/components/interfaces/Database/RLSTester/useTestQueryRLS.ts
index 91ede81b5a0..c94328db294 100644
--- a/apps/studio/components/interfaces/Database/RLSTester/useTestQueryRLS.ts
+++ b/apps/studio/components/interfaces/Database/RLSTester/useTestQueryRLS.ts
@@ -1,14 +1,21 @@
-import { type SafeSqlFragment, type UntrustedSqlFragment } from '@supabase/pg-meta'
+import { safeSql, type SafeSqlFragment, type UntrustedSqlFragment } from '@supabase/pg-meta'
import { useState } from 'react'
import { toast } from 'sonner'
import { checkIfAppendLimitRequired, suffixWithLimit } from '../../SQLEditor/SQLEditor.utils'
import { type ParseQueryResults } from './RLSTester.types'
-import { filterTablePolicies } from './useTestQueryRLS.utils'
+import {
+ filterTablePolicies,
+ getTestQueryBlockedReason,
+ type TestQueryBlockedReason,
+} from './useTestQueryRLS.utils'
import { useParseClientCodeMutation } from '@/data/ai/parse-client-code-mutation'
import { useDatabasePoliciesQuery } from '@/data/database-policies/database-policies-query'
import { useCheckTableRLSStatusMutation } from '@/data/database/table-check-rls-mutation'
-import { useParseSQLQueryMutation } from '@/data/misc/parse-query-mutation'
+import {
+ useParseSQLQueryMutation,
+ type ParseSQLQueryOperations,
+} from '@/data/misc/parse-query-mutation'
import { useExecuteSqlMutation } from '@/data/sql/execute-sql-mutation'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { wrapWithRoleImpersonation } from '@/lib/role-impersonation'
@@ -19,9 +26,31 @@ import {
useImpersonatedUser,
useRoleImpersonationStateSnapshot,
} from '@/state/role-impersonation-state'
+import { type ResponseError } from '@/types'
const limit = 100
+export type { TestQueryBlockedReason }
+
+// [Joshen] Pre-requisite work for identifying UPDATE / DELETE failures due to RLS - not yet wired
+// in since those operations are currently blocked (see TestQueryBlockedReason's 'unsupported-
+// operation'). Exported so it isn't flagged as unused until the follow-up PR wires it back in.
+export const wrapReturnRowsAffected = (sql: SafeSqlFragment) => {
+ return safeSql`
+ DO $$
+DECLARE
+ row_count integer;
+BEGIN
+ ${sql}${(sql.endsWith(';') ? '' : ';') as SafeSqlFragment}
+ GET DIAGNOSTICS row_count = ROW_COUNT;
+ -- store it somewhere you can read back
+ PERFORM set_config('rls_tester.rows_affected', row_count::text, true);
+END $$;
+
+SELECT current_setting('rls_tester.rows_affected', true);
+`
+}
+
/**
* [Joshen] Testing a SQL query for its RLS access involves 3 async steps
* 0. (Optional) Inferring client library code to SQL query via the AI Assistant
@@ -83,27 +112,41 @@ export const useTestQueryRLS = () => {
onError: () => {},
})
+ /**
+ * Returns true if the query was blocked (multiple statements, or an unacknowledged mutation)
+ * and did not run, false if it ran (successfully or not)
+ */
const testQuery = async ({
value,
option,
+ acknowledgeMutation = false,
onExecuteSQL,
onParseQuery,
+ onValidationBlocked,
}: {
value: SafeSqlFragment
option: 'anon' | 'authenticated'
+ acknowledgeMutation?: boolean
onExecuteSQL: ({
result,
+ operation,
isAutoLimit,
}: {
result: Object[] | null
+ operation: ParseSQLQueryOperations
isAutoLimit: boolean
}) => void
onParseQuery: (results?: ParseQueryResults) => void
- }) => {
- if (!project) return console.error('Project is required')
+ onValidationBlocked: (reason: TestQueryBlockedReason) => void
+ }): Promise<boolean> => {
+ if (!project) {
+ console.error('Project is required')
+ return true
+ }
if (option === 'authenticated' && !user) {
- return toast('Select which user to test as before running the query')
+ toast('Select which user to test as before running the query')
+ return true
}
try {
@@ -114,8 +157,15 @@ export const useTestQueryRLS = () => {
const formattedSql = suffixWithLimit(value, limit)
const data = await parseQuery({ sql: formattedSql })
- if (data.operation !== 'SELECT') {
- return toast('Only SELECT statements are supported with the RLS Tester at the moment')
+ const blockedReason = getTestQueryBlockedReason({
+ statementCount: data.statementCount,
+ operation: data.operation,
+ hasSandbox: !!sandbox,
+ acknowledgeMutation,
+ })
+ if (blockedReason) {
+ onValidationBlocked(blockedReason)
+ return true
}
const formattedTables = data.tables.map((x) => {
@@ -151,39 +201,50 @@ export const useTestQueryRLS = () => {
})
const autoLimit = appendAutoLimit ? limit : undefined
+ // UPDATE/DELETE are blocked above, so wrapReturnRowsAffected isn't wired in here yet -
+ // it's kept for the follow-up PR that adds proper UPDATE/DELETE support
const sql = wrapWithRoleImpersonation(formattedSql, impersonatedRoleState)
- const { result } = sandbox
- ? await sandbox.run({ sql }).catch((e) => {
- setSandboxError(e instanceof Error ? e : new Error(String(e)))
- throw e
- })
- : await executeSql({
- sql,
- autoLimit,
- projectRef: project.ref,
- connectionString: project.connectionString,
- isRoleImpersonationEnabled: isRoleImpersonationEnabled(impersonatedRoleState.role),
- isStatementTimeoutDisabled: true,
- handleError: (e) => {
+ try {
+ const { result } = sandbox
+ ? await sandbox.run({ sql }).catch((e) => {
+ setSandboxError(e instanceof Error ? e : new Error(String(e)))
throw e
- },
- queryKey: ['rls-tester'],
- })
- onExecuteSQL({ result, isAutoLimit: !!autoLimit })
+ })
+ : await executeSql({
+ sql,
+ autoLimit,
+ projectRef: project.ref,
+ connectionString: project.connectionString,
+ isRoleImpersonationEnabled: isRoleImpersonationEnabled(impersonatedRoleState.role),
+ isStatementTimeoutDisabled: true,
+ handleError: (e) => {
+ throw e
+ },
+ queryKey: ['rls-tester'],
+ })
- onParseQuery({
- tables,
- operation: data.operation,
- role: role?.role,
- user,
- })
+ onExecuteSQL({ result, operation: data.operation, isAutoLimit: !!autoLimit })
+ onParseQuery({ tables, operation: data.operation, role: role?.role, user })
+ } catch (error) {
+ const isRLSInsertError = Boolean(
+ (error as ResponseError)?.message?.includes('new row violates row-level security policy')
+ )
+ onExecuteSQL({ result: null, operation: data.operation, isAutoLimit: false })
+ if (isRLSInsertError) {
+ onParseQuery({ tables, operation: data.operation, role: role?.role, user })
+ } else {
+ onParseQuery(undefined)
+ }
+ }
} catch (error) {
- onExecuteSQL({ result: null, isAutoLimit: false })
+ onExecuteSQL({ result: null, operation: undefined, isAutoLimit: false })
onParseQuery(undefined)
} finally {
setIsLoading(false)
}
+
+ return false
}
return {
diff --git a/apps/studio/components/interfaces/Database/RLSTester/useTestQueryRLS.utils.ts b/apps/studio/components/interfaces/Database/RLSTester/useTestQueryRLS.utils.ts
index cf4140e16ab..b0e698dc43b 100644
--- a/apps/studio/components/interfaces/Database/RLSTester/useTestQueryRLS.utils.ts
+++ b/apps/studio/components/interfaces/Database/RLSTester/useTestQueryRLS.utils.ts
@@ -1,6 +1,38 @@
import type { Policy } from '@/components/interfaces/Database/Policies/PolicyTableRow/PolicyTableRow.utils'
import type { ParseSQLQueryResponse } from '@/data/misc/parse-query-mutation'
+export type TestQueryBlockedReason =
+ | { type: 'multiple-statements' }
+ | { type: 'unsupported-operation'; operation: 'UPDATE' | 'DELETE' }
+ | { type: 'mutation'; operation: 'INSERT' }
+
+/**
+ * Decides whether a query should be blocked from running, and why. Checked in this order:
+ * multiple statements first (regardless of operation), then unsupported operations (UPDATE/
+ * DELETE aren't testable yet - RLS blocks them silently instead of raising an error), then
+ * INSERT mutations against the real database that haven't been acknowledged yet.
+ */
+export function getTestQueryBlockedReason({
+ statementCount,
+ operation,
+ hasSandbox,
+ acknowledgeMutation,
+}: {
+ statementCount: number
+ operation: ParseSQLQueryResponse['operation']
+ hasSandbox: boolean
+ acknowledgeMutation: boolean
+}): TestQueryBlockedReason | undefined {
+ if (statementCount > 1) return { type: 'multiple-statements' }
+ if (operation === 'UPDATE' || operation === 'DELETE') {
+ return { type: 'unsupported-operation', operation }
+ }
+ if (operation === 'INSERT' && !hasSandbox && !acknowledgeMutation) {
+ return { type: 'mutation', operation }
+ }
+ return undefined
+}
+
export function filterTablePolicies({
policies,
schema,
diff --git a/apps/studio/data/misc/parse-query-mutation.ts b/apps/studio/data/misc/parse-query-mutation.ts
index 0a36df7bca5..a30e4eb930d 100644
--- a/apps/studio/data/misc/parse-query-mutation.ts
+++ b/apps/studio/data/misc/parse-query-mutation.ts
@@ -6,9 +6,12 @@ import { BASE_PATH } from '@/lib/constants'
import { ResponseError, UseCustomMutationOptions } from '@/types'
type ParseSQLQueryVariables = { sql: string }
+export type ParseSQLQueryOperations = 'SELECT' | 'INSERT' | 'UPDATE' | 'DELETE' | undefined
export type ParseSQLQueryResponse = {
tables: string[]
- operation: 'SELECT' | 'INSERT' | 'UPDATE' | 'DELETE' | undefined
+ operation: ParseSQLQueryOperations
+ whereClause: string | null
+ statementCount: number
}
export async function parseSQLQuery({ sql }: ParseSQLQueryVariables) {
diff --git a/apps/studio/pages/api/parse-query.ts b/apps/studio/pages/api/parse-query.ts
index 4ca8ce1e5cb..b11f6190749 100644
--- a/apps/studio/pages/api/parse-query.ts
+++ b/apps/studio/pages/api/parse-query.ts
@@ -1,20 +1,14 @@
import { parse } from 'libpg-query'
import { NextApiRequest, NextApiResponse } from 'next'
-const getOperation = async (sql: string) => {
- const ast = await parse(sql)
- const stmt = ast.stmts?.[0]?.stmt
-
- if (!stmt) return null
-
+const getOperation = (stmt: Record<string, unknown>) => {
if ('SelectStmt' in stmt) return 'SELECT'
if ('InsertStmt' in stmt) return 'INSERT'
if ('UpdateStmt' in stmt) return 'UPDATE'
if ('DeleteStmt' in stmt) return 'DELETE'
}
-const getTablesInQuery = async (sql: string) => {
- const ast = await parse(sql)
+const getTablesInQuery = (ast: unknown) => {
const tables: string[] = []
function traverse(node: unknown): void {
@@ -40,6 +34,67 @@ const getTablesInQuery = async (sql: string) => {
return [...new Set(tables)].sort((a, b) => a.localeCompare(b))
}
+// libpg-query nodes only expose the location of their own leading token (e.g. a BoolExpr's
+// location is its "AND"/"OR" operator, not the start of its left operand), and some nodes
+// (SortBy) use -1 as an "unset" sentinel. Recursing to the smallest non-negative location in
+// a subtree gives the true start of that subtree's text in the original SQL.
+const getMinLocation = (node: unknown): number | undefined => {
+ if (!node || typeof node !== 'object') return undefined
+ const obj = node as Record<string, unknown>
+ let min: number | undefined
+ const consider = (loc: unknown) => {
+ if (typeof loc === 'number' && loc >= 0 && (min === undefined || loc < min)) min = loc
+ }
+ consider(obj.location)
+ for (const value of Object.values(obj)) {
+ if (Array.isArray(value)) value.forEach((item) => consider(getMinLocation(item)))
+ else if (value && typeof value === 'object') consider(getMinLocation(value))
+ }
+ return min
+}
+
+// Clauses that can immediately follow WHERE in each statement type, paired with the keyword
+// that introduces them in the original SQL — used to find where the WHERE condition's text
+// ends, since libpg-query has no deparser to do this for us.
+const FOLLOWING_CLAUSES: Record<string, [field: string, keyword: RegExp][]> = {
+ SelectStmt: [
+ ['groupClause', /\bgroup\s+by\b/i],
+ ['havingClause', /\bhaving\b/i],
+ ['windowClause', /\bwindow\b/i],
+ ['sortClause', /\border\s+by\b/i],
+ ['limitOffset', /\boffset\b/i],
+ ['limitCount', /\blimit\b/i],
+ ['lockingClause', /\bfor\b/i],
+ ],
+ UpdateStmt: [['returningList', /\breturning\b/i]],
+ DeleteStmt: [['returningList', /\breturning\b/i]],
+}
+
+const getWhereClauseText = (sql: string, stmtType: string, stmt: Record<string, unknown>) => {
+ const start = getMinLocation(stmt.whereClause)
+ if (start === undefined) return null
+
+ const candidateEnds: number[] = []
+ for (const [field, keyword] of FOLLOWING_CLAUSES[stmtType] ?? []) {
+ const value = stmt[field]
+ const node = Array.isArray(value) ? value[0] : value
+ if (!node) continue
+
+ // Bound the keyword search to before the clause's own expression when we know where that
+ // starts; otherwise (e.g. lockingClause, which carries no location at all) search onward.
+ const exprStart = getMinLocation(node)
+ const window =
+ exprStart !== undefined && exprStart > start ? sql.slice(start, exprStart) : sql.slice(start)
+ const match = keyword.exec(window)
+ if (match) candidateEnds.push(start + match.index)
+ else if (exprStart !== undefined && exprStart > start) candidateEnds.push(exprStart)
+ }
+
+ const end =
+ candidateEnds.length > 0 ? Math.min(...candidateEnds) : sql.replace(/;\s*$/, '').length
+ return sql.slice(start, end).trim()
+}
+
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== 'POST') {
res.setHeader('Allow', ['POST'])
@@ -53,9 +108,19 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
return res.status(400).json({ error: 'Missing or invalid "sql" in request body' })
}
- const tables = await getTablesInQuery(sql)
- const operation = await getOperation(sql)
- return res.status(200).json({ tables, operation })
+ const ast = await parse(sql)
+ const statementCount = ast.stmts?.length ?? 0
+ const stmt = ast.stmts?.[0]?.stmt as Record<string, unknown> | undefined
+ const [stmtType, stmtNode] = stmt ? Object.entries(stmt)[0] : []
+
+ const tables = getTablesInQuery(ast)
+ const operation = stmt ? getOperation(stmt) : null
+ const whereClause =
+ stmtType && stmtNode
+ ? getWhereClauseText(sql, stmtType, stmtNode as Record<string, unknown>)
+ : null
+
+ return res.status(200).json({ tables, operation, whereClause, statementCount })
} catch (error) {
const message =
(error as { sqlDetails?: { message?: string } })?.sqlDetails?.message ??
diff --git a/apps/studio/state/postgres-sandbox/sandbox.core.ts b/apps/studio/state/postgres-sandbox/sandbox.core.ts
index 5751ecdb646..08c24b598b8 100644
--- a/apps/studio/state/postgres-sandbox/sandbox.core.ts
+++ b/apps/studio/state/postgres-sandbox/sandbox.core.ts
@@ -54,10 +54,8 @@ const boot = async (): Promise<SandboxCore> => {
const run = async ({ sql }: { sql: string }) => {
try {
- // [Joshen] First 2 results will be from role impersonation, the actual result from the
- // query will be returned as the 3rd result.
const results = await pg.exec(sql)
- return { result: results[2].rows ?? [] }
+ return { result: results.at(-1)?.rows ?? [] }
} catch (error) {
await pg.exec('ROLLBACK').catch(() => {})
throw error instanceof Error ? error : new Error(getErrorMessage(error) ?? String(error))