The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Chore/linter v3 (#22842)
Terry Sutton8916d8022b87
diff --git a/apps/studio/components/interfaces/Linter/LintPageTabs.tsx b/apps/studio/components/interfaces/Linter/LintPageTabs.tsxnew file mode 100644index 00000000000..ae42b11687e--- /dev/null+++ b/apps/studio/components/interfaces/Linter/LintPageTabs.tsx@@ -0,0 +1,122 @@+import { MessageSquareMore } from 'lucide-react'++import { InformationCircleIcon } from '@heroicons/react/16/solid'++import {+ TabsList_Shadcn_,+ TabsTrigger_Shadcn_,+ Tabs_Shadcn_,+ TooltipContent_Shadcn_,+ TooltipTrigger_Shadcn_,+ Tooltip_Shadcn_,+ cn,+} from 'ui'++import { LINTER_LEVELS, LINT_TABS } from 'components/interfaces/Linter/Linter.constants'+import { Lint } from 'data/lint/lint-query'+import { useRouter } from 'next/router'+import { lintCountLabel } from './Linter.utils'++interface LintPageTabsProps {+ currentTab: string+ setCurrentTab: (value: LINTER_LEVELS) => void+ setSelectedLint: (value: Lint | null) => void+ setSelectedRow: (value: number | undefined) => void+ isLoading: boolean+ activeLints: Lint[]+}+const LintPageTabs = ({+ currentTab,+ setCurrentTab,+ setSelectedLint,+ setSelectedRow,+ isLoading,+ activeLints,+}: LintPageTabsProps) => {+ const router = useRouter()++ const warnLintsCount = activeLints.filter((x) => x.level === 'WARN').length+ const errorLintsCount = activeLints.filter((x) => x.level === 'ERROR').length+ const infoLintsCount = activeLints.filter((x) => x.level === 'INFO').length++ const LintCountLabel = ({ tab }: { tab: (typeof LINT_TABS)[number] }) => {+ const getCountLabel = () => {+ switch (tab.id) {+ case LINTER_LEVELS.ERROR:+ return lintCountLabel(isLoading, errorLintsCount, 'errors')+ case LINTER_LEVELS.WARN:+ return lintCountLabel(isLoading, warnLintsCount, 'warnings')+ case LINTER_LEVELS.INFO:+ return lintCountLabel(isLoading, infoLintsCount, 'suggestions')+ default:+ return null+ }+ }++ return (+ <span className="text-xs text-foreground-muted group-hover:text-foreground-lighter group-data-[state=active]:text-foreground-lighter transition">+ {getCountLabel()}+ </span>+ )+ }++ return (+ <Tabs_Shadcn_+ defaultValue={currentTab}+ onValueChange={(value) => {+ setCurrentTab(value as LINTER_LEVELS)+ setSelectedLint(null)+ setSelectedRow(undefined)+ const { sort, search, ...rest } = router.query+ router.push({ ...router, query: { ...rest, preset: value } })+ }}+ >+ <TabsList_Shadcn_ className={cn('flex gap-0 border-0 items-end z-10 relative')}>+ {LINT_TABS.map((tab) => (+ <TabsTrigger_Shadcn_+ key={tab.id}+ value={tab.id}+ className={cn(+ 'group relative',+ 'px-6 py-3 border-b-0 flex flex-col items-start !shadow-none border-default border-t',+ 'even:border-x last:border-r even:!border-x-strong last:!border-r-strong',+ tab.id === currentTab ? '!bg-surface-200' : '!bg-surface-200/[33%]',+ 'hover:!bg-surface-100',+ 'data-[state=active]:!bg-surface-200',+ 'hover:text-foreground-light',+ 'transition'+ )}+ >+ {tab.id === currentTab && (+ <div className="absolute top-0 left-0 w-full h-[1px] bg-foreground" />+ )}+ <div className="flex items-center gap-x-2">+ <span+ className={+ tab.id === LINTER_LEVELS.ERROR+ ? 'text-destructive-600'+ : tab.id === LINTER_LEVELS.WARN+ ? 'text-warning-600'+ : 'text-brand-500'+ }+ >+ <MessageSquareMore size={14} fill="currentColor" strokeWidth={0} />+ </span>++ <span className="">{tab.label}</span>+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild>+ <InformationCircleIcon className="transition text-foreground-muted w-3 h-3 data-[state=delayed-open]:text-foreground-light" />+ </TooltipTrigger_Shadcn_>+ <TooltipContent_Shadcn_ side="top">{tab.description}</TooltipContent_Shadcn_>+ </Tooltip_Shadcn_>+ </div>+ <LintCountLabel tab={tab} />+ </TabsTrigger_Shadcn_>+ ))}+ </TabsList_Shadcn_>+ </Tabs_Shadcn_>+ )+}++export default LintPageTabsdiff --git a/apps/studio/components/interfaces/Linter/Linter.constants.ts b/apps/studio/components/interfaces/Linter/Linter.constants.tsnew file mode 100644index 00000000000..c19aa38c748--- /dev/null+++ b/apps/studio/components/interfaces/Linter/Linter.constants.ts@@ -0,0 +1,33 @@+import { Lint } from 'data/lint/lint-query'+export enum LINTER_LEVELS {+ ERROR = 'ERROR',+ WARN = 'WARN',+ INFO = 'INFO',+}++export type LintInfo = {+ name: string+ title: string+ icon: JSX.Element+ link: (args: { projectRef: string; metadata: Lint['metadata'] }) => string+ linkText: string+ docsLink: string+}++export const LINT_TABS = [+ {+ id: LINTER_LEVELS.ERROR,+ label: 'Errors',+ description: 'You should consider these issues urgent and and fix them as soon as you can.',+ },+ {+ id: LINTER_LEVELS.WARN,+ label: 'Warnings ',+ description: 'You should try and read through these issues and fix them if necessary.',+ },+ {+ id: LINTER_LEVELS.INFO,+ label: 'Info ',+ description: 'You should read through these suggestions and consider implementing them.',+ },+]diff --git a/apps/studio/components/interfaces/Linter/Linter.utils.tsx b/apps/studio/components/interfaces/Linter/Linter.utils.tsxnew file mode 100644index 00000000000..53a26103806--- /dev/null+++ b/apps/studio/components/interfaces/Linter/Linter.utils.tsx@@ -0,0 +1,210 @@+import { LINT_TYPES, Lint } from 'data/lint/lint-query'+import { Box, Eye, Lock, Table2, Unlock, TextSearch } from 'lucide-react'+import Link from 'next/link'+import { Button, Badge } from 'ui'+import { LINTER_LEVELS, LintInfo } from 'components/interfaces/Linter/Linter.constants'+import ShimmeringLoader from 'ui-patterns/ShimmeringLoader'++export const lintInfoMap: LintInfo[] = [+ {+ name: 'unindexed_foreign_keys',+ title: 'Unindexed foreign keys',+ icon: <Table2 className="text-foreground-muted" size={15} strokeWidth={1} />,+ link: ({ projectRef, metadata }) =>+ `/project/${projectRef}/database/indexes?schema=${metadata?.schema}`,+ linkText: 'Create an index',+ docsLink:+ 'https://supabase.com/docs/guides/database/database-linter?queryGroups=lint&lint=0001_unindexed_foreign_keys',+ },+ {+ name: 'auth_users_exposed',+ title: 'Exposed Auth Users',+ icon: <Lock className="text-foreground-muted" size={15} strokeWidth={1.5} />,+ link: ({ projectRef }) => `/project/${projectRef}/editor`,+ linkText: 'View table',+ docsLink:+ 'https://supabase.com/docs/guides/database/database-linter?queryGroups=lint&lint=0002_auth_users_exposed',+ },+ {+ name: 'auth_rls_initplan',+ title: 'Auth RLS Initialization Plan',+ icon: <Table2 className="text-foreground-muted" size={15} strokeWidth={1} />,+ link: ({ projectRef }) => `/project/${projectRef}/auth/policies`,+ linkText: 'View policies',+ docsLink:+ 'https://supabase.com/docs/guides/database/database-linter?queryGroups=lint&lint=0003_auth_rls_initplan',+ },+ {+ name: 'no_primary_key',+ title: 'No Primary Key',+ icon: <Table2 className="text-foreground-muted" size={15} strokeWidth={1} />,+ link: ({ projectRef }) => `/project/${projectRef}/editor`,+ linkText: 'View table',+ docsLink:+ 'https://supabase.com/docs/guides/database/database-linter?queryGroups=lint&lint=0004_no_primary_key',+ },+ {+ name: 'unused_index',+ title: 'Unused Index',+ icon: <Table2 className="text-foreground-muted" size={15} strokeWidth={1} />,+ link: ({ projectRef, metadata }) =>+ `/project/${projectRef}/database/indexes?schema=${metadata?.schema}&table=${metadata?.name}`,+ linkText: 'View index',+ docsLink:+ 'https://supabase.com/docs/guides/database/database-linter?queryGroups=lint&lint=0005_unused_index',+ },+ {+ name: 'multiple_permissive_policies',+ title: 'Multiple Permissive Policies',+ icon: <Table2 className="text-foreground-muted" size={15} strokeWidth={1} />,+ link: ({ projectRef, metadata }) =>+ `/project/${projectRef}/auth/policies?schema=${metadata?.schema}&search=${metadata?.name}`,+ linkText: 'View policies',+ docsLink:+ 'https://supabase.com/docs/guides/database/database-linter?queryGroups=lint&lint=0006_multiple_permissive_policies',+ },+ {+ name: 'policy_exists_rls_disabled',+ title: 'Policy Exists RLS Disabled',+ icon: <Table2 className="text-foreground-muted" size={15} strokeWidth={1} />,+ link: ({ projectRef, metadata }) =>+ `/project/${projectRef}/auth/policies?schema=${metadata?.schema}&search=${metadata?.name}`,+ linkText: 'View policies',+ docsLink:+ 'https://supabase.com/docs/guides/database/database-linter?queryGroups=lint&lint=0007_policy_exists_rls_disabled',+ },+ {+ name: 'rls_enabled_no_policy',+ title: 'RLS Enabled No Policy',+ icon: <Table2 className="text-foreground-muted" size={15} strokeWidth={1} />,+ link: ({ projectRef, metadata }) =>+ `/project/${projectRef}/auth/policies?schema=${metadata?.schema}&search=${metadata?.name}`,+ linkText: 'View table',+ docsLink:+ 'https://supabase.com/docs/guides/database/database-linter?queryGroups=lint&lint=0008_rls_enabled_no_policy',+ },+ {+ name: 'duplicate_index',+ title: 'Duplicate Index',+ icon: <Table2 className="text-foreground-muted" size={15} strokeWidth={1} />,+ link: ({ projectRef, metadata }) =>+ `/project/${projectRef}/database/indexes?schema=${metadata?.schema}&table=${metadata?.name}`,+ linkText: 'View index',+ docsLink:+ 'https://supabase.com/docs/guides/database/database-linter?queryGroups=lint&lint=0009_duplicate_index',+ },+ {+ name: 'security_definer_view',+ title: 'Security Definer View',+ icon: <Eye className="text-foreground-muted" size={15} strokeWidth={1.5} />,+ link: () =>+ 'https://supabase.com/docs/guides/database/database-linter?queryGroups=lint&lint=0010_security_definer_view',+ linkText: 'View docs',+ docsLink:+ 'https://supabase.com/docs/guides/database/database-linter?queryGroups=lint&lint=0010_security_definer_view',+ },+ {+ name: 'function_search_path_mutable',+ title: 'Function Search Path Mutable',+ icon: <Table2 className="text-foreground-muted" size={15} strokeWidth={1} />,+ link: ({ projectRef, metadata }) =>+ `/project/${projectRef}/database/functions?schema=${metadata?.schema}&search=${metadata?.name}`,+ linkText: 'View functions',+ docsLink:+ 'https://supabase.com/docs/guides/database/database-linter?queryGroups=lint&lint=0011_function_search_path_mutable',+ },+ {+ name: 'rls_disabled_in_public',+ title: 'RLS Disabled in Public',+ icon: <Table2 className="text-foreground-muted" size={15} strokeWidth={1} />,+ link: ({ projectRef, metadata }) =>+ `/project/${projectRef}/auth/policies?schema=${metadata?.schema}&search=${metadata?.name}`,+ linkText: 'View policies',+ docsLink:+ 'https://supabase.com/docs/guides/database/database-linter?queryGroups=lint&lint=0013_rls_disabled_in_public',+ },++ {+ name: 'extension_in_public',+ title: 'Extension in Public',+ icon: <Unlock className="text-foreground-muted" size={15} strokeWidth={1} />,+ link: ({ projectRef, metadata }) =>+ `/project/${projectRef}/database/extensions?filter=${metadata?.name}`,+ linkText: 'View extension',+ docsLink:+ 'https://supabase.com/docs/guides/database/database-linter?queryGroups=lint&lint=0014_extension_in_public',+ },+]++export const LintCTA = ({+ title,+ projectRef,+ metadata,+}: {+ title: LINT_TYPES+ projectRef: string+ metadata: Lint['metadata']+}) => {+ const lintInfo = lintInfoMap.find((item) => item.name === title)++ if (!lintInfo) {+ return null+ }++ const link = lintInfo.link({ projectRef, metadata })+ const linkText = lintInfo.linkText++ return (+ <Button asChild type="default">+ <Link href={link} target="_blank" rel="noreferrer" className="no-underline">+ {linkText}+ </Link>+ </Button>+ )+}++export const entityTypeIcon = (type: string) => {+ switch (type) {+ case 'table':+ return <Table2 className="text-foreground-muted" size={15} strokeWidth={1} />+ case 'view':+ return <Eye className="text-foreground-muted" size={15} strokeWidth={1.5} />+ default:+ return <Box className="text-foreground-muted" size={15} strokeWidth={1.5} />+ }+}++export const LintCategoryBadge = ({ category }: { category: string }) => {+ return (+ <Badge variant={category === 'SECURITY' ? 'destructive' : 'warning'} className="capitalize">+ {category.toLowerCase()}+ </Badge>+ )+}++export const NoIssuesFound = ({ level }: { level: string }) => {+ const noun = level === LINTER_LEVELS.ERROR ? 'errors' : 'warnings'+ return (+ <div className="absolute top-28 px-6 flex flex-col items-center justify-center w-full gap-y-2">+ <TextSearch className="text-foreground-muted" strokeWidth={1} />+ <div className="text-center">+ <p className="text-foreground">No {noun} detected</p>+ <p className="text-foreground-light">+ Congrats! There are no {noun} detected for this database+ </p>+ </div>+ </div>+ )+}++export const lintCountLabel = (isLoading: boolean, count: number, label: string) => (+ <>+ {isLoading ? (+ <ShimmeringLoader className="w-20 pt-1" />+ ) : (+ <>+ {count} {label}+ </>+ )}+ </>+)diff --git a/apps/studio/components/interfaces/Linter/LinterDataGrid.tsx b/apps/studio/components/interfaces/Linter/LinterDataGrid.tsxnew file mode 100644index 00000000000..e9e11de109e--- /dev/null+++ b/apps/studio/components/interfaces/Linter/LinterDataGrid.tsx@@ -0,0 +1,275 @@+import { ExternalLink, Eye, Table2, X } from 'lucide-react'+import { NoIssuesFound, lintInfoMap } from 'components/interfaces/Linter/Linter.utils'+import DataGrid from 'react-data-grid'+import { Row, DataGridHandle, Column } from 'react-data-grid'+import {+ Button,+ ResizableHandle,+ ResizablePanel,+ ResizablePanelGroup,+ TabsContent_Shadcn_,+ TabsList_Shadcn_,+ TabsTrigger_Shadcn_,+ Tabs_Shadcn_,+ cn,+} from 'ui'+import { GenericSkeletonLoader } from 'ui-patterns'+import ReactMarkdown from 'react-markdown'+import { LintCTA, LintCategoryBadge, entityTypeIcon } from './Linter.utils'+import Link from 'next/link'+import { useRef, useState } from 'react'+import { Lint } from 'data/lint/lint-query'+import { LINTER_LEVELS } from 'components/interfaces/Linter/Linter.constants'+import { useParams } from 'common'++interface LinterDataGridProps {+ isLoading: boolean+ filteredLints: Lint[]+ selectedRow: number | undefined+ setSelectedRow: (value: number | undefined) => void+ selectedLint: Lint | null+ setSelectedLint: (value: Lint | null) => void+ currentTab: LINTER_LEVELS+}++const LinterDataGrid = ({+ isLoading,+ filteredLints,+ selectedRow,+ setSelectedRow,+ selectedLint,+ setSelectedLint,+ currentTab,+}: LinterDataGridProps) => {+ const gridRef = useRef<DataGridHandle>(null)+ const { ref } = useParams()++ const [view, setView] = useState<'details' | 'suggestion'>('details')++ const lintCols = [+ {+ id: 'name',+ name: 'Issue type',+ description: undefined,+ minWidth: 240,+ value: (row: any) => (+ <div className="flex items-center gap-1.5">+ <span className="shrink-0">+ {lintInfoMap.find((item) => row.name === item.name)?.icon}+ </span>+ {<h3 className="text-xs">{lintInfoMap.find((item) => row.name === item.name)?.title}</h3>}+ </div>+ ),+ },+ {+ id: 'metadata.name',+ name: 'Entity/item',+ description: undefined,+ minWidth: 230,+ value: (row: any) => (+ <div className="flex items-center gap-1 text-xs">+ <span className="shrink-0">{entityTypeIcon(row.metadata?.type)}</span>+ {`${row.metadata.schema}.${row.metadata.name}`}+ </div>+ ),+ },+ {+ id: 'description',+ name: 'Description',+ description: undefined,+ minWidth: 400,+ value: (row: any) => <ReactMarkdown className="text-xs">{row.description}</ReactMarkdown>,+ },+ ]++ const columns = lintCols.map((col) => {+ const result: Column<any> = {+ key: col.id,+ name: col.name,+ resizable: true,+ minWidth: col.minWidth ?? 120,+ headerCellClass: 'first:pl-6 cursor-pointer',+ renderHeaderCell: () => {+ return (+ <div className="flex items-center justify-between font-mono font-normal text-xs w-full">+ <div className="flex items-center gap-x-2">+ <p className="!text-foreground">{col.name}</p>+ {col.description && <p className="text-foreground-lighter">{col.description}</p>}+ </div>+ </div>+ )+ },+ renderCell: (props) => {+ const value = col.value(props.row)++ return (+ <div+ className={cn(+ 'w-full flex flex-col justify-center font-mono text-xs',+ typeof value === 'number' ? 'text-right' : ''+ )}+ >+ <span>{value}</span>+ </div>+ )+ },+ }+ return result+ })++ return (+ <ResizablePanelGroup+ direction="horizontal"+ className="relative flex flex-grow bg-alternative min-h-0"+ autoSaveId="linter-layout-v1"+ >+ <ResizablePanel defaultSize={1}>+ <DataGrid+ ref={gridRef}+ style={{ height: '100%' }}+ className={cn('flex-1 flex-grow h-full')}+ rowHeight={44}+ headerRowHeight={36}+ columns={columns}+ rows={filteredLints ?? []}+ rowClass={(_, idx) => {+ const isSelected = idx === selectedRow+ return [+ `${isSelected ? 'bg-surface-300 dark:bg-surface-300' : 'bg-200'} cursor-pointer`,+ `${isSelected ? '[&>div:first-child]:border-l-4 border-l-secondary [&>div]:border-l-foreground' : ''}`,+ '[&>.rdg-cell]:border-box [&>.rdg-cell]:outline-none [&>.rdg-cell]:shadow-none',+ '[&>.rdg-cell:first-child>div]:ml-4',+ ].join(' ')+ }}+ renderers={{+ renderRow(idx, props) {+ return (+ <Row+ {...props}+ onClick={() => {+ if (typeof idx === 'number' && idx >= 0) {+ setSelectedRow(idx)+ setSelectedLint(props.row)+ gridRef.current?.scrollToCell({ idx: 0, rowIdx: idx })+ }+ }}+ />+ )+ },+ noRowsFallback: isLoading ? (+ <div className="absolute top-14 px-6 w-full">+ <GenericSkeletonLoader />+ </div>+ ) : (+ <NoIssuesFound level={currentTab} />+ ),+ }}+ />+ </ResizablePanel>+ {selectedLint !== null && (+ <>+ <ResizableHandle withHandle />+ <ResizablePanel defaultSize={30} maxSize={45} minSize={30} className="bg-studio border-t">+ <Button+ type="text"+ className="absolute top-3 right-3 px-1"+ icon={<X size={14} />}+ onClick={() => {+ setSelectedLint(null)+ setSelectedRow(undefined)+ }}+ />++ <Tabs_Shadcn_+ value={view}+ className="flex flex-col h-full"+ onValueChange={(value: any) => {+ setView(value)+ }}+ >+ <TabsList_Shadcn_ className="px-5 flex gap-x-4 min-h-[46px]">+ <TabsTrigger_Shadcn_+ value="details"+ className="px-0 pb-0 h-full text-xs data-[state=active]:bg-transparent !shadow-none"+ >+ Overview+ </TabsTrigger_Shadcn_>+ </TabsList_Shadcn_>+ <TabsContent_Shadcn_+ value="details"+ className="mt-0 flex-grow min-h-0 overflow-y-auto prose"+ >+ {selectedLint && (+ <div className="py-4 px-5">+ <div className="flex items-center gap-2 py-2">+ <h3 className="text-sm m-0">+ {lintInfoMap.find((item) => item.name === selectedLint.name)?.title}+ </h3>+ <LintCategoryBadge category={selectedLint.categories[0]} />+ </div>+ <div className="flex items-center gap-2 text-sm mt-4">+ <span>Entity</span>+ <div className="flex items-center gap-1 px-2 py-0.5 bg-surface-200 border rounded-lg ">+ {selectedLint.metadata?.type === 'table' && (+ <Table2 className="text-foreground-muted" size={15} strokeWidth={1} />+ )}+ {selectedLint.metadata?.type === 'view' && (+ <Eye className="text-foreground-muted" size={15} strokeWidth={1.5} />+ )}{' '}+ {`${selectedLint.metadata?.schema}.${selectedLint.metadata?.name}`}+ </div>+ </div>++ <div className="grid">+ <div>+ <h3 className="text-sm">Issue</h3>+ <ReactMarkdown className="leading-6 text-sm">+ {selectedLint.detail}+ </ReactMarkdown>+ </div>+ <div>+ <h3 className="text-sm">Description</h3>+ <ReactMarkdown className="text-sm">+ {selectedLint.description}+ </ReactMarkdown>+ </div>++ <div className="grid gap-2">+ <h3 className="text-sm">Resolve</h3>+ <div className="flex items-center gap-2">+ <LintCTA+ title={selectedLint.name}+ projectRef={ref!}+ metadata={selectedLint.metadata}+ />+ <Button asChild type="text">+ <Link+ href={+ lintInfoMap.find((item) => item.name === selectedLint.name)+ ?.docsLink ||+ 'https://supabase.com/docs/guides/database/database-linter'+ }+ target="_blank"+ rel="noreferrer"+ className="no-underline"+ >+ <span className="flex items-center gap-2">+ Learn more <ExternalLink size={14} />+ </span>+ </Link>+ </Button>+ </div>+ </div>+ </div>+ </div>+ )}+ </TabsContent_Shadcn_>+ </Tabs_Shadcn_>+ </ResizablePanel>+ </>+ )}+ </ResizablePanelGroup>+ )+}++export default LinterDataGriddiff --git a/apps/studio/components/interfaces/Linter/LinterFilters.tsx b/apps/studio/components/interfaces/Linter/LinterFilters.tsxnew file mode 100644index 00000000000..e1c9dc73003--- /dev/null+++ b/apps/studio/components/interfaces/Linter/LinterFilters.tsx@@ -0,0 +1,52 @@+import { LINTER_LEVELS, LINT_TABS } from 'components/interfaces/Linter/Linter.constants'+import { FilterPopover } from 'components/ui/FilterPopover'+import { Lint } from 'data/lint/lint-query'++interface LinterFiltersProps {+ filterOptions: {+ name: string+ value: string+ }[]+ activeLints: Lint[]+ currentTab: LINTER_LEVELS+ filters: { level: LINTER_LEVELS; filters: string[] }[]+ setFilters: (value: { level: LINTER_LEVELS; filters: string[] }[]) => void+}++const LinterFilters = ({+ filterOptions,+ activeLints,+ currentTab,+ filters,+ setFilters,+}: LinterFiltersProps) => {+ const updateFilters = (level: LINTER_LEVELS, newFilters: string[]) => {+ const updatedFilters = [...filters]++ const index = updatedFilters.findIndex((filter) => filter.level === level)+ if (index !== -1) {+ updatedFilters[index] = { ...updatedFilters[index], filters: newFilters }+ setFilters(updatedFilters)+ }+ }++ return (+ <div className="bg-surface-200 p-2 px-6 py-2 border-t -mt-px">+ {LINT_TABS.map((tab) => (+ <div key={tab.id} className={tab.id === currentTab ? '' : 'hidden'}>+ <FilterPopover+ name="Filter"+ options={filterOptions}+ disabled={activeLints.filter((x) => x.level === currentTab).length === 0}+ labelKey="name"+ valueKey="value"+ activeOptions={filters.find((filter) => filter.level === currentTab)?.filters || []}+ onSaveFilters={(values) => updateFilters(currentTab, values)}+ />+ </div>+ ))}+ </div>+ )+}++export default LinterFiltersdiff --git a/apps/studio/components/interfaces/Linter/LinterPageFooter.tsx b/apps/studio/components/interfaces/Linter/LinterPageFooter.tsxnew file mode 100644index 00000000000..119c064c91c--- /dev/null+++ b/apps/studio/components/interfaces/Linter/LinterPageFooter.tsx@@ -0,0 +1,40 @@+import { Button } from 'ui'+import { Markdown } from '../Markdown'++interface LinterPageFooterProps {+ isLoading: boolean+ isRefetching: boolean+ refetch: () => void+}++const LinterPageFooter = ({ isLoading, isRefetching, refetch }: LinterPageFooterProps) => {+ return (+ <div className="px-6 py-6 flex gap-x-4 border-t ">+ <div className="w-[35%] flex flex-col gap-y-1 text-sm">+ <p>Reset suggestions</p>+ <p className="text-xs text-foreground-light">+ Consider resetting the analysis making any changes+ </p>++ <Button+ type="default"+ className="!mt-3 w-min"+ disabled={isLoading || isRefetching}+ loading={isLoading || isRefetching}+ onClick={() => refetch()}+ >+ Rerun linter+ </Button>+ </div>+ <div className="w-[35%] flex flex-col gap-y-1 text-sm">+ <p>How are these suggestions generated?</p>+ <Markdown+ className="text-xs"+ content="These suggestions use [splinter (Supabase Postgres LINTER)](https://github.com/supabase/splinter)."+ />+ </div>+ </div>+ )+}++export default LinterPageFooterdiff --git a/apps/studio/components/interfaces/Reports/ReportLints.utils.tsx b/apps/studio/components/interfaces/Reports/ReportLints.utils.tsxdeleted file mode 100644index 106f2337eda..00000000000--- a/apps/studio/components/interfaces/Reports/ReportLints.utils.tsx+++ /dev/null@@ -1,268 +0,0 @@-import { LINT_TYPES, Lint } from 'data/lint/lint-query'-import { AlertCircle, Box, Eye, Key, Lock, Table2, Unlock } from 'lucide-react'-import Link from 'next/link'-import { Button } from 'ui'--const assertUnreachable = (n: never) => {- console.error('Unhandled lint type', n)-}--interface LintInfo {- title: string- icon: JSX.Element-}--export const lintInfoMap = [- {- name: 'unindexed_foreign_keys',- title: 'Unindexed foreign keys',- icon: <Table2 className="text-foreground-muted" size={15} strokeWidth={1} />,- },- {- name: 'auth_users_exposed',- title: 'Exposed Auth Users',- icon: <Lock className="text-foreground-muted" size={15} strokeWidth={1.5} />,- },- {- name: 'auth_rls_initplan',- title: 'Auth RLS Initialization Plan',- icon: <Table2 className="text-foreground-muted" size={15} strokeWidth={1} />,- },- {- name: 'no_primary_key',- title: 'No Primary Key',- icon: <Table2 className="text-foreground-muted" size={15} strokeWidth={1} />,- },- {- name: 'unused_index',- title: 'Unused Index',- icon: <Table2 className="text-foreground-muted" size={15} strokeWidth={1} />,- },- {- name: 'multiple_permissive_policies',- title: 'Multiple Permissive Policies',- icon: <Table2 className="text-foreground-muted" size={15} strokeWidth={1} />,- },- {- name: 'function_search_path_mutable',- title: 'Function Search Path Mutable',- icon: <Table2 className="text-foreground-muted" size={15} strokeWidth={1} />,- },- {- name: 'rls_enabled_no_policy',- title: 'RLS Enabled No Policy',- icon: <Table2 className="text-foreground-muted" size={15} strokeWidth={1} />,- },- {- name: 'policy_exists_rls_disabled',- title: 'Policy Exists RLS Disabled',- icon: <Table2 className="text-foreground-muted" size={15} strokeWidth={1} />,- },- {- name: 'rls_disabled_in_public',- title: 'RLS Disabled in Public',- icon: <Table2 className="text-foreground-muted" size={15} strokeWidth={1} />,- },- {- name: 'security_definer_view',- title: 'Security Definer View',- icon: <Eye className="text-foreground-muted" size={15} strokeWidth={1.5} />,- },- {- name: 'duplicate_index',- title: 'Duplicate Index',- icon: <Table2 className="text-foreground-muted" size={15} strokeWidth={1} />,- },- {- name: 'extension_in_public',- title: 'Extension in Public',- icon: <Unlock className="text-foreground-muted" size={15} strokeWidth={1} />,- },-]--export const LintCTA = ({- title,- projectRef,- metadata,-}: {- title: LINT_TYPES- projectRef: string- metadata: Lint['metadata']-}) => {- switch (title) {- case 'unindexed_foreign_keys':- return (- <Button asChild type="default">- <Link- href={`/project/${projectRef}/database/indexes?schema=${metadata?.schema}`}- target="_blank"- rel="noreferrer"- className="no-underline"- >- Create an index- </Link>- </Button>- )-- case 'auth_users_exposed':- return (- <Button asChild type="default">- <Link- href={`/project/${projectRef}/editor`}- target="_blank"- rel="noreferrer"- className="no-underline"- >- View table- </Link>- </Button>- )- case 'auth_rls_initplan':- return (- <Button asChild type="default">- <Link- href={`/project/${projectRef}/auth/policies`}- target="_blank"- rel="noreferrer"- className="no-underline"- >- View policies- </Link>- </Button>- )- case 'no_primary_key':- return (- <Button asChild type="default">- <Link- href={`/project/${projectRef}/editor`}- target="_blank"- rel="noreferrer"- className="no-underline"- >- View table- </Link>- </Button>- )- case 'unused_index':- return (- <Button asChild type="default">- <Link- href={`/project/${projectRef}/database/indexes?schema=${metadata?.schema}&table=${metadata?.name}`}- target="_blank"- rel="noreferrer"- className="no-underline"- >- View index- </Link>- </Button>- )- case 'duplicate_index':- return (- <Button asChild type="default">- <Link- href={`/project/${projectRef}/database/indexes?schema=${metadata?.schema}&table=${metadata?.name}`}- target="_blank"- rel="noreferrer"- className="no-underline"- >- View index- </Link>- </Button>- )- case 'multiple_permissive_policies':- return (- <Button asChild type="default">- <Link- href={`/project/${projectRef}/auth/policies?schema=${metadata?.schema}&search=${metadata?.name}`}- target="_blank"- rel="noreferrer"- className="no-underline"- >- View policies- </Link>- </Button>- )- case 'function_search_path_mutable':- return (- <Button asChild type="default">- <Link- href={`/project/${projectRef}/database/functions?schema=${metadata?.schema}&search=${metadata?.name}`}- target="_blank"- rel="noreferrer"- className="no-underline"- >- View functions- </Link>- </Button>- )- case 'rls_enabled_no_policy':- return (- <Button asChild type="default">- <Link- href={`/project/${projectRef}/auth/policies?schema=${metadata?.schema}&search=${metadata?.name}`}- target="_blank"- rel="noreferrer"- className="no-underline"- >- View policies- </Link>- </Button>- )- case 'policy_exists_rls_disabled':- return (- <Button asChild type="default">- <Link- href={`/project/${projectRef}/auth/policies?schema=${metadata?.schema}&search=${metadata?.name}`}- target="_blank"- rel="noreferrer"- className="no-underline"- >- View policies- </Link>- </Button>- )- case 'rls_disabled_in_public':- return (- <Button asChild type="default">- <Link- href={`/project/${projectRef}/auth/policies?schema=${metadata?.schema}&search=${metadata?.name}`}- target="_blank"- rel="noreferrer"- className="no-underline"- >- View policies- </Link>- </Button>- )- case 'security_definer_view':- // we don't have a good place to send the user to check out a view- return <></>- case 'extension_in_public':- return (- <Button asChild type="default">- <Link- href={`/project/${projectRef}/database/extensions?filter=${metadata?.name}`}- target="_blank"- rel="noreferrer"- className="no-underline"- >- View extension- </Link>- </Button>- )- default:- assertUnreachable(title)- return <></>- }-}--export const entityTypeIcon = (type: string) => {- switch (type) {- case 'table':- return <Table2 className="text-foreground-muted" size={15} strokeWidth={1} />- case 'view':- return <Eye className="text-foreground-muted" size={15} strokeWidth={1.5} />- default:- return <Box className="text-foreground-muted" size={15} strokeWidth={1.5} />- }-}diff --git a/apps/studio/components/layouts/DatabaseLayout/DatabaseMenu.utils.tsx b/apps/studio/components/layouts/DatabaseLayout/DatabaseMenu.utils.tsxindex 668f20bb770..b967be91515 100644--- a/apps/studio/components/layouts/DatabaseLayout/DatabaseMenu.utils.tsx+++ b/apps/studio/components/layouts/DatabaseLayout/DatabaseMenu.utils.tsx@@ -137,9 +137,15 @@ export const generateDatabaseMenu = (items: [],},{- name: 'Database Linter',- key: 'linter',- url: `/project/${ref}/database/linter`,+ name: 'Security Advisor',+ key: 'security-advisor',+ url: `/project/${ref}/database/security-advisor`,+ items: [],+ },+ {+ name: 'Performance Advisor',+ key: 'performance-advisor',+ url: `/project/${ref}/database/performance-advisor`,items: [],},],diff --git a/apps/studio/components/ui/FilterPopover.tsx b/apps/studio/components/ui/FilterPopover.tsxindex 3bf02b2dc31..390f897715c 100644--- a/apps/studio/components/ui/FilterPopover.tsx+++ b/apps/studio/components/ui/FilterPopover.tsx@@ -9,11 +9,9 @@ interface FilterPopoverProps {name: stringvariant?: 'rectangular' | 'rounded'onSaveFilters: (options: string[]) => void+ disabled?: boolean}-// [Joshen] Form + Checkbox.Group doesn't seem to work properly RE form state-// hence why the manual implementation here as a workaround-export const FilterPopover = ({options = [],activeOptions = [],@@ -22,6 +20,7 @@ export const FilterPopover = ({name,variant = 'rectangular',onSaveFilters,+ disabled,}: FilterPopoverProps) => {const [open, setOpen] = useState(false)const [selectedOptions, setSelectedOptions] = useState<string[]>([])@@ -35,6 +34,7 @@ export const FilterPopover = ({<Popoverside="bottom"align="start"+ disabled={disabled}open={open}onOpenChange={() => setOpen(!open)}header={<div className="prose text-xs">Select {name.toLowerCase()}</div>}diff --git a/apps/studio/data/lint/lint-query.ts b/apps/studio/data/lint/lint-query.tsindex 6cdcfcaa574..162c26b4388 100644--- a/apps/studio/data/lint/lint-query.ts+++ b/apps/studio/data/lint/lint-query.ts@@ -2,7 +2,9 @@ import { UseQueryOptions, useQuery } from '@tanstack/react-query'import { executeSql } from '../sql/execute-sql-query'import { lintKeys } from './keys'-export const LINT_SQL = `(+export const LINT_SQL = `set local search_path = '';++(with foreign_keys as (selectcl.relnamespace::regnamespace as schema_,@@ -38,6 +40,7 @@ select'unindexed_foreign_keys' as name,'INFO' as level,'EXTERNAL' as facing,+ array['PERFORMANCE'] as categories,'Identifies foreign key constraints without a covering index, which can impact database performance.' as description,format('Table \`%s.%s\` has a foreign key \`%s\` without a covering index. This can lead to suboptimal query performance.',@@ -77,6 +80,7 @@ select'auth_users_exposed' as name,'WARN' as level,'EXTERNAL' as facing,+ array['SECURITY'] as categories,'Detects if auth.users is exposed to anon or authenticated roles via a view or materialized view in the public schema, potentially compromising user data security.' as description,format('View/Materialized View "%s" in the public schema may expose \`auth.users\` data to anon or authenticated roles.',@@ -92,14 +96,14 @@ selectformat('auth_users_exposed_%s_%s', 'public', c.relname) as cache_keyfrom-- Identify the oid for auth.users- pg_catalog.pg_class auth_users_pg_class+ pg_catalog.pg_class auth_users_pg_classjoin pg_catalog.pg_namespace auth_users_pg_namespace- on auth_users_pg_class.relnamespace = auth_users_pg_namespace.oid- and auth_users_pg_class.relname = 'users'- and auth_users_pg_namespace.nspname = 'auth'- -- Depends on auth.users+ on auth_users_pg_class.relnamespace = auth_users_pg_namespace.oid+ and auth_users_pg_class.relname = 'users'+ and auth_users_pg_namespace.nspname = 'auth'+ -- Depends on auth.usersjoin pg_catalog.pg_depend d- on d.refobjid = auth_users_pg_class.oid+ on d.refobjid = auth_users_pg_class.oidjoin pg_catalog.pg_rewrite ron r.oid = d.objidjoin pg_catalog.pg_class c@@ -217,9 +221,10 @@ select'auth_rls_initplan' as name,'WARN' as level,'EXTERNAL' as facing,+ array['PERFORMANCE'] as categories,'Detects if calls to \`auth.<function>()\` in RLS policies are being unnecessarily re-evaluated for each row' as description,format(- 'Table \`%s\` has a row level security policy \`%s\` that re-evaluates an auth.<function>() for each row. This produces suboptimal query performance at scale. Resolve the issue by replacing \`auth.<function>()\` with \`(select auth.<function>())\`. See https://supabase.com/docs/guides/database/postgres/row-level-security#call-functions-with-select for more.',+ 'Table \`%s\` has a row level security policy \`%s\` that re-evaluates an auth.<function>() for each row. This produces suboptimal query performance at scale. Resolve the issue by replacing \`auth.<function>()\` with \`(select auth.<function>())\`. See [docs](https://supabase.com/docs/guides/database/postgres/row-level-security#call-functions-with-select) for more info.',table_,policy_name) as detail,@@ -240,16 +245,16 @@ whereand ((-- Example: auth.uid()- qual ~ '(auth)\\.(uid|jwt|role|email)\\(\\)'+ qual ~ '(auth)\.(uid|jwt|role|email)\(\)'-- Example: select auth.uid()- and lower(qual) !~ 'select\\s+(auth)\\.(uid|jwt|role|email)\\(\\)'+ and lower(qual) !~ 'select\s+(auth)\.(uid|jwt|role|email)\(\)')or(-- Example: auth.uid()- with_check ~ '(auth)\\.(uid|jwt|role|email)\\(\\)'+ with_check ~ '(auth)\.(uid|jwt|role|email)\(\)'-- Example: select auth.uid()- and lower(with_check) !~ 'select\\s+(auth)\\.(uid|jwt|role|email)\\(\\)'+ and lower(with_check) !~ 'select\s+(auth)\.(uid|jwt|role|email)\(\)')))union all@@ -258,6 +263,7 @@ select'no_primary_key' as name,'INFO' as level,'EXTERNAL' as facing,+ array['PERFORMANCE'] as categories,'Detects if a table does not have a primary key. Tables without a primary key can be inefficient to interact with at scale.' as description,format('Table \`%s.%s\` does not have a primary key',@@ -265,7 +271,7 @@ selectpgc.relname) as detail,'https://supabase.com/docs/guides/database/database-linter?lint=0004_no_primary_key' as remediation,- jsonb_build_object(+ jsonb_build_object('schema', pgns.nspname,'name', pgc.relname,'type', 'table'@@ -302,6 +308,7 @@ select'unused_index' as name,'INFO' as level,'EXTERNAL' as facing,+ array['PERFORMANCE'] as categories,'Detects if an index has never been used and may be a candidate for removal.' as description,format('Index \`%s\` on table \`%s.%s\` has not been used',@@ -343,6 +350,7 @@ select'multiple_permissive_policies' as name,'WARN' as level,'EXTERNAL' as facing,+ array['PERFORMANCE'] as categories,'Detects if multiple permissive row level security policies are present on a table for the same \`role\` and \`action\` (e.g. insert). Multiple permissive policies are suboptimal for performance as each policy must be executed for every relevant query.' as description,format('Table \`%s.%s\` has multiple permissive policies for role \`%s\` for action \`%s\`. Policies include \`%s\`',@@ -413,6 +421,7 @@ select'policy_exists_rls_disabled' as name,'INFO' as level,'EXTERNAL' as facing,+ array['SECURITY'] as categories,'Detects cases where row level security (RLS) policies have been created, but RLS has not been enabled for the underlying table.' as description,format('Table \`%s.%s\` has RLS policies but RLS is not enabled on the table. Policies include %s.',@@ -457,6 +466,7 @@ select'rls_enabled_no_policy' as name,'INFO' as level,'EXTERNAL' as facing,+ array['SECURITY'] as categories,'Detects cases where row level security (RLS) has been enabled on a table but no RLS policies have been created.' as description,format('Table \`%s.%s\` has RLS enabled, but no policies exist',@@ -501,6 +511,7 @@ select'duplicate_index' as name,'WARN' as level,'EXTERNAL' as facing,+ array['PERFORMANCE'] as categories,'Detects cases where two ore more identical indexes exist.' as description,format('Table \`%s.%s\` has identical indexes %s. Drop all except one of them',@@ -554,6 +565,7 @@ select'security_definer_view' as name,'WARN' as level,'EXTERNAL' as facing,+ array['SECURITY'] as categories,'Detects views that are SECURITY DEFINER meaning that they ignore row level security (RLS) policies.' as description,format('View \`%s.%s\` is SECURITY DEFINER',@@ -582,21 +594,22 @@ wherec.relkind = 'v'and n.nspname = 'public'and dep.objid is null -- exclude views owned by extensions- and not (- lower(coalesce(c.reloptions::text,'{}'))::text[]- && array[- 'security_invoker=1',- 'security_invoker=true',- 'security_invoker=yes',- 'security_invoker=on'- ]- ))+ and not (+ lower(coalesce(c.reloptions::text,'{}'))::text[]+ && array[+ 'security_invoker=1',+ 'security_invoker=true',+ 'security_invoker=yes',+ 'security_invoker=on'+ ]+ ))union all(select'function_search_path_mutable' as name,'WARN' as level,'EXTERNAL' as facing,+ array['SECURITY'] as categories,'Detects functions with a mutable search_path parameter which could fail to execute successfully for some roles.' as description,format('Function \`%s.%s\` has a role mutable search_path',@@ -635,6 +648,7 @@ select'rls_disabled_in_public' as name,'ERROR' as level,'EXTERNAL' as facing,+ array['SECURITY'] as categories,'Detects cases where row level security (RLS) has not been enabled on a table in the \`public\` schema.' as description,format('Table \`%s.%s\` is public, but RLS has not been enabled.',@@ -667,6 +681,7 @@ select'extension_in_public' as name,'WARN' as level,'EXTERNAL' as facing,+ array['SECURITY'] as categories,'Detects extensions installed in the \`public\` schema.' as description,format('Extension \`%s\` is installed in the public schema. Move it to another schema.',@@ -713,6 +728,7 @@ export type Lint = {name: LINT_TYPESlevel: 'ERROR' | 'WARN' | 'INFO'facing: string+ categories: ['PERFORMANCE' | 'SECURITY']description: stringdetail: stringremediation: any@@ -744,6 +760,7 @@ const getProjectLints = async (},signal)+return result}diff --git a/apps/studio/pages/project/[ref]/database/linter.tsx b/apps/studio/pages/project/[ref]/database/linter.tsxdeleted file mode 100644index ef2d6d39a90..00000000000--- a/apps/studio/pages/project/[ref]/database/linter.tsx+++ /dev/null@@ -1,470 +0,0 @@-import { Eye, MessageSquareMore, Table2, TextSearch, X } from 'lucide-react'-import { useRef, useState } from 'react'--import { InformationCircleIcon } from '@heroicons/react/16/solid'-import { useParams } from 'common'--import { lintInfoMap } from 'components/interfaces/Reports/ReportLints.utils'-import { DatabaseLayout } from 'components/layouts'-import { FormHeader } from 'components/ui/Forms'-import { Lint, useProjectLintsQuery } from 'data/lint/lint-query'-import { useSelectedProject } from 'hooks'-import { useRouter } from 'next/router'-import DataGrid, { Column, DataGridHandle, Row } from 'react-data-grid'-import type { NextPageWithLayout } from 'types'-import {- Button,- LoadingLine,- ResizableHandle,- ResizablePanel,- ResizablePanelGroup,- TabsContent_Shadcn_,- TabsList_Shadcn_,- TabsTrigger_Shadcn_,- Tabs_Shadcn_,- TooltipContent_Shadcn_,- TooltipTrigger_Shadcn_,- Tooltip_Shadcn_,- cn,-} from 'ui'-import { GenericSkeletonLoader } from 'ui-patterns'--import { FilterPopover } from 'components/ui/FilterPopover'-import ReactMarkdown from 'react-markdown'-import ShimmeringLoader from 'ui-patterns/ShimmeringLoader'-import { Markdown } from '../../../../components/interfaces/Markdown'-import {- LintCTA,- entityTypeIcon,-} from '../../../../components/interfaces/Reports/ReportLints.utils'--enum LINTER_LEVELS {- ERROR = 'ERROR',- WARN = 'WARN',- INFO = 'INFO',-}--const LINT_TABS = [- {- id: LINTER_LEVELS.ERROR,- label: 'Errors',- description: 'You should consider these issues urgent and and fix them as soon as you can.',- },- {- id: LINTER_LEVELS.WARN,- label: 'Warnings ',- description: 'You should try and read through these issues and fix them if necessary.',- },- {- id: LINTER_LEVELS.INFO,- label: 'Info ',- description: 'You should read through these suggestions and consider implementing them.',- },-]--const ProjectLints: NextPageWithLayout = () => {- const project = useSelectedProject()- const router = useRouter()- const { ref } = useParams()- const gridRef = useRef<DataGridHandle>(null)- const { preset } = useParams()-- // need to maintain a list of filters for each tab- const [filters, setFilters] = useState([- { level: LINTER_LEVELS.ERROR, filters: [] },- { level: LINTER_LEVELS.WARN, filters: [] },- { level: LINTER_LEVELS.INFO, filters: [] },- ])-- const [currentTab, setCurrentTab] = useState<LINTER_LEVELS>(- (preset as LINTER_LEVELS) ?? LINTER_LEVELS.ERROR- )- const [selectedRow, setSelectedRow] = useState<number>()- const [selectedLint, setSelectedLint] = useState<Lint | null>(null)- const [view, setView] = useState<'details' | 'suggestion'>('details')-- const { data, isLoading, isRefetching, refetch } = useProjectLintsQuery({- projectRef: project?.ref,- connectionString: project?.connectionString,- })-- const activeLints = data || []-- const currentTabFilters = (filters.find((filter) => filter.level === currentTab)?.filters ||- []) as string[]-- const filteredLints = activeLints- .filter((x) => x.level === currentTab)- .filter((x) => (currentTabFilters.length > 0 ? currentTabFilters.includes(x.name) : x))-- const warnLintsCount = activeLints.filter((x) => x.level === 'WARN').length- const errorLintsCount = activeLints.filter((x) => x.level === 'ERROR').length- const infoLintsCount = activeLints.filter((x) => x.level === 'INFO').length-- const filterOptions = lintInfoMap- // only show filters for lint types which are present in the results and not ignored- .filter((item) =>- activeLints.some((lint) => lint.name === item.name && lint.level === currentTab)- )- .map((type) => ({- name: type.title,- value: type.name,- }))-- const updateFilters = (level: any, newFilters: any) => {- // Create a copy of the current filters state- const updatedFilters = [...filters]- // Find the index of the filter object corresponding to the provided level- const index = updatedFilters.findIndex((filter) => filter.level === level)- if (index !== -1) {- // Update the filters array at the found index with the new filters- updatedFilters[index] = { ...updatedFilters[index], filters: newFilters }- // Update the filters state with the updated array- setFilters(updatedFilters)- }- }-- const lintCountLabel = (count: number, label: string) => (- <>- {isLoading ? (- <ShimmeringLoader className="w-20 pt-1" />- ) : (- <>- {count} {label}- </>- )}- </>- )-- const lintCols = [- {- id: 'name',- name: 'Issue type',- description: undefined,- minWidth: 240,- value: (row: any) => (- <div className="flex items-center gap-1.5">- <span className="shrink-0">- {lintInfoMap.find((item) => row.name === item.name)?.icon}- </span>- {<h3 className="text-xs">{lintInfoMap.find((item) => row.name === item.name)?.title}</h3>}- </div>- ),- },- {- id: 'metadata.name',- name: 'Entity/item',- description: undefined,- minWidth: 230,- value: (row: any) => (- <div className="flex items-center gap-1 text-xs">- <span className="shrink-0">{entityTypeIcon(row.metadata?.type)}</span>- {`${row.metadata.schema}.${row.metadata.name}`}- </div>- ),- },- {- id: 'description',- name: 'Description',- description: undefined,- minWidth: 400,- value: (row: any) => <ReactMarkdown className="text-xs">{row.description}</ReactMarkdown>,- },- ]-- const columns = lintCols.map((col) => {- const result: Column<any> = {- key: col.id,- name: col.name,- resizable: true,- minWidth: col.minWidth ?? 120,- headerCellClass: 'first:pl-6 cursor-pointer',- renderHeaderCell: () => {- return (- <div className="flex items-center justify-between font-mono font-normal text-xs w-full">- <div className="flex items-center gap-x-2">- <p className="!text-foreground">{col.name}</p>- {col.description && <p className="text-foreground-lighter">{col.description}</p>}- </div>- </div>- )- },- renderCell: (props) => {- const value = col.value(props.row)-- return (- <div- className={cn(- 'w-full flex flex-col justify-center font-mono text-xs',- typeof value === 'number' ? 'text-right' : ''- )}- >- <span>{value}</span>- </div>- )- },- }- return result- })-- return (- <div className="h-full flex flex-col">- <FormHeader- className="py-4 px-6 !mb-0"- title="Suggestions"- docsUrl="https://supabase.github.io/splinter/"- />- <Tabs_Shadcn_- defaultValue={currentTab}- onValueChange={(value) => {- setCurrentTab(value as LINTER_LEVELS)- setSelectedLint(null)- setSelectedRow(undefined)- const { sort, search, ...rest } = router.query- router.push({ ...router, query: { ...rest, preset: value } })- }}- >- <TabsList_Shadcn_ className={cn('flex gap-0 border-0 items-end z-10 relative')}>- {LINT_TABS.map((tab) => (- <TabsTrigger_Shadcn_- key={tab.id}- value={tab.id}- className={cn(- 'group relative',- 'px-6 py-3 border-b-0 flex flex-col items-start !shadow-none border-default border-t',- 'even:border-x last:border-r even:!border-x-strong last:!border-r-strong',- tab.id === currentTab ? '!bg-surface-200' : '!bg-surface-200/[33%]',- 'hover:!bg-surface-100',- 'data-[state=active]:!bg-surface-200',- 'hover:text-foreground-light',- 'transition'- )}- >- {tab.id === currentTab && (- <div className="absolute top-0 left-0 w-full h-[1px] bg-foreground" />- )}- <div className="flex items-center gap-x-2">- <span- className={- tab.id === LINTER_LEVELS.ERROR- ? 'text-destructive-600'- : tab.id === LINTER_LEVELS.WARN- ? 'text-warning-600'- : 'text-brand-500'- }- >- <MessageSquareMore size={14} fill="currentColor" strokeWidth={0} />- </span>-- <span className="">{tab.label}</span>- <Tooltip_Shadcn_>- <TooltipTrigger_Shadcn_ asChild>- <InformationCircleIcon className="transition text-foreground-muted w-3 h-3 data-[state=delayed-open]:text-foreground-light" />- </TooltipTrigger_Shadcn_>- <TooltipContent_Shadcn_ side="top">{tab.description}</TooltipContent_Shadcn_>- </Tooltip_Shadcn_>- </div>- <span className="text-xs text-foreground-muted group-hover:text-foreground-lighter group-data-[state=active]:text-foreground-lighter transition">- {tab.id === LINTER_LEVELS.ERROR && lintCountLabel(errorLintsCount, 'errors')}- {tab.id === LINTER_LEVELS.WARN && lintCountLabel(warnLintsCount, 'warnings')}- {tab.id === LINTER_LEVELS.INFO && lintCountLabel(infoLintsCount, 'suggestions')}- </span>- </TabsTrigger_Shadcn_>- ))}- </TabsList_Shadcn_>- </Tabs_Shadcn_>-- <div className="bg-surface-200 p-2 px-6 py-2 border-t -mt-px">- {LINT_TABS.map((tab) => (- <div key={tab.id} className={tab.id === currentTab ? '' : 'hidden'}>- <FilterPopover- name="Filter"- options={filterOptions}- labelKey="name"- valueKey="value"- activeOptions={filters.find((filter) => filter.level === currentTab)?.filters || []}- onSaveFilters={(values) => updateFilters(currentTab, values)}- />- </div>- ))}- </div>- <div className="col-span-12 flex items-center justify-between">- <div className="flex items-center gap-x-4"></div>- </div>- <LoadingLine loading={isRefetching} />- <ResizablePanelGroup- direction="horizontal"- className="relative flex flex-grow bg-alternative min-h-0"- autoSaveId="linter-layout-v1"- >- <ResizablePanel defaultSize={1}>- <DataGrid- ref={gridRef}- style={{ height: '100%' }}- className={cn('flex-1 flex-grow h-full')}- rowHeight={44}- headerRowHeight={36}- columns={columns}- rows={filteredLints ?? []}- rowClass={(_, idx) => {- const isSelected = idx === selectedRow- return [- `${isSelected ? 'bg-surface-300 dark:bg-surface-300' : 'bg-200'} cursor-pointer`,- `${isSelected ? '[&>div:first-child]:border-l-4 border-l-secondary [&>div]:border-l-foreground' : ''}`,- '[&>.rdg-cell]:border-box [&>.rdg-cell]:outline-none [&>.rdg-cell]:shadow-none',- '[&>.rdg-cell:first-child>div]:ml-4',- ].join(' ')- }}- renderers={{- renderRow(idx, props) {- return (- <Row- {...props}- onClick={() => {- if (typeof idx === 'number' && idx >= 0) {- setSelectedRow(idx)- setSelectedLint(props.row)- gridRef.current?.scrollToCell({ idx: 0, rowIdx: idx })- }- }}- />- )- },- noRowsFallback: isLoading ? (- <div className="absolute top-14 px-6 w-full">- <GenericSkeletonLoader />- </div>- ) : (- <div className="absolute top-20 px-6 flex flex-col items-center justify-center w-full gap-y-2">- <TextSearch className="text-foreground-muted" strokeWidth={1} />- <div className="text-center">- <p className="text-foreground">No issues detected</p>- <p className="text-foreground-light">- Congrats! There are no suggestions available for this database- </p>- </div>- </div>- ),- }}- />- </ResizablePanel>- {selectedLint !== null && (- <>- <ResizableHandle withHandle />- <ResizablePanel- defaultSize={30}- maxSize={45}- minSize={30}- className="bg-studio border-t"- >- <Button- type="text"- className="absolute top-3 right-3 px-1"- icon={<X size={14} />}- onClick={() => {- setSelectedLint(null)- setSelectedRow(undefined)- }}- />- <Tabs_Shadcn_- value={view}- className="flex flex-col h-full"- onValueChange={(value: any) => {- setView(value)- }}- >- <TabsList_Shadcn_ className="px-5 flex gap-x-4 min-h-[46px]">- <TabsTrigger_Shadcn_- value="details"- className="px-0 pb-0 h-full text-xs data-[state=active]:bg-transparent !shadow-none"- >- Overview- </TabsTrigger_Shadcn_>- </TabsList_Shadcn_>- <TabsContent_Shadcn_- value="details"- className="mt-0 flex-grow min-h-0 overflow-y-auto prose"- >- {selectedLint && (- <div className={cn('py-4 px-5')}>- <h3 className="text-sm">- {lintInfoMap.find((item) => item.name === selectedLint.name)?.title}- </h3>- <div className="flex items-center gap-2 text-sm">- <span>Entity</span>- <div className="flex items-center gap-1 px-2 py-0.5 bg-surface-200 border rounded-lg ">- {selectedLint.metadata?.type === 'table' && (- <Table2 className="text-foreground-muted" size={15} strokeWidth={1} />- )}- {selectedLint.metadata?.type === 'view' && (- <Eye className="text-foreground-muted" size={15} strokeWidth={1.5} />- )}{' '}- {`${selectedLint.metadata?.schema}.${selectedLint.metadata?.name}`}- </div>- </div>-- <div className="grid">- <div>- <h3 className="text-sm">Issue</h3>- <ReactMarkdown className="leading-6 text-sm">- {selectedLint.detail}- </ReactMarkdown>- </div>- <div>- <h3 className="text-sm">Description</h3>- <ReactMarkdown className="text-sm">- {selectedLint.description}- </ReactMarkdown>- </div>-- <div className="grid gap-2">- <h3 className="text-sm">Resolve</h3>- <div>- <LintCTA- title={selectedLint.name}- projectRef={ref!}- metadata={selectedLint.metadata}- />- </div>- </div>- </div>- </div>- )}- </TabsContent_Shadcn_>- </Tabs_Shadcn_>- </ResizablePanel>- </>- )}- </ResizablePanelGroup>- <div className="px-6 py-6 flex gap-x-4 border-t ">- <div className="w-[35%] flex flex-col gap-y-1 text-sm">- <p>Reset suggestions</p>- <p className="text-xs text-foreground-light">- Consider resetting the analysis making any changes- </p>-- <Button- type="default"- className="!mt-3 w-min"- disabled={isLoading || isRefetching}- loading={isLoading || isRefetching}- onClick={() => refetch()}- >- Rerun linter- </Button>- </div>- <div className="w-[35%] flex flex-col gap-y-1 text-sm">- <p>How are these suggestions generated?</p>- <Markdown- className="text-xs"- content="These suggestions use [splinter (Supabase Postgres LINTER)](https://github.com/supabase/splinter)."- />- </div>- </div>- </div>- )-}--ProjectLints.getLayout = (page) => <DatabaseLayout title="Linter">{page}</DatabaseLayout>--export default ProjectLintsdiff --git a/apps/studio/pages/project/[ref]/database/performance-advisor.tsx b/apps/studio/pages/project/[ref]/database/performance-advisor.tsxnew file mode 100644index 00000000000..c69b9c2d7c4--- /dev/null+++ b/apps/studio/pages/project/[ref]/database/performance-advisor.tsx@@ -0,0 +1,97 @@+import { useState } from 'react'+import { useParams } from 'common'+import { lintInfoMap } from 'components/interfaces/Linter/Linter.utils'+import { DatabaseLayout } from 'components/layouts'+import { FormHeader } from 'components/ui/Forms'+import { Lint, useProjectLintsQuery } from 'data/lint/lint-query'+import { useSelectedProject } from 'hooks'+import type { NextPageWithLayout } from 'types'+import { LoadingLine } from 'ui'++import LintPageTabs from 'components/interfaces/Linter/LintPageTabs'+import { LINTER_LEVELS } from 'components/interfaces/Linter/Linter.constants'+import LinterDataGrid from 'components/interfaces/Linter/LinterDataGrid'+import LinterPageFooter from 'components/interfaces/Linter/LinterPageFooter'+import LinterFilters from 'components/interfaces/Linter/LinterFilters'++const ProjectLints: NextPageWithLayout = () => {+ const project = useSelectedProject()+ const { preset } = useParams()++ // need to maintain a list of filters for each tab+ const [filters, setFilters] = useState<{ level: LINTER_LEVELS; filters: string[] }[]>([+ { level: LINTER_LEVELS.ERROR, filters: [] },+ { level: LINTER_LEVELS.WARN, filters: [] },+ { level: LINTER_LEVELS.INFO, filters: [] },+ ])++ const [currentTab, setCurrentTab] = useState<LINTER_LEVELS>(+ (preset as LINTER_LEVELS) ?? LINTER_LEVELS.ERROR+ )+ const [selectedRow, setSelectedRow] = useState<number>()+ const [selectedLint, setSelectedLint] = useState<Lint | null>(null)++ const { data, isLoading, isRefetching, refetch } = useProjectLintsQuery({+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ })++ const activeLints = data?.filter((x) => x.categories.includes('PERFORMANCE')) || []++ const currentTabFilters = (filters.find((filter) => filter.level === currentTab)?.filters ||+ []) as string[]++ const filteredLints = activeLints+ .filter((x) => x.level === currentTab)+ .filter((x) => (currentTabFilters.length > 0 ? currentTabFilters.includes(x.name) : x))++ const filterOptions = lintInfoMap+ // only show filters for lint types which are present in the results and not ignored+ .filter((item) =>+ activeLints.some((lint) => lint.name === item.name && lint.level === currentTab)+ )+ .map((type) => ({+ name: type.title,+ value: type.name,+ }))++ return (+ <div className="h-full flex flex-col">+ <FormHeader+ className="py-4 px-6 !mb-0"+ title="Performance Advisor"+ docsUrl="https://supabase.com/docs/guides/database/database-linter"+ />+ <LintPageTabs+ activeLints={activeLints}+ isLoading={isLoading}+ currentTab={currentTab}+ setCurrentTab={setCurrentTab}+ setSelectedLint={setSelectedLint}+ setSelectedRow={setSelectedRow}+ />+ <LinterFilters+ filterOptions={filterOptions}+ activeLints={activeLints}+ currentTab={currentTab}+ filters={filters}+ setFilters={setFilters}+ />+ <LoadingLine loading={isRefetching} />+ <LinterDataGrid+ filteredLints={filteredLints}+ currentTab={currentTab}+ selectedRow={selectedRow}+ setSelectedRow={setSelectedRow}+ selectedLint={selectedLint}+ setSelectedLint={setSelectedLint}+ isLoading={isLoading}+ />+ <LinterPageFooter isLoading={isLoading} isRefetching={isRefetching} refetch={refetch} />+ </div>+ )+}++ProjectLints.getLayout = (page) => <DatabaseLayout title="Linter">{page}</DatabaseLayout>++export default ProjectLintsdiff --git a/apps/studio/pages/project/[ref]/database/security-advisor.tsx b/apps/studio/pages/project/[ref]/database/security-advisor.tsxnew file mode 100644index 00000000000..5f9eb0a9a2c--- /dev/null+++ b/apps/studio/pages/project/[ref]/database/security-advisor.tsx@@ -0,0 +1,97 @@+import { useState } from 'react'+import { useParams } from 'common'+import { lintInfoMap } from 'components/interfaces/Linter/Linter.utils'+import { DatabaseLayout } from 'components/layouts'+import { FormHeader } from 'components/ui/Forms'+import { Lint, useProjectLintsQuery } from 'data/lint/lint-query'+import { useSelectedProject } from 'hooks'+import type { NextPageWithLayout } from 'types'+import { LoadingLine } from 'ui'++import LintPageTabs from 'components/interfaces/Linter/LintPageTabs'+import { LINTER_LEVELS } from 'components/interfaces/Linter/Linter.constants'+import LinterDataGrid from 'components/interfaces/Linter/LinterDataGrid'+import LinterPageFooter from 'components/interfaces/Linter/LinterPageFooter'+import LinterFilters from 'components/interfaces/Linter/LinterFilters'++const ProjectLints: NextPageWithLayout = () => {+ const project = useSelectedProject()+ const { preset } = useParams()++ // need to maintain a list of filters for each tab+ const [filters, setFilters] = useState<{ level: LINTER_LEVELS; filters: string[] }[]>([+ { level: LINTER_LEVELS.ERROR, filters: [] },+ { level: LINTER_LEVELS.WARN, filters: [] },+ { level: LINTER_LEVELS.INFO, filters: [] },+ ])++ const [currentTab, setCurrentTab] = useState<LINTER_LEVELS>(+ (preset as LINTER_LEVELS) ?? LINTER_LEVELS.ERROR+ )+ const [selectedRow, setSelectedRow] = useState<number>()+ const [selectedLint, setSelectedLint] = useState<Lint | null>(null)++ const { data, isLoading, isRefetching, refetch } = useProjectLintsQuery({+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ })++ const activeLints = data?.filter((x) => x.categories.includes('SECURITY')) || []++ const currentTabFilters = (filters.find((filter) => filter.level === currentTab)?.filters ||+ []) as string[]++ const filteredLints = activeLints+ .filter((x) => x.level === currentTab)+ .filter((x) => (currentTabFilters.length > 0 ? currentTabFilters.includes(x.name) : x))++ const filterOptions = lintInfoMap+ // only show filters for lint types which are present in the results and not ignored+ .filter((item) =>+ activeLints.some((lint) => lint.name === item.name && lint.level === currentTab)+ )+ .map((type) => ({+ name: type.title,+ value: type.name,+ }))++ return (+ <div className="h-full flex flex-col">+ <FormHeader+ className="py-4 px-6 !mb-0"+ title="Security Advisor"+ docsUrl="https://supabase.com/docs/guides/database/database-linter"+ />+ <LintPageTabs+ activeLints={activeLints}+ isLoading={isLoading}+ currentTab={currentTab}+ setCurrentTab={setCurrentTab}+ setSelectedLint={setSelectedLint}+ setSelectedRow={setSelectedRow}+ />+ <LinterFilters+ filterOptions={filterOptions}+ activeLints={activeLints}+ currentTab={currentTab}+ filters={filters}+ setFilters={setFilters}+ />+ <LoadingLine loading={isRefetching} />+ <LinterDataGrid+ filteredLints={filteredLints}+ currentTab={currentTab}+ selectedRow={selectedRow}+ setSelectedRow={setSelectedRow}+ selectedLint={selectedLint}+ setSelectedLint={setSelectedLint}+ isLoading={isLoading}+ />+ <LinterPageFooter isLoading={isLoading} isRefetching={isRefetching} refetch={refetch} />+ </div>+ )+}++ProjectLints.getLayout = (page) => <DatabaseLayout title="Linter">{page}</DatabaseLayout>++export default ProjectLintsdiff --git a/packages/ui/src/components/Popover/Popover.tsx b/packages/ui/src/components/Popover/Popover.tsxindex 267126b1eca..9becd336a51 100644--- a/packages/ui/src/components/Popover/Popover.tsx+++ b/packages/ui/src/components/Popover/Popover.tsx@@ -12,6 +12,7 @@ interface RootProps {children?: React.ReactNodeclassName?: stringdefaultOpen?: boolean+ disabled?: booleanmodal?: booleanonOpenChange?: RadixPopoverTypes.PopoverProps['onOpenChange']open?: boolean@@ -42,6 +43,7 @@ function Popover({header,footer,size = 'content',+ disabled,}: RootProps) {const __styles = styleHandler('popover')@@ -59,6 +61,7 @@ function Popover({><RadixPopover.Trigger// className={DropdownStyles['sbui-popover__trigger']}+ disabled={disabled}className={__styles.trigger}aria-label={ariaLabel}>