The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(studio): SQL editor logs source — toolbar UI + creation flow (#48452)
Charisc16c7e94ccd9
diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditorLayout.tsx b/apps/studio/components/interfaces/SQLEditor/SQLEditorLayout.tsxindex d149bdeb95e..f229f200768 100644--- a/apps/studio/components/interfaces/SQLEditor/SQLEditorLayout.tsx+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditorLayout.tsx@@ -95,6 +95,7 @@ const SQLEditorToolbar = () => {return (<UtilityActionsid={id}+ runSource={runSource}isExecuting={isExecuting}isDisabled={diff.isDiffOpen}hasSelection={hasSelection}diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/DatabaseSubMenu.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/DatabaseSubMenu.tsxnew file mode 100644index 00000000000..59458d69a99--- /dev/null+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/DatabaseSubMenu.tsx@@ -0,0 +1,95 @@+import { LOCAL_STORAGE_KEYS, useParams } from 'common'+import { Check, Plus } from 'lucide-react'+import Link from 'next/link'+import {+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,+} from 'ui'++import { useReadReplicasQuery } from '@/data/read-replicas/replicas-query'+import { formatDatabaseID, formatDatabaseRegion } from '@/data/read-replicas/replicas.utils'+import { useIsFeatureEnabled } from '@/hooks/misc/useIsFeatureEnabled'+import { useLocalStorageQuery } from '@/hooks/misc/useLocalStorage'+import { useDatabaseSelectorStateSnapshot } from '@/state/database-selector'+import { useSqlEditorSessionSnapshot } from '@/state/sql-editor/sql-editor-session-state'++/** The label a database row/summary shows: the primary, or a replica by region + id. */+function databaseLabel(identifier: string, region: string, projectRef: string | undefined) {+ if (identifier === projectRef) return 'Primary database'+ return `Read replica (${formatDatabaseRegion(region)} - ${formatDatabaseID(identifier)})`+}++export const DatabaseSubMenu = ({ id }: { id: string }) => {+ const { ref: projectRef } = useParams()+ const sessionSnap = useSqlEditorSessionSnapshot()+ const dbSelector = useDatabaseSelectorStateSnapshot()+ const { infrastructureReadReplicas } = useIsFeatureEnabled(['infrastructure:read_replicas'])++ const [lastSelectedDb, setLastSelectedDb] = useLocalStorageQuery(+ LOCAL_STORAGE_KEYS.SQL_EDITOR_LAST_SELECTED_DB(projectRef ?? ''),+ ''+ )++ const { data } = useReadReplicasQuery({ projectRef })+ const databases = (data ?? [])+ .slice()+ .sort((a, b) => (a.inserted_at > b.inserted_at ? 1 : 0))+ .sort((database) => (database.identifier === projectRef ? -1 : 0))++ const selectedDatabaseId =+ lastSelectedDb.length > 0 ? lastSelectedDb : (dbSelector.selectedDatabaseId ?? projectRef)+ const selectedDatabase = databases.find((db) => db.identifier === selectedDatabaseId)++ const newReplicaURL = `/project/${projectRef}/database/replication?destinationType=Read+Replica`++ const handleSelect = (databaseId: string) => {+ dbSelector.setSelectedDatabaseId(databaseId)+ setLastSelectedDb(databaseId)+ sessionSnap.resetResult(id)+ }++ return (+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <div className="flex flex-col">+ <span>Database</span>+ <span className="text-foreground-lighter text-xs">+ {selectedDatabase+ ? databaseLabel(selectedDatabase.identifier, selectedDatabase.region, projectRef)+ : 'Primary database'}+ </span>+ </div>+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="w-64">+ {databases.map((database) => {+ const isUnhealthy = database.status !== 'ACTIVE_HEALTHY'+ return (+ <DropdownMenuItem+ key={database.identifier}+ className="justify-between"+ disabled={isUnhealthy}+ onClick={() => handleSelect(database.identifier)}+ >+ <span>{databaseLabel(database.identifier, database.region, projectRef)}</span>+ {database.identifier === selectedDatabaseId && <Check size={14} />}+ </DropdownMenuItem>+ )+ })}+ {infrastructureReadReplicas && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem asChild className="gap-x-2">+ <Link href={newReplicaURL}>+ <Plus size={14} strokeWidth={1.5} />+ Create a new read replica+ </Link>+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ )+}diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/LogsCustomRangeDialog.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/LogsCustomRangeDialog.tsxnew file mode 100644index 00000000000..76ba203f1df--- /dev/null+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/LogsCustomRangeDialog.tsx@@ -0,0 +1,58 @@+import { useState } from 'react'+import { type DateRange } from 'react-day-picker'+import {+ Button,+ Calendar,+ Dialog,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from 'ui'++export const LogsCustomRangeDialog = ({+ open,+ onOpenChange,+ onApply,+}: {+ open: boolean+ onOpenChange: (open: boolean) => void+ onApply: (range: { from: Date; to: Date }) => void+}) => {+ const [range, setRange] = useState<DateRange | undefined>()++ const canApply = range?.from !== undefined && range?.to !== undefined++ const handleApply = () => {+ if (range?.from === undefined || range?.to === undefined) return+ onApply({ from: range.from, to: range.to })+ onOpenChange(false)+ }++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent size="large">+ <DialogHeader>+ <DialogTitle>Custom time range</DialogTitle>+ </DialogHeader>+ <div className="flex items-center justify-center overflow-x-auto px-2 py-2">+ <Calendar+ mode="range"+ selected={range}+ onSelect={setRange}+ numberOfMonths={2}+ hidden={{ after: new Date() }}+ />+ </div>+ <DialogFooter>+ <Button variant="default" onClick={() => onOpenChange(false)}>+ Cancel+ </Button>+ <Button disabled={!canApply} onClick={handleApply}>+ Apply+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/QuerySourceMenu.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/QuerySourceMenu.tsxnew file mode 100644index 00000000000..027ae76bd2c--- /dev/null+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/QuerySourceMenu.tsx@@ -0,0 +1,167 @@+import { useParams } from 'common'+import dayjs from 'dayjs'+import { Check, ChevronDown, Database, ScrollText } from 'lucide-react'+import { useRouter } from 'next/router'+import { useState } from 'react'+import {+ Button,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from 'ui'++import {+ datePickerValueToLogDateRange,+ type QuerySource,+ type SqlSnippetSource,+} from '../../querySource'+import { DatabaseSubMenu } from './DatabaseSubMenu'+import { LogsCustomRangeDialog } from './LogsCustomRangeDialog'+import { resolveSourceSwitch } from './QuerySourceMenu.utils'+import { RowLimitSubMenu } from './RowLimitSubMenu'+import { RunAsSubMenu } from './RunAsSubMenu'+import { TimeRangeSubMenu } from './TimeRangeSubMenu'+import { maybeShowUpgradePromptIfNotEntitled } from '@/components/interfaces/Settings/Logs/Logs.utils'+import UpgradePrompt from '@/components/interfaces/Settings/Logs/UpgradePrompt'+import { useCheckEntitlements } from '@/hooks/misc/useCheckEntitlements'+import { IS_PLATFORM } from '@/lib/constants'+import { useSqlEditorSessionSnapshot } from '@/state/sql-editor/sql-editor-session-state'+import { useSqlEditorV2StateSnapshot } from '@/state/sql-editor/sql-editor-state'++const SOURCE_LABEL: Record<SqlSnippetSource, string> = {+ database: 'Database',+ logs: 'Logs',+}++const SourceIcon = ({ source, ...props }: { source: SqlSnippetSource; className?: string }) =>+ source === 'logs' ? <ScrollText {...props} /> : <Database {...props} />++type QuerySourceMenuProps = {+ id: string+ runSource: QuerySource+ /** Whether creating a logs snippet is available (feature-flagged). */+ canCreateLogsSnippet: boolean+}++/**+ * The consolidated SQL-editor source control: a single toolbar dropdown that+ * both labels the snippet's source (Database / Logs) and hosts every+ * source-specific control as a flyout submenu — database selector + role+ * impersonation + row limit for a database snippet, time range for a logs+ * snippet. The logs "Custom range…" calendar and the retention upgrade prompt are+ * rendered as siblings of the dropdown (not inside it) so they survive the menu+ * closing.+ *+ * A snippet's source is immutable, so the source rows aren't a plain toggle.+ * Once a snippet exists — a saved query, or a new one the user has already typed+ * into — switching backends opens a *fresh* tab with a new snippet of that+ * source, leaving the existing query untouched (there's no sense running a query+ * against the wrong backend). Only a brand-new, not-yet-materialized blank tab+ * re-flavors in place, so we don't spawn a redundant snippet before the user has+ * written anything.+ */+export const QuerySourceMenu = ({ id, runSource, canCreateLogsSnippet }: QuerySourceMenuProps) => {+ const { ref } = useParams()+ const router = useRouter()+ const snapV2 = useSqlEditorV2StateSnapshot()+ const sessionSnap = useSqlEditorSessionSnapshot()++ const [isCustomRangeOpen, setIsCustomRangeOpen] = useState(false)+ const [showUpgradePrompt, setShowUpgradePrompt] = useState(false)++ const { getEntitlementNumericValue } = useCheckEntitlements('log.retention_days')+ const entitledToLogDays = getEntitlementNumericValue()++ const currentSource = runSource.type+ const isLogs = currentSource === 'logs'+ // 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 switchSource = (target: SqlSnippetSource) => {+ const next = resolveSourceSwitch({ ref, target, currentSource, isBlankNewTab })+ if (next === null) return+ router[next.method](next.url)+ }++ const applyCustomRange = ({ from, to }: { from: Date; to: Date }) => {+ const fromIso = dayjs(from).startOf('day').toISOString()+ if (maybeShowUpgradePromptIfNotEntitled(fromIso, entitledToLogDays)) {+ setShowUpgradePrompt(true)+ return+ }+ sessionSnap.setLogRange(+ id,+ datePickerValueToLogDateRange({+ from: fromIso,+ to: dayjs(to).endOf('day').toISOString(),+ isHelper: false,+ })+ )+ }++ return (+ <>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ variant="default"+ aria-label={`Query source: ${SOURCE_LABEL[currentSource]}`}+ icon={<SourceIcon source={currentSource} className="text-foreground-light" />}+ iconRight={<ChevronDown size={14} className="text-foreground-light" />}+ >+ {SOURCE_LABEL[currentSource]}+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-60">+ <DropdownMenuItem className="justify-between" onClick={() => switchSource('database')}>+ <span className="flex items-center gap-x-2">+ <Database size={14} className="text-foreground-light" />+ Database+ </span>+ {!isLogs && <Check size={14} />}+ </DropdownMenuItem>+ {(canCreateLogsSnippet || isLogs) && (+ <DropdownMenuItem className="justify-between" onClick={() => switchSource('logs')}>+ <span className="flex items-center gap-x-2">+ <ScrollText size={14} className="text-foreground-light" />+ Logs+ </span>+ {isLogs && <Check size={14} />}+ </DropdownMenuItem>+ )}++ <DropdownMenuSeparator />++ {runSource.type === 'logs' ? (+ <TimeRangeSubMenu+ id={id}+ range={runSource.dateRange}+ onOpenCustomRange={() => setIsCustomRangeOpen(true)}+ onShowUpgrade={() => setShowUpgradePrompt(true)}+ />+ ) : (+ <>+ {IS_PLATFORM && <DatabaseSubMenu id={id} />}+ <RunAsSubMenu />+ <RowLimitSubMenu />+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>++ {isLogs && (+ <>+ <LogsCustomRangeDialog+ open={isCustomRangeOpen}+ onOpenChange={setIsCustomRangeOpen}+ onApply={applyCustomRange}+ />+ <UpgradePrompt show={showUpgradePrompt} setShowUpgradePrompt={setShowUpgradePrompt} />+ </>+ )}+ </>+ )+}diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/QuerySourceMenu.utils.test.ts b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/QuerySourceMenu.utils.test.tsnew file mode 100644index 00000000000..d005b5b44b4--- /dev/null+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/QuerySourceMenu.utils.test.ts@@ -0,0 +1,60 @@+import { describe, expect, it } from 'vitest'++import { resolveSourceSwitch } from './QuerySourceMenu.utils'++describe('resolveSourceSwitch', () => {+ it('opens a new tab (push) when switching source on an existing snippet', () => {+ expect(+ resolveSourceSwitch({+ ref: 'abc',+ target: 'logs',+ currentSource: 'database',+ isBlankNewTab: false,+ })+ ).toEqual({ method: 'push', url: '/project/abc/sql/new?skip=true&source=logs' })+ })++ it('re-flavors in place (replace) on a brand-new blank tab', () => {+ expect(+ resolveSourceSwitch({+ ref: 'abc',+ target: 'logs',+ currentSource: 'database',+ isBlankNewTab: true,+ })+ ).toEqual({ method: 'replace', url: '/project/abc/sql/new?skip=true&source=logs' })+ })++ it('omits the source param when switching to database (the default source)', () => {+ expect(+ resolveSourceSwitch({+ ref: 'abc',+ target: 'database',+ currentSource: 'logs',+ isBlankNewTab: false,+ })+ ).toEqual({ method: 'push', url: '/project/abc/sql/new?skip=true' })+ })++ it('is a no-op when the snippet is already on the target source', () => {+ expect(+ resolveSourceSwitch({+ ref: 'abc',+ target: 'database',+ currentSource: 'database',+ isBlankNewTab: false,+ })+ ).toBeNull()+ })++ it('is a no-op without a project ref', () => {+ expect(+ resolveSourceSwitch({+ ref: undefined,+ target: 'logs',+ currentSource: 'database',+ isBlankNewTab: true,+ })+ ).toBeNull()+ })+})diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/QuerySourceMenu.utils.ts b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/QuerySourceMenu.utils.tsnew file mode 100644index 00000000000..0aba7a73b97--- /dev/null+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/QuerySourceMenu.utils.ts@@ -0,0 +1,43 @@+import { type SqlSnippetSource } from '../../querySource'++export type SourceSwitchNavigation = {+ /**+ * `push` opens a new tab (leaving the current snippet intact); `replace`+ * re-flavors the current blank tab in place without a history entry.+ */+ method: 'push' | 'replace'+ url: string+}++/**+ * Decide how switching a snippet's query source should navigate. A snippet's+ * source is immutable, so switching never edits the current snippet:+ *+ * - An existing (materialized) snippet — a saved query, or a new one already+ * typed into — opens a *fresh* `/sql/new` tab of the target source (`push`), so+ * its query is never reinterpreted against the wrong backend.+ * - A brand-new, not-yet-materialized blank tab re-flavors in place (`replace`),+ * so we don't spawn a redundant snippet before anything has been written.+ *+ * Returns `null` when there's nothing to do (no project ref, or the snippet is+ * already on the target source).+ */+export function resolveSourceSwitch({+ ref,+ target,+ currentSource,+ isBlankNewTab,+}: {+ ref: string | undefined+ target: SqlSnippetSource+ currentSource: SqlSnippetSource+ isBlankNewTab: boolean+}): SourceSwitchNavigation | null {+ if (!ref || target === currentSource) return null+ const suffix = target === 'logs' ? '&source=logs' : ''+ return {+ method: isBlankNewTab ? 'replace' : 'push',+ // skip=true bypasses the "load last visited snippet" redirect on /sql/new.+ url: `/project/${ref}/sql/new?skip=true${suffix}`,+ }+}diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/RowLimitSubMenu.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/RowLimitSubMenu.tsxnew file mode 100644index 00000000000..9015dbada13--- /dev/null+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/RowLimitSubMenu.tsx@@ -0,0 +1,38 @@+import {+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,+} from 'ui'++import { ROWS_PER_PAGE_OPTIONS } from '../../SQLEditor.constants'+import { useSqlEditorSessionSnapshot } from '@/state/sql-editor/sql-editor-session-state'++export const RowLimitSubMenu = () => {+ const sessionSnap = useSqlEditorSessionSnapshot()+ const currentLabel = ROWS_PER_PAGE_OPTIONS.find((opt) => opt.value === sessionSnap.limit)?.label++ return (+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <div className="flex flex-col">+ <span>Row limit</span>+ <span className="text-foreground-lighter text-xs">{currentLabel}</span>+ </div>+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="w-40">+ <DropdownMenuRadioGroup+ value={sessionSnap.limit.toString()}+ onValueChange={(val) => sessionSnap.setLimit(Number(val))}+ >+ {ROWS_PER_PAGE_OPTIONS.map((option) => (+ <DropdownMenuRadioItem key={option.label} value={option.value.toString()}>+ {option.label}+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ )+}diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/RunAsSubMenu.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/RunAsSubMenu.tsxnew file mode 100644index 00000000000..a44a95d2d60--- /dev/null+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/RunAsSubMenu.tsx@@ -0,0 +1,31 @@+import { DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger } from 'ui'++import { RoleImpersonationSelector } from '@/components/interfaces/RoleImpersonationSelector'+import { useRoleImpersonationStateSnapshot } from '@/state/role-impersonation-state'++const SERVICE_ROLE_LABEL = 'postgres'++export const RunAsSubMenu = () => {+ const state = useRoleImpersonationStateSnapshot()+ const currentRole = state.role?.role ?? SERVICE_ROLE_LABEL++ return (+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <div className="flex flex-col">+ <span>Run as</span>+ <span className="text-foreground-lighter text-xs">{currentRole}</span>+ </div>+ </DropdownMenuSubTrigger>+ {/* Stops propagation so the authenticated-user search input isn't swallowed by the+ dropdown's typeahead. */}+ <DropdownMenuSubContent className="w-80 p-0" onKeyDown={(e) => e.stopPropagation()}>+ <RoleImpersonationSelector+ header="Run SQL query as a role"+ serviceRoleLabel={SERVICE_ROLE_LABEL}+ orientation="vertical"+ />+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ )+}diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/TimeRangeSubMenu.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/TimeRangeSubMenu.tsxnew file mode 100644index 00000000000..39517f8c7b6--- /dev/null+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/QuerySourceMenu/TimeRangeSubMenu.tsx@@ -0,0 +1,88 @@+import { Check, Lock } from 'lucide-react'+import {+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,+} from 'ui'++import {+ datePickerValueToLogDateRange,+ logDateRangesEqual,+ type LogDateRange,+} from '../../querySource'+import { EXPLORER_DATEPICKER_HELPERS } from '@/components/interfaces/Settings/Logs/Logs.constants'+import { maybeShowUpgradePromptIfNotEntitled } from '@/components/interfaces/Settings/Logs/Logs.utils'+import { useCheckEntitlements } from '@/hooks/misc/useCheckEntitlements'+import { useSqlEditorSessionSnapshot } from '@/state/sql-editor/sql-editor-session-state'++export const TimeRangeSubMenu = ({+ id,+ range,+ onOpenCustomRange,+ onShowUpgrade,+}: {+ id: string+ range: LogDateRange+ onOpenCustomRange: () => void+ onShowUpgrade: () => void+}) => {+ const sessionSnap = useSqlEditorSessionSnapshot()+ const { getEntitlementNumericValue } = useCheckEntitlements('log.retention_days')+ const entitledToLogDays = getEntitlementNumericValue()++ const isCustomRange = range.kind === 'absolute'+ const presets = EXPLORER_DATEPICKER_HELPERS.map((helper) => ({+ helper,+ range: datePickerValueToLogDateRange({+ from: helper.calcFrom(),+ to: helper.calcTo(),+ isHelper: true,+ text: helper.text,+ }),+ }))+ const selectedPreset = presets.find((preset) => logDateRangesEqual(range, preset.range))++ return (+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <div className="flex flex-col">+ <span>Time range</span>+ <span className="text-foreground-lighter text-xs">+ {isCustomRange ? 'Custom range' : (selectedPreset?.helper.text ?? 'Custom range')}+ </span>+ </div>+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="w-52">+ {presets.map(({ helper, range: presetRange }) => {+ const isSelected = !isCustomRange && logDateRangesEqual(range, presetRange)+ const isLocked = maybeShowUpgradePromptIfNotEntitled(helper.calcFrom(), entitledToLogDays)++ return (+ <DropdownMenuItem+ key={helper.text}+ className="justify-between"+ onClick={() => {+ if (isLocked) return onShowUpgrade()+ sessionSnap.setLogRange(id, presetRange)+ }}+ >+ <span>{helper.text}</span>+ {isLocked ? (+ <Lock size={14} className="text-foreground-lighter" />+ ) : (+ isSelected && <Check size={14} />+ )}+ </DropdownMenuItem>+ )+ })}+ <DropdownMenuSeparator />+ <DropdownMenuItem className="justify-between" onClick={onOpenCustomRange}>+ <span>Custom range…</span>+ {isCustomRange && <Check size={14} />}+ </DropdownMenuItem>+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ )+}diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/RunButton.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/RunButton.tsxindex 861481f457d..6fdaae2365e 100644--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/RunButton.tsx+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/RunButton.tsx@@ -1,5 +1,7 @@import { Loader2 } from 'lucide-react'-import { Button, KeyboardShortcut } from 'ui'+import { KeyboardShortcut } from 'ui'++import { ButtonTooltip } from '@/components/ui/ButtonTooltip'interface SqlRunButtonProps {isDisabled?: boolean@@ -7,6 +9,13 @@ interface SqlRunButtonProps {hasSelection?: booleanclassName?: stringonClick: () => void+ /**+ * Explanation shown in a tooltip while the button is disabled — e.g. why a+ * logs query can't run on this project. A disabled `<button>` swallows pointer+ * events, so the tooltip is rendered via `ButtonTooltip` (pointer-events-auto)+ * to stay reachable.+ */+ disabledReason?: string}export const SqlRunButton = ({@@ -15,9 +24,10 @@ export const SqlRunButton = ({hasSelection = false,className,onClick,+ disabledReason,}: SqlRunButtonProps) => {return (- <Button+ <ButtonTooltiponClick={onClick}disabled={isDisabled}variant="primary"@@ -31,8 +41,9 @@ export const SqlRunButton = ({)}className={className}+ tooltip={{ content: { side: 'bottom', text: isDisabled ? disabledReason : undefined } }}>{hasSelection ? 'Run selected' : 'Run'}- </Button>+ </ButtonTooltip>)}diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsxindex 4a6b55cf89b..a5c69be3d40 100644--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx@@ -1,5 +1,5 @@import { Hotkey } from '@tanstack/react-hotkeys'-import { LOCAL_STORAGE_KEYS, useParams } from 'common'+import { LOCAL_STORAGE_KEYS, useFlag, useParams } from 'common'import { AlignLeft, Check, ChevronDown, Heart, Keyboard, MoreVertical } from 'lucide-react'import { toast } from 'sonner'import {@@ -18,8 +18,10 @@ import {TooltipTrigger,} from 'ui'+import { type QuerySource } from '../querySource'import { ROWS_PER_PAGE_OPTIONS } from '../SQLEditor.constants'import { AutosaveStatus } from './AutosaveStatus'+import { QuerySourceMenu } from './QuerySourceMenu/QuerySourceMenu'import { SqlRunButton } from './RunButton'import { SqlSaveButton } from './SaveButton'import SavingIndicator from './SavingIndicator'@@ -35,6 +37,7 @@ import { useSqlEditorV2StateSnapshot } from '@/state/sql-editor/sql-editor-stateexport type UtilityActionsProps = {id: string+ runSource: QuerySourceisExecuting?: booleanisDisabled?: booleanhasSelection?: boolean@@ -45,6 +48,7 @@ export type UtilityActionsProps = {export const UtilityActions = ({id,+ runSource,isExecuting = false,isDisabled = false,hasSelection = false,@@ -57,6 +61,14 @@ export const UtilityActions = ({const sessionSnap = useSqlEditorSessionSnapshot()const isManualSaveEnabled = useIsSqlEditorManualSaveEnabled()+ const isLogsSourceEnabled = useFlag('sqlEditorLogsSource')+ const isOtelLogsEnabled = useFlag('otelLegacyLogs')++ const isLogs = runSource.type === 'logs'+ const canCreateLogsSnippet = isLogsSourceEnabled && isOtelLogsEnabled+ const canShowSourceIndicator = isLogs || canCreateLogsSnippet+ const isLogsRunBlocked = isLogs && !isOtelLogsEnabled+const [isAiOpen] = useLocalStorageQuery(LOCAL_STORAGE_KEYS.SQL_EDITOR_AI_OPEN, true)const [intellisenseEnabled, setIntellisenseEnabled] = useLocalStorageQuery(LOCAL_STORAGE_KEYS.SQL_EDITOR_INTELLISENSE,@@ -141,7 +153,7 @@ export const UtilityActions = ({</DropdownMenuItem></>)}- <DropdownMenuItem className="justify-between" onClick={prettifyQuery}>+ <DropdownMenuItem className="justify-between" onClick={prettifyQuery} disabled={isLogs}><span className="flex items-center gap-x-2"><AlignLeft size={14} strokeWidth={2} className="text-foreground-light" />Prettify SQL@@ -208,6 +220,7 @@ export const UtilityActions = ({<Buttonvariant="text"onClick={prettifyQuery}+ disabled={isLogs}className="px-1"icon={<AlignLeft strokeWidth={2} className="text-foreground-light" />}aria-label="Prettify SQL"@@ -223,51 +236,66 @@ export const UtilityActions = ({</div><div className="flex items-center gap-x-2">- <div className="flex items-center">- {IS_PLATFORM && (- <DatabaseSelector- selectedDatabaseId={lastSelectedDb.length === 0 ? undefined : lastSelectedDb}- variant="connected-on-right"- onSelectId={onSelectDatabase}- />- )}- <RoleImpersonationPopover- serviceRoleLabel="postgres"- header="Run SQL query as a role"- variant={IS_PLATFORM ? 'connected-on-left' : 'regular'}+ {canShowSourceIndicator ? (+ <QuerySourceMenu+ id={id}+ runSource={runSource}+ canCreateLogsSnippet={canCreateLogsSnippet}/>- </div>+ ) : (+ <>+ <div className="flex items-center">+ {IS_PLATFORM && (+ <DatabaseSelector+ selectedDatabaseId={lastSelectedDb.length === 0 ? undefined : lastSelectedDb}+ variant="connected-on-right"+ onSelectId={onSelectDatabase}+ />+ )}+ <RoleImpersonationPopover+ serviceRoleLabel="postgres"+ header="Run SQL query as a role"+ variant={IS_PLATFORM ? 'connected-on-left' : 'regular'}+ />+ </div>- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button- variant="default"- iconRight={<ChevronDown size={14} className="text-foreground-light" />}- >- <span className="text-foreground-light">Limit</span>{' '}- {ROWS_PER_PAGE_OPTIONS.find((opt) => opt.value === sessionSnap.limit)?.label}- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent className="w-40" align="end">- <DropdownMenuRadioGroup- value={sessionSnap.limit.toString()}- onValueChange={(val) => sessionSnap.setLimit(Number(val))}- >- {ROWS_PER_PAGE_OPTIONS.map((option) => (- <DropdownMenuRadioItem key={option.label} value={option.value.toString()}>- {option.label}- </DropdownMenuRadioItem>- ))}- </DropdownMenuRadioGroup>- </DropdownMenuContent>- </DropdownMenu>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ variant="default"+ iconRight={<ChevronDown size={14} className="text-foreground-light" />}+ >+ <span className="text-foreground-light">Limit</span>{' '}+ {ROWS_PER_PAGE_OPTIONS.find((opt) => opt.value === sessionSnap.limit)?.label}+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent className="w-40" align="end">+ <DropdownMenuRadioGroup+ value={sessionSnap.limit.toString()}+ onValueChange={(val) => sessionSnap.setLimit(Number(val))}+ >+ {ROWS_PER_PAGE_OPTIONS.map((option) => (+ <DropdownMenuRadioItem key={option.label} value={option.value.toString()}>+ {option.label}+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ </DropdownMenuContent>+ </DropdownMenu>+ </>+ )}<div className="flex items-center">{isManualSaveEnabled && <SqlSaveButton id={id} className="rounded-r-none" />}<SqlRunButtonhasSelection={hasSelection}- isDisabled={isDisabled || isExecuting}+ isDisabled={isDisabled || isExecuting || isLogsRunBlocked}isExecuting={isExecuting}+ disabledReason={+ isLogsRunBlocked+ ? "Querying logs from the SQL editor isn't available for this project yet"+ : undefined+ }className={isManualSaveEnabled ? 'rounded-l-none' : undefined}onClick={executeQuery}/>diff --git a/apps/studio/components/interfaces/SQLEditor/querySource.test.ts b/apps/studio/components/interfaces/SQLEditor/querySource.test.tsindex 9c63333f64e..5b79d3b7768 100644--- a/apps/studio/components/interfaces/SQLEditor/querySource.test.ts+++ b/apps/studio/components/interfaces/SQLEditor/querySource.test.ts@@ -6,6 +6,7 @@ import {DEFAULT_LOG_DATE_RANGE,getSnippetSource,isoDateTimeString,+ logDateRangesEqual,logDateRangeToDatePickerValue,resolveLogRunRange,type LogDateRange,@@ -228,3 +229,57 @@ describe('querySource.ts:resolveLogRunRange', () => {})})})++describe('querySource.ts:logDateRangesEqual', () => {+ it('matches relative ranges on amount + unit regardless of label formatting', () => {+ const lastHourPreset = EXPLORER_DATEPICKER_HELPERS.find((h) => h.text === 'Last hour')!+ const presetRange = datePickerValueToLogDateRange({+ from: lastHourPreset.calcFrom(),+ to: lastHourPreset.calcTo(),+ isHelper: true,+ text: lastHourPreset.text,+ })++ expect(+ logDateRangesEqual(presetRange, { kind: 'relative', last: { amount: 1, unit: 'hour' } })+ ).toBe(true)+ })++ it('does not match relative ranges with a different amount or unit', () => {+ expect(+ logDateRangesEqual(+ { kind: 'relative', last: { amount: 1, unit: 'hour' } },+ { kind: 'relative', last: { amount: 3, unit: 'hour' } }+ )+ ).toBe(false)+ expect(+ logDateRangesEqual(+ { kind: 'relative', last: { amount: 1, unit: 'hour' } },+ { kind: 'relative', last: { amount: 1, unit: 'day' } }+ )+ ).toBe(false)+ })++ it('matches absolute ranges on their ISO endpoints', () => {+ const from = isoDateTimeString('2025-01-01T00:00:00.000Z')!+ const to = isoDateTimeString('2025-01-02T00:00:00.000Z')!+ expect(logDateRangesEqual({ kind: 'absolute', from, to }, { kind: 'absolute', from, to })).toBe(+ true+ )+ })++ it('never matches a relative range against an absolute one', () => {+ const from = isoDateTimeString('2025-01-01T00:00:00.000Z')!+ const to = isoDateTimeString('2025-01-02T00:00:00.000Z')!+ expect(+ logDateRangesEqual(+ { kind: 'relative', last: { amount: 1, unit: 'hour' } },+ {+ kind: 'absolute',+ from,+ to,+ }+ )+ ).toBe(false)+ })+})diff --git a/apps/studio/components/interfaces/SQLEditor/querySource.ts b/apps/studio/components/interfaces/SQLEditor/querySource.tsindex e4d2b305d56..1ba1c4fd1ea 100644--- a/apps/studio/components/interfaces/SQLEditor/querySource.ts+++ b/apps/studio/components/interfaces/SQLEditor/querySource.ts@@ -25,6 +25,16 @@ export function getSnippetSource(snippet: Pick<Snippet, 'type'>): SqlSnippetSourreturn snippet.type === 'log_sql' ? 'logs' : 'database'}+/**+ * Parse a raw `source` value (e.g. the `?source=` query param a creation entry+ * threads through `/sql/new`) into a `SqlSnippetSource`. Only the explicit+ * `'logs'` opts a new snippet into the logs backend; anything else — including an+ * absent param — is a database snippet, keeping database the safe default.+ */+export function parseSqlSnippetSource(raw: string | undefined): SqlSnippetSource {+ return raw === 'logs' ? 'logs' : 'database'+}+/*** An ISO-8601 datetime proven valid at construction via a dayjs parse. Absolute* log ranges carry these instead of raw strings so an unvalidated datetime can@@ -135,6 +145,22 @@ export function logDateRangeToDatePickerValue(range: LogDateRange): DatePickerVareturn { from: range.from, to: range.to, isHelper: false }}+/**+ * Structural equality for two log date ranges. Relative ranges match on amount ++ * unit, NOT display text — "Last hour" and "Last 1 hour" render differently but+ * are the same range, so comparing labels is unreliable. Absolute ranges match on+ * their (validated) ISO endpoints.+ */+export function logDateRangesEqual(a: LogDateRange, b: LogDateRange): boolean {+ if (a.kind === 'relative' && b.kind === 'relative') {+ return a.last.amount === b.last.amount && a.last.unit === b.last.unit+ }+ if (a.kind === 'absolute' && b.kind === 'absolute') {+ return a.from === b.from && a.to === b.to+ }+ return false+}+/*** Resolve a `LogDateRange` to concrete ISO endpoints for a run. Relative ranges* re-resolve against `now` (so "last hour" is always the hour before the run);diff --git a/apps/studio/components/interfaces/SQLEditor/usePrettifyQuery.ts b/apps/studio/components/interfaces/SQLEditor/usePrettifyQuery.tsindex 9a70c333034..8e287272600 100644--- a/apps/studio/components/interfaces/SQLEditor/usePrettifyQuery.ts+++ b/apps/studio/components/interfaces/SQLEditor/usePrettifyQuery.ts@@ -24,9 +24,12 @@ export function usePrettifyQuery({ id, isDiffOpen }: { id: string; isDiffOpen: bconst state = getSqlEditorV2StateSnapshot()const snippet = state.snippets[id]+ // pg formatting can mangle ClickHouse syntax (backtick identifiers), so+ // Prettify is a no-op for logs snippets — the UI also hides the affordance.+ if (snippet?.snippet.type === 'log_sql') return+if (editor.isReady() && project) {- const fallback =- snippet?.snippet.type === 'log_sql' ? undefined : snippet?.snippet.content?.unchecked_sql+ const fallback = snippet?.snippet.content?.unchecked_sqlconst sql = editor.getSql(fallback)if (sql === undefined) returndiff --git a/apps/studio/components/interfaces/SQLEditor/useRunSource.ts b/apps/studio/components/interfaces/SQLEditor/useRunSource.tsindex 9bccf7fb62b..aa7cbf05b6f 100644--- a/apps/studio/components/interfaces/SQLEditor/useRunSource.ts+++ b/apps/studio/components/interfaces/SQLEditor/useRunSource.ts@@ -1,6 +1,13 @@+import { useParams } from 'common'import { useMemo } from 'react'-import { DEFAULT_LOG_DATE_RANGE, type QuerySource } from './querySource'+import {+ DEFAULT_LOG_DATE_RANGE,+ getSnippetSource,+ parseSqlSnippetSource,+ type QuerySource,+ type SqlSnippetSource,+} from './querySource'import { useSqlEditorSessionSnapshot } from '@/state/sql-editor/sql-editor-session-state'import { useSqlEditorV2StateSnapshot } from '@/state/sql-editor/sql-editor-state'@@ -10,18 +17,26 @@ import { useSqlEditorV2StateSnapshot } from '@/state/sql-editor/sql-editor-state* the user hasn't picked one); every other snippet targets the database. Source* is derived from the snippet's content type and is NOT flag-gated here — a* URL-opened logs snippet routes correctly even with the feature flag off.+ *+ * Before the snippet exists in the store (a fresh `/sql/new` tab, materialized+ * lazily on the first keystroke) the source falls back to the `?source=` URL+ * param, so a "New logs query" tab shows the logs toolbar and range picker+ * immediately rather than flashing the database controls until the user types.*/export function useRunSource(id: string): QuerySource {+ const { source: sourceParam } = useParams()const snapV2 = useSqlEditorV2StateSnapshot()const sessionSnap = useSqlEditorSessionSnapshot()- const snippetType = snapV2.snippets[id]?.snippet.type+ const snippet = snapV2.snippets[id]?.snippet+ const source: SqlSnippetSource =+ snippet !== undefined ? getSnippetSource(snippet) : parseSqlSnippetSource(sourceParam)const logRange = sessionSnap.logRange[id]return useMemo<QuerySource>(() => {- if (snippetType === 'log_sql') {+ if (source === 'logs') {return { type: 'logs', dateRange: logRange ?? DEFAULT_LOG_DATE_RANGE }}return { type: 'database' }- }, [snippetType, logRange])+ }, [source, logRange])}diff --git a/apps/studio/components/interfaces/SQLEditor/useSnippetEditor.ts b/apps/studio/components/interfaces/SQLEditor/useSnippetEditor.tsindex 76c5a139296..f7bfd296d9c 100644--- a/apps/studio/components/interfaces/SQLEditor/useSnippetEditor.ts+++ b/apps/studio/components/interfaces/SQLEditor/useSnippetEditor.ts@@ -2,6 +2,7 @@ import { useParams } from 'common'import { useRouter } from 'next/router'import { useEffect, useEffectEvent } from 'react'+import { parseSqlSnippetSource } from './querySource'import { createSqlSnippetSkeletonV2 } from './SQLEditor.utils'import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'import { useProfile } from '@/lib/profile'@@ -25,7 +26,7 @@ import { useTabsStateSnapshot } from '@/state/tabs'export function useSnippetEditor({ id, snippetName }: { id: string; snippetName: string }) {const router = useRouter()const { profile } = useProfile()- const { ref, content } = useParams()+ const { ref, content, source } = useParams()const { data: project } = useSelectedProjectQuery()const snapV2 = useSqlEditorV2StateSnapshot()@@ -45,6 +46,9 @@ export function useSnippetEditor({ id, snippetName }: { id: string; snippetName:sql: value,owner_id: profile?.id,project_id: project?.id,+ // A creation entry (e.g. "New logs query") threads the target backend+ // through `/sql/new?source=`; default to a database snippet otherwise.+ source: parseSqlSnippetSource(source),})snapV2.addSnippet({ projectRef: ref, snippet: newSnippet })// When the editor was seeded from a `content` deep-link, replace ratherdiff --git a/apps/studio/components/layouts/SQLEditorLayout/SQLEditorMenu.tsx b/apps/studio/components/layouts/SQLEditorLayout/SQLEditorMenu.tsxindex a27febc9d52..0fad5971029 100644--- a/apps/studio/components/layouts/SQLEditorLayout/SQLEditorMenu.tsx+++ b/apps/studio/components/layouts/SQLEditorLayout/SQLEditorMenu.tsx@@ -1,7 +1,7 @@import { PermissionAction } from '@supabase/shared-types/out/constants'import { useDebounce } from '@uidotdev/usehooks'import { LOCAL_STORAGE_KEYS, useFlag, useParams } from 'common'-import { FilePlus, FolderPlus, Plus, X } from 'lucide-react'+import { FilePlus, FolderPlus, Plus, ScrollText, X } from 'lucide-react'import { useRouter } from 'next/router'import { useEffect, useState } from 'react'import { toast } from 'sonner'@@ -24,6 +24,7 @@ import {import { SearchList } from './SQLEditorNavV2/SearchList'import { SQLEditorNav } from './SQLEditorNavV2/SQLEditorNav'+import { type SqlSnippetSource } from '@/components/interfaces/SQLEditor/querySource'import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'import { useLocalStorage } from '@/hooks/misc/useLocalStorage'import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'@@ -39,6 +40,9 @@ export const SQLEditorMenu = () => {const snapV2 = useSqlEditorV2StateSnapshot()const topForPostgres = useFlag('topForPostgres')+ const sqlEditorLogsSource = useFlag('sqlEditorLogsSource')+ const otelLegacyLogs = useFlag('otelLegacyLogs')+ const canCreateLogsSnippet = sqlEditorLogsSource && otelLegacyLogsconst [search, setSearch] = useState('')const [showSearch, setShowSearch] = useState(false)@@ -66,7 +70,7 @@ export const SQLEditorMenu = () => {snapV2.addNewFolder({ projectRef: ref })}- const handleNewQuery = async () => {+ const handleNewQuery = async (source: SqlSnippetSource = 'database') => {if (!ref) return console.error('Project ref is required')if (!project) return console.error('Project is required')if (!profile) return console.error('Profile is required')@@ -74,7 +78,8 @@ export const SQLEditorMenu = () => {return toast('Your queries will not be saved as you do not have sufficient permissions')}try {- router.push(`/project/${ref}/sql/new?skip=true`)+ const suffix = source === 'logs' ? '&source=logs' : ''+ router.push(`/project/${ref}/sql/new?skip=true${suffix}`)setSearch('')setShowSearch(false)} catch (error: any) {@@ -156,6 +161,12 @@ export const SQLEditorMenu = () => {<FilePlus size={14} />Create a new snippet</DropdownMenuItem>+ {canCreateLogsSnippet && (+ <DropdownMenuItem className="gap-x-2" onClick={() => handleNewQuery('logs')}>+ <ScrollText size={14} />+ Create a new logs query+ </DropdownMenuItem>+ )}<DropdownMenuItem className="gap-x-2" onClick={() => createNewFolder()}><FolderPlus size={14} />Create a new folderdiff --git a/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorTreeViewItem.tsx b/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorTreeViewItem.tsxindex 828f99b7687..21ae2a5e129 100644--- a/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorTreeViewItem.tsx+++ b/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorTreeViewItem.tsx@@ -28,6 +28,7 @@ import {TreeViewItem,} from 'ui'+import { getSnippetSource } from '@/components/interfaces/SQLEditor/querySource'import { createSqlSnippetSkeletonV2 } from '@/components/interfaces/SQLEditor/SQLEditor.utils'import { getContentById, getSqlSnippetById } from '@/data/content/content-id-query'import { useSQLSnippetFolderContentsQuery } from '@/data/content/sql-folder-contents-query'@@ -225,6 +226,7 @@ export const SQLEditorTreeViewItem = ({sql,owner_id: profile?.id,project_id: project?.id,+ source: getSnippetSource(snippet),})snapV2.addSnippet({ projectRef, snippet: snippetCopy })@@ -420,16 +422,18 @@ export const SQLEditorTreeViewItem = ({{isFavorite ? 'Remove from' : 'Add to'} favorites</ContextMenuItem>)}- {onSelectDownload !== undefined && IS_PLATFORM && (- <ContextMenuItem- className="gap-x-2"- onSelect={() => onSelectDownload()}- onFocusCapture={(e) => e.stopPropagation()}- >- <Download size={14} />- Export query- </ContextMenuItem>- )}+ {onSelectDownload !== undefined &&+ IS_PLATFORM &&+ getSnippetSource(element.metadata) !== 'logs' && (+ <ContextMenuItem+ className="gap-x-2"+ onSelect={() => onSelectDownload()}+ onFocusCapture={(e) => e.stopPropagation()}+ >+ <Download size={14} />+ Export query+ </ContextMenuItem>+ )}{onSelectDelete !== undefined && isOwner && (<><ContextMenuSeparator />