Skip to content

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

Chore/add sessions database connections (#48094)

Joshen Limc7803b8b9b07
diff --git a/apps/studio/components/interfaces/Observability/DatabaseConnections/Activity.tsx b/apps/studio/components/interfaces/Observability/DatabaseConnections/Activity.tsx
new file mode 100644
index 00000000000..7af3cb57b58
--- /dev/null
+++ b/apps/studio/components/interfaces/Observability/DatabaseConnections/Activity.tsx
@@ -0,0 +1,463 @@
+import dayjs from 'dayjs'
+import { isEqual } from 'lodash'
+import { Minus, MoreVertical, StopCircle } from 'lucide-react'
+import { parseAsArrayOf, parseAsInteger, parseAsJson, parseAsString, useQueryState } from 'nuqs'
+import { Fragment, useEffect, useState } from 'react'
+import { toast } from 'sonner'
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ Badge,
+ Button,
+ Card,
+ cn,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuTrigger,
+ HoverCard,
+ HoverCardContent,
+ HoverCardTrigger,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from 'ui'
+import { CodeBlock } from 'ui-patterns/CodeBlock'
+import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'
+
+import { ReportsSelectFilter, selectFilterSchema } from '../../Reports/v2/ReportsSelectFilter'
+import { formatDuration } from '@/components/interfaces/QueryPerformance/QueryPerformance.utils'
+import { DropdownMenuItemTooltip } from '@/components/ui/DropdownMenuItemTooltip'
+import { InlineLinkClassName } from '@/components/ui/InlineLink'
+import { useDatabaseRolesQuery } from '@/data/database-roles/database-roles-query'
+import { useDatabaseActivityQuery, type DatabaseActivity } from '@/data/database/activity-query'
+import { useQueryAbortMutation } from '@/data/sql/abort-query-mutation'
+import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
+import { formatSql } from '@/lib/formatSql'
+
+const getDuration = (activity: DatabaseActivity) => {
+ const { state } = activity
+ if (state === 'active' && activity.query_start) {
+ return dayjs().utc().diff(dayjs(activity.query_start).utc(), 'second')
+ }
+ if (state === 'idle' && activity.state_change) {
+ return dayjs().utc().diff(dayjs(activity.state_change).utc(), 'second')
+ }
+ if (
+ (state === 'idle in transaction' || state === 'idle in transaction (aborted)') &&
+ activity.transaction_start
+ ) {
+ return dayjs().utc().diff(dayjs(activity.transaction_start).utc(), 'second')
+ }
+ return null
+}
+
+const DEFAULT_ROLES_FILTER = ['anon', 'authenticated', 'postgres']
+
+interface ActivityProps {
+ live?: boolean
+}
+
+export const Activity = ({ live }: ActivityProps) => {
+ const { data: project } = useSelectedProjectQuery()
+
+ const [, setNow] = useState(() => dayjs())
+ const [selectedPid] = useQueryState('pid', parseAsInteger)
+ const [stateFilter, setStateFilter] = useQueryState(
+ 'state',
+ parseAsJson(selectFilterSchema.parse).withDefault([])
+ )
+ const [rolesFilter, setRolesFilter] = useQueryState(
+ 'roles',
+ parseAsArrayOf(parseAsString, ',').withDefault(DEFAULT_ROLES_FILTER)
+ )
+
+ const hasNoFiltersApplied = stateFilter.length === 0 && isEqual(rolesFilter, DEFAULT_ROLES_FILTER)
+
+ const { data, isPending, isSuccess } = useDatabaseActivityQuery(
+ {
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ },
+ { refetchInterval: live ? 3000 : false }
+ )
+
+ const { data: roles } = useDatabaseRolesQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ })
+
+ const activities = data?.filter((activity) => {
+ const matchesState =
+ !stateFilter ||
+ stateFilter.length === 0 ||
+ (activity.state !== null && stateFilter.includes(activity.state))
+ const matchesRole = rolesFilter.length === 0 || rolesFilter.includes(activity.role_name)
+ return matchesState && matchesRole
+ })
+
+ const stateOptions = [
+ 'Idle',
+ 'Active',
+ 'Idle in transaction',
+ 'Idle in transaction (aborted)',
+ 'Fastpath function call',
+ 'Disabled',
+ ].map((x) => ({
+ label: x,
+ value: x.toLowerCase(),
+ quantity: data?.filter(
+ (y) =>
+ y.state === x.toLowerCase() &&
+ (rolesFilter.length === 0 || rolesFilter.includes(y.role_name))
+ ).length,
+ }))
+
+ const priorityRoles = ['anon', 'authenticated', 'postgres']
+
+ const roleOptions = (roles ?? [])
+ .map((x) => ({
+ label: x.name,
+ value: x.name,
+ quantity: data?.filter(
+ (y) =>
+ y.role_name === x.name &&
+ (!stateFilter ||
+ stateFilter.length === 0 ||
+ (y.state !== null && stateFilter.includes(y.state)))
+ ).length,
+ }))
+ .sort((a, b) => {
+ const aIndex = priorityRoles.indexOf(a.value)
+ const bIndex = priorityRoles.indexOf(b.value)
+ if (aIndex !== -1 && bIndex !== -1) return aIndex - bIndex
+ if (aIndex !== -1) return -1
+ if (bIndex !== -1) return 1
+ return 0
+ })
+
+ // [Joshen] Just to trigger a UI re-render for the duration to be "live"
+ useEffect(() => {
+ const interval = setInterval(() => setNow(dayjs()), 1000)
+ return () => clearInterval(interval)
+ }, [])
+
+ useEffect(() => {
+ if (selectedPid && isSuccess) {
+ document
+ .getElementById(selectedPid.toString())
+ ?.scrollIntoView({ behavior: 'smooth', block: 'center' })
+ }
+ }, [selectedPid, isSuccess])
+
+ return (
+ <div className="flex flex-col gap-y-4">
+ <div className="flex gap-x-4">
+ <h2>Sessions</h2>
+ <div className="flex gap-x-2">
+ <ReportsSelectFilter
+ showSearch
+ label="Roles"
+ options={roleOptions}
+ value={rolesFilter ?? []}
+ onChange={setRolesFilter}
+ isLoading={isPending}
+ popoverClassName="w-72"
+ />
+ <ReportsSelectFilter
+ label="State"
+ options={stateOptions}
+ value={stateFilter ?? []}
+ onChange={setStateFilter}
+ isLoading={isPending}
+ popoverClassName="w-60"
+ />
+ </div>
+ </div>
+
+ <Card>
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-[70px]">State</TableHead>
+ <TableHead className="max-w-[300px]">Query · Session</TableHead>
+ <TableHead>Duration</TableHead>
+ <TableHead>Blocked by</TableHead>
+ <TableHead />
+ </TableRow>
+ </TableHeader>
+
+ <TableBody>
+ {isPending ? (
+ Array.from({ length: 3 }).map((_, i) => (
+ <TableRow key={i}>
+ <TableCell>
+ <ShimmeringLoader />
+ </TableCell>
+ <TableCell>
+ <ShimmeringLoader />
+ </TableCell>
+ <TableCell>
+ <ShimmeringLoader />
+ </TableCell>
+ <TableCell colSpan={2}>
+ <ShimmeringLoader />
+ </TableCell>
+ </TableRow>
+ ))
+ ) : (activities ?? []).length === 0 ? (
+ <TableRow>
+ {hasNoFiltersApplied ? (
+ <TableCell colSpan={5}>
+ <p className="text-sm text-foreground">No active sessions</p>
+ <p className="text-sm text-foreground-lighter mt-1">
+ There are currently no active database connections for the anon,
+ authenticated, and postgres roles.
+ </p>
+ </TableCell>
+ ) : (
+ <TableCell colSpan={5}>
+ <p className="text-sm text-foreground">No results found</p>
+ <p className="text-sm text-foreground-lighter mt-1">
+ There are no sessions that match the selected filters. Try adjusting or
+ clearing them.
+ </p>
+ <Button
+ variant="default"
+ className="mt-2"
+ onClick={() => {
+ setStateFilter([])
+ setRolesFilter(DEFAULT_ROLES_FILTER)
+ }}
+ >
+ Reset filters
+ </Button>
+ </TableCell>
+ )}
+ </TableRow>
+ ) : null}
+
+ {activities?.map((activity) => (
+ <ActivityRow key={activity.pid} activity={activity} />
+ ))}
+ </TableBody>
+ </Table>
+ </Card>
+ </div>
+ )
+}
+
+const ActivityRow = ({ activity }: { activity: DatabaseActivity }) => {
+ const { data: project } = useSelectedProjectQuery()
+ const [showTerminateConfirmDialog, setShowTerminateConfirmDialog] = useState(false)
+ const [selectedPid, setSelectedPid] = useQueryState('pid', parseAsInteger)
+
+ const { data } = useDatabaseActivityQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ })
+
+ const { data: roles } = useDatabaseRolesQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ })
+ const superuserRoles = roles?.filter((role) => role.isSuperuser).map((role) => role.name)
+
+ const { mutateAsync: abortQuery } = useQueryAbortMutation({
+ onSuccess: () => {
+ toast.success(`Successfully aborted query (ID: ${activity.pid})`)
+ },
+ })
+
+ const getBadgeVariant = (state: DatabaseActivity['state']) => {
+ if (state === 'active') return 'success'
+ if (state === 'idle in transaction') return 'warning'
+ return 'default'
+ }
+
+ const durationSeconds = getDuration(activity)
+
+ /**
+ * Queries in "active state": 30s threshold is long enough (most CRUD queries should be quick)
+ * Queries in "idle in transaction" state: This actively holds locks and blocks autovacuum while contributing nothing, so important to surface early at 10s threshold
+ */
+ const queryRunningLongWarning =
+ !!durationSeconds &&
+ ((activity.state === 'active' && durationSeconds >= 30) ||
+ (activity.state === 'idle in transaction' && durationSeconds >= 10))
+
+ const onConfirmTerminate = async () => {
+ try {
+ await abortQuery({
+ pid: activity.pid,
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ })
+ } catch (error) {}
+ }
+
+ return (
+ <>
+ <TableRow id={activity.pid.toString()} key={activity.pid}>
+ <TableCell className="relative w-[70px]">
+ {selectedPid === activity.pid && (
+ <div className="absolute h-full bg-brand top-0 left-0 w-1 bg-foreground-lighter"></div>
+ )}
+ <Badge variant={getBadgeVariant(activity.state)}>{activity.state}</Badge>
+ </TableCell>
+ <TableCell className="max-w-[300px]">
+ <HoverCard openDelay={100} closeDelay={100}>
+ <HoverCardTrigger>
+ <p
+ className={cn(
+ 'truncate font-mono tracking-tighter',
+ activity.query === null && 'text-foreground-lighter'
+ )}
+ >
+ {activity.query ?? 'No query'}
+ </p>
+ </HoverCardTrigger>
+ {activity.query && (
+ <HoverCardContent align="start" className="w-96 p-0">
+ <CodeBlock
+ hideLineNumbers
+ className={cn(
+ 'max-w-96 border-none [&>code]:text-xs max-h-64',
+ '[&>code]:m-0 [&>code>span]:flex [&>code>span]:flex-wrap min-h-11'
+ )}
+ wrapperClassName={cn('[&_pre]:px-4 [&_pre]:py-0')}
+ language="pgsql"
+ value={formatSql(activity.query)}
+ />
+ </HoverCardContent>
+ )}
+ </HoverCard>
+ <p className="text-xs text-foreground-lighter flex items-center gap-x-1 mt-0.5 truncate">
+ <span>PID: {activity.pid}</span>
+ <span>·</span>
+ <span>{activity.role_name}</span>
+ {activity.application_name && (
+ <>
+ <span>·</span>
+ <span>{activity.application_name}</span>
+ </>
+ )}
+ </p>
+ </TableCell>
+
+ <TableCell>
+ <p
+ className={cn(
+ 'tabular-nums truncate',
+ queryRunningLongWarning ? 'text-warning' : undefined
+ )}
+ >
+ {durationSeconds !== null ? (
+ formatDuration(durationSeconds * 1000, 0)
+ ) : (
+ <Minus size={12} className="text-foreground-lighter" />
+ )}
+ </p>
+ </TableCell>
+
+ <TableCell>
+ {activity.blocked_by.length > 0 ? (
+ activity.blocked_by.map((pid, index) => {
+ const blockedProcess = data?.find((x) => x.pid === pid)
+
+ return (
+ <Fragment key={pid}>
+ {index > 0 && ', '}
+ <Tooltip>
+ <TooltipTrigger
+ className={cn(InlineLinkClassName, 'cursor-pointer')}
+ onClick={() => setSelectedPid(pid)}
+ >
+ {pid}
+ </TooltipTrigger>
+ <TooltipContent side="bottom" className="min-w-64 max-w-80">
+ <p className="truncate">
+ <code className="tracking-tighter">{blockedProcess?.query}</code>
+ </p>
+ <p className="text-xs text-foreground-lighter flex items-center gap-x-0.5 mt-0.5 truncate">
+ <span>PID: {blockedProcess?.pid}</span>
+ <span>·</span>
+ <span>{blockedProcess?.role_name}</span>
+ {blockedProcess?.application_name && (
+ <>
+ <span>·</span>
+ <span>{blockedProcess?.application_name}</span>
+ </>
+ )}
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ </Fragment>
+ )
+ })
+ ) : (
+ <Minus size={12} className="text-foreground-lighter" />
+ )}
+ </TableCell>
+
+ <TableCell className="text-right">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ aria-label="More actions"
+ variant="text"
+ className="px-1"
+ icon={<MoreVertical />}
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-44">
+ <DropdownMenuItemTooltip
+ className="gap-x-2"
+ disabled={superuserRoles?.includes(activity.role_name)}
+ onClick={() => setShowTerminateConfirmDialog(true)}
+ tooltip={{
+ content: {
+ side: 'left',
+ text: 'Unable to terminate queries run by superuser roles',
+ },
+ }}
+ >
+ <StopCircle size={12} />
+ <span>Terminate</span>
+ </DropdownMenuItemTooltip>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </TableCell>
+ </TableRow>
+
+ <AlertDialog open={showTerminateConfirmDialog} onOpenChange={setShowTerminateConfirmDialog}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Confirm to terminate this process?</AlertDialogTitle>
+ <AlertDialogDescription>
+ This will force the query to stop running.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction variant="warning" onClick={onConfirmTerminate}>
+ Terminate
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
+ )
+}
diff --git a/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.utils.ts b/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.utils.ts
index a8dcebdce41..3278b4fa426 100644
--- a/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.utils.ts
+++ b/apps/studio/components/interfaces/QueryPerformance/QueryPerformance.utils.ts
@@ -6,7 +6,7 @@ import { getErrorMessage } from '@/lib/get-error-message'
dayjs.extend(duration)
-export const formatDuration = (milliseconds: number) => {
+export const formatDuration = (milliseconds: number, precision: number = 2) => {
const duration = dayjs.duration(milliseconds, 'milliseconds')
const days = Math.floor(duration.asDays())
@@ -16,7 +16,7 @@ export const formatDuration = (milliseconds: number) => {
const totalSeconds = duration.asSeconds()
if (totalSeconds < 60) {
- return `${totalSeconds.toFixed(2)}s`
+ return `${totalSeconds.toFixed(precision)}s`
}
const parts = []
diff --git a/apps/studio/components/interfaces/QueryPerformance/SqlMonacoBlock.tsx b/apps/studio/components/interfaces/QueryPerformance/SqlMonacoBlock.tsx
index a2f1fde9b21..c53a0a72b15 100644
--- a/apps/studio/components/interfaces/QueryPerformance/SqlMonacoBlock.tsx
+++ b/apps/studio/components/interfaces/QueryPerformance/SqlMonacoBlock.tsx
@@ -9,6 +9,10 @@ type SqlMonacoBlockProps = {
wrapperClassName?: string
}
+// [Joshen] This is technically a duplicate of CodeBlock from `ui-patterns`
+// Should decide which is the preferred and consolidate - although rendering CodeEditor
+// is much heavier due to Monaco Editor. I'd rather we use CodeBlock (or improve that)
+// for read-only rendering of code contents
export const SqlMonacoBlock = ({ value, wrapperClassName }: SqlMonacoBlockProps) => {
const [copied, setCopied] = useState(false)
diff --git a/apps/studio/components/interfaces/Reports/v2/ReportsSelectFilter.tsx b/apps/studio/components/interfaces/Reports/v2/ReportsSelectFilter.tsx
index b7deb03170e..4727ce55c6a 100644
--- a/apps/studio/components/interfaces/Reports/v2/ReportsSelectFilter.tsx
+++ b/apps/studio/components/interfaces/Reports/v2/ReportsSelectFilter.tsx
@@ -10,6 +10,7 @@ import { z } from 'zod'
export interface ReportSelectOption {
label: React.ReactNode
value: string
+ quantity?: number
description?: string
}
@@ -23,6 +24,7 @@ interface ReportsSelectFilterProps {
onChange: (value: SelectFilters) => void
isLoading?: boolean
className?: string
+ popoverClassName?: string
showSearch?: boolean
}
@@ -33,6 +35,7 @@ export const ReportsSelectFilter = ({
onChange,
isLoading = false,
className,
+ popoverClassName,
showSearch = false,
}: ReportsSelectFilterProps) => {
const [open, setOpen] = useState(false)
@@ -47,7 +50,7 @@ export const ReportsSelectFilter = ({
}, [open, value])
const handleApply = () => {
- onChange(tempValue)
+ onChange([...tempValue].sort())
setOpen(false)
}
@@ -80,9 +83,9 @@ export const ReportsSelectFilter = ({
</span>
</Button>
</PopoverTrigger>
- <PopoverContent align="start" className="p-0 w-72">
+ <PopoverContent align="start" className={cn('p-0 w-72', popoverClassName)}>
<Command>
- {showSearch && <CommandInput placeholder="Search..." />}
+ {showSearch && <CommandInput placeholder="Search..." className="text-xs" />}
<CommandList className="max-h-72">
<CommandEmpty>No options found.</CommandEmpty>
<CommandGroup>
@@ -90,9 +93,7 @@ export const ReportsSelectFilter = ({
<CommandItem key={option.value}>
<Label
key={option.value}
- className={
- 'flex items-center overflow-hidden p-1 rounded-xs gap-x-3 w-full h-full'
- }
+ className={'flex items-center overflow-hidden rounded-xs gap-x-3 w-full h-full'}
>
<Checkbox
id={`${label}-${option.value}`}
@@ -106,10 +107,15 @@ export const ReportsSelectFilter = ({
}}
onKeyDown={handleKeyDown}
/>
- <div className="flex flex-col text-xs">
- {option.label}
- {option.description && (
- <span className="text-foreground-lighter">{option.description}</span>
+ <div className="flex items-center justify-between w-full">
+ <div className="flex flex-col text-xs">
+ <span className="flex items-center gap-x-2">{option.label}</span>
+ {option.description && (
+ <span className="text-foreground-lighter">{option.description}</span>
+ )}
+ </div>
+ {!!option.quantity && (
+ <code className="p-0 px-1 text-code-inline">{option.quantity}</code>
)}
</div>
</Label>
diff --git a/apps/studio/components/layouts/ObservabilityLayout/ObservabilityMenu.utils.tsx b/apps/studio/components/layouts/ObservabilityLayout/ObservabilityMenu.utils.tsx
index ad7bd6d8816..efd8b8c1b98 100644
--- a/apps/studio/components/layouts/ObservabilityLayout/ObservabilityMenu.utils.tsx
+++ b/apps/studio/components/layouts/ObservabilityLayout/ObservabilityMenu.utils.tsx
@@ -95,7 +95,7 @@ export const useGenerateObservabilityMenu = () => {
? [
{
name: 'Database Connections',
- key: 'database-connections',
+ key: 'connections',
url: `${baseUrl}/connections`,
shortcutId: SHORTCUT_IDS.NAV_OBSERVABILITY_API_GATEWAY,
},
diff --git a/apps/studio/components/ui/DropdownMenuItemTooltip.tsx b/apps/studio/components/ui/DropdownMenuItemTooltip.tsx
index 28cfc1d28a3..8cb3e913655 100644
--- a/apps/studio/components/ui/DropdownMenuItemTooltip.tsx
+++ b/apps/studio/components/ui/DropdownMenuItemTooltip.tsx
@@ -1,4 +1,4 @@
-import { ComponentProps, ComponentPropsWithoutRef, ElementRef, forwardRef } from 'react'
+import { ComponentProps, ComponentPropsWithoutRef, ElementRef, forwardRef, ReactNode } from 'react'
import { cn, DropdownMenuItem, Tooltip, TooltipContent, TooltipTrigger } from 'ui'
export const DropdownMenuItemTooltip = forwardRef<
@@ -6,7 +6,7 @@ export const DropdownMenuItemTooltip = forwardRef<
ComponentPropsWithoutRef<typeof DropdownMenuItem> & {
tooltip: {
content: ComponentProps<typeof TooltipContent> & {
- text?: string
+ text?: string | ReactNode
}
}
}
diff --git a/apps/studio/data/database/activity-query.ts b/apps/studio/data/database/activity-query.ts
new file mode 100644
index 00000000000..447f0f62658
--- /dev/null
+++ b/apps/studio/data/database/activity-query.ts
@@ -0,0 +1,119 @@
+import { getPgStatActivitySql } from '@supabase/pg-meta'
+import { useQuery } from '@tanstack/react-query'
+
+import { databaseKeys } from './keys'
+import { executeSql } from '@/data/sql/execute-sql-mutation'
+import { ResponseError, UseCustomQueryOptions } from '@/types'
+
+type LockWaitEvent =
+ | 'relation'
+ | 'extend'
+ | 'page'
+ | 'tuple'
+ | 'transactionid'
+ | 'virtualxid'
+ | 'speculative token'
+ | 'object'
+ | 'userlock'
+ | 'advisory'
+ | 'applytransaction'
+
+type ClientWaitEvent = 'ClientRead' | 'ClientWrite' | 'WalSenderWaitForWAL' | 'WalSenderWriteData'
+
+type TimeoutWaitEvent =
+ | 'BaseBackupThrottle'
+ | 'CheckpointWriteDelay'
+ | 'PgSleep'
+ | 'RecoveryApplyDelay'
+ | 'VacuumDelay'
+ | 'VacuumTruncate'
+
+type ActivityWaitEvent =
+ | 'ArchiverMain'
+ | 'AutoVacuumMain'
+ | 'BgWriterHibernate'
+ | 'BgWriterMain'
+ | 'CheckpointerMain'
+ | 'LogicalApplyMain'
+ | 'LogicalLauncherMain'
+ | 'WalReceiverMain'
+ | 'WalSenderMain'
+ | 'WalWriterMain'
+
+type BufferPinWaitEvent = 'BufferPin'
+type IOWaitEvent = string
+type IPCWaitEvent = string
+type LWLockWaitEvent = string
+
+/**
+ * wait_event_type: What the session is blocked on
+ * wait_event: The specific event within that wait type
+ * */
+type WaitEvent =
+ | { wait_event_type: 'Lock'; wait_event: LockWaitEvent }
+ | { wait_event_type: 'Client'; wait_event: ClientWaitEvent }
+ | { wait_event_type: 'Timeout'; wait_event: TimeoutWaitEvent }
+ | { wait_event_type: 'Activity'; wait_event: ActivityWaitEvent }
+ | { wait_event_type: 'BufferPin'; wait_event: BufferPinWaitEvent }
+ | { wait_event_type: 'Extension'; wait_event: string }
+ | { wait_event_type: 'IO'; wait_event: IOWaitEvent }
+ | { wait_event_type: 'IPC'; wait_event: IPCWaitEvent }
+ | { wait_event_type: 'LWLock'; wait_event: LWLockWaitEvent }
+ | { wait_event_type: null; wait_event: null }
+
+export type DatabaseActivity = {
+ pid: number
+ role_name: string
+ application_name: string
+ blocked_by: number[]
+ query: string | null
+ query_start: string | null
+ transaction_start: string | null
+ state_change: string | null
+ state:
+ | 'idle'
+ | 'active'
+ | 'idle in transaction'
+ | 'idle in transaction (aborted)'
+ | 'fastpath function call'
+ | 'disabled'
+ | null
+} & WaitEvent
+
+export type DatabaseActivityVariables = {
+ projectRef?: string
+ connectionString?: string | null
+}
+
+export async function getDatabaseActivity(
+ { projectRef, connectionString }: DatabaseActivityVariables,
+ signal?: AbortSignal
+) {
+ const sql = getPgStatActivitySql()
+
+ const { result } = await executeSql(
+ { projectRef, connectionString, sql, queryKey: ['activity'] },
+ signal
+ )
+
+ return (result ?? []).filter(
+ (x: DatabaseActivity) => !x.query?.startsWith(sql)
+ ) as DatabaseActivity[]
+}
+
+export type DatabaseActivityData = Awaited<ReturnType<typeof getDatabaseActivity>>
+export type DatabaseActivityError = ResponseError
+
+export const useDatabaseActivityQuery = <TData = DatabaseActivityData>(
+ { projectRef, connectionString }: DatabaseActivityVariables,
+ {
+ enabled = true,
+ ...options
+ }: UseCustomQueryOptions<DatabaseActivityData, DatabaseActivityError, TData> = {}
+) =>
+ useQuery<DatabaseActivityData, DatabaseActivityError, TData>({
+ queryKey: databaseKeys.databaseActivity(projectRef),
+ queryFn: ({ signal }) => getDatabaseActivity({ projectRef, connectionString }, signal),
+ enabled: enabled && typeof projectRef !== 'undefined',
+ ...options,
+ })
diff --git a/apps/studio/data/database/keys.ts b/apps/studio/data/database/keys.ts
index 9a2b67d9aa6..b020ef61788 100644
--- a/apps/studio/data/database/keys.ts
+++ b/apps/studio/data/database/keys.ts
@@ -64,6 +64,8 @@ export const databaseKeys = {
) => ['projects', projectRef, 'table-index-advisor', schema, table] as const,
supamonitorEnabled: (projectRef: string | undefined) =>
['projects', projectRef, 'supamonitor-enabled'] as const,
+ databaseActivity: (projectRef: string | undefined) =>
+ ['projects', projectRef, 'database-activity'] as const,
}
export const getLiveTupleEstimateKey = (
diff --git a/apps/studio/pages/project/[ref]/observability/connections.tsx b/apps/studio/pages/project/[ref]/observability/connections.tsx
new file mode 100644
index 00000000000..96efd9538ca
--- /dev/null
+++ b/apps/studio/pages/project/[ref]/observability/connections.tsx
@@ -0,0 +1,55 @@
+import { Pause, Play } from 'lucide-react'
+import { useState } from 'react'
+import { Badge, Button, Tooltip, TooltipContent, TooltipTrigger } from 'ui'
+
+import { Activity } from '@/components/interfaces/Observability/DatabaseConnections/Activity'
+import ReportPadding from '@/components/interfaces/Reports/ReportPadding'
+import { DefaultLayout } from '@/components/layouts/DefaultLayout'
+import ObservabilityLayout from '@/components/layouts/ObservabilityLayout/ObservabilityLayout'
+import type { NextPageWithLayout } from '@/types'
+
+export const DatabaseConnections: NextPageWithLayout = () => {
+ const [live, setLive] = useState(true)
+
+ return (
+ <ReportPadding>
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-x-2">
+ <h1>Database Connections</h1>
+ {live && (
+ <Tooltip>
+ <TooltipTrigger>
+ <Badge variant="success">
+ <span className="h-1.5 w-1.5 bg-brand rounded-full animate-pulse" />
+ <span>Live</span>
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent side="bottom">
+ Data on this page is refreshed every 3 seconds
+ </TooltipContent>
+ </Tooltip>
+ )}
+ </div>
+ <div className="flex items-center gap-x-2">
+ <Button
+ variant={live ? 'default' : 'primary'}
+ onClick={() => setLive((prev) => !prev)}
+ icon={live ? <Pause /> : <Play />}
+ >
+ {live ? 'Pause' : 'Live'}
+ </Button>
+ </div>
+ </div>
+
+ <Activity live={live} />
+ </ReportPadding>
+ )
+}
+
+DatabaseConnections.getLayout = (page) => (
+ <DefaultLayout>
+ <ObservabilityLayout title="Database Connections">{page}</ObservabilityLayout>
+ </DefaultLayout>
+)
+
+export default DatabaseConnections
diff --git a/apps/studio/routeTree.gen.ts b/apps/studio/routeTree.gen.ts
index 92c65cbe685..8f8e52c4d4d 100644
--- a/apps/studio/routeTree.gen.ts
+++ b/apps/studio/routeTree.gen.ts
@@ -118,6 +118,7 @@ import { Route as ProjectRefObservabilityQueryInsightsRouteImport } from './rout
import { Route as ProjectRefObservabilityPostgrestRouteImport } from './routes/project/$ref/observability/postgrest'
import { Route as ProjectRefObservabilityEdgeFunctionsRouteImport } from './routes/project/$ref/observability/edge-functions'
import { Route as ProjectRefObservabilityDatabaseRouteImport } from './routes/project/$ref/observability/database'
+import { Route as ProjectRefObservabilityConnectionsRouteImport } from './routes/project/$ref/observability/connections'
import { Route as ProjectRefObservabilityAuthRouteImport } from './routes/project/$ref/observability/auth'
import { Route as ProjectRefObservabilityApiOverviewRouteImport } from './routes/project/$ref/observability/api-overview'
import { Route as ProjectRefObservabilityIdRouteImport } from './routes/project/$ref/observability/$id'
@@ -890,6 +891,12 @@ const ProjectRefObservabilityDatabaseRoute =
path: '/database',
getParentRoute: () => ProjectRefObservabilityRoute,
} as any)
+const ProjectRefObservabilityConnectionsRoute =
+ ProjectRefObservabilityConnectionsRouteImport.update({
+ id: '/connections',
+ path: '/connections',
+ getParentRoute: () => ProjectRefObservabilityRoute,
+ } as any)
const ProjectRefObservabilityAuthRoute =
ProjectRefObservabilityAuthRouteImport.update({
id: '/auth',
@@ -2178,6 +2185,7 @@ export interface FileRoutesByFullPath {
'/project/$ref/observability/$id': typeof ProjectRefObservabilityIdRoute
'/project/$ref/observability/api-overview': typeof ProjectRefObservabilityApiOverviewRoute
'/project/$ref/observability/auth': typeof ProjectRefObservabilityAuthRoute
+ '/project/$ref/observability/connections': typeof ProjectRefObservabilityConnectionsRoute
'/project/$ref/observability/database': typeof ProjectRefObservabilityDatabaseRoute
'/project/$ref/observability/edge-functions': typeof ProjectRefObservabilityEdgeFunctionsRoute
'/project/$ref/observability/postgrest': typeof ProjectRefObservabilityPostgrestRoute
@@ -2473,6 +2481,7 @@ export interface FileRoutesByTo {
'/project/$ref/observability/$id': typeof ProjectRefObservabilityIdRoute
'/project/$ref/observability/api-overview': typeof ProjectRefObservabilityApiOverviewRoute
'/project/$ref/observability/auth': typeof ProjectRefObservabilityAuthRoute
+ '/project/$ref/observability/connections': typeof ProjectRefObservabilityConnectionsRoute
'/project/$ref/observability/database': typeof ProjectRefObservabilityDatabaseRoute
'/project/$ref/observability/edge-functions': typeof ProjectRefObservabilityEdgeFunctionsRoute
'/project/$ref/observability/postgrest': typeof ProjectRefObservabilityPostgrestRoute
@@ -2781,6 +2790,7 @@ export interface FileRoutesById {
'/project/$ref/observability/$id': typeof ProjectRefObservabilityIdRoute
'/project/$ref/observability/api-overview': typeof ProjectRefObservabilityApiOverviewRoute
'/project/$ref/observability/auth': typeof ProjectRefObservabilityAuthRoute
+ '/project/$ref/observability/connections': typeof ProjectRefObservabilityConnectionsRoute
'/project/$ref/observability/database': typeof ProjectRefObservabilityDatabaseRoute
'/project/$ref/observability/edge-functions': typeof ProjectRefObservabilityEdgeFunctionsRoute
'/project/$ref/observability/postgrest': typeof ProjectRefObservabilityPostgrestRoute
@@ -3089,6 +3099,7 @@ export interface FileRouteTypes {
| '/project/$ref/observability/$id'
| '/project/$ref/observability/api-overview'
| '/project/$ref/observability/auth'
+ | '/project/$ref/observability/connections'
| '/project/$ref/observability/database'
| '/project/$ref/observability/edge-functions'
| '/project/$ref/observability/postgrest'
@@ -3384,6 +3395,7 @@ export interface FileRouteTypes {
| '/project/$ref/observability/$id'
| '/project/$ref/observability/api-overview'
| '/project/$ref/observability/auth'
+ | '/project/$ref/observability/connections'
| '/project/$ref/observability/database'
| '/project/$ref/observability/edge-functions'
| '/project/$ref/observability/postgrest'
@@ -3691,6 +3703,7 @@ export interface FileRouteTypes {
| '/project/$ref/observability/$id'
| '/project/$ref/observability/api-overview'
| '/project/$ref/observability/auth'
+ | '/project/$ref/observability/connections'
| '/project/$ref/observability/database'
| '/project/$ref/observability/edge-functions'
| '/project/$ref/observability/postgrest'
@@ -4735,6 +4748,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof ProjectRefObservabilityDatabaseRouteImport
parentRoute: typeof ProjectRefObservabilityRoute
}
+ '/project/$ref/observability/connections': {
+ id: '/project/$ref/observability/connections'
+ path: '/connections'
+ fullPath: '/project/$ref/observability/connections'
+ preLoaderRoute: typeof ProjectRefObservabilityConnectionsRouteImport
+ parentRoute: typeof ProjectRefObservabilityRoute
+ }
'/project/$ref/observability/auth': {
id: '/project/$ref/observability/auth'
path: '/auth'
@@ -6557,6 +6577,7 @@ interface ProjectRefObservabilityRouteChildren {
ProjectRefObservabilityIdRoute: typeof ProjectRefObservabilityIdRoute
ProjectRefObservabilityApiOverviewRoute: typeof ProjectRefObservabilityApiOverviewRoute
ProjectRefObservabilityAuthRoute: typeof ProjectRefObservabilityAuthRoute
+ ProjectRefObservabilityConnectionsRoute: typeof ProjectRefObservabilityConnectionsRoute
ProjectRefObservabilityDatabaseRoute: typeof ProjectRefObservabilityDatabaseRoute
ProjectRefObservabilityEdgeFunctionsRoute: typeof ProjectRefObservabilityEdgeFunctionsRoute
ProjectRefObservabilityPostgrestRoute: typeof ProjectRefObservabilityPostgrestRoute
@@ -6573,6 +6594,8 @@ const ProjectRefObservabilityRouteChildren: ProjectRefObservabilityRouteChildren
ProjectRefObservabilityApiOverviewRoute:
ProjectRefObservabilityApiOverviewRoute,
ProjectRefObservabilityAuthRoute: ProjectRefObservabilityAuthRoute,
+ ProjectRefObservabilityConnectionsRoute:
+ ProjectRefObservabilityConnectionsRoute,
ProjectRefObservabilityDatabaseRoute: ProjectRefObservabilityDatabaseRoute,
ProjectRefObservabilityEdgeFunctionsRoute:
ProjectRefObservabilityEdgeFunctionsRoute,
diff --git a/apps/studio/routes/project/$ref/observability/connections.tsx b/apps/studio/routes/project/$ref/observability/connections.tsx
new file mode 100644
index 00000000000..eebbb30806d
--- /dev/null
+++ b/apps/studio/routes/project/$ref/observability/connections.tsx
@@ -0,0 +1,14 @@
+import { createFileRoute } from '@tanstack/react-router'
+
+import DatabaseConnections from '@/pages/project/[ref]/observability/connections'
+
+export const Route = createFileRoute('/project/$ref/observability/connections')({
+ component: ObservabilityConnectionsRoute,
+ staticData: {
+ observabilityLayoutTitle: 'API Gateway',
+ },
+})
+
+function ObservabilityConnectionsRoute() {
+ return <DatabaseConnections dehydratedState={undefined} />
+}
diff --git a/packages/pg-meta/src/sql/studio/database/activity.ts b/packages/pg-meta/src/sql/studio/database/activity.ts
new file mode 100644
index 00000000000..6059b36d377
--- /dev/null
+++ b/packages/pg-meta/src/sql/studio/database/activity.ts
@@ -0,0 +1,23 @@
+import { safeSql, type SafeSqlFragment } from '../../../pg-format'
+
+export const getPgStatActivitySql = (): SafeSqlFragment => {
+ return safeSql`
+select
+ a.pid,
+ a.usename as role_name,
+ a.application_name,
+ a.state,
+ a.query,
+ a.wait_event_type,
+ a.wait_event,
+ a.xact_start as transaction_start,
+ a.query_start,
+ a.state_change,
+ pg_blocking_pids(a.pid) as blocked_by
+from pg_stat_activity a
+where a.datname = current_database()
+ and a.pid <> pg_backend_pid()
+ and a.backend_type = 'client backend'
+order by a.query_start asc nulls last;
+`
+}
diff --git a/packages/pg-meta/src/sql/studio/database/index.ts b/packages/pg-meta/src/sql/studio/database/index.ts
index 48e84d36ea3..f323bdcceb0 100644
--- a/packages/pg-meta/src/sql/studio/database/index.ts
+++ b/packages/pg-meta/src/sql/studio/database/index.ts
@@ -19,3 +19,4 @@ export * from './types'
export * from './vault'
export * from './views'
export * from './publications'
+export * from './activity'