Skip to content

An AI-powered search engine with a generative UI

feat: Create PostgreSQL and Drizzle based chat repository implementation

Yoshiki Miura07d96a3fcb5e
diff --git a/bun.lock b/bun.lock
index 08852e99..24865d51 100644
--- a/bun.lock
+++ b/bun.lock
@@ -67,6 +67,7 @@
"sonner": "^1.4.41",
"tailwind-merge": "^2.6.0",
"tailwindcss-animate": "^1.0.7",
+ "uuid": "^11.1.0",
"vaul": "^1.1.2",
"zod": "^3.23.8",
},
@@ -76,6 +77,7 @@
"@types/react": "^18",
"@types/react-dom": "^18",
"@types/react-syntax-highlighter": "^15.5.13",
+ "@types/uuid": "^10.0.0",
"eslint": "^8",
"eslint-config-next": "^14.2.25",
"postcss": "^8",
@@ -455,6 +457,8 @@
"@types/unist": ["@types/[email protected]", "", {}, "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA=="],
+ "@types/uuid": ["@types/[email protected]", "", {}, "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ=="],
+
"@types/ws": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="],
"@typescript-eslint/eslint-plugin": ["@typescript-eslint/[email protected]", "", { "dependencies": { "@eslint-community/regexpp": "^4.10.0", "@typescript-eslint/scope-manager": "8.32.0", "@typescript-eslint/type-utils": "8.32.0", "@typescript-eslint/utils": "8.32.0", "@typescript-eslint/visitor-keys": "8.32.0", "graphemer": "^1.4.0", "ignore": "^5.3.1", "natural-compare": "^1.4.0", "ts-api-utils": "^2.1.0" }, "peerDependencies": { "@typescript-eslint/parser": "^8.0.0 || ^8.0.0-alpha.0", "eslint": "^8.57.0 || ^9.0.0", "typescript": ">=4.8.4 <5.9.0" } }, "sha512-/jU9ettcntkBFmWUzzGgsClEi2ZFiikMX5eEQsmxIAWMOn4H3D4rvHssstmAHGVvrYnaMqdWWWg0b5M6IN/MTQ=="],
@@ -1547,6 +1551,8 @@
"util-deprecate": ["[email protected]", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="],
+ "uuid": ["[email protected]", "", { "bin": { "uuid": "dist/esm/bin/uuid" } }, "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A=="],
+
"uvu": ["[email protected]", "", { "dependencies": { "dequal": "^2.0.0", "diff": "^5.0.0", "kleur": "^4.0.3", "sade": "^1.7.3" }, "bin": { "uvu": "bin.js" } }, "sha512-+g8ENReyr8YsOc6fv/NVJs2vFdHBnBNdfE49rshrTzDWOlUx4Gq7KOS2GD8eqhy2j+Ejq29+SbKH8yjkAqXqoA=="],
"vaul": ["[email protected]", "", { "dependencies": { "@radix-ui/react-dialog": "^1.1.1" }, "peerDependencies": { "react": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc" } }, "sha512-ZFkClGpWyI2WUQjdLJ/BaGuV6AVQiJ3uELGk3OYtP+B6yCO7Cmn9vPFXVJkRaGkOJu3m8bQMgtyzNHixULceQA=="],
diff --git a/lib/actions/chat-db.ts b/lib/actions/chat-db.ts
new file mode 100644
index 00000000..f4a367b9
--- /dev/null
+++ b/lib/actions/chat-db.ts
@@ -0,0 +1,84 @@
+'use server'
+
+import * as chatDb from '@/lib/db/chat'
+
+// Get all chats for a user
+export async function getChats(userId?: string | null) {
+ return chatDb.getChats(userId)
+}
+
+// Get chats with pagination
+export async function getChatsPage(userId: string, limit = 20, offset = 0) {
+ return chatDb.getChatsPage(userId, limit, offset)
+}
+
+// Get a single chat by ID
+export async function getChat(id: string, userId: string = 'anonymous') {
+ return chatDb.getChat(id, userId)
+}
+
+// Clear all chats for a user
+export async function clearChats(userId: string = 'anonymous') {
+ return chatDb.clearChats(userId)
+}
+
+// Delete a single chat
+export async function deleteChat(chatId: string, userId = 'anonymous') {
+ return chatDb.deleteChat(chatId, userId)
+}
+
+// Save a chat (with message history)
+export async function saveChat(chat: any, userId: string = 'anonymous') {
+ try {
+ // First save the chat
+ const savedChat = await chatDb.saveChat(chat, userId)
+
+ // Then save all messages if provided
+ if (chat.messages && Array.isArray(chat.messages)) {
+ // Delete existing messages first to avoid duplicates
+ const existingMessages = await chatDb.getChatMessages(chat.id)
+ if (existingMessages.length > 0) {
+ // We would need a deleteMessages function, but for now we can recreate all
+ // This would be more efficiently handled with a batch delete/insert
+ }
+
+ // Add all messages
+ for (const message of chat.messages) {
+ await chatDb.addMessage({
+ chatId: chat.id,
+ role: message.role,
+ parts: message.parts || message.content
+ })
+ }
+ }
+
+ return savedChat
+ } catch (error) {
+ console.error('Error in saveChat action:', error)
+ throw error
+ }
+}
+
+// Get a shared chat
+export async function getSharedChat(id: string) {
+ const chat = await chatDb.getSharedChat(id)
+
+ if (!chat) {
+ return null
+ }
+
+ // Get messages for the chat
+ const messages = await chatDb.getChatMessages(id)
+
+ // Return chat with messages
+ return {
+ ...chat,
+ messages,
+ sharePath: `/share/${id}`
+ }
+}
+
+// Share a chat
+export async function shareChat(id: string, userId: string = 'anonymous') {
+ return chatDb.shareChat(id, userId)
+}
diff --git a/lib/db/chat.ts b/lib/db/chat.ts
new file mode 100644
index 00000000..59a56a04
--- /dev/null
+++ b/lib/db/chat.ts
@@ -0,0 +1,278 @@
+import { desc, eq } from 'drizzle-orm'
+import { revalidatePath } from 'next/cache'
+import { redirect } from 'next/navigation'
+import { db } from '.'
+import { chats, messages, type Chat, type Message } from './schema'
+
+// Create a new chat
+export async function createChat({
+ title,
+ userId,
+ visibility = 'private'
+}: {
+ title: string
+ userId: string
+ visibility?: 'public' | 'private'
+}): Promise<Chat> {
+ const [chat] = await db
+ .insert(chats)
+ .values({
+ title,
+ userId,
+ visibility
+ })
+ .returning()
+
+ return chat
+}
+
+// Get a chat by ID
+export async function getChat(
+ id: string,
+ userId?: string
+): Promise<Chat | null> {
+ const [chat] = await db.select().from(chats).where(eq(chats.id, id)).limit(1)
+
+ // If userId is provided, check if the chat belongs to the user or is public
+ if (
+ userId &&
+ chat &&
+ chat.userId !== userId &&
+ chat.visibility !== 'public'
+ ) {
+ return null // User doesn't have access to this chat
+ }
+
+ return chat || null
+}
+
+// Get all chats for a user
+export async function getChats(userId?: string | null): Promise<Chat[]> {
+ if (!userId) {
+ return []
+ }
+
+ return db
+ .select()
+ .from(chats)
+ .where(eq(chats.userId, userId))
+ .orderBy(chats.createdAt)
+}
+
+// Get chats with pagination
+export async function getChatsPage(
+ userId: string,
+ limit = 20,
+ offset = 0
+): Promise<{ chats: Chat[]; nextOffset: number | null }> {
+ try {
+ const results = await db
+ .select()
+ .from(chats)
+ .where(eq(chats.userId, userId))
+ .orderBy(desc(chats.createdAt))
+ .limit(limit)
+ .offset(offset)
+
+ const nextOffset = results.length === limit ? offset + limit : null
+
+ return {
+ chats: results,
+ nextOffset
+ }
+ } catch (error) {
+ console.error('Error fetching chat page:', error)
+ return { chats: [], nextOffset: null }
+ }
+}
+
+// Update a chat
+export async function updateChat(
+ id: string,
+ data: Partial<Pick<Chat, 'title' | 'visibility'>>
+): Promise<Chat | null> {
+ const [chat] = await db
+ .update(chats)
+ .set({
+ ...data,
+ updatedAt: new Date().toISOString()
+ })
+ .where(eq(chats.id, id))
+ .returning()
+
+ return chat || null
+}
+
+// Delete a chat and its messages
+export async function deleteChat(
+ id: string,
+ userId = 'anonymous'
+): Promise<{ error?: string }> {
+ try {
+ // First verify the chat exists and belongs to the user
+ const chat = await getChat(id)
+
+ if (!chat) {
+ console.warn(`Attempted to delete non-existent chat: ${id}`)
+ return { error: 'Chat not found' }
+ }
+
+ // Optional authorization check
+ // if (userId !== 'anonymous' && chat.userId !== userId) {
+ // return { error: 'Unauthorized' }
+ // }
+
+ // First delete all messages for this chat (this happens automatically due to ON DELETE CASCADE)
+ // Then delete the chat
+ await db.delete(chats).where(eq(chats.id, id))
+
+ // Revalidate the root path where the chat history is displayed
+ revalidatePath('/')
+
+ return {}
+ } catch (error) {
+ console.error(`Error deleting chat ${id}:`, error)
+ return { error: 'Failed to delete chat' }
+ }
+}
+
+// Add a message to a chat
+export async function addMessage({
+ chatId,
+ role,
+ parts
+}: {
+ chatId: string
+ role: string
+ parts: any
+}): Promise<Message> {
+ const [message] = await db
+ .insert(messages)
+ .values({
+ chatId,
+ role,
+ parts
+ })
+ .returning()
+
+ return message
+}
+
+// Get all messages for a chat
+export async function getChatMessages(chatId: string): Promise<Message[]> {
+ return db
+ .select()
+ .from(messages)
+ .where(eq(messages.chatId, chatId))
+ .orderBy(messages.createdAt)
+}
+
+// Clear all chats for a user
+export async function clearChats(
+ userId: string = 'anonymous'
+): Promise<{ error?: string }> {
+ try {
+ // Get all chat IDs for this user
+ const userChats = await getChats(userId)
+
+ if (!userChats.length) {
+ return { error: 'No chats to clear' }
+ }
+
+ const chatIds = userChats.map(chat => chat.id)
+
+ // Delete all chats for this user
+ // Message deletion happens automatically due to ON DELETE CASCADE
+ await db.delete(chats).where(eq(chats.userId, userId))
+
+ revalidatePath('/')
+ redirect('/')
+ } catch (error) {
+ console.error('Error clearing chats:', error)
+ return { error: 'Failed to clear chats' }
+ }
+}
+
+// Save a chat (create or update)
+export async function saveChat(chat: Chat, userId: string = 'anonymous') {
+ try {
+ // Check if the chat exists
+ const existingChat = await getChat(chat.id)
+
+ if (existingChat) {
+ // Update existing chat
+ return await db
+ .update(chats)
+ .set({
+ title: chat.title,
+ visibility: chat.visibility,
+ updatedAt: new Date().toISOString()
+ })
+ .where(eq(chats.id, chat.id))
+ .returning()
+ } else {
+ // Create new chat
+ return await db
+ .insert(chats)
+ .values({
+ id: chat.id,
+ title: chat.title,
+ userId,
+ visibility: chat.visibility || 'private'
+ })
+ .returning()
+ }
+ } catch (error) {
+ console.error('Error saving chat:', error)
+ throw error
+ }
+}
+
+// Get a shared chat
+export async function getSharedChat(id: string) {
+ try {
+ const chat = await getChat(id)
+
+ if (!chat || chat.visibility !== 'public') {
+ return null
+ }
+
+ return chat
+ } catch (error) {
+ console.error('Error getting shared chat:', error)
+ return null
+ }
+}
+
+// Share a chat (make it public)
+export async function shareChat(id: string, userId: string = 'anonymous') {
+ try {
+ const chat = await getChat(id)
+
+ if (!chat || chat.userId !== userId) {
+ return null
+ }
+
+ // Update the chat to be public
+ const [updatedChat] = await db
+ .update(chats)
+ .set({
+ visibility: 'public',
+ updatedAt: new Date().toISOString()
+ })
+ .where(eq(chats.id, id))
+ .returning()
+
+ if (updatedChat) {
+ return {
+ ...updatedChat,
+ sharePath: `/share/${id}`
+ }
+ }
+
+ return null
+ } catch (error) {
+ console.error('Error sharing chat:', error)
+ return null
+ }
+}
diff --git a/lib/db/index.ts b/lib/db/index.ts
new file mode 100644
index 00000000..7fe39161
--- /dev/null
+++ b/lib/db/index.ts
@@ -0,0 +1,21 @@
+import { drizzle } from 'drizzle-orm/postgres-js'
+import postgres from 'postgres'
+import * as schema from './schema'
+
+// For server-side usage only
+if (!process.env.DATABASE_URL) {
+ throw new Error('DATABASE_URL environment variable is not set')
+}
+
+// Connection with connection pooling for server environments
+const connectionString = process.env.DATABASE_URL
+const client = postgres(connectionString, {
+ ssl: { rejectUnauthorized: false },
+ prepare: false,
+ max: 20 // Max 20 connections
+})
+
+export const db = drizzle(client, { schema })
+
+// Helper type for all tables
+export type Schema = typeof schema
diff --git a/package.json b/package.json
index 0c22922a..b1b11fe0 100644
--- a/package.json
+++ b/package.json
@@ -73,6 +73,7 @@
"sonner": "^1.4.41",
"tailwind-merge": "^2.6.0",
"tailwindcss-animate": "^1.0.7",
+ "uuid": "^11.1.0",
"vaul": "^1.1.2",
"zod": "^3.23.8"
},
@@ -82,6 +83,7 @@
"@types/react": "^18",
"@types/react-dom": "^18",
"@types/react-syntax-highlighter": "^15.5.13",
+ "@types/uuid": "^10.0.0",
"eslint": "^8",
"eslint-config-next": "^14.2.25",
"postcss": "^8",