Skip to content

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

Chore/remove react query (#19332)

Terry Suttona5ffe1e693fb
diff --git a/apps/database-new/app/NewThreadInput.tsx b/apps/database-new/app/NewThreadInput.tsx
index 2419589ca24..19756ad519c 100644
--- a/apps/database-new/app/NewThreadInput.tsx
+++ b/apps/database-new/app/NewThreadInput.tsx
@@ -3,17 +3,15 @@
import { CHAT_EXAMPLES } from '@/data/chat-examples'
import { useAppStateSnapshot } from '@/lib/state'
import { createClient } from '@/lib/supabase/client'
-import { useMutation } from '@tanstack/react-query'
import { ExternalLink } from 'lucide-react'
-import { useRouter } from 'next/navigation'
-import { createRef, useState } from 'react'
+import { useState } from 'react'
+import { useFormState } from 'react-dom'
import { AssistantChatForm, cn } from 'ui'
+import { updateThread } from './actions'
const suggestions = CHAT_EXAMPLES
const NewThreadInput = () => {
- const router = useRouter()
-
const [value, setValue] = useState(() => {
if (typeof window !== 'undefined') {
const localPrompt = localStorage.getItem('prompt')
@@ -25,59 +23,41 @@ const NewThreadInput = () => {
return ''
})
- const supabase = createClient()
+ const initialState = {
+ message: undefined,
+ success: undefined,
+ data: {
+ value,
+ },
+ }
+ const [state, formAction] = useFormState(updateThread, initialState)
+ const supabase = createClient()
const snap = useAppStateSnapshot()
- const { mutate, isPending, isSuccess } = useMutation({
- mutationFn: async (prompt: string) => {
- const {
- data: { user },
- } = await supabase.auth.getUser()
-
- const body = { prompt, userID: user?.id } // Include userID in the body object
-
- const response = await fetch('/api/ai/sql/threads/create', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(body),
- })
- const result = await response.json()
- return result
- },
- onSuccess(data) {
- const url = `/${data.threadId}/${data.runId}`
- router.push(url)
- },
- })
-
return (
<>
<div className="relative w-10/12 xl:w-11/12 max-w-xl">
<AssistantChatForm
+ action={formAction}
key={'new-thread-form'}
id={'new-thread-form'}
onSubmit={async (event) => {
- event.preventDefault()
-
+ console.log('hello')
const {
data: { user },
} = await supabase.auth.getUser()
-
if (!user) {
+ event.preventDefault()
localStorage.setItem('prompt', value)
snap.setLoginDialogOpen(true)
return
}
- if (value.length > 0) {
- mutate(value)
- }
}}
value={value}
placeholder="e.g Create a Telegram-like chat application"
- disabled={isPending || isSuccess}
- loading={isPending || isSuccess}
onValueChange={(e) => setValue(e.target.value)}
+ message={state.message}
/>
</div>
<div className="flex gap-3">
diff --git a/apps/database-new/app/[threadId]/[runId]/[messageId]/CodeEditor.tsx b/apps/database-new/app/[threadId]/[runId]/[messageId]/CodeEditor.tsx
new file mode 100644
index 00000000000..31c7c550088
--- /dev/null
+++ b/apps/database-new/app/[threadId]/[runId]/[messageId]/CodeEditor.tsx
@@ -0,0 +1,28 @@
+import { format } from 'sql-formatter'
+
+import { getThread } from './MessageId.utils'
+import { MonacoEditor } from './MonacoEditor'
+import { CodeEditorContainer } from './CodeEditorContainer'
+
+export async function CodeEditor({ params }: { params: any }) {
+ const { threadId, runId, messageId } = params
+
+ const content = await getThread({ threadId, runId, messageId })
+
+ const code = format(content, { language: 'postgresql' })
+
+ // useEffect(() => {
+ // snap.setSelectedCode(code)
+ // }, [code])
+
+ /**
+ * - CodeEditorContainer is a client component, which uses valtio state
+ * - MonacoEditor is a server component injected into it
+ */
+
+ return (
+ <CodeEditorContainer>
+ <MonacoEditor id="sql-editor" language="pgsql" value={code} />
+ </CodeEditorContainer>
+ )
+}
diff --git a/apps/database-new/components/CodeEditor/CodeEditor.utils.ts b/apps/database-new/app/[threadId]/[runId]/[messageId]/CodeEditor.utils.ts
similarity index 100%
rename from apps/database-new/components/CodeEditor/CodeEditor.utils.ts
rename to apps/database-new/app/[threadId]/[runId]/[messageId]/CodeEditor.utils.ts
diff --git a/apps/database-new/app/[threadId]/[runId]/[messageId]/CodeEditorContainer.tsx b/apps/database-new/app/[threadId]/[runId]/[messageId]/CodeEditorContainer.tsx
new file mode 100644
index 00000000000..7a65631a585
--- /dev/null
+++ b/apps/database-new/app/[threadId]/[runId]/[messageId]/CodeEditorContainer.tsx
@@ -0,0 +1,24 @@
+'use client'
+
+import { cn } from 'ui'
+
+import { useAppStateSnapshot } from '@/lib/state'
+import { ReactNode } from 'react'
+
+function CodeEditorContainer({ children }: { children: ReactNode }) {
+ const snap = useAppStateSnapshot()
+
+ return (
+ <div
+ className={cn(
+ snap.hideCode ? 'max-w-0' : 'max-w-lg 2xl:max-w-xl',
+ 'w-full xl:border-l',
+ 'grow flex flex-col h-full'
+ )}
+ >
+ {children}
+ </div>
+ )
+}
+
+export { CodeEditorContainer }
diff --git a/apps/database-new/app/[threadId]/[runId]/[messageId]/MessageId.utils.ts b/apps/database-new/app/[threadId]/[runId]/[messageId]/MessageId.utils.ts
new file mode 100644
index 00000000000..73e2ef4ccb1
--- /dev/null
+++ b/apps/database-new/app/[threadId]/[runId]/[messageId]/MessageId.utils.ts
@@ -0,0 +1,66 @@
+'use server'
+
+import OpenAI from 'openai'
+
+import { AssistantMessage } from '@/lib/types'
+import { compact, sortBy } from 'lodash'
+
+const openai = new OpenAI()
+
+async function getThread({
+ threadId,
+ runId,
+ messageId,
+}: {
+ threadId: string
+ runId: string
+ messageId: string
+}) {
+ const [run, { data: _messages }] = await Promise.all([
+ openai.beta.threads.runs.retrieve(threadId, runId),
+ openai.beta.threads.messages.list(threadId),
+ ])
+
+ let messages = compact(
+ await Promise.all(
+ _messages.map(async (m) => {
+ if (m.role === 'user' && m.content[0].type === 'text') {
+ return {
+ id: m.id,
+ role: 'user' as const,
+ created_at: m.created_at,
+ text: m.content[0].text.value,
+ }
+ }
+
+ if (m.content.length >= 1 && m.content[0].type === 'text') {
+ let sql = ''
+ if (m.content[0].type === 'text') {
+ sql = m.content[0].text.value.replaceAll('\n', '')
+ }
+ return {
+ id: m.id,
+ role: 'assistant' as const,
+ created_at: m.created_at,
+ sql,
+ }
+ }
+ })
+ )
+ )
+
+ messages = sortBy(messages, (m) => m.created_at)
+
+ const userMessages = messages.filter((m) => m.role === 'user')
+
+ const selectedMessageIdx = messages.findIndex((m) => m.id === messageId)
+ const selectedMessageReply = (
+ selectedMessageIdx !== -1 ? messages[selectedMessageIdx + 1] : undefined
+ ) as AssistantMessage | undefined
+
+ const content = selectedMessageReply?.sql.replaceAll('```sql', '').replaceAll('```', '') || ''
+
+ return content
+}
+
+export { getThread }
diff --git a/apps/database-new/components/CodeEditor/CodeEditor.tsx b/apps/database-new/app/[threadId]/[runId]/[messageId]/MonacoEditor.tsx
similarity index 56%
rename from apps/database-new/components/CodeEditor/CodeEditor.tsx
rename to apps/database-new/app/[threadId]/[runId]/[messageId]/MonacoEditor.tsx
index 0f72dee6ff8..f7cf4421cc4 100644
--- a/apps/database-new/components/CodeEditor/CodeEditor.tsx
+++ b/apps/database-new/app/[threadId]/[runId]/[messageId]/MonacoEditor.tsx
@@ -1,12 +1,7 @@
-import Editor, { BeforeMount, EditorProps, OnMount } from '@monaco-editor/react'
-import { merge } from 'lodash'
-import { useTheme } from 'next-themes'
-import { useEffect, useRef } from 'react'
-import { format } from 'sql-formatter'
-import { cn } from 'ui'
+'use client'
-import { useAppStateSnapshot } from '@/lib/state'
-import { getTheme } from './CodeEditor.utils'
+import Editor, { BeforeMount, EditorProps } from '@monaco-editor/react'
+import { merge } from 'lodash'
interface MonacoEditorProps {
id: string
@@ -22,27 +17,6 @@ interface MonacoEditorProps {
value?: string
}
-export const CodeEditor = ({ content = '' }: { content: string }) => {
- const snap = useAppStateSnapshot()
- const code = format(content, { language: 'postgresql' })
-
- useEffect(() => {
- snap.setSelectedCode(code)
- }, [code])
-
- return (
- <div
- className={cn(
- snap.hideCode ? 'max-w-0' : 'max-w-lg 2xl:max-w-xl',
- 'w-full xl:border-l',
- 'grow flex flex-col h-full'
- )}
- >
- <MonacoEditor id="sql-editor" language="pgsql" value={code} />
- </div>
- )
-}
-
const MonacoEditor = ({
id,
language,
@@ -51,11 +25,11 @@ const MonacoEditor = ({
options,
value,
}: MonacoEditorProps) => {
- const monacoRef = useRef<any>()
- const { resolvedTheme } = useTheme()
+ // const monacoRef = useRef<any>()
+ // const { resolvedTheme } = useTheme()
const beforeMount: BeforeMount = (monaco) => {
- monacoRef.current = monaco
+ // monacoRef.current = monaco
monaco.editor.defineTheme('supabase', {
base: 'vs-dark',
inherit: true,
@@ -70,21 +44,21 @@ const MonacoEditor = ({
})
}
- const onMount: OnMount = async (editor) => {
- // Add margin above first line
- editor.changeViewZones((accessor) => {
- accessor.addZone({
- afterLineNumber: 0,
- heightInPx: 4,
- domNode: document.createElement('div'),
- })
- })
+ // const onMount: OnMount = async (editor) => {
+ // // Add margin above first line
+ // editor.changeViewZones((accessor) => {
+ // accessor.addZone({
+ // afterLineNumber: 0,
+ // heightInPx: 4,
+ // domNode: document.createElement('div'),
+ // })
+ // })
- if (resolvedTheme) {
- const mode: any = getTheme(resolvedTheme)
- monacoRef.current.editor.defineTheme('supabase', mode)
- }
- }
+ // if (resolvedTheme) {
+ // const mode: any = getTheme(resolvedTheme)
+ // monacoRef.current.editor.defineTheme('supabase', mode)
+ // }
+ // }
const optionsMerged = merge(
{
@@ -98,7 +72,10 @@ const MonacoEditor = ({
lineNumbers: hideLineNumbers ? 'off' : undefined,
glyphMargin: hideLineNumbers ? false : undefined,
lineNumbersMinChars: hideLineNumbers ? 0 : undefined,
+ occurrencesHighlight: false,
folding: hideLineNumbers ? false : undefined,
+ renderLineHighlight: 'none',
+ selectionHighlight: false,
},
options
)
@@ -109,14 +86,16 @@ const MonacoEditor = ({
<Editor
path={id}
theme="supabase"
- className={cn('bg-alternative [&>div]:p-0')}
+ className={'bg-alternative [&>div]:p-0'}
value={value ?? undefined}
defaultLanguage={language}
defaultValue={defaultValue ?? undefined}
loading={false}
options={optionsMerged}
beforeMount={beforeMount}
- onMount={onMount}
+ // onMount={onMount}
/>
)
}
+
+export { MonacoEditor }
diff --git a/apps/database-new/components/SchemaGraph/SchemaGraph.constants.ts b/apps/database-new/app/[threadId]/[runId]/[messageId]/SchemaFlow.constants.ts
similarity index 100%
rename from apps/database-new/components/SchemaGraph/SchemaGraph.constants.ts
rename to apps/database-new/app/[threadId]/[runId]/[messageId]/SchemaFlow.constants.ts
diff --git a/apps/database-new/app/[threadId]/[runId]/[messageId]/SchemaFlow.tsx b/apps/database-new/app/[threadId]/[runId]/[messageId]/SchemaFlow.tsx
new file mode 100644
index 00000000000..d85a1c3859e
--- /dev/null
+++ b/apps/database-new/app/[threadId]/[runId]/[messageId]/SchemaFlow.tsx
@@ -0,0 +1,22 @@
+import { format } from 'sql-formatter'
+
+import { getThread } from './MessageId.utils'
+
+import { parseTables } from '@/lib/utils'
+import SchemaFlowHandler from './SchemaFlowHandler'
+
+export async function SchemaFlow({ params }: { params: any }) {
+ const { threadId, runId, messageId } = params
+
+ const content = await getThread({ threadId, runId, messageId })
+
+ // const code = format(content, { language: 'postgresql' })
+
+ const tables = await parseTables(content)
+
+ // useEffect(() => {
+ // snap.setSelectedCode(code)
+ // }, [code])
+
+ return <SchemaFlowHandler tables={tables} />
+}
diff --git a/apps/database-new/components/SchemaGraph/SchemaGraph.utils.ts b/apps/database-new/app/[threadId]/[runId]/[messageId]/SchemaFlow.utils.ts
similarity index 98%
rename from apps/database-new/components/SchemaGraph/SchemaGraph.utils.ts
rename to apps/database-new/app/[threadId]/[runId]/[messageId]/SchemaFlow.utils.ts
index f8f53dac981..fd2ea3af829 100644
--- a/apps/database-new/components/SchemaGraph/SchemaGraph.utils.ts
+++ b/apps/database-new/app/[threadId]/[runId]/[messageId]/SchemaFlow.utils.ts
@@ -2,7 +2,7 @@ import { PostgresTable } from '@/lib/types'
import dagre from '@dagrejs/dagre'
import { uniqBy } from 'lodash'
import { Edge, Node, Position } from 'reactflow'
-import { NODE_ROW_HEIGHT, NODE_WIDTH } from './SchemaGraph.constants'
+import { NODE_ROW_HEIGHT, NODE_WIDTH } from './SchemaFlow.constants'
import { TableNodeData } from './TableNode'
export async function getGraphDataFromTables(tables: PostgresTable[]): Promise<{
diff --git a/apps/database-new/components/SchemaGraph/SchemaGraph.tsx b/apps/database-new/app/[threadId]/[runId]/[messageId]/SchemaFlowHandler.tsx
similarity index 87%
rename from apps/database-new/components/SchemaGraph/SchemaGraph.tsx
rename to apps/database-new/app/[threadId]/[runId]/[messageId]/SchemaFlowHandler.tsx
index b6caf9f3773..80c2e7dad6e 100644
--- a/apps/database-new/components/SchemaGraph/SchemaGraph.tsx
+++ b/apps/database-new/app/[threadId]/[runId]/[messageId]/SchemaFlowHandler.tsx
@@ -11,14 +11,14 @@ import ReactFlow, {
import 'reactflow/dist/style.css'
import { cn } from 'ui'
-import { getGraphDataFromTables } from './SchemaGraph.utils'
+import { getGraphDataFromTables } from './SchemaFlow.utils'
import TableNode from './TableNode'
interface SchemaGraphProps {
tables: PostgresTable[]
}
-const TablesGraph = ({ tables }: SchemaGraphProps) => {
+const SchemaFlowHandler = ({ tables }: SchemaGraphProps) => {
const { resolvedTheme } = useTheme()
const [mounted, setMounted] = useState(false)
const reactFlowInstance = useReactFlow()
@@ -73,12 +73,12 @@ const TablesGraph = ({ tables }: SchemaGraphProps) => {
)
}
-const SchemaGraph = ({ tables }: SchemaGraphProps) => {
+const ExportedSchemaGraph = ({ tables }: SchemaGraphProps) => {
return (
<ReactFlowProvider>
- <TablesGraph tables={tables} />
+ <SchemaFlowHandler tables={tables} />
</ReactFlowProvider>
)
}
-export default SchemaGraph
+export default ExportedSchemaGraph
diff --git a/apps/database-new/components/SchemaGraph/TableNode.tsx b/apps/database-new/app/[threadId]/[runId]/[messageId]/TableNode.tsx
similarity index 98%
rename from apps/database-new/components/SchemaGraph/TableNode.tsx
rename to apps/database-new/app/[threadId]/[runId]/[messageId]/TableNode.tsx
index ed6dd823489..3b5073cc15e 100644
--- a/apps/database-new/components/SchemaGraph/TableNode.tsx
+++ b/apps/database-new/app/[threadId]/[runId]/[messageId]/TableNode.tsx
@@ -1,7 +1,7 @@
import { DiamondIcon, Fingerprint, Hash, Key, Table2 } from 'lucide-react'
import { Handle, NodeProps } from 'reactflow'
import { cn } from 'ui'
-import { NODE_WIDTH } from './SchemaGraph.constants'
+import { NODE_WIDTH } from './SchemaFlow.constants'
export type TableNodeData = {
name: string
diff --git a/apps/database-new/app/[threadId]/[runId]/[messageId]/page.tsx b/apps/database-new/app/[threadId]/[runId]/[messageId]/page.tsx
index 649a60b6c00..c8c73b6dc5f 100644
--- a/apps/database-new/app/[threadId]/[runId]/[messageId]/page.tsx
+++ b/apps/database-new/app/[threadId]/[runId]/[messageId]/page.tsx
@@ -1,66 +1,33 @@
-'use client'
-import { last, sortBy } from 'lodash'
-import { useParams, useRouter } from 'next/navigation'
-import { useEffect, useMemo, useRef, useState } from 'react'
-
-import { CodeEditor } from '@/components/CodeEditor/CodeEditor'
-import SchemaGraph from '@/components/SchemaGraph/SchemaGraph'
-import { useMessagesQuery } from '@/data/messages-query'
-import { AssistantMessage, PostgresTable } from '@/lib/types'
-import { parseTables } from '@/lib/utils'
-
-export default function ThreadPage() {
- const router = useRouter()
- const { threadId, runId, messageId }: { threadId: string; runId: string; messageId: string } =
- useParams()
- const [tables, setTables] = useState<PostgresTable[]>([])
-
- const { data, isSuccess } = useMessagesQuery({ threadId, runId })
-
- // [Joshen] Slightly hacky here, just so the useEffect triggers once - until we figure out something better
- const isLoadingPrev = useRef<boolean>(false)
- const isLoading = isSuccess && data.status === 'loading'
-
- const messages = useMemo(() => {
- if (isSuccess) return sortBy(data.messages, (m) => m.created_at)
- return []
- }, [data?.messages, isSuccess])
-
- const userMessages = messages.filter((m) => m.role === 'user')
-
- const selectedMessageIdx = useMemo(() => {
- return messages.findIndex((m) => m.id === messageId)
- }, [messages, messageId])
-
- const selectedMessageReply = useMemo(
- () =>
- (selectedMessageIdx !== -1 ? messages[selectedMessageIdx + 1] : undefined) as
- | AssistantMessage
- | undefined,
- [messages, selectedMessageIdx]
- )
+import { CodeEditor } from '@/app/[threadId]/[runId]/[messageId]/CodeEditor'
+import { SchemaFlow } from '@/app/[threadId]/[runId]/[messageId]/SchemaFlow'
+import { Loader2 } from 'lucide-react'
+import { Suspense } from 'react'
+
+interface ThreadPageProps {
+ params: {
+ threadId: string
+ runId: string
+ messageId: string
+ }
+}
- const content = useMemo(
- () => selectedMessageReply?.sql.replaceAll('```sql', '').replaceAll('```', '') || '',
- [selectedMessageReply?.sql]
+export default async function ThreadPage({ params }: ThreadPageProps) {
+ return (
+ <div className="grow max-h-screen flex flex-row items-center justify-between bg-alternative h-full">
+ <Suspense fallback={<Loader />}>
+ <SchemaFlow params={params} />
+ </Suspense>
+ <Suspense fallback={<Loader />}>
+ <CodeEditor params={params} />
+ </Suspense>
+ </div>
)
+}
- useEffect(() => {
- parseTables(content).then((t) => setTables(t))
- }, [content])
-
- useEffect(() => {
- if (isLoadingPrev.current && !isLoading) {
- const latestMessage = last(userMessages)
- if (latestMessage) router.push(`/${threadId}/${runId}/${latestMessage.id}`)
- }
- isLoadingPrev.current = isLoading
- }, [isLoading])
-
+const Loader = () => {
return (
- <div className="grow max-h-screen flex flex-row items-center justify-between bg-alternative h-full">
- <SchemaGraph tables={tables} />
- <CodeEditor content={content} />
+ <div className="flex items-center justify-center w-full h-full text-muted">
+ <Loader2 className="animate-spin opacity-100" size={16} strokeWidth={1} />
</div>
)
}
diff --git a/apps/database-new/app/[threadId]/[runId]/page.tsx b/apps/database-new/app/[threadId]/[runId]/page.tsx
index f7013008d1d..e4c38f97b41 100644
--- a/apps/database-new/app/[threadId]/[runId]/page.tsx
+++ b/apps/database-new/app/[threadId]/[runId]/page.tsx
@@ -1,10 +1,9 @@
'use client'
+
import { last, sortBy } from 'lodash'
import { useParams, useRouter } from 'next/navigation'
import { useEffect, useMemo } from 'react'
-import { CodeEditor } from '@/components/CodeEditor/CodeEditor'
-import SchemaGraph from '@/components/SchemaGraph/SchemaGraph'
import { useMessagesQuery } from '@/data/messages-query'
export default function ThreadPage() {
@@ -27,8 +26,8 @@ export default function ThreadPage() {
return (
<div className="grow max-h-screen flex flex-row items-center justify-between bg-alternative h-full">
- <SchemaGraph tables={[]} />
- <CodeEditor content="" />
+ {/* <SchemaGraph tables={[]} />
+ <CodeEditor content="" /> */}
</div>
)
}
diff --git a/apps/database-new/app/actions.ts b/apps/database-new/app/actions.ts
index b75da415f47..69602421433 100644
--- a/apps/database-new/app/actions.ts
+++ b/apps/database-new/app/actions.ts
@@ -1,5 +1,10 @@
'use server'
+import { last, sortBy } from 'lodash'
+
+import { AssistantMessage } from '@/lib/types'
+import { parseTables } from '@/lib/utils'
+
import { createClient } from '@/lib/supabase/server'
import { revalidatePath } from 'next/cache'
import { cookies } from 'next/headers'
@@ -95,3 +100,84 @@ export async function updateThreadName(prevState: any, formData: FormData) {
}
}
}
+
+export async function updateThread(prevState: any, formData: FormData) {
+ const cookieStore = cookies()
+ const supabase = createClient(cookieStore)
+
+ let redirectUrl = ''
+
+ try {
+ const schema = z.object({
+ value: z.string(),
+ })
+
+ const data = schema.parse({
+ value: formData.get('value'),
+ })
+
+ const {
+ data: { user },
+ error: userError,
+ } = await supabase.auth.getUser()
+
+ if (userError || !user) {
+ return {
+ success: false,
+ message: 'Failed to get user',
+ data: undefined,
+ }
+ }
+
+ const thread = await openai.beta.threads.create()
+
+ await openai.beta.threads.messages.create(thread.id, {
+ role: 'user',
+ content: data.value,
+ })
+
+ const createRun = await openai.beta.threads.runs.create(thread.id, {
+ assistant_id: 'asst_oLWrK8lScZVNEpfjwUIvBAnq',
+ })
+
+ const [run, { data: messages }] = await Promise.all([
+ openai.beta.threads.runs.retrieve(thread.id, createRun.id),
+ openai.beta.threads.messages.list(thread.id),
+ ])
+
+ const threadTitle = messages
+ .filter((m) => m.role === 'user' && m.content[0]?.type === 'text')
+ .map((m) => {
+ if (m.content[0]?.type === 'text') {
+ return m.content[0]?.text?.value
+ }
+ return undefined
+ })
+ .find((text) => text !== undefined)
+
+ try {
+ console.log('inserting thread')
+ const { error } = await supabase.from('threads').insert({
+ thread_id: thread.id,
+ run_id: run.id,
+ user_id: user.id,
+ thread_title: threadTitle as string,
+ })
+ revalidatePath('/profile')
+ if (error) throw error
+ } catch (error) {
+ console.error(error)
+ }
+
+ redirectUrl = `/${thread.id}/${run.id}`
+ } catch (error: any) {
+ console.error(error)
+ return {
+ success: false,
+ message: 'Failed to update title to update title',
+ data: undefined,
+ }
+ }
+
+ redirect(redirectUrl)
+}
diff --git a/apps/database-new/app/globals.css b/apps/database-new/app/globals.css
index 62af4851ba2..cbddebb9cc0 100644
--- a/apps/database-new/app/globals.css
+++ b/apps/database-new/app/globals.css
@@ -78,10 +78,10 @@
html,
body,
main {
- @apply bg-background;
+ /* @apply bg-background;
@apply text-foreground;
height: 100%;
- width: 100%;
+ width: 100%; */
padding: 0;
margin: 0;
-moz-osx-font-smoothing: grayscale;
diff --git a/apps/database-new/app/layout.tsx b/apps/database-new/app/layout.tsx
index 589ff07cda2..1f61a9104e6 100644
--- a/apps/database-new/app/layout.tsx
+++ b/apps/database-new/app/layout.tsx
@@ -16,10 +16,12 @@ export const metadata: Metadata = {
description: 'Generate schemas from your ideas',
}
+// supressHydrationWarning:
+// https://github.com/pacocoursey/next-themes#with-app
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
- <html lang="en" className="dark">
- <body className="flex flex-col">
+ <html lang="en" className="dark h-full bg-background" suppressHydrationWarning>
+ <body className="flex flex-col h-full">
<ThemeProvider defaultTheme="system" enableSystem disableTransitionOnChange>
<ReactQueryProvider>
<Header />
diff --git a/apps/database-new/app/profile/Threads.tsx b/apps/database-new/app/profile/Threads.tsx
index 65cf54260e6..4405473e556 100644
--- a/apps/database-new/app/profile/Threads.tsx
+++ b/apps/database-new/app/profile/Threads.tsx
@@ -1,9 +1,6 @@
import { Database } from '@/types/supabase'
import EmptyState from './EmptyState'
import Thread from './Thread'
-// import { useState, useEffect } from 'react'
-import ConfirmDeleteThreadModal from './ConfirmDeleteThreadModal'
-import EditThreadModal from './EditThreadModal'
import { cookies } from 'next/headers'
import { createClient } from '@/lib/supabase/server'
@@ -19,7 +16,11 @@ async function Threads() {
if (!user) return <p>Error fetching user details</p>
- const { data } = await supabase.from('threads').select().eq('user_id', user.id)
+ const { data } = await supabase
+ .from('threads')
+ .select()
+ .eq('user_id', user.id)
+ .order('created_at', { ascending: false })
const threads = data ?? []
diff --git a/apps/database-new/app/profile/layout.tsx b/apps/database-new/app/profile/layout.tsx
index 5b64d287224..89d3d8e6058 100644
--- a/apps/database-new/app/profile/layout.tsx
+++ b/apps/database-new/app/profile/layout.tsx
@@ -1,9 +1,3 @@
-'use client'
-import dayjs from 'dayjs'
-import relativeTime from 'dayjs/plugin/relativeTime'
-
-dayjs.extend(relativeTime)
-
export default function Layout({ children }: { children: React.ReactNode }) {
return <div className="px-4 xl:px-0 xl:max-w-4xl mx-auto h-full">{children}</div>
}
diff --git a/apps/database-new/app/profile/page.tsx b/apps/database-new/app/profile/page.tsx
index cf788f21f27..0183e144d71 100644
--- a/apps/database-new/app/profile/page.tsx
+++ b/apps/database-new/app/profile/page.tsx
@@ -18,19 +18,6 @@ export const metadata: Metadata = {
// export const dynamic = 'force-dynamic'
const Profile = async () => {
- // async function handleThreadActions(formData: FormData) {
- // 'use server'
-
- // const action = formData.get('action') as string
- // const threadID = formData.get('threadID') as string
-
- // if (!threadID) return
-
- // if (action === 'delete') {
- // deleteThread(threadID)
- // }
- // }
-
return (
<div className="grid grid-cols-4 gap-x-8 py-6 xl:py-12 gap-y-6 xl:gap-y-0">
<div className="col-span-4 xl:col-span-1 flex flex-col gap-y-6">
diff --git a/apps/database-new/lib/utils.ts b/apps/database-new/lib/utils.ts
index b494603ae97..ba0fdb739e4 100644
--- a/apps/database-new/lib/utils.ts
+++ b/apps/database-new/lib/utils.ts
@@ -1,10 +1,18 @@
import { parseQuery } from '@gregnr/libpg-query'
+import dayjs from 'dayjs'
import { compact } from 'lodash'
import { z } from 'zod'
-
-import dayjs from 'dayjs'
import { PostgresColumn, PostgresTable } from './types'
+const NameDefinition = z.union([
+ z.object({
+ sval: z.string(),
+ }),
+ z.object({
+ str: z.string(),
+ }),
+])
+
const constraintDefinitionSchema = z.object({
Constraint: z.discriminatedUnion('contype', [
z
@@ -41,17 +49,13 @@ const constraintDefinitionSchema = z.object({
fk_attrs: z
.array(
z.object({
- String: z.object({
- sval: z.string(),
- }),
+ String: NameDefinition,
})
)
.optional(),
pk_attrs: z.array(
z.object({
- String: z.object({
- sval: z.string(),
- }),
+ String: NameDefinition,
})
),
}),
@@ -62,13 +66,7 @@ const columnDefinitionSchema = z.object({
ColumnDef: z.object({
colname: z.string(),
typeName: z.object({
- names: z.array(
- z.object({
- String: z.object({
- sval: z.string(),
- }),
- })
- ),
+ names: z.array(z.object({ String: NameDefinition })),
}),
constraints: z.array(constraintDefinitionSchema).optional(),
}),
@@ -95,6 +93,16 @@ const parseQueryResultSchema = z.object({
),
})
+const extractNameDefinition = (obj: z.infer<typeof NameDefinition>) => {
+ if ('sval' in obj) {
+ return obj?.sval
+ }
+ if ('str' in obj) {
+ return obj?.str
+ }
+ return null
+}
+
/**
* Parses SQL into tables compatible with the existing schema visualizer.
*
@@ -105,8 +113,8 @@ export async function parseTables(sql: string) {
// See: https://github.com/pyramation/libpg-query-node/pull/34
const result = await parseQuery(sql)
-
const parsedSql = parseQueryResultSchema.safeParse(result)
+
if (!parsedSql.success) {
console.log(parsedSql.error)
return []
@@ -124,9 +132,11 @@ export async function parseTables(sql: string) {
const columns = compact(
statement.tableElts.map((column) => {
if ('ColumnDef' in column) {
- const format = column.ColumnDef.typeName.names.find(
- ({ String: { sval } }) => sval !== 'pg_catalog'
- )?.String.sval
+ const format = compact(
+ column.ColumnDef.typeName.names
+ .map((name) => extractNameDefinition(name.String))
+ .filter((str) => str !== 'pg_catalog' || !!str)
+ )[0]
if (!format) {
return undefined
@@ -158,12 +168,20 @@ export async function parseTables(sql: string) {
)
if (found && found.Constraint.contype === 'CONSTR_FOREIGN') {
+ const targetColumn = compact(
+ found.Constraint.pk_attrs.map((name) => extractNameDefinition(name.String))
+ )[0]
+
+ if (!targetColumn) {
+ return null
+ }
+
return {
- id: `${statement.relation.relname}_${column.ColumnDef.colname}_${found.Constraint.pktable.relname}_${found.Constraint.pk_attrs[0].String.sval}`,
+ id: `${statement.relation.relname}_${column.ColumnDef.colname}_${found.Constraint.pktable.relname}_${targetColumn}`,
source_table_name: statement.relation.relname,
source_column_name: column.ColumnDef.colname,
target_table_name: found.Constraint.pktable.relname,
- target_column_name: found.Constraint.pk_attrs[0].String.sval,
+ target_column_name: targetColumn,
}
}
}
@@ -181,15 +199,25 @@ export async function parseTables(sql: string) {
) {
const pkTable = constraint.Constraint.pktable
const pgAttrs = constraint.Constraint.pk_attrs
- return constraint.Constraint.fk_attrs.map((attr, index) => {
- return {
- id: `${statement.relation.relname}_${attr.String.sval}_${pkTable.relname}_${pgAttrs[index].String.sval}`,
- source_table_name: statement.relation.relname,
- source_column_name: attr.String.sval,
- target_table_name: pkTable.relname,
- target_column_name: pgAttrs[index].String.sval,
- }
- })
+ return compact(
+ constraint.Constraint.fk_attrs.map((attr, index) => {
+ const attrString = extractNameDefinition(attr.String)
+
+ const pgAttrString = extractNameDefinition(pgAttrs[index].String)
+
+ if (!attrString || !pgAttrString) {
+ return null
+ }
+
+ return {
+ id: `${statement.relation.relname}_${attrString}_${pkTable.relname}_${pgAttrString}`,
+ source_table_name: statement.relation.relname,
+ source_column_name: attrString,
+ target_table_name: pkTable.relname,
+ target_column_name: pgAttrString,
+ }
+ })
+ )
}
}
})
diff --git a/apps/database-new/package.json b/apps/database-new/package.json
index 9fccee5f608..db88150b75c 100644
--- a/apps/database-new/package.json
+++ b/apps/database-new/package.json
@@ -20,8 +20,8 @@
"eslint-config-next": "^14.0.3",
"lodash": "^4.17.21",
"lucide-react": "^0.292.0",
- "openai": "^4.17.0",
"next": "^14.0.3",
+ "openai": "^4.17.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-flow": "^1.0.3",
diff --git a/packages/ui/index.tsx b/packages/ui/index.tsx
index a2f981243be..4876d4deb62 100644
--- a/packages/ui/index.tsx
+++ b/packages/ui/index.tsx
@@ -181,7 +181,6 @@ export { Separator } from './src/components/shadcn/ui/separator'
// patterns
-
export * from './src/patterns/SchemaTableNode'
export { AssistantChatForm } from './src/patterns/AssistantChatForm'
diff --git a/packages/ui/src/patterns/AssistantChatForm.tsx b/packages/ui/src/patterns/AssistantChatForm.tsx
index 728e8b08271..3543cb9ea70 100644
--- a/packages/ui/src/patterns/AssistantChatForm.tsx
+++ b/packages/ui/src/patterns/AssistantChatForm.tsx
@@ -2,16 +2,18 @@ import { Loader2 } from 'lucide-react'
import React, { ChangeEvent, createRef, useEffect } from 'react'
import { TextArea } from '../components/shadcn/ui/text-area'
import { cn } from '../lib/utils'
+import { useFormStatus } from 'react-dom'
export interface FormProps extends React.FormHTMLAttributes<HTMLFormElement> {
- loading: boolean
+ loading?: boolean
disabled?: boolean
value?: string
onValueChange: (value: ChangeEvent<HTMLTextAreaElement>) => void
+ message?: string
}
const AssistantChatForm = React.forwardRef<HTMLFormElement, FormProps>(
- ({ loading, disabled, value, onValueChange, ...props }, ref) => {
+ ({ loading, disabled, value, onValueChange, message, ...props }, ref) => {
const textAreaRef = createRef<HTMLTextAreaElement>()
const submitRef = createRef<HTMLButtonElement>()
@@ -40,16 +42,20 @@ const AssistantChatForm = React.forwardRef<HTMLFormElement, FormProps>(
}
}
- return (
- <form ref={ref} className="relative" {...props}>
- <div className={cn('absolute', 'top-2 left-2', 'ml-1 w-6 h-6 rounded-full bg-dbnew')}></div>
+ const TextAreaElement = () => {
+ const { pending } = useFormStatus()
+
+ return (
<TextArea
+ name="value"
ref={textAreaRef}
autoFocus
rows={1}
- disabled={disabled}
+ disabled={disabled || pending}
contentEditable
aria-expanded={false}
+ aria-required={true}
+ required
className={
'transition-all text-sm pl-12 pr-10 rounded-[18px] resize-none box-border leading-6'
}
@@ -59,10 +65,17 @@ const AssistantChatForm = React.forwardRef<HTMLFormElement, FormProps>(
onChange={(event: ChangeEvent<HTMLTextAreaElement>) => onValueChange(event)}
onKeyDown={handleKeyDown}
/>
+ )
+ }
+
+ const SubmitButton = () => {
+ const { pending } = useFormStatus()
+
+ return (
<div className="absolute right-1.5 top-1.5 flex gap-3 items-center">
- {loading && (
+ {loading || pending ? (
<Loader2 size={22} className="animate-spin w-7 h-7 text-muted" strokeWidth={1} />
- )}
+ ) : null}
<button
ref={submitRef}
@@ -71,7 +84,7 @@ const AssistantChatForm = React.forwardRef<HTMLFormElement, FormProps>(
'transition-all',
'flex items-center justify-center w-7 h-7 border border-control rounded-full mr-0.5 p-1.5 background-alternative',
!value ? 'text-muted opacity-50' : 'text-default opacity-100',
- loading && 'hidden'
+ loading || pending ? 'hidden' : ''
)}
>
<svg
@@ -90,6 +103,17 @@ const AssistantChatForm = React.forwardRef<HTMLFormElement, FormProps>(
</svg>
</button>
</div>
+ )
+ }
+
+ return (
+ <form ref={ref} className="relative" {...props}>
+ <div className={cn('absolute', 'top-2 left-2', 'ml-1 w-6 h-6 rounded-full bg-dbnew')}></div>
+ <TextAreaElement />
+ <SubmitButton />
+ <p aria-live="polite" className="sr-only" role="status">
+ {message}
+ </p>
</form>
)
}