diff --git a/.jules/bolt.md b/.jules/bolt.md new file mode 100644 index 0000000..c5dbbd8 --- /dev/null +++ b/.jules/bolt.md @@ -0,0 +1,3 @@ +## 2024-05-15 - [Database Query Optimization: Resolving N+1 Problems] +**Learning:** Performing database queries within a loop (`Promise.all` with `map`) leads to an N+1 query problem, increasing latency and database load linearly with the size of the initial result set. +**Action:** Use Drizzle ORMs `inArray` operator to batch related records into a single query and group them in memory using `reduce`, significantly reducing the number of roundtrips and overall execution time. diff --git a/lib/actions/orders.ts b/lib/actions/orders.ts index 3d367bb..07a2394 100644 --- a/lib/actions/orders.ts +++ b/lib/actions/orders.ts @@ -3,7 +3,7 @@ import { db } from "@/lib/db"; import { orders, orderItems, products, productVariants, user, bargainSessions } from "@/lib/db/schema"; import { getServerSession } from "@/lib/auth-server"; -import { eq, desc, sql, and, isNull } from "drizzle-orm"; +import { eq, desc, sql, and, isNull, inArray } from "drizzle-orm"; import { revalidatePath } from "next/cache"; import { markCouponUsed } from "./admin"; @@ -297,22 +297,30 @@ export async function getUserOrders() { .where(eq(orders.userId, session.user.id)) .orderBy(desc(orders.createdAt)); - // Fetch items for each order - const ordersWithItems = await Promise.all( - userOrders.map(async (order) => { - const items = await db - .select() - .from(orderItems) - .where(eq(orderItems.orderId, order.id)); + if (userOrders.length === 0) { + return []; + } - return { - ...order, - items, - }; - }) - ); + // Optimize N+1 query: Fetch all items for all orders in a single query + const orderIds = userOrders.map(order => order.id); + const allOrderItems = await db + .select() + .from(orderItems) + .where(inArray(orderItems.orderId, orderIds)); - return ordersWithItems; + // Group items by orderId + const itemsByOrderId = allOrderItems.reduce((acc, item) => { + if (!acc[item.orderId]) { + acc[item.orderId] = []; + } + acc[item.orderId].push(item); + return acc; + }, {} as Record); + + return userOrders.map(order => ({ + ...order, + items: itemsByOrderId[order.id] || [], + })); } // ============================================