Skip to content

Commit

Permalink
use json_array_length
Browse files Browse the repository at this point in the history
  • Loading branch information
goto-bus-stop committed Aug 24, 2024
1 parent c900820 commit 6db054f
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions src/plugins/playlists.js
Original file line number Diff line number Diff line change
Expand Up @@ -153,17 +153,15 @@ class PlaylistsRepository {
const { db } = this.#uw;

const playlist = await db.selectFrom('playlists')
.leftJoin('playlistItems', 'playlistItems.playlistID', 'playlists.id')
.where('userID', '=', user.id)
.where('playlists.id', '=', id)
.groupBy('playlists.id')
.select([
'playlists.id',
'playlists.userID',
'playlists.name',
'playlists.createdAt',
'playlists.updatedAt',
db.fn.countAll().as('size'),
(eb) => sql`json_array_length(${eb.ref('playlists.items')})`.as('size'),
])
.executeTakeFirst();

Expand Down Expand Up @@ -212,10 +210,13 @@ class PlaylistsRepository {
const { db } = this.#uw;

const playlists = await db.selectFrom('playlists')
.leftJoin('playlistItems', 'playlistItems.playlistID', 'playlists.id')
.where('userID', '=', user.id)
.select(['playlists.id', 'name', db.fn.countAll().as('size'), 'playlists.createdAt'])
.groupBy('playlists.id')
.select([
'id',
'name',
(eb) => sql`json_array_length(${eb.ref('items')})`.as('size'),
'createdAt',
])
.execute();

return playlists.map((playlist) => {
Expand Down Expand Up @@ -372,24 +373,26 @@ class PlaylistsRepository {

const totalQuery = db.selectFrom('playlists')
.select(sql`json_array_length(items)`.as('count'))
.where('id', '=', playlist.id);
.where('id', '=', playlist.id)
.executeTakeFirstOrThrow();

const filteredQuery = filter == null ? totalQuery : db.selectFrom('playlistItems')
.select((eb) => eb.fn.countAll().as('count'))
.where('playlistID', '=', playlist.id)
.where((eb) => eb.or([
eb('playlistItems.artist', 'like', filter),
eb('playlistItems.title', 'like', filter),
]));
]))
.executeTakeFirstOrThrow();

const [
playlistItemsRaw,
filtered,
total,
] = await Promise.all([
query.execute(),
filteredQuery.executeTakeFirstOrThrow(),
totalQuery.executeTakeFirstOrThrow(),
filteredQuery,
totalQuery,
]);

const playlistItems = playlistItemsRaw.map(playlistItemFromSelection);
Expand Down

0 comments on commit 6db054f

Please sign in to comment.