Skip to content

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

Chore/assistant tweaks 281024 (#30134)

Joshen Lim01e81fd4008a
diff --git a/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionList.tsx b/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionList.tsx
index c86f4e08d2d..b5f5bc8021d 100644
--- a/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionList.tsx
+++ b/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionList.tsx
@@ -1,5 +1,6 @@
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { includes, noop, sortBy } from 'lodash'
+import { Edit, Edit2, FileText, MoreVertical, Trash } from 'lucide-react'
import { useRouter } from 'next/router'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
@@ -7,12 +8,13 @@ import Table from 'components/to-be-cleaned/Table'
import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import { useDatabaseFunctionsQuery } from 'data/database-functions/database-functions-query'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { Edit3, FileText, MoreVertical, Trash } from 'lucide-react'
+import { useAppStateSnapshot } from 'state/app-state'
import {
Button,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
+ DropdownMenuSeparator,
DropdownMenuTrigger,
} from 'ui'
@@ -33,6 +35,7 @@ const FunctionList = ({
}: FunctionListProps) => {
const router = useRouter()
const { project: selectedProject } = useProjectContext()
+ const { setAiAssistantPanel } = useAppStateSnapshot()
const { data: functions } = useDatabaseFunctionsQuery({
projectRef: selectedProject?.ref,
@@ -116,11 +119,21 @@ const FunctionList = ({
</DropdownMenuItem>
)}
<DropdownMenuItem className="space-x-2" onClick={() => editFunction(x)}>
- <Edit3 size={14} />
+ <Edit2 size={14} />
<p>Edit function</p>
</DropdownMenuItem>
+ <DropdownMenuItem
+ className="space-x-2"
+ onClick={() => {
+ setAiAssistantPanel({ open: true, editor: 'functions', entity: x })
+ }}
+ >
+ <Edit size={14} />
+ <p>Edit function with Assistant</p>
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
<DropdownMenuItem className="space-x-2" onClick={() => deleteFunction(x)}>
- <Trash stroke="red" size={14} />
+ <Trash size={14} className="text-destructive" />
<p>Delete function</p>
</DropdownMenuItem>
</DropdownMenuContent>
diff --git a/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionsList.tsx b/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionsList.tsx
index 521ea2827c9..56b09f32faf 100644
--- a/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionsList.tsx
+++ b/apps/studio/components/interfaces/Database/Functions/FunctionsList/FunctionsList.tsx
@@ -5,6 +5,7 @@ import { Search } from 'lucide-react'
import { useRouter } from 'next/router'
import { useParams } from 'common'
+import { useIsDatabaseFunctionsAssistantEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import ProductEmptyState from 'components/to-be-cleaned/ProductEmptyState'
import Table from 'components/to-be-cleaned/Table'
@@ -17,18 +18,10 @@ import { useSchemasQuery } from 'data/database/schemas-query'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { useQuerySchemaState } from 'hooks/misc/useSchemaQueryState'
import { EXCLUDED_SCHEMAS } from 'lib/constants/schemas'
-import {
- AiIconAnimation,
- Button,
- Input,
- Tooltip_Shadcn_,
- TooltipContent_Shadcn_,
- TooltipTrigger_Shadcn_,
-} from 'ui'
+import { useAppStateSnapshot } from 'state/app-state'
+import { AiIconAnimation, Input } from 'ui'
import ProtectedSchemaWarning from '../../ProtectedSchemaWarning'
import FunctionList from './FunctionList'
-import { useAppStateSnapshot } from 'state/app-state'
-import { useIsDatabaseFunctionsAssistantEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
interface FunctionsListProps {
createFunction: () => void
@@ -136,39 +129,47 @@ const FunctionsList = ({
<div className="flex items-center gap-x-2">
{!isLocked && (
- <ButtonTooltip
- disabled={!canCreateFunctions}
- onClick={() => createFunction()}
- tooltip={{
- content: {
- side: 'bottom',
- text: !canCreateFunctions
- ? 'You need additional permissions to create functions'
- : undefined,
- },
- }}
- >
- Create a new function
- </ButtonTooltip>
- )}
- {enableFunctionsAssistant && (
- <Tooltip_Shadcn_>
- <TooltipTrigger_Shadcn_ asChild>
- <Button
+ <>
+ <ButtonTooltip
+ disabled={!canCreateFunctions}
+ onClick={() => createFunction()}
+ tooltip={{
+ content: {
+ side: 'bottom',
+ text: !canCreateFunctions
+ ? 'You need additional permissions to create functions'
+ : undefined,
+ },
+ }}
+ >
+ Create a new function
+ </ButtonTooltip>
+ {enableFunctionsAssistant && (
+ <ButtonTooltip
type="default"
+ disabled={!canCreateFunctions}
className="px-1 pointer-events-auto"
icon={
<AiIconAnimation className="scale-75 [&>div>div]:border-black dark:[&>div>div]:border-white" />
}
- onClick={() => setAiAssistantPanel({ open: true, editor: 'functions' })}
+ onClick={() =>
+ setAiAssistantPanel({
+ open: true,
+ editor: 'functions',
+ entity: undefined,
+ })
+ }
+ tooltip={{
+ content: {
+ side: 'bottom',
+ text: !canCreateFunctions
+ ? 'You need additional permissions to create functions'
+ : 'Create with Supabase Assistant',
+ },
+ }}
/>
- </TooltipTrigger_Shadcn_>
- <TooltipContent_Shadcn_ side="bottom">
- {!canCreateFunctions
- ? 'You need additional permissions to create functions'
- : 'Create with Supabase Assistant'}
- </TooltipContent_Shadcn_>
- </Tooltip_Shadcn_>
+ )}
+ </>
)}
</div>
</div>
diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
index fcbf8d16652..59864323626 100644
--- a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx
@@ -60,6 +60,7 @@ import { ContextBadge } from './ContextBadge'
import { EntitiesDropdownMenu } from './EntitiesDropdownMenu'
import { Message } from './Message'
import { SchemasDropdownMenu } from './SchemasDropdownMenu'
+import { useEntityDefinitionQuery } from 'data/database/entity-definition-query'
const ANIMATION_DURATION = 0.3
@@ -88,7 +89,7 @@ export const AIAssistant = ({
const disablePrompts = useFlag('disableAssistantPrompts')
const { aiAssistantPanel } = useAppStateSnapshot()
- const { editor } = aiAssistantPanel
+ const { editor, entity } = aiAssistantPanel
const inputRef = useRef<HTMLTextAreaElement>(null)
const bottomRef = useRef<HTMLDivElement>(null)
@@ -114,6 +115,13 @@ export const AIAssistant = ({
selectedSchemas.length === 0 &&
selectedTables.length === 0
+ const { data: existingDefinition } = useEntityDefinitionQuery({
+ id: entity?.id,
+ type: editor,
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ })
+
const { data } = useEntityDefinitionsQuery(
{
schemas: selectedSchemas,
@@ -123,17 +131,17 @@ export const AIAssistant = ({
{ enabled: includeSchemaMetadata }
)
- const entityDefinitions = includeSchemaMetadata
- ? selectedTables.length === 0
- ? data?.map((def) => def.sql.trim())
+ const tableDefinitions =
+ selectedTables.length === 0
+ ? data?.map((def) => def.sql.trim()) ?? []
: data
?.filter((def) => {
return selectedTables.some((table) => {
return def.sql.startsWith(`CREATE TABLE ${table.schema}.${table.name}`)
})
})
- .map((def) => def.sql.trim())
- : undefined
+ .map((def) => def.sql.trim()) ?? []
+ const entityDefinitions = includeSchemaMetadata ? tableDefinitions : undefined
const { mutate: sendEvent } = useSendEventMutation()
const sendTelemetryEvent = (action: string) => {
@@ -151,7 +159,7 @@ export const AIAssistant = ({
} = useChat({
id,
api: `${BASE_PATH}/api/ai/sql/generate-v2`,
- body: { entityDefinitions, context: selectedDatabaseEntity },
+ body: { entityDefinitions, context: selectedDatabaseEntity, existingSql: existingDefinition },
onError: (error) => setAssistantError(JSON.parse(error.message).error),
})
@@ -621,6 +629,11 @@ export const AIAssistant = ({
sendMessageToAssistant(value)
}}
/>
+ {!hasMessages && (
+ <div className="text-xs text-foreground-lighter text-opacity-60 bg-control px-3 pb-2">
+ The Assistant is in Alpha and your prompts might be rate limited
+ </div>
+ )}
</div>
<AnimatePresence>
diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.ts b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.ts
index b0b28d12550..10285b026b6 100644
--- a/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.ts
+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.ts
@@ -1,3 +1,4 @@
+import { CommonDatabaseEntity } from 'state/app-state'
import { SupportedAssistantEntities, SupportedAssistantQuickPromptTypes } from './AIAssistant.types'
const PLACEHOLDER_PREFIX = `-- Press tab to use this code
@@ -5,12 +6,17 @@ const PLACEHOLDER_PREFIX = `-- Press tab to use this code
const PLACEHOLDER_LIMIT = `Just three examples will do.`
-export const generateTitle = (editor?: SupportedAssistantEntities | null) => {
+export const generateTitle = (
+ editor?: SupportedAssistantEntities | null,
+ entity?: CommonDatabaseEntity
+) => {
switch (editor) {
case 'functions':
- return 'Create a new function'
+ if (entity === undefined) return 'Create a new function'
+ else return `Edit function: ${entity.name}`
case 'rls-policies':
- return 'Create a new RLS policy'
+ if (entity === undefined) return 'Create a new RLS policy'
+ else return `Edit RLS policy: ${entity.name}`
default:
return 'SQL Scratch Pad'
}
@@ -27,10 +33,15 @@ export const generateCTA = (editor?: SupportedAssistantEntities | null) => {
}
}
-export const generatePlaceholder = (editor?: SupportedAssistantEntities | null) => {
+export const generatePlaceholder = (
+ editor?: SupportedAssistantEntities | null,
+ entity?: CommonDatabaseEntity,
+ existingDefinition?: string
+) => {
switch (editor) {
case 'functions':
- return `${PLACEHOLDER_PREFIX}
+ if (entity === undefined) {
+ return `${PLACEHOLDER_PREFIX}
CREATE FUNCTION *schema*.*function_name*(*param1 type*, *param2 type*)\n
&nbsp;&nbsp;RETURNS *return_type*\n
&nbsp;&nbsp;LANGUAGE *plpgsql*\n
@@ -44,6 +55,26 @@ BEGIN\n
END;\n
$$;
`
+ } else {
+ return `${PLACEHOLDER_PREFIX}
+-- To rename the function\n
+ALTER FUNCTION *${entity.name}* RENAME TO *new_name*;\n
+&nbsp;\n
+-- To change the schema of the function\n
+ALTER FUNCTION *${entity.name}* SET SCHEMA *new_schema*;\n
+&nbsp;\n
+-- To update the function body or the arguments, use\n
+-- the create or replace statement instead\n
+${existingDefinition
+ ?.replaceAll(
+ '\n ',
+ `\n\
+ &nbsp;&nbsp;`
+ )
+ .replaceAll('\n', '\n\n')
+ .trim()}
+`
+ }
case 'rls-policies':
return `${PLACEHOLDER_PREFIX}
CREATE POLICY *name* ON *table_name*\n
diff --git a/apps/studio/components/ui/AIAssistantPanel/AIAssistantPanel.tsx b/apps/studio/components/ui/AIAssistantPanel/AIAssistantPanel.tsx
index 0963a2dc747..937e55bdce5 100644
--- a/apps/studio/components/ui/AIAssistantPanel/AIAssistantPanel.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/AIAssistantPanel.tsx
@@ -48,6 +48,7 @@ import CodeEditor from '../CodeEditor/CodeEditor'
import { AIAssistant } from './AIAssistant'
import { generateCTA, generatePlaceholder, generateTitle, validateQuery } from './AIAssistant.utils'
import { ASSISTANT_SUPPORT_ENTITIES } from './AiAssistant.constants'
+import { useEntityDefinitionQuery } from 'data/database/entity-definition-query'
export const AiAssistantPanel = () => {
const os = detectOS()
@@ -58,7 +59,7 @@ export const AiAssistantPanel = () => {
const { aiAssistantPanel, setAiAssistantPanel } = useAppStateSnapshot()
const isEnabled = useIsDatabaseFunctionsAssistantEnabled()
- const { open, editor, content } = aiAssistantPanel
+ const { open, editor, content, entity } = aiAssistantPanel
const previousEditor = usePrevious(editor)
const [isAcknowledged, setIsAcknowledged] = useLocalStorage(
@@ -73,11 +74,18 @@ export const AiAssistantPanel = () => {
const [showWarning, setShowWarning] = useState<boolean>(false)
const [debugThread, setDebugThread] = useState<MessageWithDebug[]>([])
+ const { data: existingDefinition } = useEntityDefinitionQuery({
+ id: entity?.id,
+ type: editor,
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ })
+
// [Joshen] JFYI I'm opting to just have the assistant always show and not toggle-able
// I don't really see any negatives of keeping it open (or benefits from hiding) tbh
// const [showAssistant, setShowAssistant] = useState(true)
- const title = generateTitle(editor)
- const placeholder = generatePlaceholder(editor)
+ const title = generateTitle(editor, entity)
+ const placeholder = generatePlaceholder(editor, entity, existingDefinition)
const ctaText = generateCTA(editor)
const editorRef = useRef<IStandaloneCodeEditor | undefined>()
const editorModel = editorRef.current?.getModel()
@@ -128,7 +136,7 @@ export const AiAssistantPanel = () => {
id: chatId,
api: `${BASE_PATH}/api/ai/sql/generate-v2`,
// [Joshen] Don't need entity definitions if calling here cause support action
- // via AI here is just to explain code segment, no need for context
+ // via AI here is just to explain code segment, no need for entity definitions context
body: {},
})
@@ -236,6 +244,17 @@ export const AiAssistantPanel = () => {
[editorModel]
)
+ const onTogglePanel = () => {
+ if (open) {
+ // [Joshen] Save the code content when closing - should allow users to continue from
+ // where they left off IF they are opening the assistant again in the same "editor" context
+ const existingValue = editorRef.current?.getValue() ?? ''
+ setAiAssistantPanel({ open: false, content: existingValue })
+ } else {
+ setAiAssistantPanel({ open: true, editor: null, entity: undefined })
+ }
+ }
+
useEffect(() => {
if (open) {
// [Joshen] Only reset the assistant if the editor changed
@@ -265,14 +284,12 @@ export const AiAssistantPanel = () => {
// [Joshen] Just to test the concept of a universal assistant of sorts
useEffect(() => {
const handler = (e: KeyboardEvent) => {
- if (e.metaKey && e.code === 'KeyI') {
- setAiAssistantPanel({ open: true, editor: null })
- }
+ if (e.metaKey && e.code === 'KeyI') onTogglePanel()
}
if (project !== undefined && isEnabled) window.addEventListener('keydown', handler)
return () => window.removeEventListener('keydown', handler)
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [project, isEnabled])
+ }, [project, isEnabled, open])
// [Joshen] Whenever the deps change recalculate the height of the editor
useEffect(() => {
@@ -281,19 +298,7 @@ export const AiAssistantPanel = () => {
}, [error, showWarning, isExecuting, numResults, showResults])
return (
- <Sheet
- open={open}
- onOpenChange={() => {
- if (open) {
- // [Joshen] Save the code content when closing - should allow users to continue from
- // where they left off IF they are opening the assistant again in the same "editor" context
- const existingValue = editorRef.current?.getValue() ?? ''
- setAiAssistantPanel({ open: false, content: existingValue })
- } else {
- setAiAssistantPanel({ open: true })
- }
- }}
- >
+ <Sheet open={open} onOpenChange={() => onTogglePanel()}>
<SheetContent showClose={true} className={cn('flex gap-0 w-[1200px]')}>
{/* Assistant */}
<AIAssistant
@@ -352,10 +357,7 @@ export const AiAssistantPanel = () => {
actions={{
runQuery: { enabled: true, callback: () => onExecuteSql() },
explainCode: { enabled: true, callback: onExplainSql },
- closeAssistant: {
- enabled: true,
- callback: () => setAiAssistantPanel({ open: false }),
- },
+ closeAssistant: { enabled: true, callback: () => onTogglePanel() },
}}
/>
</div>
@@ -426,11 +428,7 @@ export const AiAssistantPanel = () => {
</div>
)}
<SheetFooter className="bg-surface-100 flex items-center !justify-end px-5 py-4 w-full border-t">
- <Button
- type="default"
- disabled={isExecuting}
- onClick={() => setAiAssistantPanel({ open: false })}
- >
+ <Button type="default" disabled={isExecuting} onClick={() => onTogglePanel()}>
Cancel
</Button>
<Button
diff --git a/apps/studio/data/database/entity-definition-query.ts b/apps/studio/data/database/entity-definition-query.ts
new file mode 100644
index 00000000000..ddc44aa59fd
--- /dev/null
+++ b/apps/studio/data/database/entity-definition-query.ts
@@ -0,0 +1,61 @@
+import { UseQueryOptions } from '@tanstack/react-query'
+import { ExecuteSqlData, ExecuteSqlError, useExecuteSqlQuery } from '../sql/execute-sql-query'
+import { databaseKeys } from './keys'
+import { SupportedAssistantEntities } from 'components/ui/AIAssistantPanel/AIAssistant.types'
+
+// [Joshen] Eventually should support table definition and view definition as well if possible
+export const getEntityDefinitionQuery = ({
+ id,
+ type,
+}: {
+ id?: number
+ type?: SupportedAssistantEntities | 'table' | 'view' | null
+}) => {
+ if (!id || !type) return ''
+
+ switch (type) {
+ case 'functions':
+ return /* SQL */ `
+ select pg_get_functiondef(${id})
+ `.trim()
+ case 'rls-policies':
+ // [Joshen] Eventually to-do, unless we have to piece it manually?
+ return /* SQL */ `
+ select 1;
+ `.trim()
+ }
+
+ return ''
+}
+
+export type EntityDefinitionVariables = {
+ id?: number
+ type?: SupportedAssistantEntities | null
+ projectRef?: string
+ connectionString?: string
+}
+
+// type EntityDefinition = { id: number; sql: string }
+export type EntityDefinitionData = string
+export type EntityDefinitionError = ExecuteSqlError
+
+export const useEntityDefinitionQuery = <TData extends EntityDefinitionData = EntityDefinitionData>(
+ { id, type, projectRef, connectionString }: EntityDefinitionVariables,
+ { enabled = true, ...options }: UseQueryOptions<ExecuteSqlData, EntityDefinitionError, TData> = {}
+) => {
+ return useExecuteSqlQuery(
+ {
+ projectRef,
+ connectionString,
+ sql: getEntityDefinitionQuery({ id, type }),
+ queryKey: databaseKeys.entityDefinition(projectRef, id),
+ },
+ {
+ select(data) {
+ return data.result[0].pg_get_functiondef
+ },
+ enabled: enabled && typeof id !== 'undefined' && typeof type !== 'undefined',
+ ...options,
+ }
+ )
+}
diff --git a/apps/studio/data/database/keys.ts b/apps/studio/data/database/keys.ts
index 2f43f0492aa..c3a98169d40 100644
--- a/apps/studio/data/database/keys.ts
+++ b/apps/studio/data/database/keys.ts
@@ -1,4 +1,8 @@
+import { SupportedAssistantEntities } from 'components/ui/AIAssistantPanel/AIAssistant.types'
+
export const databaseKeys = {
+ entityDefinition: (projectRef: string | undefined, id?: number) =>
+ ['projects', projectRef, 'entity-definition', id].filter(Boolean),
entityDefinitions: (projectRef: string | undefined, schemas: string[]) =>
['projects', projectRef, 'entity-definitions', schemas] as const,
backups: (projectRef: string | undefined) => [projectRef, 'database', 'backups'] as const,
diff --git a/apps/studio/data/database/table-definition-query.ts b/apps/studio/data/database/table-definition-query.ts
index 9f29d08c6a7..be3f657168b 100644
--- a/apps/studio/data/database/table-definition-query.ts
+++ b/apps/studio/data/database/table-definition-query.ts
@@ -7,6 +7,7 @@ type GetTableDefinition = {
name?: string
}
+// [Joshen] Eventually move this into entity-definition-query
export const getTableDefinitionQuery = ({ schema = 'public', name }: GetTableDefinition) => {
const sql = /* SQL */ `
${CREATE_PG_GET_TABLEDEF_SQL}
diff --git a/apps/studio/data/database/view-definition-query.ts b/apps/studio/data/database/view-definition-query.ts
index 6fb09d538fc..fe2a98567aa 100644
--- a/apps/studio/data/database/view-definition-query.ts
+++ b/apps/studio/data/database/view-definition-query.ts
@@ -6,6 +6,7 @@ type GetViewDefinition = {
name?: string
}
+// [Joshen] Eventually move this into entity-definition-query
export const getViewDefinitionQuery = ({ schema, name }: GetViewDefinition) => {
const sql = /* SQL */ `
select pg_get_viewdef(to_regclass('"${schema}"."${name}"'), true) as definition
diff --git a/apps/studio/state/app-state.ts b/apps/studio/state/app-state.ts
index 807e7815c97..9a8b06eecc4 100644
--- a/apps/studio/state/app-state.ts
+++ b/apps/studio/state/app-state.ts
@@ -10,10 +10,20 @@ const EMPTY_DASHBOARD_HISTORY: {
editor: undefined,
}
+export type CommonDatabaseEntity = {
+ id: number
+ name: string
+ schema: string
+ [key: string]: any
+}
+
type AiAssistantPanelType = {
open: boolean
editor?: SupportedAssistantEntities | null
+ // Raw string content for the monaco editor, currently used to retain where the user left off when toggling off the panel
content?: string
+ // Mainly used for editing a database entity (e.g editing a function, RLS policy etc)
+ entity?: CommonDatabaseEntity
}
export const appState = proxy({
@@ -95,9 +105,19 @@ export const appState = proxy({
appState.navigationPanelJustClosed = value
},
- aiAssistantPanel: { open: false, editor: null, content: '' } as AiAssistantPanelType,
+ aiAssistantPanel: {
+ open: false,
+ editor: null,
+ content: '',
+ entity: undefined,
+ } as AiAssistantPanelType,
setAiAssistantPanel: (value: AiAssistantPanelType) => {
- appState.aiAssistantPanel = { ...appState.aiAssistantPanel, ...value }
+ const hasEntityChanged = value.entity?.id !== appState.aiAssistantPanel.entity?.id
+ appState.aiAssistantPanel = {
+ ...appState.aiAssistantPanel,
+ content: hasEntityChanged ? '' : appState.aiAssistantPanel.content,
+ ...value,
+ }
},
})
diff --git a/packages/ai-commands/src/sql/chat.ts b/packages/ai-commands/src/sql/chat.ts
index 4b8457cd74f..75e4b02e978 100644
--- a/packages/ai-commands/src/sql/chat.ts
+++ b/packages/ai-commands/src/sql/chat.ts
@@ -55,6 +55,7 @@ export async function chatSql(
if the function returns a type of trigger. When generating functions, do the following:
- If the function returns a trigger type, ensure that it uses security definer, otherwise default to security invoker. Include this in the create functions SQL statement.
- Ensure to set the search_path configuration parameter as '', include this in the create functions SQL statement.
+ - Default to create or replace whenever possible for updating an existing function, otherwise use the alter function statement
Please make sure that all queries are valid Postgres SQL queries.
`
}
@@ -62,7 +63,7 @@ export async function chatSql(
initMessages.push({ role: 'user', content: generateInstructionsBasedOnContext() })
}
- if (entityDefinitions) {
+ if (entityDefinitions && entityDefinitions.length > 0) {
const definitions = codeBlock`${entityDefinitions.join('\n\n')}`
initMessages.push({
role: 'user',