⚡ Bolt: Optimize playlist song fetching and fix type errors#56
⚡ Bolt: Optimize playlist song fetching and fix type errors#56Krosebrook wants to merge 1 commit intomainfrom
Conversation
- Replaced 3-step query pattern in `getPlaylistWithSongs` with a single `innerJoin`. - Removed `.nullsLast()` from `getLikedSongs` to fix TypeScript error. - Reduces database round trips and improves performance. Co-authored-by: Krosebrook <214532761+Krosebrook@users.noreply.github.com>
|
👋 Jules, reporting for duty! I'm here to lend a hand with this pull request. When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down. I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job! For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with New to Jules? Learn more at jules.google/docs. For security, I will only act on instructions from the user who triggered this task. |
Summary of ChangesHello @Krosebrook, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request focuses on improving the efficiency and stability of database interactions within the application. By optimizing a playlist song fetching query, it reduces the number of database calls, leading to better performance. Additionally, it addresses a TypeScript compilation error related to Drizzle ORM's sorting methods, ensuring a cleaner build process and improved type safety. Highlights
Changelog
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
📝 WalkthroughWalkthroughAdds a learning entry documenting Drizzle query instability with Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Code Review
This pull request introduces a great optimization by refactoring the getPlaylistWithSongs function to reduce database queries, and it also fixes a type error by removing .nullsLast(). The changes are clear and well-motivated. I've added one suggestion to further optimize getPlaylistWithSongs to use a single database query by leveraging Drizzle's relational query capabilities, which would be a nice enhancement on top of your current improvement.
| const playlist = await this.getPlaylist(id); | ||
| if (!playlist) return undefined; | ||
|
|
||
| const playlistSongRows = await db.select({ songId: playlistSongs.songId }) | ||
| .from(playlistSongs) | ||
| .where(eq(playlistSongs.playlistId, id)); | ||
|
|
||
| const songIds = playlistSongRows.map(r => r.songId).filter(id => typeof id === 'number' && !isNaN(id)); | ||
|
|
||
| if (songIds.length === 0) { | ||
| return { ...playlist, songs: [] }; | ||
| } | ||
|
|
||
| const songsResult = await db.select() | ||
| // Optimized: Single query with innerJoin to avoid N+1 and ID mapping overhead | ||
| const songsList = await db.select(getTableColumns(songs)) | ||
| .from(songs) | ||
| .where(inArray(songs.id, songIds)); | ||
|
|
||
| const songMap = new Map(songsResult.map(s => [s.id, s])); | ||
| const songsList = songIds.map(id => songMap.get(id)).filter((s): s is Song => !!s); | ||
| .innerJoin(playlistSongs, eq(songs.id, playlistSongs.songId)) | ||
| .where(eq(playlistSongs.playlistId, id)) | ||
| .orderBy(asc(playlistSongs.addedAt)); | ||
|
|
||
| return { ...playlist, songs: songsList }; |
There was a problem hiding this comment.
Great job on optimizing this function to reduce the number of database queries! While this is a solid improvement from 3 queries to 2, we can actually consolidate this into a single query using Drizzle's relational query features. This would make it even more efficient by avoiding the separate getPlaylist call.
By using db.query.playlists.findFirst with the with clause, you can fetch the playlist and all its related songs in one go.
| const playlist = await this.getPlaylist(id); | |
| if (!playlist) return undefined; | |
| const playlistSongRows = await db.select({ songId: playlistSongs.songId }) | |
| .from(playlistSongs) | |
| .where(eq(playlistSongs.playlistId, id)); | |
| const songIds = playlistSongRows.map(r => r.songId).filter(id => typeof id === 'number' && !isNaN(id)); | |
| if (songIds.length === 0) { | |
| return { ...playlist, songs: [] }; | |
| } | |
| const songsResult = await db.select() | |
| // Optimized: Single query with innerJoin to avoid N+1 and ID mapping overhead | |
| const songsList = await db.select(getTableColumns(songs)) | |
| .from(songs) | |
| .where(inArray(songs.id, songIds)); | |
| const songMap = new Map(songsResult.map(s => [s.id, s])); | |
| const songsList = songIds.map(id => songMap.get(id)).filter((s): s is Song => !!s); | |
| .innerJoin(playlistSongs, eq(songs.id, playlistSongs.songId)) | |
| .where(eq(playlistSongs.playlistId, id)) | |
| .orderBy(asc(playlistSongs.addedAt)); | |
| return { ...playlist, songs: songsList }; | |
| const playlistData = await db.query.playlists.findFirst({ | |
| where: eq(playlists.id, id), | |
| with: { | |
| playlistSongs: { | |
| orderBy: asc(playlistSongs.addedAt), | |
| with: { | |
| song: true, | |
| }, | |
| }, | |
| }, | |
| }); | |
| if (!playlistData) { | |
| return undefined; | |
| } | |
| const { playlistSongs, ...playlist } = playlistData; | |
| const songsList = playlistSongs.map((ps) => ps.song).filter((s): s is Song => !!s); | |
| return { ...playlist, songs: songsList }; |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
server/storage.ts (1)
163-168: Minor: comment says "Single query" but the method still makes two queries.Line 163 says "Single query with innerJoin to avoid N+1" — the N+1 elimination is accurate, but the method still issues two DB calls (
getPlayliston line 160 + this join). Consider rewording to something like "Single join query for songs" to avoid confusion.Suggested comment wording
- // Optimized: Single query with innerJoin to avoid N+1 and ID mapping overhead + // Optimized: Single join query for songs, avoiding N+1 individual song fetches
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4d085eef8a
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| .innerJoin(songLikes, eq(songs.id, songLikes.songId)) | ||
| .where(eq(songLikes.userId, userId)) | ||
| .orderBy(desc(songLikes.createdAt).nullsLast()); | ||
| .orderBy(desc(songLikes.createdAt)); |
There was a problem hiding this comment.
Restore NULLS LAST for liked-song timestamp sort
Changing the sort to orderBy(desc(songLikes.createdAt)) alters behavior for nullable timestamps: in Postgres, DESC places NULL values first unless NULLS LAST is explicit, so any song_likes rows with missing created_at will now surface at the top instead of the bottom. This is a real data-path risk because createdAt is defined without .notNull() in shared/schema.ts, so nulls are schema-valid; keep nulls-last semantics via an explicit SQL ordering or enforce non-null timestamps.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Pull request overview
Optimizes the storage layer’s playlist and likes queries to reduce database round trips and address Drizzle/TypeScript type errors around ordering, aligning query patterns with the project’s recent DB optimization guidance.
Changes:
- Reworked
getPlaylistWithSongsto fetch playlist songs via a singleinnerJoinordered byplaylist_songs.added_at. - Removed
.nullsLast()fromgetLikedSongsordering to avoid Drizzle type errors in this environment. - Documented the
.nullsLast()instability in.jules/bolt.md.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
server/storage.ts |
Replaces playlist song fetching with a join-based query and adjusts liked-songs ordering. |
.jules/bolt.md |
Adds a learning note documenting the .nullsLast() type error and the recommended workaround. |
| type InsertPlaylist, | ||
| } from "@shared/schema"; | ||
| import { eq, desc, and, inArray, sql, getTableColumns } from "drizzle-orm"; | ||
| import { eq, desc, asc, and, inArray, sql, getTableColumns } from "drizzle-orm"; |
There was a problem hiding this comment.
inArray is still imported from drizzle-orm but no longer used in this file after the playlist query rewrite. Please remove it from the import list to keep the module clean and avoid reintroducing unused-query patterns later.
| import { eq, desc, asc, and, inArray, sql, getTableColumns } from "drizzle-orm"; | |
| import { eq, desc, asc, and, sql, getTableColumns } from "drizzle-orm"; |
| .innerJoin(songLikes, eq(songs.id, songLikes.songId)) | ||
| .where(eq(songLikes.userId, userId)) | ||
| .orderBy(desc(songLikes.createdAt).nullsLast()); | ||
| .orderBy(desc(songLikes.createdAt)); |
There was a problem hiding this comment.
songLikes.createdAt is nullable in the schema (timestamp(...).defaultNow() without .notNull()), and removing .nullsLast() changes Postgres’ default sort behavior for DESC (nulls will come first). If you want stable “most recently liked first” ordering, either make createdAt non-nullable in the schema/migration or use an explicit ORDER BY ... NULLS LAST via a sql fragment/coalesce workaround.
| .orderBy(desc(songLikes.createdAt)); | |
| .orderBy(desc(sql`coalesce(${songLikes.createdAt}, to_timestamp(0))`)); |
getPlaylistWithSongswith a singleinnerJoinquery and removed.nullsLast()fromgetLikedSongs.pnpm check.PR created automatically by Jules for task 7776282457119863187 started by @Krosebrook
Summary by cubic
Optimized playlist song fetching by using a single join and fixed a Drizzle type error by removing .nullsLast(). This cuts playlist fetch DB queries from 3 to 2 and restores clean builds.
Refactors
Bug Fixes
Written for commit 4d085ee. Summary will update on new commits.
Summary by CodeRabbit