Move SQL logic to separate function
Idk if this makes any sense, and I don't really like the code atm, but the view .zig files lookk nicer?
This commit is contained in:
parent
09f542e26e
commit
7f3778e82f
4 changed files with 370 additions and 253 deletions
|
|
@ -1,51 +1,13 @@
|
|||
const std = @import("std");
|
||||
const jetzig = @import("jetzig");
|
||||
const TableRow = @import("../../types.zig").TableRow;
|
||||
const HyperlinkData = @import("../../types.zig").HyperlinkData;
|
||||
const queries = @import("../../queries.zig");
|
||||
|
||||
pub fn index(request: *jetzig.Request) !jetzig.View {
|
||||
var root = try request.data(.object);
|
||||
var songs_view = try root.put("songs", .array);
|
||||
|
||||
const query =
|
||||
\\SELECT songs.name, songs.id, artists.name, artists.id, COUNT(scrobbles) AS scrobbles
|
||||
\\FROM albumsongs
|
||||
\\INNER JOIN songs ON albumsongs.song_id = songs.id
|
||||
\\INNER JOIN scrobbles ON scrobbles.albumsong = albumsongs.id
|
||||
\\INNER JOIN albumsongsartists ON albumsongsartists.albumsong_id = albumsongs.id
|
||||
\\INNER JOIN artists ON artists.id = albumsongsartists.artist_id
|
||||
\\GROUP BY songs.id, artists.id
|
||||
\\ORDER BY scrobbles DESC, songs.name ASC
|
||||
;
|
||||
const songs = try queries.entityQueryResult(request, queries.generateQuery(.song, .entities), .{}, .array);
|
||||
try root.put("songs", songs);
|
||||
|
||||
var songs_js_result = try request.repo.executeSql(query, .{});
|
||||
defer songs_js_result.deinit();
|
||||
|
||||
const Song = struct { name: []const u8, id: i32, artist_name: []const u8, artist_id: i32, scrobbles: i64 };
|
||||
|
||||
var prev_song_id: ?i32 = null;
|
||||
|
||||
var row: ?TableRow = null;
|
||||
var artistlist = std.ArrayList(HyperlinkData).init(request.allocator);
|
||||
|
||||
blk: while (try songs_js_result.postgresql.result.next()) |song_row| {
|
||||
const song = try song_row.to(Song, .{ .dupe = true, .allocator = request.allocator });
|
||||
if (song.id == prev_song_id) {
|
||||
try artistlist.append(.{ .name = song.artist_name, .id = song.artist_id });
|
||||
continue :blk;
|
||||
} else {
|
||||
try artistlist.append(.{ .name = song.artist_name, .id = song.artist_id });
|
||||
|
||||
row = TableRow{
|
||||
.song = .{ .name = song.name, .id = song.id },
|
||||
.artistlist = try artistlist.toOwnedSlice(),
|
||||
.scrobbles = song.scrobbles,
|
||||
};
|
||||
|
||||
try songs_view.append(row);
|
||||
}
|
||||
prev_song_id = song.id;
|
||||
}
|
||||
return request.render(.ok);
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue