Skip to content

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

Merge branch 'feat/ai-sql-editor' into feat/ai-sql-editor-schema-suggestion-popover

Greg Richardson0a7a1b7ef64a
diff --cc studio/components/interfaces/SQLEditor/SQLEditor.tsx
index 14f12c9f462,6023ac8a6d8..45ecc7ab323
--- a/studio/components/interfaces/SQLEditor/SQLEditor.tsx
+++ b/studio/components/interfaces/SQLEditor/SQLEditor.tsx
@@@ -45,10 -46,16 +46,17 @@@ import
IconSettings,
IconX,
Input,
+ Input_Shadcn_,
+ cn,
+ AiIconAnimation,
} from 'ui'
+import AISchemaSuggestionPopover from './AISchemaSuggestionPopover'
import AISettingsModal from './AISettingsModal'
- import { sqlAiDisclaimerComment, untitledSnippetTitle } from './SQLEditor.constants'
+ import {
+ destructiveSqlRegex,
+ sqlAiDisclaimerComment,
+ untitledSnippetTitle,
+ } from './SQLEditor.constants'
import { IStandaloneCodeEditor, IStandaloneDiffEditor } from './SQLEditor.types'
import { createSqlSnippetSkeleton } from './SQLEditor.utils'
import UtilityPanel from './UtilityPanel/UtilityPanel'
@@@ -142,13 -150,8 +151,13 @@@ 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 [, setAiQueryCount] = useLocalStorageQuery('supabase_sql-editor-ai-query-count', 0)
+ const [, setIsSchemaSuggestionDismissed] = useLocalStorageQuery(
+ 'supabase_sql-editor-ai-schema-suggestion-dismissed',
+ false
+ )
const includeSchemaMetadata = (isOptedInToAI || !IS_PLATFORM) && isOptedInToAISchema
@@@ -421,260 -449,269 +455,283 @@@
executeQuery(true)
}}
/>
- <div className="flex h-full flex-col">
- <AISchemaSuggestionPopover
- onClickSettings={() => {
- setIsAISettingsOpen(true)
- }}
- >
- <motion.div
- key="ask-ai-input-container"
- layoutId="ask-ai-input-container"
- variants={{
- visible: {
- borderRadius: 0,
- },
+ <div className="flex h-full flex-col relative">
+ {isAiOpen && (
- <motion.div
- key="ask-ai-input-container"
- layoutId="ask-ai-input-container"
- variants={{
- visible: {
- borderRadius: 0,
- x: 0,
- },
- hidden: {
- x: 100,
- },
++ <AISchemaSuggestionPopover
++ onClickSettings={() => {
++ setIsAISettingsOpen(true)
}}
- initial="visible"
- initial={isFirstRender ? 'visible' : 'hidden'}
-- animate="visible"
- className="w-full flex justify-center z-10 mt-0.5 bg-brand-400"
- className="w-full flex justify-center z-10 h-[60px] bg-brand-300 border-b border-brand-400 px-5"
>
- <AnimatePresence initial={false} exitBeforeEnter>
- {!isEditSqlLoading ? (
- <motion.div
- key="ask-ai-input"
- className="w-full"
- variants={{
- visible: {
- opacity: 1,
- y: 0,
- },
- hidden: {
- opacity: 0,
- y: -25,
- },
- }}
- initial="hidden"
- animate="visible"
- exit="hidden"
- transition={{
- duration: 0.1,
- }}
- >
- <Input
- autoFocus
- size="xlarge"
- value={aiInput}
- onChange={(e) => setAiInput(e.currentTarget.value)}
- disabled={isDiffOpen}
- inputRef={inputRef}
- icon={
- <div className="h-full flex flex-row gap-3 items-center">
- <motion.div layoutId="ask-ai-input-icon" className="ml-1">
- <AiIcon className="w-4 h-4" />
- </motion.div>
-
- {debugSolution && (
- <div className="h-full w-full flex flex-row items-center overflow-y-hidden mr-[16.5rem] text-sm text-white">
- {debugSolution}
- </div>
- )}
- </div>
- }
- inputClassName="w-full !border-brand-900 border-none bg-transparent !shadow-none py-4 focus:!ring-0 placeholder:text-scale-900 pr-20"
- iconContainerClassName="transition text-scale-800 text-brand-900"
- placeholder={!debugSolution ? 'Ask Supabase AI to modify your query' : ''}
- className="w-full"
- actions={
- <div className="flex flex-row items-center gap-2 space-x-1 mr-6">
- {isDiffOpen ? (
- <>
- <div className="flex items-center">
- <Button
- className="rounded-r-none"
- type="primary"
- size="tiny"
- icon={
- !isAcceptDiffLoading ? (
- <IconCheck />
- ) : (
- <IconLoader className="animate-spin" size={14} />
- )
- }
- iconRight={
- <div className="opacity-30">
- <IconCornerDownLeft size={12} strokeWidth={1.5} />
- </div>
- }
- onClick={acceptAiHandler}
- >
- {getDiffTypeButtonLabel(selectedDiffType)}
- </Button>
- <Dropdown
- align="end"
- side="bottom"
- overlay={Object.values(DiffType)
- .filter((diffType) => diffType !== selectedDiffType)
- .map((diffType) => (
- <Dropdown.Item
- key={diffType}
- onClick={() => {
- setSelectedDiffType(diffType)
- switch (diffType) {
- case DiffType.Modification:
- return compareAsModification()
- case DiffType.Addition:
- return compareAsAddition()
- case DiffType.NewSnippet:
- return compareAsNewSnippet()
- default:
- throw new Error(`Unknown diff type '${diffType}'`)
- }
- }}
- >
- {getDiffTypeDropdownLabel(diffType)}
- </Dropdown.Item>
- ))}
- >
- <Button
- type="primary"
- className="rounded-l-none border-l-0 px-[4px] py-[5px]"
- icon={<IconChevronDown />}
- />
- </Dropdown>
- </div>
- <Button
- type="alternative"
- size="tiny"
- icon={<IconX />}
- iconRight={<span className="opacity-30">ESC</span>}
- onClick={discardAiHandler}
- >
- Discard
- </Button>
- </>
- ) : (
- <>
- <IconCornerDownLeft size={16} strokeWidth={1.5} />
- <IconSettings
- className="cursor-pointer"
- onClick={() => {
- setIsSchemaSuggestionDismissed(true)
- setIsAISettingsOpen(true)
- }}
- />
- </>
- <div
- className={cn(
- 'w-full !border-brand-900 border-none !shadow-none',
- 'flex items-center gap-3'
- )}
++ <motion.div
++ key="ask-ai-input-container"
++ layoutId="ask-ai-input-container"
++ variants={{
++ visible: {
++ borderRadius: 0,
++ x: 0,
++ },
++ hidden: {
++ x: 100,
++ },
++ }}
++ 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"
+ >
- <motion.div layoutId="ask-ai-input-icon" transition={{ duration: 0.1 }}>
- <AiIconAnimation loading={isEditSqlLoading} />
- </motion.div>
-
- <AnimatePresence initial={false} exitBeforeEnter>
- {debugSolution && (
- <div className="h-full w-full flex flex-row items-center overflow-y-hidden text-sm text-white">
- {debugSolution}
- </div>
++ <div
++ className={cn(
++ 'w-full !border-brand-900 border-none !shadow-none',
++ 'flex items-center gap-3'
+ )}
- {!isEditSqlLoading && !debugSolution && (
- <motion.div
- key="ask-ai-input"
- className="w-full h-full relative flex items-center"
- variants={{
- visible: {
- opacity: 1,
- y: 0,
- },
- hidden: {
- opacity: 0,
- y: -25,
- },
- }}
- initial="hidden"
- animate="visible"
- exit="hidden"
- transition={{
- duration: 0.1,
- }}
- >
- <Input_Shadcn_
- autoFocus
- value={aiInput}
- onChange={(e) => setAiInput(e.currentTarget.value)}
- disabled={isDiffOpen}
- ref={inputRef}
- className={cn(
- '!p-0 bg-transparent border-transparent text-sm text-brand-600 dark:text-brand placeholder:text-brand-500 focus:!ring-0',
- 'focus-visible:ring-0 focus-visible:ring-offset-0',
- 'appearance-none outline-none'
- )}
- placeholder={!debugSolution ? 'Ask Supabase AI to modify your query' : ''}
- onKeyDown={(e) => {
- if (e.key === 'Escape' && !aiInput) {
- setIsAiOpen(false)
- }
++ >
++ <motion.div layoutId="ask-ai-input-icon" transition={{ duration: 0.1 }}>
++ <AiIconAnimation loading={isEditSqlLoading} />
++ </motion.div>
++
++ <AnimatePresence initial={false} exitBeforeEnter>
++ {debugSolution && (
++ <div className="h-full w-full flex flex-row items-center overflow-y-hidden text-sm text-white">
++ {debugSolution}
++ </div>
++ )}
++ {!isEditSqlLoading && !debugSolution && (
++ <motion.div
++ key="ask-ai-input"
++ className="w-full h-full relative flex items-center"
++ variants={{
++ visible: {
++ opacity: 1,
++ y: 0,
++ },
++ hidden: {
++ opacity: 0,
++ y: -25,
++ },
+ }}
- onKeyPress={async (e) => {
- if (e.key === 'Enter') {
- console.log('entering')
- try {
- const prompt = e.currentTarget.value
-
- if (!prompt) {
- return
- }
-
- const sql = editorRef.current?.getValue()
-
- if (!sql) {
- return
- }
-
- const { sql: modifiedSql } = await editSql({
- prompt,
- sql: sql.replace(sqlAiDisclaimerComment, '').trim(),
- entityDefinitions,
- })
-
- const formattedSql =
- sqlAiDisclaimerComment +
- '\n\n' +
- format(modifiedSql, {
- language: 'postgresql',
- keywordCase: 'lower',
++ initial="hidden"
++ animate="visible"
++ exit="hidden"
++ transition={{
++ duration: 0.1,
++ }}
++ >
++ <Input_Shadcn_
++ autoFocus
++ value={aiInput}
++ onChange={(e) => setAiInput(e.currentTarget.value)}
++ disabled={isDiffOpen}
++ ref={inputRef}
++ className={cn(
++ '!p-0 bg-transparent border-transparent text-sm text-brand-600 dark:text-brand placeholder:text-brand-500 focus:!ring-0',
++ 'focus-visible:ring-0 focus-visible:ring-offset-0',
++ 'appearance-none outline-none'
+ )}
- </div>
- }
- onKeyPress={async (e) => {
- if (e.key === 'Enter') {
- try {
- const prompt = e.currentTarget.value
-
- if (!prompt) {
- return
++ placeholder={!debugSolution ? 'Ask Supabase AI to modify your query' : ''}
++ onKeyDown={(e) => {
++ if (e.key === 'Escape' && !aiInput) {
++ setIsAiOpen(false)
+ }
-
- const sql = editorRef.current?.getValue()
-
- if (!sql) {
- return
++ }}
++ onKeyPress={async (e) => {
++ if (e.key === 'Enter') {
++ console.log('entering')
++ try {
++ const prompt = e.currentTarget.value
++
++ if (!prompt) {
++ return
++ }
++
++ const sql = editorRef.current?.getValue()
++
++ if (!sql) {
++ return
++ }
++
++ const { sql: modifiedSql } = await editSql({
++ prompt,
++ sql: sql.replace(sqlAiDisclaimerComment, '').trim(),
++ entityDefinitions,
+ })
+
- // TODO: show error
- if (formattedSql.trim() === sql.trim()) {
- ui.setNotification({
- category: 'error',
- message:
- 'Unable to edit SQL. Try adding more details to your prompt.',
- })
- return
- }
-
- setSqlDiff({
- original: sql,
- modified: formattedSql,
- })
- } catch (error: unknown) {
- if (
- error &&
- typeof error === 'object' &&
- 'message' in error &&
- typeof error.message === 'string'
- ) {
- ui.setNotification({
- category: 'error',
- message: error.message,
++ setAiQueryCount((count) => count + 1)
++
++ const formattedSql =
++ sqlAiDisclaimerComment +
++ '\n\n' +
++ format(modifiedSql, {
++ language: 'postgresql',
++ keywordCase: 'lower',
++ })
++
++ // TODO: show error
++ if (formattedSql.trim() === sql.trim()) {
++ ui.setNotification({
++ category: 'error',
++ message:
++ 'Unable to edit SQL. Try adding more details to your prompt.',
++ })
++ return
++ }
++
++ setSqlDiff({
++ original: sql,
++ modified: formattedSql,
+ })
++ } catch (error: unknown) {
++ if (
++ error &&
++ typeof error === 'object' &&
++ 'message' in error &&
++ typeof error.message === 'string'
++ ) {
++ ui.setNotification({
++ category: 'error',
++ message: error.message,
++ })
++ }
+ }
}
-
- const { sql: modifiedSql } = await editSql({
- prompt,
- sql: sql.replace(sqlAiDisclaimerComment, '').trim(),
- entityDefinitions,
- })
-
- setAiQueryCount((count) => count + 1)
-
- const formattedSql =
- sqlAiDisclaimerComment +
- '\n\n' +
- format(modifiedSql, {
- language: 'postgresql',
- keywordCase: 'lower',
- })
-
- // TODO: show error
- if (formattedSql.trim() === sql.trim()) {
- ui.setNotification({
- category: 'error',
- message:
- 'Unable to edit SQL. Try adding more details to your prompt.',
- })
- return
- }
- }}
- />
- </motion.div>
- )}
- {isEditSqlLoading && (
- <motion.div
- key="ask-ai-loading"
- className="p-0 flex flex-row gap-2 items-center w-full"
- variants={{
- visible: {
- opacity: 1,
- y: 0,
- },
- hidden: {
- opacity: 0,
- y: 25,
- },
- }}
- transition={{
- duration: 0.2,
- }}
- initial="hidden"
- animate="visible"
- exit="hidden"
- >
- <motion.span
- className="text-sm text-brand px-3"
- animate={{
- opacity: ['0.5', '0.75', '0.5'],
- transition: {
- ease: 'linear',
- duration: 0.33,
- repeat: Infinity,
++ }}
++ />
++ </motion.div>
++ )}
++ {isEditSqlLoading && (
++ <motion.div
++ key="ask-ai-loading"
++ className="p-0 flex flex-row gap-2 items-center w-full"
++ variants={{
++ visible: {
++ opacity: 1,
++ y: 0,
++ },
++ hidden: {
++ opacity: 0,
++ y: 25,
+ },
+ }}
++ transition={{
++ duration: 0.2,
++ }}
++ initial="hidden"
++ animate="visible"
++ exit="hidden"
+ >
- Thinking...
- </motion.span>
- </motion.div>
- )}
- </AnimatePresence>
- <div className="flex flex-row items-center gap-3 mr-1">
- {isDiffOpen ? (
- <>
- <div className="flex items-center">
++ <motion.span
++ className="text-sm text-brand px-3"
++ animate={{
++ opacity: ['0.5', '0.75', '0.5'],
++ transition: {
++ ease: 'linear',
++ duration: 0.33,
++ repeat: Infinity,
++ },
++ }}
++ >
++ Thinking...
++ </motion.span>
++ </motion.div>
++ )}
++ </AnimatePresence>
++ <div className="flex flex-row items-center gap-3 mr-1">
++ {isDiffOpen ? (
++ <>
++ <div className="flex items-center">
++ <Button
++ className="rounded-r-none"
++ type="primary"
++ size="tiny"
++ icon={
++ !isAcceptDiffLoading ? (
++ <IconCheck />
++ ) : (
++ <IconLoader className="animate-spin" size={14} />
++ )
+ }
-
- setSqlDiff({
- original: sql,
- modified: formattedSql,
- })
- } catch (error: unknown) {
- if (isError(error)) {
- ui.setNotification({
- category: 'error',
- message: error.message,
- })
++ iconRight={
++ <div className="opacity-30">
++ <IconCornerDownLeft size={12} strokeWidth={1.5} />
++ </div>
+ }
- }
- }
- }}
- />
- </motion.div>
- ) : (
- <motion.div
- key="ask-ai-loading"
- className="p-4 flex flex-row gap-2 items-center w-full"
- variants={{
- visible: {
- opacity: 1,
- y: 0,
- },
- hidden: {
- opacity: 0,
- y: 25,
- },
- }}
- transition={{
- duration: 0.2,
- }}
- initial="hidden"
- animate="visible"
- exit="hidden"
- >
- <motion.div
- className="text-brand-900"
- animate={{
- scale: [0.9, 1.1, 0.9],
- transition: {
- ease: 'linear',
- duration: 2,
- repeat: Infinity,
- },
- }}
- >
- <AiIcon className="w-4 h-4" />
- </motion.div>
- <motion.span
- animate={{
- opacity: ['0.5', '0.75', '0.5'],
- transition: {
- ease: 'linear',
- duration: 2,
- repeat: Infinity,
- },
- }}
- >
- Thinking...
- </motion.span>
- </motion.div>
- )}
- </AnimatePresence>
- </motion.div>
- </AISchemaSuggestionPopover>
++ onClick={acceptAiHandler}
++ >
++ {getDiffTypeButtonLabel(selectedDiffType)}
++ </Button>
++ <Dropdown
++ align="end"
++ side="bottom"
++ overlay={Object.values(DiffType)
++ .filter((diffType) => diffType !== selectedDiffType)
++ .map((diffType) => (
++ <Dropdown.Item
++ key={diffType}
++ onClick={() => {
++ setSelectedDiffType(diffType)
++ switch (diffType) {
++ case DiffType.Modification:
++ return compareAsModification()
++ case DiffType.Addition:
++ return compareAsAddition()
++ case DiffType.NewSnippet:
++ return compareAsNewSnippet()
++ default:
++ throw new Error(`Unknown diff type '${diffType}'`)
++ }
++ }}
++ >
++ {getDiffTypeDropdownLabel(diffType)}
++ </Dropdown.Item>
++ ))}
++ >
++ <Button
++ type="primary"
++ className="rounded-l-none border-l-0 px-[4px] py-[5px]"
++ icon={<IconChevronDown />}
++ />
++ </Dropdown>
++ </div>
+ <Button
- className="rounded-r-none"
- type="primary"
++ type="alternative"
+ size="tiny"
- icon={
- !isAcceptDiffLoading ? (
- <IconCheck />
- ) : (
- <IconLoader className="animate-spin" size={14} />
- )
- }
- iconRight={
- <div className="opacity-30">
- <IconCornerDownLeft size={12} strokeWidth={1.5} />
- </div>
- }
- onClick={acceptAiHandler}
++ icon={<IconX />}
++ iconRight={<span className="opacity-30">ESC</span>}
++ onClick={discardAiHandler}
+ >
- {getDiffTypeButtonLabel(selectedDiffType)}
++ Discard
+ </Button>
- <Dropdown
- align="end"
- side="bottom"
- overlay={Object.values(DiffType)
- .filter((diffType) => diffType !== selectedDiffType)
- .map((diffType) => (
- <Dropdown.Item
- key={diffType}
- onClick={() => {
- setSelectedDiffType(diffType)
- switch (diffType) {
- case DiffType.Modification:
- return compareAsModification()
- case DiffType.Addition:
- return compareAsAddition()
- case DiffType.NewSnippet:
- return compareAsNewSnippet()
- default:
- throw new Error(`Unknown diff type '${diffType}'`)
- }
- }}
- >
- {getDiffTypeDropdownLabel(diffType)}
- </Dropdown.Item>
- ))}
++ </>
++ ) : (
++ <>
++ <div
++ className={cn(
++ 'transition text-brand',
++ !aiInput ? 'opacity-0' : 'opacity-30'
++ )}
+ >
- <Button
- type="primary"
- className="rounded-l-none border-l-0 px-[4px] py-[5px]"
- icon={<IconChevronDown />}
- />
- </Dropdown>
- </div>
- <Button
- type="alternative"
- size="tiny"
- icon={<IconX />}
- iconRight={<span className="opacity-30">ESC</span>}
- onClick={discardAiHandler}
- >
- Discard
- </Button>
- </>
- ) : (
- <>
- <div
- className={cn('transition text-brand', !aiInput ? 'opacity-0' : 'opacity-30')}
- >
- <IconCornerDownLeft size={16} strokeWidth={1.5} />
- </div>
- <button
- onClick={() => setIsAISettingsOpen(true)}
- className="text-brand-600 dark:text-brand hover:text-brand-600 transition"
- >
- <IconSettings className="cursor-pointer" />
- </button>
- <button
- className="text-brand-600 dark:text-brand hover:text-brand-600"
- onClick={() => setIsAiOpen(false)}
- >
- <IconX size={21} />
- </button>
- </>
- )}
++ <IconCornerDownLeft size={16} strokeWidth={1.5} />
++ </div>
++ <button
++ onClick={() => {
++ setIsSchemaSuggestionDismissed(true)
++ setIsAISettingsOpen(true)
++ }}
++ className="text-brand-600 dark:text-brand hover:text-brand-600 transition"
++ >
++ <IconSettings className="cursor-pointer" />
++ </button>
++ <button
++ className="text-brand-600 dark:text-brand hover:text-brand-600"
++ onClick={() => setIsAiOpen(false)}
++ >
++ <IconX size={21} />
++ </button>
++ </>
++ )}
++ </div>
+ </div>
- </div>
- </motion.div>
++ </motion.div>
++ </AISchemaSuggestionPopover>
+ )}
<Split
style={{ height: '100%' }}
direction="vertical"
diff --cc studio/components/interfaces/SQLEditor/SQLTemplates/SQLAI.tsx
index 00000000000,c0ed4563389..e663164afaf
mode 000000,100644..100644
--- a/studio/components/interfaces/SQLEditor/SQLTemplates/SQLAI.tsx
+++ b/studio/components/interfaces/SQLEditor/SQLTemplates/SQLAI.tsx
@@@ -1,0 -1,249 +1,267 @@@
+ 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, AiIconAnimation, IconCornerDownLeft, IconSettings, Input } from 'ui'
+ import AISettingsModal from '../AISettingsModal'
+ import { sqlAiDisclaimerComment } from '../SQLEditor.constants'
+ import { createSqlSnippetSkeleton } from '../SQLEditor.utils'
++import AISchemaSuggestionPopover from '../AISchemaSuggestionPopover'
+
+ 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 [, setAiQueryCount] = useLocalStorageQuery('supabase_sql-editor-ai-query-count', 0)
++ const [, setIsSchemaSuggestionDismissed] = useLocalStorageQuery(
++ 'supabase_sql-editor-ai-schema-suggestion-dismissed',
++ 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,
- },
++ <AISchemaSuggestionPopover
++ onClickSettings={() => {
++ setIsAISettingsOpen(true)
+ }}
- initial="hidden"
- animate="visible"
+ >
- <Input
- size="xlarge"
- inputRef={(inputElement: HTMLInputElement) => {
- setTimeout(() => {
- inputElement?.focus()
- }, 200)
++ <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,
++ },
+ }}
- 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
- }
++ 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
+
- const { title, sql } = await generateSql({
- prompt: e.currentTarget.value,
- entityDefinitions,
- })
++ if (!value) {
++ return
++ }
+
- const formattedSql =
- sqlAiDisclaimerComment +
- '\n\n' +
- format(sql, {
- language: 'postgresql',
- keywordCase: 'lower',
++ const { title, sql } = await generateSql({
++ prompt: e.currentTarget.value,
++ entityDefinitions,
+ })
+
- setIsAiOpen(true)
- await handleNewQuery(formattedSql, title)
++ setAiQueryCount((count) => count + 1)
+
- 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,
- })
++ 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={() => {
++ setIsSchemaSuggestionDismissed(true)
++ setIsAISettingsOpen(true)
++ }}
++ />
++ </div>
+ }
- }}
- 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>
++ </AISchemaSuggestionPopover>
+ ) : (
+ <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,
+ },
+ }}
+ >
+ <AiIconAnimation loading />
+ </motion.div>
+ </motion.div>
+ )}
+ </div>
+ </div>
+ </>
+ )
+ }
+
+ export default SQLAI