Fixed joins in getMediaFilesWhere to use outer joins when not filtering by the joined table.

This commit is contained in:
Jonathan Bernard 2016-03-16 02:14:11 -05:00
parent 4905e32e6f
commit 328957d6f7

View File

@ -414,34 +414,40 @@ public class ORM {
public List<MediaFile> getMediaFilesWhere(Map params) {
def query = new StringBuilder()
def sqlParams = []
def joins = []
def orderClauses = [] as LinkedList
def whereClauses = []
def newJoin
query.append('SELECT mf.* FROM media_files mf ')
if (params.artistId || params.playlistId) {
query.append(' JOIN artists_media_files armf ON ')
.append(' mf.id = armf.media_file_id ')
orderClauses << 'armf.artist_id ASC' }
joins << (newJoin = [
table: 'artists_media_files armf',
clauses: ['mf.id = armf.media_file_id']])
if (params.artistId) {
query.append(' AND armf.artist_id = ? ')
newJoin.clauses << 'armf.artist_id = ?'
sqlParams << params.artistId }
else newJoin.type = 'LEFT'
orderClauses << 'armf.artist_id ASC' }
if (params.albumId || params.artistId || params.playlistId) {
query.append(' JOIN albums_media_files almf ON ')
.append(' mf.id = almf.media_file_id ')
orderClauses << 'almf.album_id ASC' }
joins << (newJoin = [
table: 'albums_media_files almf',
clauses: ['mf.id = almf.media_file_id']])
if (params.albumId) {
query.append(' AND almf.album_id = ? ')
newJoin.clauses << 'almf.album_id = ?'
sqlParams << params.albumId }
else newJoin.type = 'LEFT'
orderClauses << 'almf.album_id ASC' }
if (params.playlistId) {
query.append(' JOIN playlists_media_files pmf ON ')
query.append(' pmf.media_file_id = mf.id AND ')
query.append(' pmf.playlist_id = ?')
joins << (newJoin = [
table: 'playlists_media_files pmf',
clauses: ['pmf.media_file_id = mf.id', 'pmf.playlist_id = ?']])
orderClauses.addFirst('pmf.position')
sqlParams << params.playlistId }
@ -468,14 +474,23 @@ public class ORM {
if (params.tags) {
params.tags.eachWithIndex { tag, idx ->
String L = "mft${idx}";
query.append(" JOIN media_files_tags $L ON ")
.append(" ${L}.media_file_id = mf.id AND ${L}.tag_id = ?")
joins << (newJoin = [
table: "media_files_tags $L",
clauses: ["${L}.media_file_id = mf.id",
"${L}.tag_id = ?"]])
sqlParams << tag.id } }
orderClauses << 'mf.disc_number'
orderClauses << 'mf.track_number'
joins.each { j ->
if (j.type) query.append(' ').append(j.type).append(' ')
query.append(' JOIN ')
.append(j.table)
.append(' ON ')
.append(j.clauses.join(' AND ')) }
if (whereClauses)
query.append(' WHERE ').append(whereClauses.join(' AND '))