Prisma 6 → Drizzle 2.0으로 옮긴 지 한 달째인데 운영 모니터링에서 N+1이 잡혔습니다. 분명히 with로 관계 가져왔는데 쿼리가 N+1로 쪼개져 나가요.
환경: Drizzle 2.0.3, PostgreSQL 18, Node 24
코드:
// schema.ts
export const posts = pgTable('posts', { ... })
export const tags = pgTable('tags', { ... })
export const postTags = pgTable('post_tags', { ... })
export const postsRelations = relations(posts, ({ many }) => ({
postTags: many(postTags),
}))
export const postTagsRelations = relations(postTags, ({ one }) => ({
post: one(posts, { fields: [postTags.postId], references: [posts.id] }),
tag: one(tags, { fields: [postTags.tagId], references: [tags.id] }),
}))
// 쿼리
const result = await db.query.posts.findMany({
with: { postTags: { with: { tag: true } } },
limit: 50,
})
실제 나가는 쿼리 (pg_stat_statements):
SELECT * FROM posts LIMIT 50; -- 1번
SELECT * FROM post_tags WHERE post_id = $1; -- 50번 반복
SELECT * FROM tags WHERE id = $1; -- 평균 3번씩 × 50 = 150번
총 200쿼리가 나가서 페이지 응답이 1.4초로 느립니다. Prisma의 include는 IN 절로 묶어서 3쿼리로 끝나던 게 왜 Drizzle에선 다른가요?
댓글 0