From cd96408c618eedc73eeb41044a307700bed1d5c7 Mon Sep 17 00:00:00 2001 From: Julio Biason Date: Fri, 6 Sep 2013 12:36:53 -0300 Subject: [PATCH] joins, arent they marvelous --- lyricsnode/routes/round.js | 76 +++++++++++++++----------------------- 1 file changed, 29 insertions(+), 47 deletions(-) diff --git a/lyricsnode/routes/round.js b/lyricsnode/routes/round.js index 5cb9d8c..460fddf 100644 --- a/lyricsnode/routes/round.js +++ b/lyricsnode/routes/round.js @@ -81,63 +81,45 @@ db = new sqlite3.Database(dbName(), sqlite3.OPEN_READWRITE, function (error) { * Select a song and display it *********************************************************************/ function index(req, res) { - var song = null; - var artist = null; - var lyrics = null; - if (!db) { res.render('db-error'); return; } - function pickArtist() { - console.log('Retrieving artist for song...'); - db.get('SELECT * FROM artists WHERE id = ' + song.artist, function (err, selectArtist) { - if (err) { - throw err; - } - - artist = selectArtist; - console.log(artist); - pickLyrics(); - }); - } - - function pickLyrics() { - console.log('Retrieving lyrics for song... '); - db.get('SELECT * FROM lyrics WHERE song = ' + song.id, function (err, selectLyrics) { - if (err) { - throw err; - } - - lyrics = selectLyrics; - console.log(lyrics); - answer(); - }); - } - - function answer() { - var params = { - title: 'Round', - lyrics: lyrics.lyrics, - song_title: song.title, - song_artist: artist.name, - acronym_title: acronymize(song.title), - acronym_artist: acronymize(artist.name), - id: song.id - }; - res.render('index', params); - } - console.log('Picking song...'); - db.get('SELECT * FROM songs WHERE done_in IS NULL ORDER BY random() LIMIT 1', function (err, selectSong) { + var query = [ + 'SELECT', + ' songs.id as song_id,', + ' songs.title as song_title,', + ' artists.name as artist_name,', + ' lyrics.lyrics as lyrics', + 'FROM songs,', + ' artists,', + ' lyrics', + 'WHERE songs.done_in is NULL', + ' AND songs.artist = artists.id', + ' AND songs.id = lyrics.song', + 'ORDER BY random()', + 'LIMIT 1' + ]; + console.log(query.join(' ')); + + db.get(query.join(' '), function (err, selectSong) { if (err) { throw err; } - song = selectSong; - console.log(song); - pickArtist(); + console.log(selectSong); + var params = { + title: 'Round', + lyrics: selectSong.lyrics, + song_title: selectSong.song_title, + song_artist: selectSong.artist_name, + acronym_title: acronymize(selectSong.song_title), + acronym_artist: acronymize(selectSong.artist_name), + id: selectSong.song_id + }; + res.render('index', params); }); }