Skip to content

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

Send entity definitions into AI prompt if opted in

Joshen Lim15d2007cf55d
diff --git a/packages/ui/src/components/Command/CommandMenuProvider.tsx b/packages/ui/src/components/Command/CommandMenuProvider.tsx
index 161e71681eb..b8978509ad9 100644
--- a/packages/ui/src/components/Command/CommandMenuProvider.tsx
+++ b/packages/ui/src/components/Command/CommandMenuProvider.tsx
@@ -23,7 +23,7 @@ export interface CommandMenuContextValue {
/**
* Any additional metadata that CMDK component can use in its AI prompts
*/
- metadata: any
+ metadata?: { definitions: string }
/**
* Opt in flag to use additional metadata in AI prompts
*/
@@ -65,7 +65,7 @@ export interface CommandMenuProviderProps {
/**
* Any additional metadata that CMDK component can use in its AI prompts
*/
- metadata?: any
+ metadata?: { definitions: string }
/**
* TODO: remove this prop, temporary hack as ReactMarkdown fails our jest tests
* if we import the package directly within this UI package
diff --git a/packages/ui/src/components/Command/GenerateSQL/GenerateSQL.tsx b/packages/ui/src/components/Command/GenerateSQL/GenerateSQL.tsx
index 8363b52d78e..4d4d566b647 100644
--- a/packages/ui/src/components/Command/GenerateSQL/GenerateSQL.tsx
+++ b/packages/ui/src/components/Command/GenerateSQL/GenerateSQL.tsx
@@ -18,7 +18,7 @@ import { CommandItem } from '../Command.utils'
import { useCommandMenu } from '../CommandMenuProvider'
import { SAMPLE_QUERIES } from '../Command.constants'
import SQLOutputActions from './SQLOutputActions'
-import { getEdgeFunctionUrl, promptDataReducer } from './GenerateSQL.utils'
+import { getEdgeFunctionUrl, promptDataReducer, generatePrompt } from './GenerateSQL.utils'
const GenerateSQL = () => {
const [promptIndex, setPromptIndex] = useState(0)
@@ -33,8 +33,6 @@ const GenerateSQL = () => {
const cantHelp = answer?.trim() === "Sorry, I don't know how to help with that."
- console.log('Generate SQL', { isOptedInToAI, metadata })
-
const handleConfirm = useCallback(
async (query: string) => {
const edgeFunctionUrl = getEdgeFunctionUrl()
@@ -50,14 +48,7 @@ const GenerateSQL = () => {
setHasClippyError(false)
setIsLoading(true)
- // [Joshen] Eventually we need to pass the table data in here as well
- const queryToSend = `
-Generate a Postgres SQL query based on the following natural language prompt. For primary keys, always use "integer primary key generated always as identity":
-${query}
-
-Postgres SQL query:
-`.trim()
-
+ const queryToSend = generatePrompt(query, isOptedInToAI ? metadata : undefined)
const eventSource = new SSE(`${edgeFunctionUrl}/clippy-search`, {
headers: {
apikey: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ?? '',
diff --git a/packages/ui/src/components/Command/GenerateSQL/GenerateSQL.utils.ts b/packages/ui/src/components/Command/GenerateSQL/GenerateSQL.utils.ts
index afddc313f66..4b247174aa6 100644
--- a/packages/ui/src/components/Command/GenerateSQL/GenerateSQL.utils.ts
+++ b/packages/ui/src/components/Command/GenerateSQL/GenerateSQL.utils.ts
@@ -55,3 +55,22 @@ export function promptDataReducer(
return [...current]
}
+
+export const generatePrompt = (query: string, metadata?: { definitions: string }) => {
+ const { definitions } = metadata || {}
+ return `
+${
+ definitions !== undefined
+ ? `
+Given the following Postgres SQL tables:
+${definitions}
+`
+ : ''
+}
+
+Generate a Postgres SQL query based on the following natural language prompt. For primary keys, always use "integer primary key generated always as identity":
+${query}
+
+Postgres SQL query:
+`.trim()
+}
diff --git a/studio/components/interfaces/App/CommandMenuWrapper.tsx b/studio/components/interfaces/App/CommandMenuWrapper.tsx
index bcf03622896..71f12976f89 100644
--- a/studio/components/interfaces/App/CommandMenuWrapper.tsx
+++ b/studio/components/interfaces/App/CommandMenuWrapper.tsx
@@ -13,15 +13,15 @@ import { useSqlEditorStateSnapshot } from 'state/sql-editor'
import { useProfileQuery } from 'data/profile/profile-query'
import { SqlSnippet } from 'data/content/sql-snippets-query'
import { useProjectApiQuery } from 'data/config/project-api-query'
+import { useEntityDefinitionsQuery } from 'data/database/entity-definitions-query'
const CommandMenuWrapper = observer(({ children }: PropsWithChildren<{}>) => {
const { ref } = useParams()
const { ui } = useStore()
-
const { opt_in_tags } = ui.selectedOrganization ?? {}
- const isOptedInToAI = opt_in_tags?.includes('AI_SQL_GENERATOR_OPT_IN') ?? false
const snap = useSqlEditorStateSnapshot()
+ const isOptedInToAI = opt_in_tags?.includes('AI_SQL_GENERATOR_OPT_IN') ?? false
const { data: profile } = useProfileQuery()
const { data: settings } = useProjectApiQuery({ projectRef: ref })
@@ -35,6 +35,15 @@ const CommandMenuWrapper = observer(({ children }: PropsWithChildren<{}>) => {
service: settings?.autoApiService?.serviceApiKey ?? undefined,
}
+ const { data } = useEntityDefinitionsQuery(
+ {
+ projectRef: ui.selectedProject?.ref,
+ connectionString: ui.selectedProject?.connectionString,
+ },
+ { enabled: isOptedInToAI }
+ )
+ const cmdkMetadata = { definitions: (data ?? []).map((def) => def.sql.trim()).join('\n\n') }
+
const onSaveGeneratedSQL = async (answer: string, resolve: any) => {
if (!ref) return console.error('Project ref is required')
if (!canCreateSQLSnippet) {
@@ -85,6 +94,7 @@ ${answer}
apiKeys={apiKeys}
MarkdownHandler={(props) => <ReactMarkdown remarkPlugins={[remarkGfm]} {...props} />}
onSaveGeneratedSQL={onSaveGeneratedSQL}
+ metadata={cmdkMetadata}
isOptedInToAI={isOptedInToAI}
>
{children}
diff --git a/studio/components/interfaces/TableGridEditor/TableDefinition.tsx b/studio/components/interfaces/TableGridEditor/TableDefinition.tsx
index cb11f3c126c..b1fbb00953b 100644
--- a/studio/components/interfaces/TableGridEditor/TableDefinition.tsx
+++ b/studio/components/interfaces/TableGridEditor/TableDefinition.tsx
@@ -19,13 +19,10 @@ export interface TableDefinitionProps {
const TableDefinition = ({ id }: TableDefinitionProps) => {
const editorRef = useRef(null)
const monacoRef = useRef(null)
-
- const { ui } = useStore()
const { isDarkMode } = useTheme()
-
const entityType = useEntityType(id)
-
const { project } = useProjectContext()
+
const viewResult = useViewDefinitionQuery(
{
schema: entityType?.schema,
diff --git a/studio/data/database/entity-definitions-query.ts b/studio/data/database/entity-definitions-query.ts
new file mode 100644
index 00000000000..e660a869236
--- /dev/null
+++ b/studio/data/database/entity-definitions-query.ts
@@ -0,0 +1,123 @@
+import { UseQueryOptions } from '@tanstack/react-query'
+import { useCallback } from 'react'
+import { ExecuteSqlData, useExecuteSqlPrefetch, useExecuteSqlQuery } from '../sql/execute-sql-query'
+import { CREATE_PG_GET_TABLEDEF_SQL } from './database-query-constants'
+
+export const getEntityDefinitionsQuery = (limit = 100) => {
+ const sql = /* SQL */ `
+${CREATE_PG_GET_TABLEDEF_SQL}
+
+with records as (
+ select
+ c.oid::int8 as "id",
+ case c.relkind
+ when 'r' then pg_temp.pg_get_tabledef(
+ concat(nc.nspname),
+ concat(c.relname),
+ false,
+ 'FKEYS_INTERNAL',
+ 'NO_TRIGGERS'
+ )
+ when 'v' then concat(
+ 'create view ', concat(nc.nspname, '.', c.relname), ' as',
+ pg_get_viewdef(concat(nc.nspname, '.', c.relname), true)
+ )
+ when 'm' then concat(
+ 'create materialized view ', concat(nc.nspname, '.', c.relname), ' as',
+ pg_get_viewdef(concat(nc.nspname, '.', c.relname), true)
+ )
+ when 'f' then pg_temp.pg_get_tabledef(
+ concat(nc.nspname),
+ concat(c.relname),
+ false,
+ 'FKEYS_INTERNAL',
+ 'NO_TRIGGERS'
+ )
+ when 'p' then pg_temp.pg_get_tabledef(
+ concat(nc.nspname),
+ concat(c.relname),
+ false,
+ 'FKEYS_INTERNAL',
+ 'NO_TRIGGERS'
+ )
+ end as "sql"
+ from
+ pg_namespace nc
+ join pg_class c on nc.oid = c.relnamespace
+ where
+ c.relkind in ('r', 'v', 'm', 'f', 'p')
+ and not pg_is_other_temp_schema(nc.oid)
+ and (
+ pg_has_role(c.relowner, 'USAGE')
+ or has_table_privilege(
+ c.oid,
+ 'SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER'
+ )
+ or has_any_column_privilege(c.oid, 'SELECT, INSERT, UPDATE, REFERENCES')
+ )
+ and nc.nspname = 'public'
+ order by c.relname asc
+ limit ${limit}
+ offset 0
+)
+select
+ jsonb_build_object(
+ 'definitions', coalesce(jsonb_agg(
+ jsonb_build_object(
+ 'id', r.id,
+ 'sql', r.sql
+ )
+ ), '[]'::jsonb)
+ ) "data"
+from records r;
+ `.trim()
+
+ return sql
+}
+
+export type EntityDefinitionsVariables = {
+ limit?: number
+ projectRef?: string
+ connectionString?: string
+}
+
+type EntityDefinition = { id: number; sql: string }
+export type EntityDefinitionsData = EntityDefinition[]
+export type EntityDefinitionsError = unknown
+
+export const useEntityDefinitionsQuery = <
+ TData extends EntityDefinitionsData = EntityDefinitionsData
+>(
+ { limit, projectRef, connectionString }: EntityDefinitionsVariables,
+ options: UseQueryOptions<ExecuteSqlData, EntityDefinitionsError, TData> = {}
+) => {
+ return useExecuteSqlQuery(
+ {
+ projectRef,
+ connectionString,
+ sql: getEntityDefinitionsQuery(limit),
+ queryKey: ['entity-definitions'],
+ },
+ {
+ select(data) {
+ return data.result[0].data.definitions
+ },
+ ...options,
+ }
+ )
+}
+
+export const useEntityDefinitionsQueryPrefetch = () => {
+ const prefetch = useExecuteSqlPrefetch()
+
+ return useCallback(
+ ({ projectRef, connectionString }: EntityDefinitionsVariables) =>
+ prefetch({
+ projectRef,
+ connectionString,
+ sql: getEntityDefinitionsQuery(),
+ queryKey: ['entity-definitions'],
+ }),
+ [prefetch]
+ )
+}