Skip to content

Commit c9e2e3f

Browse files
authored
Merge pull request supabase-community#21 from supabase-community/fix/vercel-dynamic-path-500
Fix Vercel dynamic path 500 error
2 parents 136b701 + 3d9195f commit c9e2e3f

File tree

15 files changed

+437
-339
lines changed

15 files changed

+437
-339
lines changed

apps/postgres-new/app/db/[id]/page.tsx

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,23 +2,28 @@
22

33
import { useRouter } from 'next/navigation'
44
import { useEffect } from 'react'
5+
import { useApp } from '~/components/app-provider'
56
import Workspace from '~/components/workspace'
6-
import { getDb } from '~/lib/db'
77

88
export default function Page({ params }: { params: { id: string } }) {
99
const databaseId = params.id
1010
const router = useRouter()
11+
const { dbManager } = useApp()
1112

1213
useEffect(() => {
1314
async function run() {
15+
if (!dbManager) {
16+
throw new Error('dbManager is not available')
17+
}
18+
1419
try {
15-
await getDb(databaseId)
20+
await dbManager.getDbInstance(databaseId)
1621
} catch (err) {
1722
router.push('/')
1823
}
1924
}
2025
run()
21-
}, [databaseId, router])
26+
}, [dbManager, databaseId, router])
2227

2328
return <Workspace databaseId={databaseId} visibility="local" />
2429
}

apps/postgres-new/app/page.tsx

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@
33
import { customAlphabet } from 'nanoid'
44
import { useRouter } from 'next/navigation'
55
import { useCallback, useEffect, useMemo } from 'react'
6+
import { useApp } from '~/components/app-provider'
67
import Workspace from '~/components/workspace'
78
import { useDatabaseCreateMutation } from '~/data/databases/database-create-mutation'
89
import { useDatabaseUpdateMutation } from '~/data/databases/database-update-mutation'
9-
import { dbExists, getDb } from '~/lib/db'
1010

1111
// Use a DNS safe alphabet
1212
const nanoid = customAlphabet('0123456789abcdefghijklmnopqrstuvwxyz', 16)
@@ -16,6 +16,7 @@ function uniqueId() {
1616
}
1717

