Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .jules/bolt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
## 2025-01-28 - N+1 Query Resolution with Drizzle ORM
**Learning:** Resolving N+1 query issues with Drizzle ORM when fetching related items inside a loop using `Promise.all` can be effectively optimized by leveraging the `inArray` operator to batch database queries.
**Action:** When working with nested models mapping over `Promise.all` for database calls, use `inArray` to fetch relationships at once and then assemble them in memory, ensuring to check `if (array.length === 0) return []` first to prevent an empty `IN()` clause error.
38 changes: 23 additions & 15 deletions lib/actions/orders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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));
const orderIds = userOrders.map((o) => o.id);
if (orderIds.length === 0) {
return [];
}

return {
...order,
items,
};
})
);
// Fetch all items for these orders in a single query to avoid N+1
const allItems = await db
.select()
.from(orderItems)
.where(inArray(orderItems.orderId, orderIds));

return ordersWithItems;
// Group items by orderId in memory
const itemsByOrderId = allItems.reduce((acc, item) => {
if (!acc[item.orderId]) {
acc[item.orderId] = [];
}
acc[item.orderId].push(item);
return acc;
}, {} as Record<string, typeof allItems>);

return userOrders.map((order) => ({
...order,
items: itemsByOrderId[order.id] || [],
}));
}

// ============================================
Expand Down