Skip to content

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

feat(sql-editor): split ai input into its own screen

Greg Richardsona5c6b007be8f
diff --git a/packages/ui/src/components/Command/Command.icons.tsx b/packages/ui/src/components/Command/Command.icons.tsx
index 6c84745a927..d313e0d9bf4 100644
--- a/packages/ui/src/components/Command/Command.icons.tsx
+++ b/packages/ui/src/components/Command/Command.icons.tsx
@@ -6,7 +6,7 @@ interface AiIconProps {
}
export const AiIcon = ({ className }: AiIconProps) => (
- <AiIconAnimation className={cn('mr-2', className)} allowHoverEffect />
+ <AiIconAnimation className={className} allowHoverEffect />
)
export const AiIconChat = ({ loading = false }) => (
diff --git a/studio/components/interfaces/SQLEditor/AISettingsModal.tsx b/studio/components/interfaces/SQLEditor/AISettingsModal.tsx
index defa6f52e73..bdc898342d2 100644
--- a/studio/components/interfaces/SQLEditor/AISettingsModal.tsx
+++ b/studio/components/interfaces/SQLEditor/AISettingsModal.tsx
@@ -13,7 +13,7 @@ const AISettingsModal = (props: ModalProps) => {
const isOptedInToAI =
selectedOrganization?.opt_in_tags?.includes('AI_SQL_GENERATOR_OPT_IN') ?? false
const [isOptedInToAISchema, setIsOptedInToAISchema] = useLocalStorageQuery(
- 'supabase_sql-editor-ai-schema',
+ 'supabase_sql-editor-ai-schema-enabled',
false
)
diff --git a/studio/components/interfaces/SQLEditor/SQLEditor.tsx b/studio/components/interfaces/SQLEditor/SQLEditor.tsx
index b98faf8f10d..973dd3a836f 100644
--- a/studio/components/interfaces/SQLEditor/SQLEditor.tsx
+++ b/studio/components/interfaces/SQLEditor/SQLEditor.tsx
@@ -141,7 +141,7 @@ const SQLEditor = () => {
const [sqlDiff, setSqlDiff] = useState<ContentDiff>()
const inputRef = useRef<HTMLInputElement>(null)
- const [aiOpen, setAiOpen] = useState(false)
+ const [isAiOpen, setIsAiOpen] = useLocalStorageQuery('supabase_sql-editor-ai-open', true)
const [isAISettingsOpen, setIsAISettingsOpen] = useState(false)
const [isConfirmModalOpen, setIsConfirmModalOpen] = useState(false)
@@ -150,12 +150,17 @@ const SQLEditor = () => {
const selectedProject = useSelectedProject()
const isOptedInToAI =
selectedOrganization?.opt_in_tags?.includes('AI_SQL_GENERATOR_OPT_IN') ?? false
- const [isOptedInToAISchema] = useLocalStorageQuery('supabase_sql-editor-ai-schema', false)
+ const [isOptedInToAISchema] = useLocalStorageQuery('supabase_sql-editor-ai-schema-enabled', false)
const [isAcceptDiffLoading, setIsAcceptDiffLoading] = useState(false)
const includeSchemaMetadata = (isOptedInToAI || !IS_PLATFORM) && isOptedInToAISchema
const [selectedDiffType, setSelectedDiffType] = useState(DiffType.Modification)
+ const [isFirstRender, setIsFirstRender] = useState(true)
+
+ useEffect(() => {
+ setIsFirstRender(false)
+ }, [])
const { data } = useEntityDefinitionsQuery(
{
@@ -445,16 +450,20 @@ const SQLEditor = () => {
}}
/>
<div className="flex h-full flex-col relative">
- {aiOpen && (
+ {isAiOpen && (
<motion.div
key="ask-ai-input-container"
layoutId="ask-ai-input-container"
variants={{
visible: {
borderRadius: 0,
+ x: 0,
+ },
+ hidden: {
+ x: 100,
},
}}
- initial="visible"
+ initial={isFirstRender ? 'visible' : 'hidden'}
animate="visible"
className="w-full flex justify-center z-10 h-[60px] bg-brand-300 border-b border-brand-400 px-5"
>
@@ -464,7 +473,9 @@ const SQLEditor = () => {
'flex items-center gap-3'
)}
>
- <AiIconAnimation loading={isEditSqlLoading} />
+ <motion.div layoutId="ask-ai-input-icon" transition={{ duration: 0.1 }}>
+ <AiIconAnimation loading={isEditSqlLoading} />
+ </motion.div>
<AnimatePresence initial={false} exitBeforeEnter>
{debugSolution && (
@@ -507,7 +518,7 @@ const SQLEditor = () => {
placeholder={!debugSolution ? 'Ask Supabase AI to modify your query' : ''}
onKeyDown={(e) => {
if (e.key === 'Escape' && !aiInput) {
- setAiOpen(false)
+ setIsAiOpen(false)
}
}}
onKeyPress={async (e) => {
@@ -570,9 +581,6 @@ const SQLEditor = () => {
}
}}
/>
- {/* <div className="opacity-30">
- <IconCornerDownLeft size={12} strokeWidth={1.5} />
- </div> */}
</motion.div>
) : (
<motion.div
@@ -611,7 +619,7 @@ const SQLEditor = () => {
</motion.div>
)}
</AnimatePresence>
- <div className="flex flex-row items-center gap-2">
+ <div className="flex flex-row items-center gap-3 mr-1">
{isDiffOpen ? (
<>
<div className="flex items-center">
@@ -693,7 +701,7 @@ const SQLEditor = () => {
</button>
<button
className="text-brand-600 dark:text-brand hover:text-brand-600"
- onClick={() => setAiOpen(false)}
+ onClick={() => setIsAiOpen(false)}
>
<IconX size={21} />
</button>
@@ -717,20 +725,22 @@ const SQLEditor = () => {
onDragEnd={onDragEnd}
>
<div className="flex-grow overflow-y-auto border-b">
- {!aiOpen && (
- <button
- onClick={() => setAiOpen(!aiOpen)}
+ {!isAiOpen && (
+ <motion.button
+ layoutId="ask-ai-input-icon"
+ transition={{ duration: 0.1 }}
+ onClick={() => setIsAiOpen(!isAiOpen)}
className={cn(
'group',
'absolute z-10',
'rounded-lg',
- 'right-[18px] top-4',
+ 'right-[24px] top-4',
'transition-all duration-200',
'ease-out'
)}
>
<AiIconAnimation loading={false} allowHoverEffect />
- </button>
+ </motion.button>
)}
{isLoading ? (
diff --git a/studio/components/interfaces/SQLEditor/SQLTemplates/SQLAI.tsx b/studio/components/interfaces/SQLEditor/SQLTemplates/SQLAI.tsx
new file mode 100644
index 00000000000..a774795d0e2
--- /dev/null
+++ b/studio/components/interfaces/SQLEditor/SQLTemplates/SQLAI.tsx
@@ -0,0 +1,249 @@
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { useParams, useTelemetryProps } from 'common'
+import { useSqlGenerateMutation } from 'data/ai/sql-generate-mutation'
+import { SqlSnippet } from 'data/content/sql-snippets-query'
+import { useEntityDefinitionsQuery } from 'data/database/entity-definitions-query'
+import { motion } from 'framer-motion'
+import {
+ useCheckPermissions,
+ useLocalStorageQuery,
+ useSelectedOrganization,
+ useSelectedProject,
+ useStore,
+} from 'hooks'
+import { IS_PLATFORM } from 'lib/constants'
+import { uuidv4 } from 'lib/helpers'
+import { useProfile } from 'lib/profile'
+import Telemetry from 'lib/telemetry'
+import { isError } from 'lodash'
+import router from 'next/router'
+import { useState } from 'react'
+import { format } from 'sql-formatter'
+import { useSqlEditorStateSnapshot } from 'state/sql-editor'
+import { AiIcon, IconCornerDownLeft, IconSettings, Input } from 'ui'
+import AISettingsModal from '../AISettingsModal'
+import { sqlAiDisclaimerComment } from '../SQLEditor.constants'
+import { createSqlSnippetSkeleton } from '../SQLEditor.utils'
+
+const SQLAI = () => {
+ const { ui } = useStore()
+ const { profile } = useProfile()
+ const { ref } = useParams()
+
+ const { mutateAsync: generateSql, isLoading: isSqlGenerateLoading } = useSqlGenerateMutation()
+ const [isAISettingsOpen, setIsAISettingsOpen] = useState(false)
+ const selectedOrganization = useSelectedOrganization()
+ const selectedProject = useSelectedProject()
+ const isOptedInToAI =
+ selectedOrganization?.opt_in_tags?.includes('AI_SQL_GENERATOR_OPT_IN') ?? false
+ const [isOptedInToAISchema] = useLocalStorageQuery('supabase_sql-editor-ai-schema-enabled', false)
+ const [, setIsAiOpen] = useLocalStorageQuery('supabase_sql-editor-ai-open', false)
+ const telemetryProps = useTelemetryProps()
+ const snap = useSqlEditorStateSnapshot()
+ const canCreateSQLSnippet = useCheckPermissions(PermissionAction.CREATE, 'user_content', {
+ resource: { type: 'sql', owner_id: profile?.id },
+ subject: { id: profile?.id },
+ })
+
+ const includeSchemaMetadata = (isOptedInToAI || !IS_PLATFORM) && isOptedInToAISchema
+
+ const { data } = useEntityDefinitionsQuery(
+ {
+ projectRef: selectedProject?.ref,
+ connectionString: selectedProject?.connectionString,
+ },
+ { enabled: includeSchemaMetadata }
+ )
+
+ const entityDefinitions = includeSchemaMetadata ? data?.map((def) => def.sql.trim()) : undefined
+
+ // [Joshen TODO] Removed optimistic query creation logic for now, need to figure out
+ // how to do that after using ids as part of the URL
+ const handleNewQuery = async (sql: string, name: string) => {
+ if (!ref) return console.error('Project ref is required')
+ if (!canCreateSQLSnippet) {
+ return ui.setNotification({
+ category: 'info',
+ message: 'Your queries will not be saved as you do not have sufficient permissions',
+ })
+ }
+
+ try {
+ const snippet = createSqlSnippetSkeleton({ name, sql, owner_id: profile?.id })
+ const data = { ...snippet, id: uuidv4() }
+ snap.addSnippet(data as SqlSnippet, ref, true)
+ router.push(`/project/${ref}/sql/${data.id}`)
+ } catch (error: any) {
+ ui.setNotification({
+ category: 'error',
+ message: `Failed to create new query: ${error.message}`,
+ })
+ }
+ }
+
+ return (
+ <>
+ <AISettingsModal visible={isAISettingsOpen} onCancel={() => setIsAISettingsOpen(false)} />
+ <div className="mt-32 mb-32 flex flex-col items-center">
+ <motion.h1
+ className="text-scale-1200 mb-8 text-3xl"
+ variants={{
+ visible: {
+ y: 0,
+ opacity: 1,
+ },
+ hidden: {
+ y: 10,
+ opacity: 0,
+ },
+ }}
+ initial="hidden"
+ animate="visible"
+ >
+ What do you want to build?
+ </motion.h1>
+ <div className="w-full flex justify-center">
+ {!isSqlGenerateLoading ? (
+ <motion.div
+ key="ask-ai-input-container"
+ layoutId="ask-ai-input-container"
+ className="w-full max-w-2xl border border-brand-900"
+ variants={{
+ visible: {
+ y: 0,
+ opacity: 1,
+ borderRadius: 6,
+ },
+ hidden: {
+ y: -50,
+ opacity: 0,
+ borderRadius: 6,
+ },
+ }}
+ initial="hidden"
+ animate="visible"
+ >
+ <Input
+ size="xlarge"
+ inputRef={(inputElement: HTMLInputElement) => {
+ setTimeout(() => {
+ inputElement?.focus()
+ }, 200)
+ }}
+ icon={
+ <motion.div
+ className="ml-1"
+ variants={{
+ visible: {
+ scale: 1,
+ },
+ }}
+ initial="visible"
+ animate="visible"
+ transition={{ duration: 0.2 }}
+ >
+ <AiIcon className="w-4 h-4" />
+ </motion.div>
+ }
+ inputClassName="w-full border-none py-4 focus:!ring-0 pr-20 pl-12"
+ iconContainerClassName="transition text-scale-800 text-brand-900"
+ placeholder="Ask Supabase AI to build a query"
+ className="w-full"
+ onKeyPress={async (e) => {
+ if (e.key === 'Enter') {
+ try {
+ const value = e.currentTarget.value
+
+ if (!value) {
+ return
+ }
+
+ const { title, sql } = await generateSql({
+ prompt: e.currentTarget.value,
+ entityDefinitions,
+ })
+
+ const formattedSql =
+ sqlAiDisclaimerComment +
+ '\n\n' +
+ format(sql, {
+ language: 'postgresql',
+ keywordCase: 'lower',
+ })
+
+ setIsAiOpen(true)
+ await handleNewQuery(formattedSql, title)
+
+ Telemetry.sendEvent(
+ {
+ category: 'sql_editor',
+ action: 'ai_suggestion_created',
+ label: 'create_snippet',
+ },
+ telemetryProps,
+ router
+ )
+ } catch (error: unknown) {
+ if (isError(error)) {
+ ui.setNotification({
+ category: 'error',
+ message: error.message,
+ })
+ }
+ }
+ }
+ }}
+ actions={
+ <div className="flex items-center space-x-1 mr-4 gap-2">
+ <IconCornerDownLeft size={16} strokeWidth={1.5} />
+ <IconSettings
+ className="cursor-pointer"
+ onClick={() => setIsAISettingsOpen(true)}
+ />
+ </div>
+ }
+ />
+ </motion.div>
+ ) : (
+ <motion.div
+ key="ask-ai-loading"
+ layoutId="ask-ai-input-container"
+ className="p-5 border border-brand-900 text-brand-900"
+ variants={{
+ visible: {
+ borderRadius: 50,
+ },
+ }}
+ transition={{
+ type: 'spring',
+ mass: 0.1,
+ stiffness: 200,
+ damping: 30,
+ }}
+ initial="visible"
+ animate="visible"
+ >
+ <motion.div
+ key="ask-ai-loading-icon"
+ layoutId="ask-ai-input-icon"
+ animate={{
+ scale: [0.9, 1.1, 0.9],
+ transition: {
+ delay: 0.2,
+ ease: 'linear',
+ duration: 2,
+ repeat: Infinity,
+ },
+ }}
+ >
+ <AiIcon className="w-4 h-4" />
+ </motion.div>
+ </motion.div>
+ )}
+ </div>
+ </div>
+ </>
+ )
+}
+
+export default SQLAI
diff --git a/studio/components/interfaces/SQLEditor/SQLTemplates/SQLQuickstarts.tsx b/studio/components/interfaces/SQLEditor/SQLTemplates/SQLQuickstarts.tsx
index 859a2ab16f0..870310b3eca 100644
--- a/studio/components/interfaces/SQLEditor/SQLTemplates/SQLQuickstarts.tsx
+++ b/studio/components/interfaces/SQLEditor/SQLTemplates/SQLQuickstarts.tsx
@@ -3,32 +3,14 @@ import { partition } from 'lodash'
import { observer } from 'mobx-react-lite'
import { useParams, useTelemetryProps } from 'common'
-import {
- SQL_TEMPLATES,
- sqlAiDisclaimerComment,
-} from 'components/interfaces/SQLEditor/SQLEditor.constants'
-import { useSqlGenerateMutation } from 'data/ai/sql-generate-mutation'
+import { SQL_TEMPLATES } from 'components/interfaces/SQLEditor/SQLEditor.constants'
import { SqlSnippet } from 'data/content/sql-snippets-query'
-import { useEntityDefinitionsQuery } from 'data/database/entity-definitions-query'
-import { isError } from 'data/utils/error-check'
-import { motion } from 'framer-motion'
-import {
- useCheckPermissions,
- useLocalStorageQuery,
- useSelectedOrganization,
- useSelectedProject,
- useStore,
-} from 'hooks'
-import { IS_PLATFORM } from 'lib/constants'
+import { useCheckPermissions, useStore } from 'hooks'
import { uuidv4 } from 'lib/helpers'
import { useProfile } from 'lib/profile'
import Telemetry from 'lib/telemetry'
import { useRouter } from 'next/router'
-import { useState } from 'react'
-import { format } from 'sql-formatter'
import { useSqlEditorStateSnapshot } from 'state/sql-editor'
-import { AiIcon, IconCornerDownLeft, IconSettings, Input } from 'ui'
-import AISettingsModal from '../AISettingsModal'
import { createSqlSnippetSkeleton } from '../SQLEditor.utils'
import SQLCard from './SQLCard'
@@ -37,26 +19,7 @@ const SQLQuickstarts = observer(() => {
const { ref } = useParams()
const router = useRouter()
const { profile } = useProfile()
- const [sql, quickStart] = partition(SQL_TEMPLATES, { type: 'template' })
- const { mutateAsync: generateSql, isLoading: isSqlGenerateLoading } = useSqlGenerateMutation()
- const [isAISettingsOpen, setIsAISettingsOpen] = useState(false)
- const selectedOrganization = useSelectedOrganization()
- const selectedProject = useSelectedProject()
- const isOptedInToAI =
- selectedOrganization?.opt_in_tags?.includes('AI_SQL_GENERATOR_OPT_IN') ?? false
- const [isOptedInToAISchema] = useLocalStorageQuery('supabase_sql-editor-ai-schema', false)
-
- const includeSchemaMetadata = (isOptedInToAI || !IS_PLATFORM) && isOptedInToAISchema
-
- const { data } = useEntityDefinitionsQuery(
- {
- projectRef: selectedProject?.ref,
- connectionString: selectedProject?.connectionString,
- },
- { enabled: includeSchemaMetadata }
- )
-
- const entityDefinitions = includeSchemaMetadata ? data?.map((def) => def.sql.trim()) : undefined
+ const [, quickStart] = partition(SQL_TEMPLATES, { type: 'template' })
const telemetryProps = useTelemetryProps()
const snap = useSqlEditorStateSnapshot()
@@ -90,194 +53,43 @@ const SQLQuickstarts = observer(() => {
}
return (
- <>
- <AISettingsModal visible={isAISettingsOpen} onCancel={() => setIsAISettingsOpen(false)} />
- <div className="block h-full space-y-8 overflow-y-auto p-6">
- <div className="mt-32 mb-32 flex flex-col items-center">
- <motion.h1
- className="text-scale-1200 mb-8 text-3xl"
- variants={{
- visible: {
- y: 0,
- opacity: 1,
- },
- hidden: {
- y: 10,
- opacity: 0,
- },
- }}
- initial="hidden"
- animate="visible"
- >
- What do you want to build?
- </motion.h1>
- <div className="w-full flex justify-center">
- {!isSqlGenerateLoading ? (
- <motion.div
- key="ask-ai-input-container"
- layoutId="ask-ai-input-container"
- className="w-full max-w-2xl border border-brand-900"
- variants={{
- visible: {
- y: 0,
- opacity: 1,
- borderRadius: 6,
- },
- hidden: {
- y: -50,
- opacity: 0,
- borderRadius: 6,
- },
- }}
- initial="hidden"
- animate="visible"
- >
- <Input
- size="xlarge"
- inputRef={(inputElement: HTMLInputElement) => {
- setTimeout(() => {
- inputElement?.focus()
- }, 200)
- }}
- icon={
- <motion.div
- key="ask-ai-input-icon"
- layoutId="ask-ai-input-icon"
- className="ml-1"
- variants={{
- visible: {
- scale: 1,
- },
- }}
- initial="visible"
- animate="visible"
- >
- <AiIcon className="w-4 h-4" />
- </motion.div>
- }
- inputClassName="w-full border-none py-4 focus:!ring-0 pr-20"
- iconContainerClassName="transition text-scale-800 text-brand-900"
- placeholder="Ask Supabase AI to build a query"
- className="w-full"
- onKeyPress={async (e) => {
- if (e.key === 'Enter') {
- try {
- const value = e.currentTarget.value
-
- if (!value) {
- return
- }
-
- const { title, sql } = await generateSql({
- prompt: e.currentTarget.value,
- entityDefinitions,
- })
-
- const formattedSql =
- sqlAiDisclaimerComment +
- '\n\n' +
- format(sql, {
- language: 'postgresql',
- keywordCase: 'lower',
- })
-
- await handleNewQuery(formattedSql, title)
- } catch (error: unknown) {
- if (isError(error)) {
- ui.setNotification({
- category: 'error',
- message: error.message,
- })
- }
- }
- }
- }}
- actions={
- <div className="flex items-center space-x-1 mr-4 gap-2">
- <IconCornerDownLeft size={16} strokeWidth={1.5} />
- <IconSettings
- className="cursor-pointer"
- onClick={() => setIsAISettingsOpen(true)}
- />
- </div>
- }
- />
- </motion.div>
- ) : (
- <motion.div
- key="ask-ai-loading"
- layoutId="ask-ai-input-container"
- className="p-5 border border-brand-900 text-brand-900"
- variants={{
- visible: {
- borderRadius: 50,
- },
- }}
- transition={{
- type: 'spring',
- mass: 0.1,
- stiffness: 200,
- damping: 30,
- }}
- initial="visible"
- animate="visible"
- >
- <motion.div
- key="ask-ai-loading-icon"
- layoutId="ask-ai-input-icon"
- animate={{
- scale: [0.9, 1.1, 0.9],
- transition: {
- delay: 0.2,
- ease: 'linear',
- duration: 2,
- repeat: Infinity,
- },
- }}
- >
- <AiIcon className="w-4 h-4" />
- </motion.div>
- </motion.div>
- )}
- </div>
+ <div className="block h-full space-y-8 overflow-y-auto p-6">
+ <div className="mb-8">
+ <div className="mb-4">
+ <h1 className="text-scale-1200 mb-3 text-xl">Quick start</h1>
+ <p className="text-scale-1100 text-sm">
+ While we're in beta, we want to offer a quick way to explore Supabase. While we build
+ importers, check out these simple starters.
+ </p>
+ <p className="text-scale-1100 text-sm">
+ Click on any script to fill the query box, modify the script, then click
+ <span className="text-code">Run</span>.
+ </p>
</div>
- <div className="mb-8">
- <div className="mb-4">
- <h1 className="text-scale-1200 mb-3 text-xl">Quick start</h1>
- <p className="text-scale-1100 text-sm">
- While we're in beta, we want to offer a quick way to explore Supabase. While we build
- importers, check out these simple starters.
- </p>
- <p className="text-scale-1100 text-sm">
- Click on any script to fill the query box, modify the script, then click
- <span className="text-code">Run</span>.
- </p>
- </div>
- <div className="grid gap-4 sm:grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4">
- {quickStart.map((x) => (
- <SQLCard
- key={x.title}
- title={x.title}
- description={x.description}
- sql={x.sql}
- onClick={(sql, title) => {
- handleNewQuery(sql, title)
- Telemetry.sendEvent(
- {
- category: 'quickstart',
- action: 'quickstart_clicked',
- label: x.title,
- },
- telemetryProps,
- router
- )
- }}
- />
- ))}
- </div>
+ <div className="grid gap-4 sm:grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4">
+ {quickStart.map((x) => (
+ <SQLCard
+ key={x.title}
+ title={x.title}
+ description={x.description}
+ sql={x.sql}
+ onClick={(sql, title) => {
+ handleNewQuery(sql, title)
+ Telemetry.sendEvent(
+ {
+ category: 'quickstart',
+ action: 'quickstart_clicked',
+ label: x.title,
+ },
+ telemetryProps,
+ router
+ )
+ }}
+ />
+ ))}
</div>
</div>
- </>
+ </div>
)
})
diff --git a/studio/components/interfaces/SQLEditor/SQLTemplates/SQLTemplates.tsx b/studio/components/interfaces/SQLEditor/SQLTemplates/SQLTemplates.tsx
index 4e9c6a283aa..c9d437238d4 100644
--- a/studio/components/interfaces/SQLEditor/SQLTemplates/SQLTemplates.tsx
+++ b/studio/components/interfaces/SQLEditor/SQLTemplates/SQLTemplates.tsx
@@ -3,32 +3,14 @@ import { partition } from 'lodash'
import { observer } from 'mobx-react-lite'
import { useParams, useTelemetryProps } from 'common'
-import {
- SQL_TEMPLATES,
- sqlAiDisclaimerComment,
-} from 'components/interfaces/SQLEditor/SQLEditor.constants'
-import { useSqlGenerateMutation } from 'data/ai/sql-generate-mutation'
+import { SQL_TEMPLATES } from 'components/interfaces/SQLEditor/SQLEditor.constants'
import { SqlSnippet } from 'data/content/sql-snippets-query'
-import { useEntityDefinitionsQuery } from 'data/database/entity-definitions-query'
-import { isError } from 'data/utils/error-check'
-import { motion } from 'framer-motion'
-import {
- useCheckPermissions,
- useLocalStorageQuery,
- useSelectedOrganization,
- useSelectedProject,
- useStore,
-} from 'hooks'
-import { IS_PLATFORM } from 'lib/constants'
+import { useCheckPermissions, useStore } from 'hooks'
import { uuidv4 } from 'lib/helpers'
import { useProfile } from 'lib/profile'
import Telemetry from 'lib/telemetry'
import { useRouter } from 'next/router'
-import { useState } from 'react'
-import { format } from 'sql-formatter'
import { useSqlEditorStateSnapshot } from 'state/sql-editor'
-import { AiIcon, IconCornerDownLeft, IconSettings, Input } from 'ui'
-import AISettingsModal from '../AISettingsModal'
import { createSqlSnippetSkeleton } from '../SQLEditor.utils'
import SQLCard from './SQLCard'
@@ -37,26 +19,7 @@ const SQLTemplates = observer(() => {
const { ref } = useParams()
const router = useRouter()
const { profile } = useProfile()
- const [sql, quickStart] = partition(SQL_TEMPLATES, { type: 'template' })
- const { mutateAsync: generateSql, isLoading: isSqlGenerateLoading } = useSqlGenerateMutation()
- const [isAISettingsOpen, setIsAISettingsOpen] = useState(false)
- const selectedOrganization = useSelectedOrganization()
- const selectedProject = useSelectedProject()
- const isOptedInToAI =
- selectedOrganization?.opt_in_tags?.includes('AI_SQL_GENERATOR_OPT_IN') ?? false
- const [isOptedInToAISchema] = useLocalStorageQuery('supabase_sql-editor-ai-schema', false)
-
- const includeSchemaMetadata = (isOptedInToAI || !IS_PLATFORM) && isOptedInToAISchema
-
- const { data } = useEntityDefinitionsQuery(
- {
- projectRef: selectedProject?.ref,
- connectionString: selectedProject?.connectionString,
- },
- { enabled: includeSchemaMetadata }
- )
-
- const entityDefinitions = includeSchemaMetadata ? data?.map((def) => def.sql.trim()) : undefined
+ const [sql] = partition(SQL_TEMPLATES, { type: 'template' })
const telemetryProps = useTelemetryProps()
const snap = useSqlEditorStateSnapshot()
@@ -90,201 +53,40 @@ const SQLTemplates = observer(() => {
}
return (
- <>
- <AISettingsModal visible={isAISettingsOpen} onCancel={() => setIsAISettingsOpen(false)} />
- <div className="block h-full space-y-8 overflow-y-auto p-6">
- <div className="mt-32 mb-32 flex flex-col items-center">
- <motion.h1
- className="text-scale-1200 mb-8 text-3xl"
- variants={{
- visible: {
- y: 0,
- opacity: 1,
- },
- hidden: {
- y: 10,
- opacity: 0,
- },
- }}
- initial="hidden"
- animate="visible"
- >
- What do you want to build?
- </motion.h1>
- <div className="w-full flex justify-center">
- {!isSqlGenerateLoading ? (
- <motion.div
- key="ask-ai-input-container"
- layoutId="ask-ai-input-container"
- className="w-full max-w-2xl border border-brand-900"
- variants={{
- visible: {
- y: 0,
- opacity: 1,
- borderRadius: 6,
- },
- hidden: {
- y: -50,
- opacity: 0,
- borderRadius: 6,
- },
- }}
- initial="hidden"
- animate="visible"
- >
- <Input
- size="xlarge"
- inputRef={(inputElement: HTMLInputElement) => {
- setTimeout(() => {
- inputElement?.focus()
- }, 200)
- }}
- icon={
- <motion.div
- key="ask-ai-input-icon"
- layoutId="ask-ai-input-icon"
- className="ml-1"
- variants={{
- visible: {
- scale: 1,
- },
- }}
- initial="visible"
- animate="visible"
- >
- <AiIcon className="w-4 h-4" />
- </motion.div>
- }
- inputClassName="w-full border-none py-4 focus:!ring-0 pr-20"
- iconContainerClassName="transition text-scale-800 text-brand-900"
- placeholder="Ask Supabase AI to build a query"
- className="w-full"
- onKeyPress={async (e) => {
- if (e.key === 'Enter') {
- try {
- const value = e.currentTarget.value
-
- if (!value) {
- return
- }
-
- const { title, sql } = await generateSql({
- prompt: e.currentTarget.value,
- entityDefinitions,
- })
-
- const formattedSql =
- sqlAiDisclaimerComment +
- '\n\n' +
- format(sql, {
- language: 'postgresql',
- keywordCase: 'lower',
- })
-
- await handleNewQuery(formattedSql, title)
-
- Telemetry.sendEvent(
- {
- category: 'sql_editor',
- action: 'ai_suggestion_created',
- label: 'create_snippet',
- },
- telemetryProps,
- router
- )
- } catch (error: unknown) {
- if (isError(error)) {
- ui.setNotification({
- category: 'error',
- message: error.message,
- })
- }
- }
- }
- }}
- actions={
- <div className="flex items-center space-x-1 mr-4 gap-2">
- <IconCornerDownLeft size={16} strokeWidth={1.5} />
- <IconSettings
- className="cursor-pointer"
- onClick={() => setIsAISettingsOpen(true)}
- />
- </div>
- }
- />
- </motion.div>
- ) : (
- <motion.div
- key="ask-ai-loading"
- layoutId="ask-ai-input-container"
- className="p-5 border border-brand-900 text-brand-900"
- variants={{
- visible: {
- borderRadius: 50,
- },
- }}
- transition={{
- type: 'spring',
- mass: 0.1,
- stiffness: 200,
- damping: 30,
- }}
- initial="visible"
- animate="visible"
- >
- <motion.div
- key="ask-ai-loading-icon"
- layoutId="ask-ai-input-icon"
- animate={{
- scale: [0.9, 1.1, 0.9],
- transition: {
- delay: 0.2,
- ease: 'linear',
- duration: 2,
- repeat: Infinity,
- },
- }}
- >
- <AiIcon className="w-4 h-4" />
- </motion.div>
- </motion.div>
- )}
- </div>
+ <div className="block h-full space-y-8 overflow-y-auto p-6">
+ <div>
+ <div className="mb-4">
+ <h1 className="text-scale-1200 mb-3 text-xl">Scripts</h1>
+ <p className="text-scale-1100 text-sm">Quick scripts to run on your database.</p>
+ <p className="text-scale-1100 text-sm">
+ Click on any script to fill the query box, modify the script, then click
+ <span className="text-code">Run</span>.
+ </p>
</div>
- <div>
- <div className="mb-4">
- <h1 className="text-scale-1200 mb-3 text-xl">Scripts</h1>
- <p className="text-scale-1100 text-sm">Quick scripts to run on your database.</p>
- <p className="text-scale-1100 text-sm">
- Click on any script to fill the query box, modify the script, then click
- <span className="text-code">Run</span>.
- </p>
- </div>
- <div className="grid gap-4 sm:grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4">
- {sql.map((x) => (
- <SQLCard
- key={x.title}
- title={x.title}
- description={x.description}
- sql={x.sql}
- onClick={(sql, title) => {
- handleNewQuery(sql, title)
- Telemetry.sendEvent(
- {
- category: 'scripts',
- action: 'script_clicked',
- label: x.title,
- },
- telemetryProps,
- router
- )
- }}
- />
- ))}
- </div>
+ <div className="grid gap-4 sm:grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4">
+ {sql.map((x) => (
+ <SQLCard
+ key={x.title}
+ title={x.title}
+ description={x.description}
+ sql={x.sql}
+ onClick={(sql, title) => {
+ handleNewQuery(sql, title)
+ Telemetry.sendEvent(
+ {
+ category: 'scripts',
+ action: 'script_clicked',
+ label: x.title,
+ },
+ telemetryProps,
+ router
+ )
+ }}
+ />
+ ))}
</div>
</div>
- </>
+ </div>
)
})
diff --git a/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabResults.tsx b/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabResults.tsx
index 0f34831106e..017fc4c1ed4 100644
--- a/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabResults.tsx
+++ b/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabResults.tsx
@@ -24,7 +24,7 @@ const UtilityTabResults = ({ id, isExecuting }: UtilityTabResultsProps) => {
const selectedProject = useSelectedProject()
const isOptedInToAI =
selectedOrganization?.opt_in_tags?.includes('AI_SQL_GENERATOR_OPT_IN') ?? false
- const [isOptedInToAISchema] = useLocalStorageQuery('supabase_sql-editor-ai-schema', false)
+ const [isOptedInToAISchema] = useLocalStorageQuery('supabase_sql-editor-ai-schema-enabled', false)
const includeSchemaMetadata = (isOptedInToAI || !IS_PLATFORM) && isOptedInToAISchema
diff --git a/studio/components/layouts/SQLEditorLayout/SQLEditorMenu.tsx b/studio/components/layouts/SQLEditorLayout/SQLEditorMenu.tsx
index d9f8dbc1460..c129263794f 100644
--- a/studio/components/layouts/SQLEditorLayout/SQLEditorMenu.tsx
+++ b/studio/components/layouts/SQLEditorLayout/SQLEditorMenu.tsx
@@ -113,6 +113,11 @@ const SideBarContent = observer(() => {
</div>
<div className="space-y-6 px-3">
<div>
+ <ProductMenuItem
+ name="Build with AI"
+ isActive={router.asPath === `/project/${ref}/sql/ai`}
+ url={`/project/${ref}/sql/ai`}
+ />
<ProductMenuItem
name="Templates"
isActive={router.asPath === `/project/${ref}/sql`}
diff --git a/studio/pages/project/[ref]/sql/ai.tsx b/studio/pages/project/[ref]/sql/ai.tsx
new file mode 100644
index 00000000000..456822164fc
--- /dev/null
+++ b/studio/pages/project/[ref]/sql/ai.tsx
@@ -0,0 +1,14 @@
+import SQLAI from 'components/interfaces/SQLEditor/SQLTemplates/SQLAI'
+import { SQLEditorLayout } from 'components/layouts'
+import { observer } from 'mobx-react-lite'
+import { NextPageWithLayout } from 'types'
+
+const SqlEditorWelcome: NextPageWithLayout = () => {
+ return <SQLAI />
+}
+
+SqlEditorWelcome.getLayout = (page) => (
+ <SQLEditorLayout title="Build with AI">{page}</SQLEditorLayout>
+)
+
+export default observer(SqlEditorWelcome)