Skip to content

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

feat: Choose which schemas to share with OpenAI (#28594)

Ivan Vasilov6a29cd2becbd
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyChat.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyChat.tsx
index 8756576903b..77ef57b1cb6 100644
--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyChat.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/AIPolicyChat.tsx
@@ -4,15 +4,26 @@ import { useRouter } from 'next/router'
import { useEffect, useRef, useState } from 'react'
import { useTelemetryProps } from 'common'
-import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'
+import { SchemaComboBox } from 'components/ui/SchemaComboBox'
import { useOrgOptedIntoAi } from 'hooks/misc/useOrgOptedIntoAi'
-import { IS_PLATFORM, LOCAL_STORAGE_KEYS } from 'lib/constants'
+import { useSchemasForAi } from 'hooks/misc/useSchemasForAi'
+import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
+import { useSelectedProject } from 'hooks/misc/useSelectedProject'
+import { IS_PLATFORM } from 'lib/constants'
import { useProfile } from 'lib/profile'
-import { useAppStateSnapshot } from 'state/app-state'
-import { AiIconAnimation, Button, cn } from 'ui'
+import { ChevronsUpDown } from 'lucide-react'
+import Link from 'next/link'
+import {
+ AiIconAnimation,
+ Button,
+ Tooltip_Shadcn_,
+ TooltipContent_Shadcn_,
+ TooltipTrigger_Shadcn_,
+} from 'ui'
import { AssistantChatForm } from 'ui-patterns'
import { MessageWithDebug } from './AIPolicyEditorPanel.utils'
import Message from './Message'
+import { ButtonTooltip } from 'components/ui/ButtonTooltip'
interface AIPolicyChatProps {
messages: MessageWithDebug[]
@@ -30,17 +41,18 @@ export const AIPolicyChat = ({
onDiff,
}: AIPolicyChatProps) => {
const router = useRouter()
+ const project = useSelectedProject()
+ const selectedOrganization = useSelectedOrganization()
const { profile } = useProfile()
- const snap = useAppStateSnapshot()
const bottomRef = useRef<HTMLDivElement>(null)
const telemetryProps = useTelemetryProps()
+ const [selectedSchemas, setSelectedSchemas] = useSchemasForAi(project?.ref!)
const [value, setValue] = useState<string>('')
const inputRef = useRef<HTMLTextAreaElement>(null)
const isOptedInToAI = useOrgOptedIntoAi()
- const [hasEnabledAISchema] = useLocalStorageQuery(LOCAL_STORAGE_KEYS.SQL_EDITOR_AI_SCHEMA, true)
- const includeSchemaMetadata = (isOptedInToAI || !IS_PLATFORM) && hasEnabledAISchema
+ const includeSchemaMetadata = isOptedInToAI || !IS_PLATFORM
const name = compact([profile?.first_name, profile?.last_name]).join(' ')
const pendingReply = loading && last(messages)?.role === 'user'
@@ -74,21 +86,49 @@ export const AIPolicyChat = ({
Make sure to verify any generated code or suggestions, and share feedback so that we can
learn and improve.`}
>
- <Button
- type="default"
- className="w-min"
- icon={
- <div
- className={cn(
- 'w-2 h-2 rounded-full',
- includeSchemaMetadata ? 'bg-brand' : 'border border-stronger'
- )}
- />
- }
- onClick={() => snap.setShowAiSettingsModal(true)}
- >
- {includeSchemaMetadata ? 'Include' : 'Exclude'} database metadata in queries
- </Button>
+ {includeSchemaMetadata ? (
+ <SchemaComboBox
+ className="w-fit"
+ disabled={!includeSchemaMetadata}
+ selectedSchemas={selectedSchemas}
+ onSelectSchemas={setSelectedSchemas}
+ label={
+ includeSchemaMetadata && selectedSchemas.length > 0
+ ? `${selectedSchemas.length} schema${
+ selectedSchemas.length > 1 ? 's' : ''
+ } selected`
+ : 'No schemas selected'
+ }
+ />
+ ) : (
+ <ButtonTooltip
+ disabled
+ size="tiny"
+ type="default"
+ className="w-min"
+ iconRight={<ChevronsUpDown size={14} />}
+ tooltip={{
+ content: {
+ side: 'bottom',
+ className: 'w-72',
+ text: (
+ <>
+ Opt in to sending anonymous data to OpenAI in your{' '}
+ <Link
+ className="underline"
+ href={`/org/${selectedOrganization?.slug}/general`}
+ >
+ organization settings
+ </Link>{' '}
+ to share schemas with the Assistant for more accurate responses.
+ </>
+ ),
+ },
+ }}
+ >
+ No schemas selected
+ </ButtonTooltip>
+ )}
</Message>
{messages.map((m) => (
diff --git a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsx b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsx
index 754cc2ae26f..1e0173b45b9 100644
--- a/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsx
+++ b/apps/studio/components/interfaces/Auth/Policies/AIPolicyEditorPanel/index.tsx
@@ -2,7 +2,7 @@ import { zodResolver } from '@hookform/resolvers/zod'
import type { PostgresPolicy } from '@supabase/postgres-meta'
import { useQueryClient } from '@tanstack/react-query'
import { useChat } from 'ai/react'
-import { useParams, useTelemetryProps } from 'common'
+import { IS_PLATFORM, useParams, useTelemetryProps } from 'common'
import { isEqual, uniqBy } from 'lodash'
import { FileDiff } from 'lucide-react'
import dynamic from 'next/dynamic'
@@ -28,19 +28,23 @@ import {
import * as z from 'zod'
import { Monaco } from '@monaco-editor/react'
+import { PermissionAction } from '@supabase/shared-types/out/constants'
import { useIsRLSAIAssistantEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import { subscriptionHasHipaaAddon } from 'components/interfaces/Billing/Subscription/Subscription.utils'
import {
IStandaloneCodeEditor,
IStandaloneDiffEditor,
} from 'components/interfaces/SQLEditor/SQLEditor.types'
+import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import { useSqlDebugMutation } from 'data/ai/sql-debug-mutation'
import { useDatabasePolicyUpdateMutation } from 'data/database-policies/database-policy-update-mutation'
import { databasePoliciesKeys } from 'data/database-policies/keys'
import { useEntityDefinitionsQuery } from 'data/database/entity-definitions-query'
import { QueryResponseError, useExecuteSqlMutation } from 'data/sql/execute-sql-mutation'
import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
+import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { useOrgOptedIntoAi } from 'hooks/misc/useOrgOptedIntoAi'
+import { useSchemasForAi } from 'hooks/misc/useSchemasForAi'
import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
import { useSelectedProject } from 'hooks/misc/useSelectedProject'
import { BASE_PATH } from 'lib/constants'
@@ -62,9 +66,6 @@ import { PolicyDetailsV2 } from './PolicyDetailsV2'
import { PolicyTemplates } from './PolicyTemplates'
import QueryError from './QueryError'
import RLSCodeEditor from './RLSCodeEditor'
-import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { ButtonTooltip } from 'components/ui/ButtonTooltip'
const DiffEditor = dynamic(
() => import('@monaco-editor/react').then(({ DiffEditor }) => DiffEditor),
@@ -164,8 +165,10 @@ export const AIPolicyEditorPanel = memo(function ({
const { data: subscription } = useOrgSubscriptionQuery({ orgSlug: selectedOrganization?.slug })
const hasHipaaAddon = subscriptionHasHipaaAddon(subscription)
+ const [selectedSchemas] = useSchemasForAi(selectedProject?.ref!)
const { data: entities } = useEntityDefinitionsQuery(
{
+ schemas: selectedSchemas,
projectRef: selectedProject?.ref,
connectionString: selectedProject?.connectionString,
},
@@ -185,7 +188,7 @@ export const AIPolicyEditorPanel = memo(function ({
id: chatId,
api: `${BASE_PATH}/api/ai/sql/suggest`,
body: {
- entityDefinitions: isOptedInToAI ? entityDefinitions : undefined,
+ entityDefinitions: isOptedInToAI || !IS_PLATFORM ? entityDefinitions : undefined,
policyDefinition:
selectedPolicy !== undefined ? generatePolicyDefinition(selectedPolicy) : undefined,
},
diff --git a/apps/studio/components/interfaces/SQLEditor/AISchemaSuggestionPopover.tsx b/apps/studio/components/interfaces/SQLEditor/AISchemaSuggestionPopover.tsx
index 3330368c9a9..c8d94bf6051 100644
--- a/apps/studio/components/interfaces/SQLEditor/AISchemaSuggestionPopover.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/AISchemaSuggestionPopover.tsx
@@ -1,12 +1,13 @@
import * as Popover from '@radix-ui/react-popover'
import { motion } from 'framer-motion'
+import { Info } from 'lucide-react'
import { PropsWithChildren, useEffect, useState } from 'react'
import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'
import { useOrgOptedIntoAi } from 'hooks/misc/useOrgOptedIntoAi'
import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
import { IS_PLATFORM } from 'lib/constants'
-import { Button, IconInfo } from 'ui'
+import { Button } from 'ui'
export interface AISchemaSuggestionPopoverProps {
delay?: number
@@ -68,8 +69,8 @@ const AISchemaSuggestionPopover = ({
>
<Popover.Arrow className="fill-background-surface-300" />
<div className="flex flex-col gap-2 border border-default rounded-md p-4 bg-surface-100 shadow-xl">
- <div className="flex flex-row items-center gap-4 max-w-md">
- <IconInfo className="w-6 h-6" />
+ <div className="flex flex-row gap-4 max-w-sm xl:max-w-xl xl:items-center">
+ <Info size={18} />
<p className="text-sm">
Generate more relevant queries by including database metadata in your requests.
</p>
diff --git a/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/AiMessagePre.tsx b/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/AiMessagePre.tsx
index e6da9d54c80..a08386377c2 100644
--- a/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/AiMessagePre.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/AiMessagePre.tsx
@@ -61,7 +61,7 @@ export const AiMessagePre = ({ onDiff, children, className }: AiMessagePreProps)
hideCopy
hideLineNumbers
/>
- <div className="absolute top-5 right-2 bg-surface-100 border-muted border rounded-lg h-[28px] hidden group-hover:block">
+ <div className="absolute top-2 right-2 bg-surface-100 border-muted border rounded-lg h-[28px] hidden group-hover:block">
<Tooltip_Shadcn_>
<TooltipTrigger_Shadcn_ asChild>
<Button
diff --git a/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/index.tsx b/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/index.tsx
index 965282a82e8..4ab53522b1b 100644
--- a/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/index.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/AiAssistantPanel/index.tsx
@@ -1,59 +1,105 @@
import { Message as MessageType } from 'ai'
import Telemetry from 'lib/telemetry'
import { compact, last } from 'lodash'
+import { ChevronsUpDown } from 'lucide-react'
+import Link from 'next/link'
import { useRouter } from 'next/router'
-import { useEffect, useRef, useState } from 'react'
+import { useEffect, useMemo, useRef, useState } from 'react'
+import { useChat } from 'ai/react'
import { useTelemetryProps } from 'common'
-import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'
-import { useOrgOptedIntoAi } from 'hooks/misc/useOrgOptedIntoAi'
-import { IS_PLATFORM, LOCAL_STORAGE_KEYS } from 'lib/constants'
+import { SchemaComboBox } from 'components/ui/SchemaComboBox'
+import { useEntityDefinitionsQuery } from 'data/database/entity-definitions-query'
+import { useSchemasForAi } from 'hooks/misc/useSchemasForAi'
+import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
+import { useSelectedProject } from 'hooks/misc/useSelectedProject'
+import { BASE_PATH } from 'lib/constants'
import { useProfile } from 'lib/profile'
-import { useAppStateSnapshot } from 'state/app-state'
-import { AiIconAnimation, Button, cn } from 'ui'
+import uuidv4 from 'lib/uuid'
+import {
+ AiIconAnimation,
+ Button,
+ cn,
+ Tooltip_Shadcn_,
+ TooltipContent_Shadcn_,
+ TooltipTrigger_Shadcn_,
+} from 'ui'
import { AssistantChatForm } from 'ui-patterns'
import { DiffType } from '../SQLEditor.types'
import Message from './Message'
+import { ButtonTooltip } from 'components/ui/ButtonTooltip'
export type MessageWithDebug = MessageType & { isDebug: boolean }
interface AiAssistantPanelProps {
- messages: MessageWithDebug[]
selectedMessage?: string
- loading: boolean
- onSubmit: (s: string) => void
- onClearHistory: () => void
+ existingSql: string
+ includeSchemaMetadata: boolean
onDiff: ({ id, diffType, sql }: { id: string; diffType: DiffType; sql: string }) => void
onClose: () => void
}
export const AiAssistantPanel = ({
- messages,
selectedMessage,
- loading,
- onSubmit,
+ existingSql,
onDiff,
- onClearHistory,
onClose,
+ includeSchemaMetadata,
}: AiAssistantPanelProps) => {
+ const project = useSelectedProject()
+ const selectedOrganization = useSelectedOrganization()
+
+ const [selectedSchemas, setSelectedSchemas] = useSchemasForAi(project?.ref!)
+
+ const { data } = useEntityDefinitionsQuery(
+ {
+ schemas: selectedSchemas,
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ },
+ { enabled: includeSchemaMetadata }
+ )
+
+ const entityDefinitions = includeSchemaMetadata ? data?.map((def) => def.sql.trim()) : undefined
+
+ // Use chat id because useChat doesn't have a reset function to clear all messages
+ const [chatId, setChatId] = useState(uuidv4())
+ const {
+ messages: chatMessages,
+ append,
+ isLoading,
+ } = useChat({
+ id: chatId,
+ api: `${BASE_PATH}/api/ai/sql/generate-v2`,
+ body: {
+ existingSql: existingSql,
+ entityDefinitions: entityDefinitions,
+ },
+ })
+
+ const messages = useMemo(() => {
+ const merged = [...chatMessages.map((m) => ({ ...m, isDebug: false }))]
+
+ return merged.sort(
+ (a, b) =>
+ (a.createdAt?.getTime() ?? 0) - (b.createdAt?.getTime() ?? 0) ||
+ a.role.localeCompare(b.role)
+ )
+ }, [chatMessages])
+
const router = useRouter()
const { profile } = useProfile()
- const snap = useAppStateSnapshot()
const bottomRef = useRef<HTMLDivElement>(null)
const telemetryProps = useTelemetryProps()
const [value, setValue] = useState<string>('')
const inputRef = useRef<HTMLTextAreaElement>(null)
- const isOptedInToAI = useOrgOptedIntoAi()
- const [hasEnabledAISchema] = useLocalStorageQuery(LOCAL_STORAGE_KEYS.SQL_EDITOR_AI_SCHEMA, true)
- const includeSchemaMetadata = (isOptedInToAI || !IS_PLATFORM) && hasEnabledAISchema
-
const name = compact([profile?.first_name, profile?.last_name]).join(' ')
- const pendingReply = loading && last(messages)?.role === 'user'
+ const pendingReply = isLoading && last(messages)?.role === 'user'
useEffect(() => {
- if (!loading) {
+ if (!isLoading) {
setValue('')
if (inputRef.current) inputRef.current.focus()
}
@@ -65,9 +111,9 @@ export const AiAssistantPanel = ({
bottomRef.current.scrollIntoView({ behavior: 'smooth' })
}
},
- loading ? 100 : 500
+ isLoading ? 100 : 500
)
- }, [loading])
+ }, [isLoading])
return (
<div className="flex flex-col h-full border-l border-control">
@@ -92,22 +138,49 @@ export const AiAssistantPanel = ({
}
>
<div className="flex flex-row justify-between space-x-2">
- <Button
- type="default"
- className="w-min"
- icon={
- <div
- className={cn(
- 'w-2 h-2 rounded-full',
- includeSchemaMetadata ? 'bg-brand' : 'border border-stronger'
- )}
- />
- }
- onClick={() => snap.setShowAiSettingsModal(true)}
- >
- {includeSchemaMetadata ? 'Include' : 'Exclude'} database metadata in queries
- </Button>
- <Button type="warning" onClick={() => onClearHistory()}>
+ {includeSchemaMetadata ? (
+ <SchemaComboBox
+ disabled={!includeSchemaMetadata}
+ selectedSchemas={selectedSchemas}
+ onSelectSchemas={setSelectedSchemas}
+ label={
+ includeSchemaMetadata && selectedSchemas.length > 0
+ ? `${selectedSchemas.length} schema${
+ selectedSchemas.length > 1 ? 's' : ''
+ } selected`
+ : 'No schemas selected'
+ }
+ />
+ ) : (
+ <ButtonTooltip
+ disabled
+ size="tiny"
+ type="default"
+ className="w-min"
+ iconRight={<ChevronsUpDown size={14} />}
+ tooltip={{
+ content: {
+ side: 'bottom',
+ className: 'w-72',
+ text: (
+ <>
+ Opt in to sending anonymous data to OpenAI in your{' '}
+ <Link
+ className="underline"
+ href={`/org/${selectedOrganization?.slug}/general`}
+ >
+ organization settings
+ </Link>{' '}
+ to share schemas with the Assistant for more accurate responses.
+ </>
+ ),
+ },
+ }}
+ >
+ No schemas selected
+ </ButtonTooltip>
+ )}
+ <Button type="warning" onClick={() => setChatId(uuidv4())}>
Clear history
</Button>
</div>
@@ -134,8 +207,8 @@ export const AiAssistantPanel = ({
<div className="sticky p-5 flex-0 border-t">
<AssistantChatForm
textAreaRef={inputRef}
- loading={loading}
- disabled={loading}
+ loading={isLoading}
+ disabled={isLoading}
icon={
<AiIconAnimation
allowHoverEffect
@@ -147,7 +220,11 @@ export const AiAssistantPanel = ({
onValueChange={(e) => setValue(e.target.value)}
onSubmit={(event) => {
event.preventDefault()
- onSubmit(value)
+ append({
+ content: value,
+ role: 'user',
+ createdAt: new Date(),
+ })
Telemetry.sendEvent(
{
category: 'sql_editor_ai_assistant',
diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
index 675da181afd..178c02b1dac 100644
--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
@@ -1,6 +1,5 @@
import type { Monaco } from '@monaco-editor/react'
import { useQueryClient } from '@tanstack/react-query'
-import { useChat } from 'ai/react'
import { motion } from 'framer-motion'
import { Loader2 } from 'lucide-react'
import dynamic from 'next/dynamic'
@@ -22,10 +21,11 @@ import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-que
import { isError } from 'data/utils/error-check'
import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'
import { useOrgOptedIntoAi } from 'hooks/misc/useOrgOptedIntoAi'
+import { useSchemasForAi } from 'hooks/misc/useSchemasForAi'
import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
import { useSelectedProject } from 'hooks/misc/useSelectedProject'
import { useFlag } from 'hooks/ui/useFlag'
-import { BASE_PATH, IS_PLATFORM, LOCAL_STORAGE_KEYS } from 'lib/constants'
+import { IS_PLATFORM, LOCAL_STORAGE_KEYS } from 'lib/constants'
import { uuidv4 } from 'lib/helpers'
import { useProfile } from 'lib/profile'
import { wrapWithRoleImpersonation } from 'lib/role-impersonation'
@@ -121,20 +121,19 @@ const SQLEditor = () => {
const [isConfirmModalOpen, setIsConfirmModalOpen] = useState(false)
const isOptedInToAI = useOrgOptedIntoAi()
- const [hasEnabledAISchema] = useLocalStorageQuery(LOCAL_STORAGE_KEYS.SQL_EDITOR_AI_SCHEMA, true)
- const includeSchemaMetadata = (isOptedInToAI || !IS_PLATFORM) && hasEnabledAISchema
+ const [selectedSchemas] = useSchemasForAi(project?.ref!)
+ const includeSchemaMetadata = isOptedInToAI || !IS_PLATFORM
const [isAcceptDiffLoading, setIsAcceptDiffLoading] = useState(false)
const [, setAiQueryCount] = useLocalStorageQuery('supabase_sql-editor-ai-query-count', 0)
- // Use chat id because useChat doesn't have a reset function to clear all messages
- const [chatId, setChatId] = useState(uuidv4())
const [selectedDiffType, setSelectedDiffType] = useState<DiffType | undefined>(undefined)
const [isFirstRender, setIsFirstRender] = useState(true)
const [lineHighlights, setLineHighlights] = useState<string[]>([])
const { data, refetch: refetchEntityDefinitions } = useEntityDefinitionsQuery(
{
+ schemas: selectedSchemas,
projectRef: project?.ref,
connectionString: project?.connectionString,
},
@@ -150,29 +149,6 @@ const SQLEditor = () => {
: !(id && ref && snap.loaded[ref])
const isLoading = urlId === 'new' ? false : snippetIsLoading
- const {
- messages: chatMessages,
- append,
- isLoading: isLoadingChat,
- } = useChat({
- id: chatId,
- api: `${BASE_PATH}/api/ai/sql/generate-v2`,
- body: {
- existingSql: editorRef.current?.getValue(),
- entityDefinitions: isOptedInToAI ? entityDefinitions : undefined,
- },
- })
-
- const messages = useMemo(() => {
- const merged = [...chatMessages.map((m) => ({ ...m, isDebug: false }))]
-
- return merged.sort(
- (a, b) =>
- (a.createdAt?.getTime() ?? 0) - (b.createdAt?.getTime() ?? 0) ||
- a.role.localeCompare(b.role)
- )
- }, [chatMessages])
-
const { mutate: execute, isLoading: isExecuting } = useExecuteSqlMutation({
onSuccess(data, vars) {
if (id) {
@@ -659,7 +635,7 @@ const SQLEditor = () => {
appSnap.setShowAiSettingsModal(true)
}}
>
- {isDiffOpen ? (
+ {isDiffOpen && (
<motion.div
key="ask-ai-input-container"
layoutId="ask-ai-input-container"
@@ -684,7 +660,7 @@ const SQLEditor = () => {
onCancel={discardAiHandler}
/>
</motion.div>
- ) : null}
+ )}
</AISchemaSuggestionPopover>
)}
<ResizablePanel collapsible collapsedSize={10} minSize={20}>
@@ -785,17 +761,9 @@ const SQLEditor = () => {
onExpand={() => setIsAiOpen(true)}
>
<AiAssistantPanel
- messages={messages}
selectedMessage={selectedMessage}
- loading={isLoadingChat}
- onSubmit={(message) =>
- append({
- content: message,
- role: 'user',
- createdAt: new Date(),
- })
- }
- onClearHistory={() => setChatId(uuidv4())}
+ existingSql={editorRef.current?.getValue() || ''}
+ includeSchemaMetadata={includeSchemaMetadata}
onDiff={updateEditorWithCheckForDiff}
onClose={() => aiPanelRef.current?.collapse()}
/>
diff --git a/apps/studio/components/interfaces/SqlGenerator/SqlGeneratorImpl.tsx b/apps/studio/components/interfaces/SqlGenerator/SqlGeneratorImpl.tsx
index 7c0b3cf8fbb..64b524cdb39 100644
--- a/apps/studio/components/interfaces/SqlGenerator/SqlGeneratorImpl.tsx
+++ b/apps/studio/components/interfaces/SqlGenerator/SqlGeneratorImpl.tsx
@@ -3,8 +3,10 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useEffectOnce } from 'react-use'
import { format } from 'sql-formatter'
+import { IS_PLATFORM } from 'common'
import { useEntityDefinitionsQuery } from 'data/database/entity-definitions-query'
-import { useAllowSendAiSchema } from 'hooks/misc/useAllowSendAiSchema'
+import { useOrgOptedIntoAi } from 'hooks/misc/useOrgOptedIntoAi'
+import { useSchemasForAi } from 'hooks/misc/useSchemasForAi'
import { useSelectedProject } from 'hooks/misc/useSelectedProject'
import { useAppStateSnapshot } from 'state/app-state'
import {
@@ -17,10 +19,10 @@ import {
Input_Shadcn_,
Modal,
StatusIcon,
- Tabs_Shadcn_,
TabsContent_Shadcn_,
TabsList_Shadcn_,
TabsTrigger_Shadcn_,
+ Tabs_Shadcn_,
cn,
} from 'ui'
import {
@@ -43,14 +45,17 @@ import { SAMPLE_QUERIES, generatePrompt } from './SqlGenerator.utils'
import { SQLOutputActions } from './SqlOutputActions'
function useSchemaMetadataForAi() {
- const allowed = useAllowSendAiSchema()
+ const isOptedInToAI = useOrgOptedIntoAi()
const project = useSelectedProject()
- const includeMetadata = allowed && !!project
+ const [schemas] = useSchemasForAi(project?.ref!)
+ const includeMetadata = (isOptedInToAI || !IS_PLATFORM) && schemas.length > 0 && !!project
+
const metadataSkipReason: AiMetadataSkipReason = !project ? 'no_project' : 'forbidden'
const { data } = useEntityDefinitionsQuery(
{
+ schemas: schemas,
projectRef: project?.ref,
connectionString: project?.connectionString,
},
diff --git a/apps/studio/components/ui/AISettingsModal.tsx b/apps/studio/components/ui/AISettingsModal.tsx
index fc7303c4daf..2c1d1519882 100644
--- a/apps/studio/components/ui/AISettingsModal.tsx
+++ b/apps/studio/components/ui/AISettingsModal.tsx
@@ -1,10 +1,10 @@
import Link from 'next/link'
-import toast from 'react-hot-toast'
-import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'
import { useOrgOptedIntoAi } from 'hooks/misc/useOrgOptedIntoAi'
+import { useSchemasForAi } from 'hooks/misc/useSchemasForAi'
import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
-import { IS_PLATFORM, LOCAL_STORAGE_KEYS } from 'lib/constants'
+import { useSelectedProject } from 'hooks/misc/useSelectedProject'
+import { IS_PLATFORM } from 'lib/constants'
import { useAppStateSnapshot } from 'state/app-state'
import {
AlertDescription_Shadcn_,
@@ -12,26 +12,19 @@ import {
Alert_Shadcn_,
Button,
Modal,
- Toggle,
WarningIcon,
} from 'ui'
+import { SchemaComboBox } from './SchemaComboBox'
const AISettingsModal = () => {
const snap = useAppStateSnapshot()
const selectedOrganization = useSelectedOrganization()
const isOptedInToAI = useOrgOptedIntoAi()
+ const selectedProject = useSelectedProject()
- const [hasEnabledAISchema, setHasEnabledAISchema] = useLocalStorageQuery(
- LOCAL_STORAGE_KEYS.SQL_EDITOR_AI_SCHEMA,
- true
- )
-
- const includeSchemaMetadata = (isOptedInToAI || !IS_PLATFORM) && hasEnabledAISchema
+ const [selectedSchemas, setSelectedSchemas] = useSchemasForAi(selectedProject?.ref!)
- const handleOptInToggle = () => {
- setHasEnabledAISchema((prev) => !prev)
- toast.success('Successfully saved settings')
- }
+ const includeSchemaMetadata = isOptedInToAI || !IS_PLATFORM
return (
<Modal
@@ -41,19 +34,25 @@ const AISettingsModal = () => {
onCancel={() => snap.setShowAiSettingsModal(false)}
>
<Modal.Content className="flex flex-col items-start justify-between gap-y-4">
- <div className="flex justify-between gap-x-5 mr-8 my-4">
- <Toggle
+ <div className="flex flex-col justify-between gap-y-2 text-sm">
+ <p className="text-foreground-light">Schemas metadata to be shared with OpenAI</p>
+ <SchemaComboBox
+ size="small"
+ label={
+ includeSchemaMetadata && selectedSchemas.length > 0
+ ? `${selectedSchemas.length} schema${
+ selectedSchemas.length > 1 ? 's' : ''
+ } selected`
+ : 'No schemas selected'
+ }
disabled={IS_PLATFORM && !isOptedInToAI}
- checked={includeSchemaMetadata}
- onChange={handleOptInToggle}
+ selectedSchemas={selectedSchemas}
+ onSelectSchemas={setSelectedSchemas}
/>
- <div className="grid gap-2">
- <p className="text-sm">Include anonymous database metadata in AI queries</p>
- <p className="text-sm text-foreground-light">
- Metadata includes table names, column names and their corresponding data types in the
- request. This will generate queries that are more relevant to your project.
- </p>
- </div>
+ <p className="text-foreground-lighter">
+ Metadata includes table names, column names and their corresponding data types in the
+ request. This will generate queries that are more relevant to your project.
+ </p>
</div>
{IS_PLATFORM && !isOptedInToAI && selectedOrganization && (
<Alert_Shadcn_ variant="warning">
diff --git a/apps/studio/components/ui/ButtonTooltip.tsx b/apps/studio/components/ui/ButtonTooltip.tsx
index c2e7a7e5a31..f1ff45d08e8 100644
--- a/apps/studio/components/ui/ButtonTooltip.tsx
+++ b/apps/studio/components/ui/ButtonTooltip.tsx
@@ -1,4 +1,4 @@
-import { ComponentProps, ComponentPropsWithoutRef, ElementRef, forwardRef } from 'react'
+import { ComponentProps, ComponentPropsWithoutRef, ElementRef, forwardRef, ReactNode } from 'react'
import { Button, TooltipContent_Shadcn_, TooltipTrigger_Shadcn_, Tooltip_Shadcn_, cn } from 'ui'
export const ButtonTooltip = forwardRef<
@@ -6,7 +6,7 @@ export const ButtonTooltip = forwardRef<
ComponentPropsWithoutRef<typeof Button> & {
tooltip: {
content: ComponentProps<typeof TooltipContent_Shadcn_> & {
- text?: string
+ text?: string | ReactNode
}
}
}
diff --git a/apps/studio/components/ui/SchemaComboBox.tsx b/apps/studio/components/ui/SchemaComboBox.tsx
new file mode 100644
index 00000000000..dc93562dc9c
--- /dev/null
+++ b/apps/studio/components/ui/SchemaComboBox.tsx
@@ -0,0 +1,141 @@
+import { Check, ChevronsUpDown } from 'lucide-react'
+import { useState } from 'react'
+
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { useSchemasQuery } from 'data/database/schemas-query'
+import {
+ AlertDescription_Shadcn_,
+ AlertTitle_Shadcn_,
+ Alert_Shadcn_,
+ Button,
+ CommandEmpty_Shadcn_,
+ CommandGroup_Shadcn_,
+ CommandInput_Shadcn_,
+ CommandItem_Shadcn_,
+ CommandList_Shadcn_,
+ Command_Shadcn_,
+ PopoverContent_Shadcn_,
+ PopoverTrigger_Shadcn_,
+ Popover_Shadcn_,
+ ScrollArea,
+} from 'ui'
+
+interface SchemaComboBoxProps {
+ className?: string
+ disabled?: boolean
+ size?: 'tiny' | 'small'
+ showError?: boolean
+ selectedSchemas: string[]
+ supportSelectAll?: boolean
+ excludedSchemas?: string[]
+ onSelectSchemas: (schemas: string[]) => void
+ label: string
+}
+
+export const SchemaComboBox = ({
+ className,
+ disabled = false,
+ size = 'tiny',
+ showError = true,
+ selectedSchemas = [],
+ excludedSchemas = [],
+ label,
+ onSelectSchemas,
+}: SchemaComboBoxProps) => {
+ const [open, setOpen] = useState(false)
+
+ const { project } = useProjectContext()
+ const {
+ data,
+ isLoading: isSchemasLoading,
+ isSuccess: isSchemasSuccess,
+ isError: isSchemasError,
+ error: schemasError,
+ refetch: refetchSchemas,
+ } = useSchemasQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ })
+
+ const schemas = (data || [])
+ .filter((schema) => !excludedSchemas.includes(schema.name))
+ .sort((a, b) => a.name.localeCompare(b.name))
+
+ const toggleSchema = (schema: string) => {
+ if (selectedSchemas.includes(schema)) {
+ onSelectSchemas(selectedSchemas.filter((s) => s !== schema))
+ } else {
+ const newSelectedSchemas = [...selectedSchemas, schema].sort((a, b) => a.localeCompare(b))
+ onSelectSchemas(newSelectedSchemas)
+ }
+ }
+
+ return (
+ <div className={className}>
+ {isSchemasLoading && (
+ <Button type="default" className="justify-start" block size={size} loading>
+ Loading schemas...
+ </Button>
+ )}
+
+ {showError && isSchemasError && (
+ <Alert_Shadcn_ variant="warning" className="!px-3 !py-3">
+ <AlertTitle_Shadcn_ className="text-xs text-amber-900">
+ Failed to load schemas
+ </AlertTitle_Shadcn_>
+ <AlertDescription_Shadcn_ className="text-xs mb-2 break-words">
+ Error: {(schemasError as any)?.message}
+ </AlertDescription_Shadcn_>
+ <Button type="default" size="tiny" onClick={() => refetchSchemas()}>
+ Reload schemas
+ </Button>
+ </Alert_Shadcn_>
+ )}
+
+ {isSchemasSuccess && (
+ <Popover_Shadcn_ open={open} onOpenChange={setOpen} modal={false}>
+ <PopoverTrigger_Shadcn_ asChild>
+ <Button
+ size={size}
+ disabled={disabled}
+ type="default"
+ className={`w-full [&>span]:w-full`}
+ iconRight={
+ <ChevronsUpDown className="text-foreground-muted" strokeWidth={2} size={14} />
+ }
+ >
+ <div className="w-full flex">
+ <p className="text-foreground">{label}</p>
+ </div>
+ </Button>
+ </PopoverTrigger_Shadcn_>
+ <PopoverContent_Shadcn_ className="p-0 w-56" side="bottom" align="start">
+ <Command_Shadcn_>
+ <CommandInput_Shadcn_ placeholder="Find schema..." />
+ <CommandList_Shadcn_>
+ <CommandEmpty_Shadcn_>No schemas found</CommandEmpty_Shadcn_>
+ <CommandGroup_Shadcn_>
+ <ScrollArea className={(schemas || []).length > 7 ? 'h-[210px]' : ''}>
+ {schemas?.map((schema) => (
+ <CommandItem_Shadcn_
+ key={schema.id}
+ className="cursor-pointer flex items-center justify-between space-x-2 w-full"
+ onSelect={() => toggleSchema(schema.name)}
+ onClick={() => toggleSchema(schema.name)}
+ >
+ <span>{schema.name}</span>
+ {selectedSchemas.includes(schema.name) && (
+ <Check className="text-brand" strokeWidth={2} size={16} />
+ )}
+ </CommandItem_Shadcn_>
+ ))}
+ </ScrollArea>
+ </CommandGroup_Shadcn_>
+ </CommandList_Shadcn_>
+ </Command_Shadcn_>
+ </PopoverContent_Shadcn_>
+ </Popover_Shadcn_>
+ )}
+ </div>
+ )
+}
diff --git a/apps/studio/data/database/entity-definitions-query.ts b/apps/studio/data/database/entity-definitions-query.ts
index 92ceb7e5069..0e820869fcf 100644
--- a/apps/studio/data/database/entity-definitions-query.ts
+++ b/apps/studio/data/database/entity-definitions-query.ts
@@ -1,8 +1,9 @@
import { UseQueryOptions } from '@tanstack/react-query'
import { ExecuteSqlData, ExecuteSqlError, useExecuteSqlQuery } from '../sql/execute-sql-query'
import { CREATE_PG_GET_TABLEDEF_SQL } from './database-query-constants'
+import { databaseKeys } from './keys'
-export const getEntityDefinitionsQuery = (limit = 100) => {
+export const getEntityDefinitionsQuery = (schemas: string[], limit = 100) => {
const sql = /* SQL */ `
${CREATE_PG_GET_TABLEDEF_SQL}
@@ -54,7 +55,7 @@ with records as (
)
or has_any_column_privilege(c.oid, 'SELECT, INSERT, UPDATE, REFERENCES')
)
- and nc.nspname = 'public'
+ and nc.nspname IN (${schemas.map((schema) => `'${schema}'`).join(', ')})
order by c.relname asc
limit ${limit}
offset 0
@@ -78,6 +79,7 @@ export type EntityDefinitionsVariables = {
limit?: number
projectRef?: string
connectionString?: string
+ schemas: string[]
}
type EntityDefinition = { id: number; sql: string }
@@ -87,20 +89,24 @@ export type EntityDefinitionsError = ExecuteSqlError
export const useEntityDefinitionsQuery = <
TData extends EntityDefinitionsData = EntityDefinitionsData,
>(
- { limit, projectRef, connectionString }: EntityDefinitionsVariables,
- options: UseQueryOptions<ExecuteSqlData, EntityDefinitionsError, TData> = {}
+ { schemas, limit, projectRef, connectionString }: EntityDefinitionsVariables,
+ {
+ enabled = true,
+ ...options
+ }: UseQueryOptions<ExecuteSqlData, EntityDefinitionsError, TData> = {}
) => {
return useExecuteSqlQuery(
{
projectRef,
connectionString,
- sql: getEntityDefinitionsQuery(limit),
- queryKey: ['entity-definitions'],
+ sql: getEntityDefinitionsQuery(schemas, limit),
+ queryKey: databaseKeys.entityDefinitions(projectRef, schemas),
},
{
select(data) {
return data.result[0].data.definitions
},
+ enabled: enabled && schemas.length > 0,
...options,
}
)
diff --git a/apps/studio/data/database/keys.ts b/apps/studio/data/database/keys.ts
index f80f1063f18..2f43f0492aa 100644
--- a/apps/studio/data/database/keys.ts
+++ b/apps/studio/data/database/keys.ts
@@ -1,4 +1,6 @@
export const databaseKeys = {
+ entityDefinitions: (projectRef: string | undefined, schemas: string[]) =>
+ ['projects', projectRef, 'entity-definitions', schemas] as const,
backups: (projectRef: string | undefined) => [projectRef, 'database', 'backups'] as const,
poolingConfiguration: (projectRef: string | undefined) =>
[projectRef, 'database', 'pooling-configuration'] as const,
diff --git a/apps/studio/hooks/misc/useAllowSendAiSchema.ts b/apps/studio/hooks/misc/useAllowSendAiSchema.ts
deleted file mode 100644
index 780ca55c269..00000000000
--- a/apps/studio/hooks/misc/useAllowSendAiSchema.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { IS_PLATFORM } from 'common'
-import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'
-import { useOrgOptedIntoAi } from 'hooks/misc/useOrgOptedIntoAi'
-import { LOCAL_STORAGE_KEYS } from 'lib/constants'
-
-export function useAllowSendAiSchema() {
- const isOptedIntoAI = useOrgOptedIntoAi()
- const [hasEnabledAISchema] = useLocalStorageQuery(LOCAL_STORAGE_KEYS.SQL_EDITOR_AI_SCHEMA, true)
- const includeSchemaMetadata = (isOptedIntoAI || !IS_PLATFORM) && hasEnabledAISchema
-
- return includeSchemaMetadata
-}
diff --git a/apps/studio/hooks/misc/useSchemasForAi.ts b/apps/studio/hooks/misc/useSchemasForAi.ts
new file mode 100644
index 00000000000..ccdebb4e268
--- /dev/null
+++ b/apps/studio/hooks/misc/useSchemasForAi.ts
@@ -0,0 +1,19 @@
+import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'
+import { LOCAL_STORAGE_KEYS } from 'lib/constants'
+import { Dispatch, SetStateAction } from 'react'
+
+/**
+ * Returns which schemas are ok to be sent to AI.
+ */
+export function useSchemasForAi(
+ ref: string
+): readonly [string[], Dispatch<SetStateAction<string[]>>] {
+ const [enabledSchemas, setEnabledSchemas] = useLocalStorageQuery(
+ LOCAL_STORAGE_KEYS.SQL_EDITOR_AI_SCHEMA(ref),
+ ['public']
+ )
+
+ if (!ref) return [[], () => {}]
+
+ return [enabledSchemas, setEnabledSchemas]
+}
diff --git a/apps/studio/lib/constants/index.ts b/apps/studio/lib/constants/index.ts
index 6f3b872c761..15a59e212ae 100644
--- a/apps/studio/lib/constants/index.ts
+++ b/apps/studio/lib/constants/index.ts
@@ -42,7 +42,9 @@ export const LOCAL_STORAGE_KEYS = {
SQL_EDITOR_INTELLISENSE: 'supabase_sql-editor-intellisense-enabled',
SQL_EDITOR_SPLIT_SIZE: 'supabase_sql-editor-split-size',
SQL_EDITOR_AI_PANEL_SPLIT_SIZE: 'supabase_sql-editor-ai-panel-split-size',
- SQL_EDITOR_AI_SCHEMA: 'supabase_sql-editor-ai-schema-enabled',
+
+ // Key to track which schemas are ok to be sent to AI. The project ref is intentionally put at the end for easier search in the browser console.
+ SQL_EDITOR_AI_SCHEMA: (ref: string) => `supabase_sql-editor-ai-schema-enabled-${ref}`,
SQL_EDITOR_AI_OPEN: 'supabase_sql-editor-ai-open',
LOG_EXPLORER_SPLIT_SIZE: 'supabase_log-explorer-split-size',
GRAPHIQL_RLS_BYPASS_WARNING: 'graphiql-rls-bypass-warning-dismissed',