1818
export default function Page() {
19+
const { dbManager } = useApp()
1920
const router = useRouter()
2021

2122
const { mutateAsync: createDatabase } = useDatabaseCreateMutation()
@@ -26,13 +27,17 @@ export default function Page() {
2627
*/
2728
const preloadDb = useCallback(
2829
async (id: string) => {
29-
const exists = await dbExists(id)
30-
if (!exists) {
30+
if (!dbManager) {
31+
throw new Error('dbManager is not available')
32+
}
33+
34+
const database = await dbManager.getDatabase(id)
35+
if (!database) {
3136
await createDatabase({ id, isHidden: true })
32-
await getDb(id)
37+
await dbManager.getDbInstance(id)
3338
}
3439
},
35-
[createDatabase]
40+
[dbManager, createDatabase]
3641
)
3742

3843
// Track the next database ID in local storage

apps/postgres-new/components/app-provider.tsx

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,18 @@ import {
1111
useCallback,
1212
useContext,
1313
useEffect,
14+
useMemo,
1415
useState,
1516
} from 'react'
16-
import { getRuntimePgVersion } from '~/lib/db'
17+
import { DbManager } from '~/lib/db'
1718
import { useAsyncMemo } from '~/lib/hooks'
1819
import { createClient } from '~/utils/supabase/client'
1920

2021
export type AppProps = PropsWithChildren
2122

23+
// Create a singleton DbManager that isn't exposed to double mounting
24+
const dbManager = typeof window !== 'undefined' ? new DbManager() : undefined
25+
2226
export default function AppProvider({ children }: AppProps) {
2327
const [isLoadingUser, setIsLoadingUser] = useState(true)
2428
const [user, setUser] = useState<User>()
@@ -78,7 +82,13 @@ export default function AppProvider({ children }: AppProps) {
7882

7983
const isPreview = process.env.NEXT_PUBLIC_IS_PREVIEW === 'true'
8084
const pgliteVersion = process.env.NEXT_PUBLIC_PGLITE_VERSION
81-
const { value: pgVersion } = useAsyncMemo(() => getRuntimePgVersion(), [])
85+
const { value: pgVersion } = useAsyncMemo(async () => {
86+
if (!dbManager) {
87+
throw new Error('dbManager is not available')
88+
}
89+
90+
return await dbManager.getRuntimePgVersion()
91+
}, [dbManager])
8292

8393
return (
8494
<AppContext.Provider
@@ -88,6 +98,7 @@ export default function AppProvider({ children }: AppProps) {
8898
signIn,
8999
signOut,
90100
isPreview,
101+
dbManager,
91102
pgliteVersion,
92103
pgVersion,
93104
}}
@@ -103,6 +114,7 @@ export type AppContextValues = {
103114
signIn: () => Promise<User | undefined>
104115
signOut: () => Promise<void>
105116
isPreview: boolean
117+
dbManager?: DbManager
106118
pgliteVersion?: string
107119
pgVersion?: string
108120
}

apps/postgres-new/components/ide.tsx

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
'use client'
22

33
import { Editor } from '@monaco-editor/react'
4-
import { deparse, parseQuery, ParseResult } from 'libpg-query/wasm'
4+
import { ParseResult } from 'libpg-query/wasm'
55
import { FileCode, MessageSquareMore, Sprout, Workflow } from 'lucide-react'
66
import { PropsWithChildren, useEffect, useState } from 'react'
77
import { format } from 'sql-formatter'
@@ -60,6 +60,9 @@ export default function IDE({ children, className }: IDEProps) {
6060
})
6161
.filter((sql) => sql !== undefined) ?? []
6262

63+
// Dynamically import (browser-only) to prevent SSR errors
64+
const { deparse, parseQuery } = await import('libpg-query/wasm')
65+
6366
const migrations: string[] = []
6467

6568
for (const sql of sqlExecutions) {

apps/postgres-new/components/workspace.tsx

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@
22

33
import { CreateMessage, Message, useChat } from 'ai/react'
44
import { createContext, useCallback, useContext, useMemo } from 'react'
5-
import { getDatabase } from '~/data/databases/database-query'
65
import { useMessageCreateMutation } from '~/data/messages/message-create-mutation'
76
import { useMessagesQuery } from '~/data/messages/messages-query'
87
import { useTablesQuery } from '~/data/tables/tables-query'
98
import { useOnToolCall } from '~/lib/hooks'
109
import { useBreakpoint } from '~/lib/use-breakpoint'
1110
import { ensureMessageId } from '~/lib/util'
11+
import { useApp } from './app-provider'
1212
import Chat, { getInitialMessages } from './chat'
1313
import IDE from './ide'
1414

@@ -33,6 +33,7 @@ export type WorkspaceProps = {
3333
}
3434

3535
export default function Workspace({ databaseId, visibility, onStart }: WorkspaceProps) {
36+
const { dbManager } = useApp()
3637
const isSmallBreakpoint = useBreakpoint('lg')
3738
const onToolCall = useOnToolCall(databaseId)
3839
const { mutateAsync: saveMessage } = useMessageCreateMutation(databaseId)
@@ -57,9 +58,13 @@ export default function Workspace({ databaseId, visibility, onStart }: Workspace
5758
initialMessages:
5859
existingMessages && existingMessages.length > 0 ? existingMessages : initialMessages,
5960
async onFinish(message) {
61+
if (!dbManager) {
62+
throw new Error('dbManager is not available')
63+
}
64+
6065
await saveMessage({ message })
6166

62-
const database = await getDatabase(databaseId)
67+
const database = await dbManager.getDatabase(databaseId)
6368
const isStartOfConversation = database.isHidden && !message.toolInvocations
6469

6570
if (isStartOfConversation) {

apps/postgres-new/data/databases/database-create-mutation.ts

Lines changed: 10 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,27 @@
11
import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
2-
import { generateId } from 'ai'
3-
import { codeBlock } from 'common-tags'
4-
import { Database, getMetaDb } from '~/lib/db'
2+
import { useApp } from '~/components/app-provider'
3+
import { Database } from '~/lib/db'
54
import { getDatabasesQueryKey } from './databases-query'
65

76
export type DatabaseCreateVariables = {
8-
id?: string
9-
isHidden?: boolean
7+
id: string
8+
isHidden: boolean
109
}
1110

1211
export const useDatabaseCreateMutation = ({
1312
onSuccess,
1413
onError,
1514
...options
1615
}: Omit<UseMutationOptions<Database, Error, DatabaseCreateVariables>, 'mutationFn'> = {}) => {
16+
const { dbManager } = useApp()
1717
const queryClient = useQueryClient()
1818

1919
return useMutation<Database, Error, DatabaseCreateVariables>({
20-
mutationFn: async ({ id = generateId(12), isHidden }) => {
21-
const metaDb = await getMetaDb()
22-
23-
const {
24-
rows: [database],
25-
} = await metaDb.query<Database>(
26-
codeBlock`
27-
insert into databases (id, is_hidden)
28-
values ($1, $2)
29-
on conflict (id) do nothing
30-
returning id, name, created_at as "createdAt", is_hidden as "isHidden"
31-
`,
32-
[id, isHidden]
33-
)
34-
35-
return database
20+
mutationFn: async ({ id, isHidden }) => {
21+
if (!dbManager) {
22+
throw new Error('dbManager is not available')
23+
}
24+
return await dbManager.createDatabase(id, { isHidden })
3625
},
3726
async onSuccess(data, variables, context) {
3827
await Promise.all([queryClient.invalidateQueries({ queryKey: getDatabasesQueryKey() })])

apps/postgres-new/data/databases/database-delete-mutation.ts

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
2-
import { codeBlock } from 'common-tags'
3-
import { Database, deleteDb, getMetaDb } from '~/lib/db'
2+
import { useApp } from '~/components/app-provider'
43
import { getDatabaseQueryKey } from './database-query'
54
import { getDatabasesQueryKey } from './databases-query'
65

@@ -13,21 +12,15 @@ export const useDatabaseDeleteMutation = ({
1312
onError,
1413
...options
1514
}: Omit<UseMutationOptions<void, Error, DatabaseDeleteVariables>, 'mutationFn'> = {}) => {
15+
const { dbManager } = useApp()
1616
const queryClient = useQueryClient()
1717

1818
return useMutation<void, Error, DatabaseDeleteVariables>({
1919
mutationFn: async ({ id }) => {
20-
const metaDb = await getMetaDb()
21-
22-
await metaDb.query<Database>(
23-
codeBlock`
24-
delete from databases
25-
where id = $1
26-
`,
27-
[id]
28-
)
29-
30-
await deleteDb(id)
20+
if (!dbManager) {
21+
throw new Error('dbManager is not available')
22+
}
23+
return await dbManager.deleteDatabase(id)
3124
},
3225
async onSuccess(data, variables, context) {
3326
await Promise.all([queryClient.invalidateQueries({ queryKey: getDatabasesQueryKey() })])
Lines changed: 12 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,23 @@
11
import { UseQueryOptions, useQuery } from '@tanstack/react-query'
2-
import { codeBlock } from 'common-tags'
3-
import { Database, getMetaDb } from '~/lib/db'
4-
5-
export async function getDatabase(id: string) {
6-
const metaDb = await getMetaDb()
7-
8-
const {
9-
rows: [database],
10-
} = await metaDb.query<Database>(
11-
codeBlock`
12-
select id, name, created_at as "createdAt", is_hidden as "isHidden"
13-
from databases
14-
where id = $1
15-
`,
16-
[id]
17-
)
18-
19-
return database
20-
}
2+
import { useApp } from '~/components/app-provider'
3+
import { Database } from '~/lib/db'
214

225
export const useDatabaseQuery = (
236
id: string,
247
options: Omit<UseQueryOptions<Database, Error>, 'queryKey' | 'queryFn'> = {}
25-
) =>
26-
useQuery<Database, Error>({
8+
) => {
9+
const { dbManager } = useApp()
10+
return useQuery<Database, Error>({
2711
...options,
2812
queryKey: getDatabaseQueryKey(id),
29-
queryFn: async () => await getDatabase(id),
13+
queryFn: async () => {
14+
if (!dbManager) {
15+
throw new Error('dbManager is not available')
16+
}
17+
return await dbManager.getDatabase(id)
18+
},
3019
staleTime: Infinity,
3120
})
21+
}
3222

3323
export const getDatabaseQueryKey = (id: string) => ['database', id]

apps/postgres-new/data/databases/database-update-mutation.ts

Lines changed: 7 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
2-
import { codeBlock } from 'common-tags'
3-
import { Database, getMetaDb } from '~/lib/db'
2+
import { useApp } from '~/components/app-provider'
3+
import { Database } from '~/lib/db'
44
import { getDatabaseQueryKey } from './database-query'
55
import { getDatabasesQueryKey } from './databases-query'
66

@@ -15,25 +15,15 @@ export const useDatabaseUpdateMutation = ({
1515
onError,
1616
...options
1717
}: Omit<UseMutationOptions<Database, Error, DatabaseUpdateVariables>, 'mutationFn'> = {}) => {
18+
const { dbManager } = useApp()
1819
const queryClient = useQueryClient()
1920

2021
return useMutation<Database, Error, DatabaseUpdateVariables>({
2122
mutationFn: async ({ id, name, isHidden }) => {
22-
const metaDb = await getMetaDb()
23-
24-
const {
25-
rows: [database],
26-
} = await metaDb.query<Database>(
27-
codeBlock`
28-
update databases
29-
set name = $2, is_hidden = $3
30-
where id = $1
31-
returning id, name, created_at as "createdAt"
32-
`,
33-
[id, name, isHidden]
34-
)
35-
36-
return database
23+
if (!dbManager) {
24+
throw new Error('dbManager is not available')
25+
}
26+
return await dbManager.updateDatabase(id, { name, isHidden })
3727
},
3828
async onSuccess(data, variables, context) {
3929
await Promise.all([queryClient.invalidateQueries({ queryKey: getDatabasesQueryKey() })])
Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,23 @@
11
import { UseQueryOptions, useQuery } from '@tanstack/react-query'
2-
import { codeBlock } from 'common-tags'
3-
import { Database, getMetaDb } from '~/lib/db'
2+
import { useApp } from '~/components/app-provider'
3+
import { Database } from '~/lib/db'
44

55
export const useDatabasesQuery = (
66
options: Omit<UseQueryOptions<Database[], Error>, 'queryKey' | 'queryFn'> = {}
7-
) =>
8-
useQuery<Database[], Error>({
7+
) => {
8+
const { dbManager } = useApp()
9+
10+
return useQuery<Database[], Error>({
911
...options,
1012
queryKey: getDatabasesQueryKey(),
1113
queryFn: async () => {
12-
const metaDb = await getMetaDb()
13-
14-
const { rows: databases } = await metaDb.query<Database>(
15-
codeBlock`
16-
select id, name, created_at as "createdAt", is_hidden as "isHidden"
17-
from databases
18-
where is_hidden = false
19-
`
20-
)
21-
22-
return databases
14+
if (!dbManager) {
15+
throw new Error('dbManager is not available')
16+
}
17+
return await dbManager.getDatabases()
2318
},
2419
staleTime: Infinity,
2520
})
21+
}
2622

2723
export const getDatabasesQueryKey = () => ['databases']

0 commit comments

Comments
 (0)