Skip to content

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

feat: add AI-powered table generation variant (2 of 3) (#38934)

Sean Oliverf73ea9bd745d
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
index 633b9c030d6..037c59d8b92 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/SidePanelEditor.tsx
@@ -627,6 +627,16 @@ const SidePanelEditor = ({
: undefined
}
isDuplicating={snap.sidePanel?.type === 'table' && snap.sidePanel.mode === 'duplicate'}
+ templateData={
+ snap.sidePanel?.type === 'table' && snap.sidePanel.templateData
+ ? {
+ ...snap.sidePanel.templateData,
+ columns: snap.sidePanel.templateData.columns
+ ? [...snap.sidePanel.templateData.columns]
+ : undefined,
+ }
+ : undefined
+ }
visible={snap.sidePanel?.type === 'table'}
closePanel={onClosePanel}
saveChanges={saveTable}
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx
index 10690bd227b..c5e7247aa4a 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx
@@ -1,7 +1,6 @@
import type { PostgresTable } from '@supabase/postgres-meta'
-import dayjs from 'dayjs'
import { isEmpty, isUndefined, noop } from 'lodash'
-import { useEffect, useMemo, useState } from 'react'
+import { useEffect, useState } from 'react'
import { toast } from 'sonner'
import { DocsButton } from 'components/ui/DocsButton'
@@ -25,7 +24,6 @@ import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
import { useUrlState } from 'hooks/ui/useUrlState'
import { useProtectedSchemas } from 'hooks/useProtectedSchemas'
import { DOCS_URL } from 'lib/constants'
-import { usePHFlag } from 'hooks/ui/useFlag'
import { useTableEditorStateSnapshot } from 'state/table-editor'
import { Badge, Checkbox, Input, SidePanel } from 'ui'
import { Admonition } from 'ui-patterns'
@@ -47,16 +45,11 @@ import {
generateTableFieldFromPostgresTable,
validateFields,
} from './TableEditor.utils'
-import { TableTemplateSelector } from './TableQuickstart/TableTemplateSelector'
-import { QuickstartVariant } from './TableQuickstart/types'
-import { LOCAL_STORAGE_KEYS } from 'common'
-import { useLocalStorage } from 'hooks/misc/useLocalStorage'
-
-const NEW_PROJECT_THRESHOLD_DAYS = 7
export interface TableEditorProps {
table?: PostgresTable
isDuplicating: boolean
+ templateData?: Partial<TableField>
visible: boolean
closePanel: () => void
saveChanges: (
@@ -85,6 +78,7 @@ export interface TableEditorProps {
export const TableEditor = ({
table,
isDuplicating,
+ templateData,
visible = false,
closePanel = noop,
saveChanges = noop,
@@ -98,31 +92,6 @@ export const TableEditor = ({
const { realtimeAll: realtimeEnabled } = useIsFeatureEnabled(['realtime:all'])
const { mutate: sendEvent } = useSendEventMutation()
- /**
- * Returns:
- * - `QuickstartVariant`: user variation (if bucketed)
- * - `false`: user not yet bucketed or targeted
- * - `undefined`: posthog still loading
- */
- const tableQuickstartVariant = usePHFlag<QuickstartVariant | false | undefined>('tableQuickstart')
-
- const [quickstartDismissed, setQuickstartDismissed] = useLocalStorage(
- LOCAL_STORAGE_KEYS.TABLE_QUICKSTART_DISMISSED,
- false
- )
-
- const isRecentProject = useMemo(() => {
- if (!project?.inserted_at) return false
- return dayjs().diff(dayjs(project.inserted_at), 'day') < NEW_PROJECT_THRESHOLD_DAYS
- }, [project?.inserted_at])
-
- const shouldShowTemplateQuickstart =
- isNewRecord &&
- !isDuplicating &&
- tableQuickstartVariant === QuickstartVariant.TEMPLATES &&
- !quickstartDismissed &&
- isRecentProject
-
const { docsRowLevelSecurityGuidePath } = useCustomContent(['docs:row_level_security_guide_path'])
const [params, setParams] = useUrlState()
@@ -267,7 +236,11 @@ export const TableEditor = ({
setIsDuplicateRows(false)
if (isNewRecord) {
const tableFields = generateTableField()
- setTableFields(tableFields)
+ if (templateData) {
+ setTableFields({ ...tableFields, ...templateData })
+ } else {
+ setTableFields(tableFields)
+ }
setFkRelations([])
} else {
const tableFields = generateTableFieldFromPostgresTable(
@@ -279,11 +252,11 @@ export const TableEditor = ({
setTableFields(tableFields)
}
}
- }, [visible])
+ }, [visible, templateData])
useEffect(() => {
if (isSuccessForeignKeyMeta) setFkRelations(formatForeignKeys(foreignKeys))
- }, [isSuccessForeignKeyMeta])
+ }, [isSuccessForeignKeyMeta, foreignKeys])
useEffect(() => {
if (importContent && !isEmpty(importContent)) {
@@ -313,20 +286,6 @@ export const TableEditor = ({
}
>
<SidePanel.Content className="space-y-10 py-6">
- {shouldShowTemplateQuickstart && (
- <TableTemplateSelector
- variant={tableQuickstartVariant}
- onSelectTemplate={(template) => {
- const updates: Partial<TableField> = {}
- if (template.name) updates.name = template.name
- if (template.comment) updates.comment = template.comment
- if (template.columns) updates.columns = template.columns
- onUpdateField(updates)
- }}
- onDismiss={() => setQuickstartDismissed(true)}
- disabled={false}
- />
- )}
<Input
data-testid="table-name-input"
label="Name"
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/QuickstartAIWidget.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/QuickstartAIWidget.tsx
new file mode 100644
index 00000000000..3127d0086d3
--- /dev/null
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/QuickstartAIWidget.tsx
@@ -0,0 +1,209 @@
+import { useCallback, useEffect, useRef, useState } from 'react'
+import { toast } from 'sonner'
+import {
+ AiIconAnimation,
+ Button,
+ Input_Shadcn_ as Input,
+ cn,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from 'ui'
+import { Columns3, Table2 } from 'lucide-react'
+import type { TableField } from '../TableEditor.types'
+import { AI_QUICK_IDEAS } from './constants'
+import type { TableSuggestion } from './types'
+import { useAITableGeneration } from './useAITableGeneration'
+import { convertTableSuggestionToTableField } from './utils'
+
+interface QuickstartAIWidgetProps {
+ onSelectTable: (tableData: Partial<TableField>) => void
+ disabled?: boolean
+}
+
+const SUCCESS_MESSAGE_DURATION_MS = 3000
+
+export const QuickstartAIWidget = ({ onSelectTable, disabled }: QuickstartAIWidgetProps) => {
+ const [lastGeneratedPrompt, setLastGeneratedPrompt] = useState('')
+ const inputRef = useRef<HTMLInputElement>(null)
+
+ const {
+ generateTables,
+ isGenerating,
+ error: apiError,
+ prompt,
+ tables: storedTables,
+ setPrompt: setAiPrompt,
+ } = useAITableGeneration()
+
+ const aiPrompt = prompt ?? ''
+ const tables = storedTables ?? []
+
+ useEffect(() => {
+ if (inputRef.current) {
+ inputRef.current.focus()
+ }
+ }, [])
+
+ useEffect(() => {
+ if (aiPrompt && tables.length > 0) {
+ setLastGeneratedPrompt(aiPrompt)
+ }
+ }, [])
+
+ const handleSelectTemplate = useCallback(
+ (template: TableSuggestion) => {
+ const tableField = convertTableSuggestionToTableField(template)
+ onSelectTable(tableField)
+ toast.success(`Applied ${template.tableName} template. You can customize the fields below.`, {
+ duration: SUCCESS_MESSAGE_DURATION_MS,
+ })
+ },
+ [onSelectTable]
+ )
+
+ const handleGenerateTables = useCallback(
+ async (promptOverride?: string) => {
+ const promptToUse = promptOverride ?? aiPrompt
+ if (!promptToUse.trim() || isGenerating) return
+
+ await generateTables(promptToUse)
+ setLastGeneratedPrompt(promptToUse)
+ },
+ [aiPrompt, generateTables, isGenerating]
+ )
+
+ const handleQuickIdea = useCallback(
+ (idea: string) => {
+ setAiPrompt(idea)
+ handleGenerateTables(idea)
+ },
+ [handleGenerateTables, setAiPrompt]
+ )
+
+ return (
+ <div className="rounded-lg border border-default bg-surface-100 p-6 transition-all hover:border-foreground-muted">
+ <div className="mb-4">
+ <div className="flex items-center gap-2 mb-2">
+ <AiIconAnimation size={16} loading={false} />
+ <h3 className="text-base font-medium">Generate tables with AI</h3>
+ </div>
+ <p className="text-sm text-foreground-lighter">
+ Describe your app and AI will create a complete table schema.
+ </p>
+ </div>
+
+ <div className="space-y-3">
+ <div className="relative">
+ <Input
+ ref={inputRef}
+ placeholder="Describe your app (e.g., 'recipe sharing app')"
+ value={aiPrompt}
+ onChange={(e) => setAiPrompt(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' && !e.shiftKey) {
+ e.preventDefault()
+ if (aiPrompt.trim()) {
+ handleGenerateTables()
+ }
+ }
+ }}
+ disabled={isGenerating || disabled}
+ aria-label="Table description for AI generation"
+ className="pr-24"
+ />
+ <Button
+ type="default"
+ size="tiny"
+ disabled={!aiPrompt.trim() || isGenerating || disabled}
+ onClick={() => handleGenerateTables()}
+ icon={<AiIconAnimation loading={isGenerating} />}
+ className="absolute right-1 top-1/2 -translate-y-1/2 !space-x-1"
+ >
+ {isGenerating
+ ? 'Generating...'
+ : aiPrompt === lastGeneratedPrompt && tables.length > 0
+ ? 'Regenerate'
+ : 'Generate'}
+ </Button>
+ </div>
+
+ {apiError && (
+ <div className="text-sm text-red-600" role="alert">
+ {apiError}
+ </div>
+ )}
+
+ {tables.length === 0 && (
+ <div>
+ <h4 className="text-xs text-foreground-light mb-2">Quick ideas:</h4>
+ <div className="flex flex-wrap gap-2">
+ {AI_QUICK_IDEAS.map((idea) => (
+ <button
+ key={idea}
+ onClick={() => handleQuickIdea(idea)}
+ disabled={isGenerating || disabled}
+ aria-label={`Generate table for ${idea}`}
+ className={cn(
+ 'flex items-center gap-1.5 px-2 py-1 rounded-md text-xs border border-default',
+ 'hover:border-foreground-muted hover:bg-surface-200',
+ 'disabled:opacity-50 disabled:cursor-not-allowed',
+ 'transition-all'
+ )}
+ >
+ <AiIconAnimation size={12} />
+ <span>{idea}</span>
+ </button>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {tables.length > 0 && (
+ <div className="grid gap-2">
+ {tables.map((template) => (
+ <button
+ key={`ai:${template.tableName}`}
+ onClick={() => handleSelectTemplate(template)}
+ disabled={disabled}
+ aria-label={`Select ${template.tableName} template with ${template.fields.length} fields`}
+ className={cn(
+ 'text-left p-3 rounded-md border transition-colors w-full bg-surface-100',
+ 'border-light hover:border-default hover:bg-surface-200 cursor-pointer',
+ 'disabled:opacity-50 disabled:cursor-not-allowed'
+ )}
+ >
+ <div className="flex items-start gap-3">
+ <div className="rounded-full bg-alternative border w-8 h-8 flex items-center justify-center flex-shrink-0">
+ <Table2 size={16} className="text-foreground" />
+ </div>
+ <div className="flex-1 min-w-0">
+ <div className="text-sm font-medium text-foreground mb-0">
+ {template.tableName}
+ </div>
+ {template.rationale && (
+ <div className="text-xs text-foreground-light mt-0.5">
+ {template.rationale}
+ </div>
+ )}
+ </div>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div className="flex items-center gap-1 text-sm text-foreground-muted ml-3">
+ <Columns3 size={14} aria-hidden="true" />
+ <span>{template.fields.length}</span>
+ </div>
+ </TooltipTrigger>
+ <TooltipContent>
+ {template.fields.length} {template.fields.length === 1 ? 'column' : 'columns'}
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/QuickstartTemplatesWidget.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/QuickstartTemplatesWidget.tsx
new file mode 100644
index 00000000000..e4fb1ee0a31
--- /dev/null
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/QuickstartTemplatesWidget.tsx
@@ -0,0 +1,125 @@
+import { Columns3, Layers, Table2 } from 'lucide-react'
+import { useCallback, useEffect, useState } from 'react'
+import { toast } from 'sonner'
+import { cn, Tooltip, TooltipContent, TooltipTrigger } from 'ui'
+import type { TableField } from '../TableEditor.types'
+import { tableTemplates } from './templates'
+import type { TableSuggestion } from './types'
+import { convertTableSuggestionToTableField } from './utils'
+
+interface QuickstartTemplatesWidgetProps {
+ onSelectTemplate: (tableData: Partial<TableField>) => void
+ disabled?: boolean
+}
+
+const SUCCESS_MESSAGE_DURATION_MS = 3000
+const CATEGORIES = Object.keys(tableTemplates)
+
+export const QuickstartTemplatesWidget = ({
+ onSelectTemplate,
+ disabled,
+}: QuickstartTemplatesWidgetProps) => {
+ const [activeCategory, setActiveCategory] = useState<string | null>(null)
+
+ useEffect(() => {
+ if (activeCategory === null && CATEGORIES.length > 0) {
+ setActiveCategory(CATEGORIES[0])
+ }
+ }, [activeCategory])
+
+ const handleSelectTemplate = useCallback(
+ (template: TableSuggestion) => {
+ const tableField = convertTableSuggestionToTableField(template)
+ onSelectTemplate(tableField)
+ toast.success(`Applied ${template.tableName} template. You can customize the fields below.`, {
+ duration: SUCCESS_MESSAGE_DURATION_MS,
+ })
+ },
+ [onSelectTemplate]
+ )
+
+ const displayedTemplates = activeCategory ? tableTemplates[activeCategory] || [] : []
+
+ return (
+ <div className="rounded-lg border border-default bg-surface-100 p-6 transition-all hover:border-foreground-muted">
+ <div className="mb-4">
+ <div className="flex items-center gap-2 mb-2">
+ <Layers size={16} className="text-foreground" />
+ <h3 className="text-base font-medium">Table quickstarts</h3>
+ </div>
+ <p className="text-sm text-foreground-lighter">
+ Select a pre-built schema to get started quickly.
+ </p>
+ </div>
+
+ <div className="space-y-3">
+ <div className="flex flex-wrap gap-2">
+ {CATEGORIES.map((category) => (
+ <button
+ key={category}
+ onClick={() => setActiveCategory(category)}
+ disabled={disabled}
+ role="tab"
+ aria-selected={activeCategory === category}
+ aria-label={`${category} templates category`}
+ className={cn(
+ 'px-3 py-1.5 rounded-md text-sm capitalize border transition-all',
+ activeCategory === category
+ ? 'border-foreground bg-surface-200 text-foreground'
+ : 'border-default hover:border-foreground-muted hover:bg-surface-100 text-foreground-light',
+ 'disabled:opacity-50 disabled:cursor-not-allowed'
+ )}
+ >
+ {category}
+ </button>
+ ))}
+ </div>
+
+ {displayedTemplates.length > 0 && (
+ <div className="grid gap-2 pt-1">
+ {displayedTemplates.map((template) => (
+ <button
+ key={`${activeCategory}:${template.tableName}`}
+ onClick={() => handleSelectTemplate(template)}
+ disabled={disabled}
+ aria-label={`Select ${template.tableName} template with ${template.fields.length} fields`}
+ className={cn(
+ 'text-left p-3 rounded-md border transition-colors w-full bg-surface-100',
+ 'border-light hover:border-default hover:bg-surface-200 cursor-pointer',
+ 'disabled:opacity-50 disabled:cursor-not-allowed'
+ )}
+ >
+ <div className="flex items-start gap-3">
+ <div className="rounded-full bg-alternative border w-8 h-8 flex items-center justify-center flex-shrink-0">
+ <Table2 size={16} className="text-foreground" />
+ </div>
+ <div className="flex-1 min-w-0">
+ <div className="text-sm font-medium text-foreground mb-0">
+ {template.tableName}
+ </div>
+ {template.rationale && (
+ <div className="text-xs text-foreground-light mt-0.5">
+ {template.rationale}
+ </div>
+ )}
+ </div>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div className="flex items-center gap-1 text-sm text-foreground-muted ml-3">
+ <Columns3 size={14} aria-hidden="true" />
+ <span>{template.fields.length}</span>
+ </div>
+ </TooltipTrigger>
+ <TooltipContent>
+ {template.fields.length} {template.fields.length === 1 ? 'column' : 'columns'}
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/TableTemplateSelector.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/TableTemplateSelector.tsx
deleted file mode 100644
index 2efb9c871af..00000000000
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/TableTemplateSelector.tsx
+++ /dev/null
@@ -1,121 +0,0 @@
-import { useState, useCallback, useEffect, useMemo } from 'react'
-import { toast } from 'sonner'
-import { Button, cn } from 'ui'
-import { tableTemplates } from './templates'
-import { QuickstartVariant } from './types'
-import { convertTableSuggestionToTableField } from './utils'
-import type { TableSuggestion } from './types'
-import type { TableField } from '../TableEditor.types'
-
-interface TableTemplateSelectorProps {
- variant: Exclude<QuickstartVariant, QuickstartVariant.CONTROL> // [Sean] this will be used in PR #38934
- onSelectTemplate: (tableField: Partial<TableField>) => void
- onDismiss?: () => void
- disabled?: boolean
-}
-
-const SUCCESS_MESSAGE_DURATION_MS = 3000
-
-export const TableTemplateSelector = ({
- variant: _variant,
- onSelectTemplate,
- onDismiss,
- disabled,
-}: TableTemplateSelectorProps) => {
- const [activeCategory, setActiveCategory] = useState<string | null>(null) // null => All
- const [selectedTemplate, setSelectedTemplate] = useState<TableSuggestion | null>(null)
-
- const handleSelectTemplate = useCallback(
- (template: TableSuggestion) => {
- const tableField = convertTableSuggestionToTableField(template)
- onSelectTemplate(tableField)
- setSelectedTemplate(template)
- toast.success(
- `${template.tableName} template applied. You can add or modify the fields below.`,
- {
- duration: SUCCESS_MESSAGE_DURATION_MS,
- }
- )
- },
- [onSelectTemplate]
- )
-
- const categories = useMemo(() => Object.keys(tableTemplates), [])
-
- useEffect(() => {
- if (activeCategory === null && categories.length > 0) {
- setActiveCategory(categories[0])
- }
- }, [categories, activeCategory])
-
- const displayed = useMemo(
- () => (activeCategory ? tableTemplates[activeCategory] || [] : []),
- [activeCategory]
- )
-
- return (
- <div className="rounded-lg border border-default bg-surface-75 p-4">
- <div className="flex items-center justify-between mb-3">
- <div>
- <h3 className="text-sm font-medium">Start faster with a table template</h3>
- <p className="text-xs text-foreground-lighter mt-1">
- Save time by starting from a ready-made table schema.
- </p>
- </div>
- {onDismiss && (
- <Button type="text" size="tiny" onClick={onDismiss}>
- Dismiss
- </Button>
- )}
- </div>
-
- <div className="flex flex-wrap gap-2 mb-3">
- {categories.map((category) => (
- <button
- key={category}
- onClick={() => setActiveCategory(category)}
- disabled={disabled}
- className={cn(
- 'px-2 py-1 rounded-md text-xs capitalize border',
- activeCategory === category
- ? 'border-foreground bg-surface-200'
- : 'border-default hover:border-foreground-muted hover:bg-surface-100',
- 'disabled:opacity-50 disabled:cursor-not-allowed'
- )}
- >
- {category}
- </button>
- ))}
- </div>
-
- <div className="grid gap-2">
- {displayed.map((t) => (
- <button
- key={`${activeCategory}:${t.tableName}`}
- onClick={() => handleSelectTemplate(t)}
- disabled={disabled}
- className={cn(
- 'text-left p-3 rounded-md border transition-all w-full',
- selectedTemplate?.tableName === t.tableName
- ? 'border-foreground bg-surface-200'
- : 'border-default hover:border-foreground-muted hover:bg-surface-100',
- 'disabled:opacity-50 disabled:cursor-not-allowed'
- )}
- >
- <div className="flex items-start justify-between">
- <div className="flex-1">
- <div className="text-sm font-medium font-mono">{t.tableName}</div>
- {t.rationale && (
- <div className="text-sm text-foreground-light mt-1">{t.rationale}</div>
- )}
- </div>
- <div className="flex items-center gap-1 text-sm text-foreground-muted ml-3">
- <span>{t.fields.length} columns</span>
- </div>
- </div>
- </button>
- ))}
- </div>
- </div>
- )
-}
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/constants.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/constants.ts
index 506a4e7d0cb..d3ed011ad47 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/constants.ts
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/constants.ts
@@ -1,7 +1,6 @@
export const LIMITS = {
MAX_PROMPT_LENGTH: 500,
- MAX_TABLES_TO_GENERATE: 3,
- MIN_TABLES_TO_GENERATE: 2,
+ MAX_TABLES: 5,
} as const
export const AI_QUICK_IDEAS = [
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/templates.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/templates.ts
index 0566358236c..68dd6dfe4da 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/templates.ts
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/templates.ts
@@ -17,8 +17,6 @@ export const tableTemplates: Record<string, TableSuggestion[]> = {
type: 'uuid',
nullable: false,
unique: true,
- isForeign: true,
- references: 'auth.users(id)',
},
{ name: 'username', type: 'text', nullable: true, unique: true },
{ name: 'display_name', type: 'text', nullable: true },
@@ -46,8 +44,6 @@ export const tableTemplates: Record<string, TableSuggestion[]> = {
name: 'author_id',
type: 'uuid',
nullable: false,
- isForeign: true,
- references: 'profiles(id)',
},
{ name: 'content', type: 'text', nullable: false },
{ name: 'image_url', type: 'text', nullable: true },
@@ -73,15 +69,11 @@ export const tableTemplates: Record<string, TableSuggestion[]> = {
name: 'follower_id',
type: 'uuid',
nullable: false,
- isForeign: true,
- references: 'profiles(id)',
},
{
name: 'following_id',
type: 'uuid',
nullable: false,
- isForeign: true,
- references: 'profiles(id)',
},
{ name: 'created_at', type: 'timestamptz', nullable: false, default: 'now()' },
],
@@ -132,8 +124,6 @@ export const tableTemplates: Record<string, TableSuggestion[]> = {
name: 'customer_id',
type: 'uuid',
nullable: false,
- isForeign: true,
- references: 'profiles(id)',
},
{ name: 'status', type: 'text', nullable: false, default: "'pending'" },
{ name: 'subtotal', type: 'numeric', nullable: false },
@@ -161,15 +151,11 @@ export const tableTemplates: Record<string, TableSuggestion[]> = {
name: 'user_id',
type: 'uuid',
nullable: false,
- isForeign: true,
- references: 'profiles(id)',
},
{
name: 'product_id',
type: 'uuid',
nullable: false,
- isForeign: true,
- references: 'products(id)',
},
{ name: 'quantity', type: 'int4', nullable: false, default: '1' },
{ name: 'added_at', type: 'timestamptz', nullable: false, default: 'now()' },
@@ -198,8 +184,6 @@ export const tableTemplates: Record<string, TableSuggestion[]> = {
name: 'author_id',
type: 'uuid',
nullable: false,
- isForeign: true,
- references: 'profiles(id)',
},
{ name: 'status', type: 'text', nullable: false, default: "'draft'" },
{ name: 'published_at', type: 'timestamptz', nullable: true },
@@ -242,8 +226,6 @@ export const tableTemplates: Record<string, TableSuggestion[]> = {
name: 'article_id',
type: 'uuid',
nullable: false,
- isForeign: true,
- references: 'articles(id)',
},
{ name: 'author_name', type: 'text', nullable: false },
{ name: 'author_email', type: 'text', nullable: false },
@@ -275,10 +257,8 @@ export const tableTemplates: Record<string, TableSuggestion[]> = {
name: 'user_id',
type: 'uuid',
nullable: false,
- isForeign: true,
- references: 'auth.users(id)',
},
- { name: 'list_id', type: 'uuid', nullable: true, isForeign: true, references: 'lists(id)' },
+ { name: 'list_id', type: 'uuid', nullable: true },
{ name: 'created_at', type: 'timestamptz', nullable: false, default: 'now()' },
{ name: 'updated_at', type: 'timestamptz', nullable: false, default: 'now()' },
],
@@ -303,8 +283,6 @@ export const tableTemplates: Record<string, TableSuggestion[]> = {
name: 'user_id',
type: 'uuid',
nullable: false,
- isForeign: true,
- references: 'auth.users(id)',
},
{ name: 'created_at', type: 'timestamptz', nullable: false, default: 'now()' },
{ name: 'updated_at', type: 'timestamptz', nullable: false, default: 'now()' },
@@ -326,8 +304,6 @@ export const tableTemplates: Record<string, TableSuggestion[]> = {
name: 'task_id',
type: 'uuid',
nullable: false,
- isForeign: true,
- references: 'tasks(id)',
},
{ name: 'title', type: 'text', nullable: false },
{ name: 'completed', type: 'bool', nullable: false, default: 'false' },
@@ -353,8 +329,6 @@ export const tableTemplates: Record<string, TableSuggestion[]> = {
name: 'user_id',
type: 'uuid',
nullable: true,
- isForeign: true,
- references: 'profiles(id)',
},
{ name: 'session_id', type: 'text', nullable: true },
{ name: 'event_type', type: 'text', nullable: false },
@@ -380,8 +354,6 @@ export const tableTemplates: Record<string, TableSuggestion[]> = {
name: 'user_id',
type: 'uuid',
nullable: true,
- isForeign: true,
- references: 'profiles(id)',
},
{ name: 'session_id', type: 'text', nullable: true },
{ name: 'path', type: 'text', nullable: false },
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/types.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/types.ts
index aeceaa3acdb..8fbe022d0ee 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/types.ts
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/types.ts
@@ -26,14 +26,6 @@ export type TableField = {
default?: string // Must be string for table editor compatibility
description?: string
isPrimary?: boolean
- isForeign?: boolean
- references?: string
-}
-
-export type TableRelationship = {
- from: string
- to: string
- type: 'one-to-one' | 'one-to-many' | 'many-to-many' | 'many-to-one'
}
export enum TableSource {
@@ -47,19 +39,11 @@ export enum QuickstartVariant {
TEMPLATES = 'templates',
}
-export enum ViewMode {
- INITIAL = 'initial',
- AI_INPUT = 'ai-input',
- AI_RESULTS = 'ai-results',
- CATEGORY_SELECTED = 'category-selected',
-}
-
export type TableSuggestion = {
tableName: string
fields: TableField[]
rationale?: string
source: TableSource
- relationships?: TableRelationship[]
}
export type AIGeneratedSchema = {
@@ -70,13 +54,10 @@ export type AIGeneratedSchema = {
name: string
type: string
isPrimary?: boolean
- isForeign?: boolean
- references?: string
isNullable?: boolean
defaultValue?: string
isUnique?: boolean
}>
- relationships?: TableRelationship[]
}>
summary: string
}
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/useAITableGeneration.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/useAITableGeneration.ts
new file mode 100644
index 00000000000..955f931b368
--- /dev/null
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/useAITableGeneration.ts
@@ -0,0 +1,307 @@
+import { constructHeaders, fetchHandler } from 'data/fetchers'
+import { useLocalStorage } from 'hooks/misc/useLocalStorage'
+import { BASE_PATH } from 'lib/constants'
+import { useCallback, useEffect, useRef, useState } from 'react'
+import { toast } from 'sonner'
+import { LIMITS } from './constants'
+import type { AIGeneratedSchema, PostgresType, TableSuggestion } from './types'
+import { TableSource } from './types'
+
+const AI_TABLES_STORAGE_KEY = 'table-quickstart-ai-results'
+const MAX_BUFFER_SIZE = 50 * 1024 // 50KB limit for streaming responses
+
+type PartialColumn = Partial<AIGeneratedSchema['tables'][number]['columns'][number]>
+type PartialTable = Partial<AIGeneratedSchema['tables'][number]> & {
+ columns?: PartialColumn[]
+}
+type PartialSchema = Partial<AIGeneratedSchema> & {
+ tables?: PartialTable[]
+}
+
+interface AITableGenerationState {
+ prompt: string
+ tables: TableSuggestion[]
+}
+
+const isNotNull = <T>(value: T | null | undefined): value is T => value != null
+
+const isIdColumn = (name: string) => name === 'id'
+
+const isPrimaryColumn = (column: { isPrimary?: boolean | null; name: string }) =>
+ column.isPrimary || isIdColumn(column.name)
+
+const getColumnDescription = (column: { isPrimary?: boolean | null; name: string }) => {
+ if (isPrimaryColumn(column)) return 'Primary key'
+ return undefined
+}
+
+const mapColumnType = (type: string): PostgresType => {
+ const typeMap: Record<string, PostgresType> = {
+ bigint: 'int8',
+ integer: 'int4',
+ smallint: 'int2',
+ boolean: 'bool',
+ text: 'text',
+ varchar: 'varchar',
+ uuid: 'uuid',
+ timestamp: 'timestamp',
+ timestamptz: 'timestamptz',
+ 'timestamp with time zone': 'timestamptz',
+ date: 'date',
+ time: 'time',
+ timetz: 'timetz',
+ 'time with time zone': 'timetz',
+ json: 'json',
+ jsonb: 'jsonb',
+ numeric: 'numeric',
+ real: 'float4',
+ 'double precision': 'float8',
+ bytea: 'bytea',
+ }
+
+ return typeMap[type.toLowerCase()] || 'text'
+}
+
+const convertAISchemaToTableSuggestions = (schema: AIGeneratedSchema): TableSuggestion[] => {
+ return schema.tables.map((table) => ({
+ tableName: table.name,
+ fields: table.columns.map((column) => ({
+ name: column.name,
+ type: mapColumnType(column.type),
+ nullable: column.isNullable ?? undefined,
+ unique: column.isUnique ?? undefined,
+ default: column.defaultValue ?? undefined,
+ description: getColumnDescription(column),
+ isPrimary: column.isPrimary || isIdColumn(column.name) || undefined,
+ })),
+ rationale: table.description,
+ source: TableSource.AI,
+ }))
+}
+
+const convertPartialSchemaToTableSuggestions = (schema: PartialSchema): TableSuggestion[] => {
+ if (!Array.isArray(schema.tables)) return []
+
+ return schema.tables
+ .map((table, tableIndex) => {
+ if (!table) return null
+
+ const tableName =
+ typeof table.name === 'string' && table.name.trim().length > 0
+ ? table.name
+ : `table_${tableIndex + 1}`
+ const columns = Array.isArray(table.columns) ? table.columns : []
+
+ const fields = columns
+ .map((column, columnIndex) => {
+ if (!column) return null
+
+ const columnName =
+ typeof column.name === 'string' && column.name.trim().length > 0
+ ? column.name
+ : `column_${columnIndex + 1}`
+ const columnType =
+ typeof column.type === 'string' && column.type.trim().length > 0 ? column.type : 'text'
+
+ return {
+ name: columnName,
+ type: mapColumnType(columnType),
+ nullable: column.isNullable ?? undefined,
+ unique: column.isUnique ?? undefined,
+ default: column.defaultValue ?? undefined,
+ description: getColumnDescription({ ...column, name: columnName }),
+ isPrimary: column.isPrimary || isIdColumn(columnName) || undefined,
+ }
+ })
+ .filter(isNotNull)
+
+ if (fields.length === 0 && !table.name) {
+ return null
+ }
+
+ return {
+ tableName,
+ fields,
+ rationale: typeof table.description === 'string' ? table.description : undefined,
+ source: TableSource.AI,
+ }
+ })
+ .filter(isNotNull)
+}
+
+const safeJsonParse = <T>(input: string): T | null => {
+ try {
+ return JSON.parse(input) as T
+ } catch {
+ return null
+ }
+}
+
+export const useAITableGeneration = () => {
+ const [isGenerating, setIsGenerating] = useState(false)
+ const [error, setError] = useState<string | null>(null)
+ const [state, setState] = useLocalStorage<AITableGenerationState>(AI_TABLES_STORAGE_KEY, {
+ prompt: '',
+ tables: [],
+ })
+ const abortControllerRef = useRef<AbortController | null>(null)
+ const isMountedRef = useRef(true)
+
+ useEffect(() => {
+ isMountedRef.current = true
+ return () => {
+ isMountedRef.current = false
+ if (abortControllerRef.current) {
+ abortControllerRef.current.abort()
+ }
+ }
+ }, [])
+
+ const generateTables = useCallback(async (prompt: string): Promise<TableSuggestion[]> => {
+ if (abortControllerRef.current) {
+ abortControllerRef.current.abort()
+ }
+
+ if (prompt.length > LIMITS.MAX_PROMPT_LENGTH) {
+ const message = `Your description is too long. Try shortening it to under ${LIMITS.MAX_PROMPT_LENGTH} characters.`
+ setError(message)
+ toast.error('Description too long', {
+ description: message,
+ })
+ return []
+ }
+
+ const abortController = new AbortController()
+ abortControllerRef.current = abortController
+
+ setIsGenerating(true)
+ setError(null)
+ setState({ prompt, tables: [] })
+
+ try {
+ const headers = await constructHeaders()
+ headers.set('Content-Type', 'application/json')
+
+ const response = await fetchHandler(`${BASE_PATH}/api/ai/table-quickstart/generate-schemas`, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({ prompt }),
+ signal: abortController.signal,
+ })
+
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({
+ error: 'Unable to generate table schema. Try again with a different description.',
+ }))
+ const errorMessage =
+ errorData?.error ||
+ 'Unable to generate table schema. Try again with a different description.'
+ if (isMountedRef.current) {
+ setError(errorMessage)
+ }
+ toast.error('Unable to generate tables', {
+ description: errorMessage,
+ })
+ return []
+ }
+
+ if (!response.body) {
+ throw new Error('Response body is null')
+ }
+
+ const reader = response.body.getReader()
+ const decoder = new TextDecoder()
+ let jsonBuffer = ''
+ let latestPartialSchema: PartialSchema = {}
+
+ try {
+ while (true) {
+ const { done, value } = await reader.read()
+ if (done) break
+
+ jsonBuffer += decoder.decode(value, { stream: true })
+
+ if (jsonBuffer.length > MAX_BUFFER_SIZE) {
+ throw new Error('Response too large')
+ }
+
+ const partialJson = safeJsonParse<PartialSchema>(jsonBuffer)
+ if (partialJson) {
+ Object.assign(latestPartialSchema, partialJson)
+ const partialSuggestions = convertPartialSchemaToTableSuggestions(latestPartialSchema)
+
+ if (isMountedRef.current && partialSuggestions.length > 0) {
+ setState({ prompt, tables: partialSuggestions })
+ }
+ }
+ }
+ } finally {
+ reader.releaseLock()
+ }
+
+ jsonBuffer += decoder.decode()
+
+ const finalSchema = safeJsonParse<AIGeneratedSchema>(jsonBuffer)
+ const finalTables = finalSchema
+ ? convertAISchemaToTableSuggestions(finalSchema)
+ : convertPartialSchemaToTableSuggestions(latestPartialSchema)
+
+ if (isMountedRef.current) {
+ setError(null)
+ setState({ prompt, tables: finalTables })
+ }
+
+ return finalTables
+ } catch (error) {
+ if (error instanceof Error && error.name === 'AbortError') {
+ return []
+ }
+
+ const message =
+ error instanceof Error ? error.message : 'Unable to generate tables. Please try again.'
+
+ if (isMountedRef.current) {
+ setError(message)
+ }
+
+ toast.error('Unable to generate tables', {
+ description: message,
+ })
+
+ return []
+ } finally {
+ if (isMountedRef.current) {
+ setIsGenerating(false)
+ }
+ abortControllerRef.current = null
+ }
+ }, [])
+
+ const clearTables = useCallback(() => {
+ if (abortControllerRef.current) {
+ abortControllerRef.current.abort()
+ abortControllerRef.current = null
+ }
+
+ setIsGenerating(false)
+ setError(null)
+ setState({ prompt: '', tables: [] })
+ }, [])
+
+ const setPrompt = useCallback(
+ (prompt: string) => {
+ setState((prev) => ({ ...prev, prompt }))
+ },
+ [setState]
+ )
+
+ return {
+ generateTables,
+ isGenerating,
+ error,
+ prompt: state.prompt,
+ tables: state.tables,
+ setPrompt,
+ clearTables,
+ }
+}
diff --git a/apps/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx b/apps/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx
index 59d87733ade..731da7c2714 100644
--- a/apps/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx
+++ b/apps/studio/components/layouts/TableEditorLayout/TableEditorMenu.tsx
@@ -147,7 +147,7 @@ export const TableEditorMenu = () => {
icon={<Plus size={14} strokeWidth={1.5} className="text-foreground-muted" />}
type="default"
className="justify-start"
- onClick={snap.onAddTable}
+ onClick={() => snap.onAddTable()}
tooltip={{
content: {
side: 'bottom',
diff --git a/apps/studio/components/layouts/Tabs/NewTab.tsx b/apps/studio/components/layouts/Tabs/NewTab.tsx
index c9826907276..aea59d0500a 100644
--- a/apps/studio/components/layouts/Tabs/NewTab.tsx
+++ b/apps/studio/components/layouts/Tabs/NewTab.tsx
@@ -1,17 +1,23 @@
import { PermissionAction } from '@supabase/shared-types/out/constants'
+import dayjs from 'dayjs'
import { partition } from 'lodash'
import { Table2 } from 'lucide-react'
import Link from 'next/link'
import { useRouter } from 'next/router'
+import { useMemo } from 'react'
import { toast } from 'sonner'
import { useParams } from 'common'
import { SQL_TEMPLATES } from 'components/interfaces/SQLEditor/SQLEditor.queries'
import { createSqlSnippetSkeletonV2 } from 'components/interfaces/SQLEditor/SQLEditor.utils'
+import { QuickstartAIWidget } from 'components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/QuickstartAIWidget'
+import { QuickstartTemplatesWidget } from 'components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/QuickstartTemplatesWidget'
+import { QuickstartVariant } from 'components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/types'
import { useSendEventMutation } from 'data/telemetry/send-event-mutation'
import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
+import { usePHFlag } from 'hooks/ui/useFlag'
import { uuidv4 } from 'lib/helpers'
import { useProfile } from 'lib/profile'
import { useSqlEditorV2StateSnapshot } from 'state/sql-editor-v2'
@@ -30,6 +36,9 @@ import { useEditorType } from '../editors/EditorsLayout.hooks'
import { ActionCard } from './ActionCard'
import { RecentItems } from './RecentItems'
+const NEW_PROJECT_THRESHOLD_DAYS = 7
+const TABLE_QUICKSTART_FLAG = 'tableQuickstart'
+
export function NewTab() {
const router = useRouter()
const { ref } = useParams()
@@ -55,6 +64,29 @@ export function NewTab() {
}
)
+ /**
+ * Returns:
+ * - `QuickstartVariant`: user variation (if bucketed into AI, Templates, or future variants)
+ * - `false`: user not yet bucketed or not targeted for experiment
+ * - `undefined`: PostHog still loading
+ */
+ const tableQuickstartVariant = usePHFlag<QuickstartVariant | false | undefined>(
+ TABLE_QUICKSTART_FLAG
+ )
+
+ const isNewProject = useMemo(() => {
+ if (!project?.inserted_at) return false
+ return dayjs().diff(dayjs(project.inserted_at), 'day') < NEW_PROJECT_THRESHOLD_DAYS
+ }, [project?.inserted_at])
+
+ const activeQuickstartVariant =
+ editor !== 'sql' &&
+ isNewProject &&
+ tableQuickstartVariant &&
+ tableQuickstartVariant !== QuickstartVariant.CONTROL
+ ? tableQuickstartVariant
+ : null
+
const tableEditorActions = [
{
icon: <Table2 className="h-4 w-4 text-foreground" strokeWidth={1.5} />,
@@ -62,7 +94,7 @@ export function NewTab() {
description: 'Design and create a new database table',
bgColor: 'bg-blue-500',
isBeta: false,
- onClick: snap.onAddTable,
+ onClick: () => snap.onAddTable(),
},
]
@@ -122,6 +154,12 @@ export function NewTab() {
<ActionCard key={`action-card-${i}`} {...item} />
))}
</div>
+ {activeQuickstartVariant === QuickstartVariant.AI && (
+ <QuickstartAIWidget onSelectTable={(tableData) => snap.onAddTable(tableData)} />
+ )}
+ {activeQuickstartVariant === QuickstartVariant.TEMPLATES && (
+ <QuickstartTemplatesWidget onSelectTemplate={(tableData) => snap.onAddTable(tableData)} />
+ )}
<RecentItems />
</div>
{editor === 'sql' && (
diff --git a/apps/studio/middleware.ts b/apps/studio/middleware.ts
index 7b894c8de92..d92b4a320be 100644
--- a/apps/studio/middleware.ts
+++ b/apps/studio/middleware.ts
@@ -15,6 +15,7 @@ const HOSTED_SUPPORTED_API_URLS = [
'/ai/onboarding/design',
'/ai/feedback/classify',
'/ai/docs',
+ '/ai/table-quickstart/generate-schemas',
'/get-ip-address',
'/get-utc-time',
'/get-deployment-commit',
diff --git a/apps/studio/pages/api/ai/table-quickstart/generate-schemas.ts b/apps/studio/pages/api/ai/table-quickstart/generate-schemas.ts
new file mode 100644
index 00000000000..9ac5e29f834
--- /dev/null
+++ b/apps/studio/pages/api/ai/table-quickstart/generate-schemas.ts
@@ -0,0 +1,129 @@
+import { streamObject } from 'ai'
+import { NextApiRequest, NextApiResponse } from 'next'
+import { z } from 'zod'
+
+import { LIMITS } from 'components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableQuickstart/constants'
+import { getModel } from 'lib/ai/model'
+import apiWrapper from 'lib/api/apiWrapper'
+
+export const maxDuration = 30
+
+const ColumnSchema = z.object({
+ name: z.string().describe('The column name in snake_case'),
+ type: z.string().describe('PostgreSQL data type (e.g., bigint, text, timestamp with time zone)'),
+ isPrimary: z.boolean().optional().nullable().describe('Whether this is a primary key'),
+ isNullable: z.boolean().optional().nullable().describe('Whether the column can be null'),
+ defaultValue: z.string().optional().nullable().describe('Default value or expression'),
+ isUnique: z
+ .boolean()
+ .optional()
+ .nullable()
+ .describe('Whether the column has a unique constraint'),
+})
+
+const TableSchema = z.object({
+ name: z.string().describe('The table name in snake_case'),
+ description: z.string().describe('A brief description of what this table stores'),
+ columns: z.array(ColumnSchema).describe('Array of columns in the table'),
+})
+
+const ResponseSchema = z.object({
+ tables: z.array(TableSchema).describe('Array of related database tables for the application'),
+ summary: z.string().optional().describe('Brief summary of the generated schema'),
+})
+
+async function handler(req: NextApiRequest, res: NextApiResponse) {
+ const { method } = req
+
+ switch (method) {
+ case 'POST':
+ return handlePost(req, res)
+ default:
+ res.setHeader('Allow', ['POST'])
+ res.status(405).json({
+ data: null,
+ error: { message: `Method ${method} Not Allowed` },
+ })
+ }
+}
+
+async function handlePost(req: NextApiRequest, res: NextApiResponse) {
+ const modelName = 'gpt-5-mini'
+ const modelResult = await getModel({
+ provider: 'openai',
+ model: modelName,
+ routingKey: 'table-quickstart',
+ isLimited: false,
+ })
+
+ if (modelResult.error || !modelResult.model) {
+ return res.status(500).json({
+ error:
+ modelResult.error?.message || 'AI service temporarily unavailable. Try again in a moment.',
+ })
+ }
+
+ const { model, providerOptions } = modelResult
+
+ const { prompt } = req.body
+
+ if (!prompt) {
+ return res.status(400).json({ error: 'Please provide a description of your app' })
+ }
+
+ if (typeof prompt !== 'string' || prompt.length > LIMITS.MAX_PROMPT_LENGTH) {
+ return res.status(400).json({
+ error: `Description too long. Keep it under ${LIMITS.MAX_PROMPT_LENGTH} characters.`,
+ })
+ }
+
+ try {
+ const abortController = new AbortController()
+ req.on('close', () => abortController.abort())
+ req.on('aborted', () => abortController.abort())
+
+ const systemPrompt = `Generate exactly 3 core database tables.
+
+ Schema rules:
+ - Primary key: id (uuid) with isPrimary: true, defaultValue: 'gen_random_uuid()'
+ - Timestamps: created_at, updated_at (timestamptz) with defaultValue: 'now()'
+ - Use text for strings, timestamptz for dates, bigint for integers
+ - snake_case naming
+
+ Output rules (minimize tokens):
+ - ALWAYS include: name, type, isNullable
+ - Include isPrimary/isUnique/defaultValue ONLY when true/set
+ - Omit summary field`
+
+ const userPrompt = `Application: ${prompt}`
+
+ const result = streamObject({
+ model,
+ abortSignal: abortController.signal,
+ schema: ResponseSchema,
+ mode: 'json',
+ ...(providerOptions && { providerOptions }),
+ system: systemPrompt,
+ prompt: userPrompt,
+ })
+
+ result.pipeTextStreamToResponse(res)
+ } catch (error) {
+ if (error instanceof Error) {
+ if (error.message.includes('context_length') || error.message.includes('too long')) {
+ return res.status(400).json({
+ error: 'Description too complex. Try using fewer words.',
+ })
+ }
+ }
+
+ return res.status(500).json({
+ error: 'Unable to generate schema. Try a different description.',
+ })
+ }
+}
+
+const wrapper = (req: NextApiRequest, res: NextApiResponse) =>
+ apiWrapper(req, res, handler, { withAuth: true })
+
+export default wrapper
diff --git a/apps/studio/state/table-editor.tsx b/apps/studio/state/table-editor.tsx
index ed325bf861b..97ca0cd5d4b 100644
--- a/apps/studio/state/table-editor.tsx
+++ b/apps/studio/state/table-editor.tsx
@@ -5,6 +5,7 @@ import { proxy, useSnapshot } from 'valtio'
import type { SupaRow } from 'components/grid/types'
import { ForeignKey } from 'components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.types'
import type { EditValue } from 'components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.types'
+import type { TableField } from 'components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.types'
import type { Dictionary } from 'types'
export const TABLE_EDITOR_DEFAULT_ROWS_PER_PAGE = 100
@@ -19,7 +20,7 @@ export type SidePanel =
| { type: 'cell'; value?: { column: string; row: Dictionary<any> } }
| { type: 'row'; row?: Dictionary<any> }
| { type: 'column'; column?: PostgresColumn }
- | { type: 'table'; mode: 'new' | 'edit' | 'duplicate' }
+ | { type: 'table'; mode: 'new' | 'edit' | 'duplicate'; templateData?: Partial<TableField> }
| { type: 'schema'; mode: 'new' | 'edit' }
| { type: 'json'; jsonValue: EditValue }
| {
@@ -89,10 +90,10 @@ export const createTableEditorState = () => {
},
/* Tables */
- onAddTable: () => {
+ onAddTable: (templateData?: Partial<TableField>) => {
state.ui = {
open: 'side-panel',
- sidePanel: { type: 'table', mode: 'new' },
+ sidePanel: { type: 'table', mode: 'new', templateData },
}
},
onEditTable: () => {