diff --git a/etiquette/photodb.py b/etiquette/photodb.py index 00f91ab..0eedaec 100644 --- a/etiquette/photodb.py +++ b/etiquette/photodb.py @@ -530,7 +530,7 @@ class PDBPhotoMixin: } yield parameters - photo_tag_rel_intersections = searchhelpers.photo_tag_rel_intersections( + photo_tag_rel_exist_clauses = searchhelpers.photo_tag_rel_exist_clauses( tag_musts, tag_mays, tag_forbids, @@ -594,17 +594,10 @@ class PDBPhotoMixin: for (column, value) in maximums.items(): wheres.append(column + ' <= ' + str(value)) - # In order to use ORDER BY RANDOM(), we must place all of the intersect - # tag searches into a subquery. If we simply try to do - # SELECT * ... INTERSECT SELECT * ... ORDER BY RANDOM() - # we get an error that random is not a column. But placing all of the - # selects into a named subquery fixes that. - query = ['SELECT * FROM'] - if photo_tag_rel_intersections: - intersections = '(%s) photos' % '\nINTERSECT\n'.join(photo_tag_rel_intersections) - query.append(intersections) - else: - query.append('photos') + if photo_tag_rel_exist_clauses: + wheres.extend(photo_tag_rel_exist_clauses) + + query = ['SELECT * FROM photos'] if wheres: wheres = 'WHERE ' + ' AND '.join(wheres) diff --git a/etiquette/searchhelpers.py b/etiquette/searchhelpers.py index 22e1599..29c703f 100644 --- a/etiquette/searchhelpers.py +++ b/etiquette/searchhelpers.py @@ -358,37 +358,36 @@ def normalize_tag_expression(expression): return expression -INTERSECT_FORMAT = ''' -SELECT * FROM photos WHERE {operator} ( +EXIST_FORMAT = ''' +{operator} ( SELECT 1 FROM photo_tag_rel WHERE photos.id == photo_tag_rel.photoid AND tagid IN {tagset} ) '''.strip() -def photo_tag_rel_intersections(tag_musts, tag_mays, tag_forbids): +def photo_tag_rel_exist_clauses(tag_musts, tag_mays, tag_forbids): (tag_musts, tag_mays, tag_forbids) = expand_mmf( tag_musts, tag_mays, tag_forbids, ) - intersections = [] + clauses = [] for tag_must_group in tag_musts: - intersections.append( ('EXISTS', tag_must_group) ) + clauses.append( ('EXISTS', tag_must_group) ) if tag_mays: - intersections.append( ('EXISTS', tag_mays) ) + clauses.append( ('EXISTS', tag_mays) ) if tag_forbids: - intersections.append( ('NOT EXISTS', tag_forbids) ) + clauses.append( ('NOT EXISTS', tag_forbids) ) - intersections = [ - #(operator, helpers.sql_listify([tag.id for tag in tagset] + [""])) + clauses = [ (operator, helpers.sql_listify(tag.id for tag in tagset)) - for (operator, tagset) in intersections + for (operator, tagset) in clauses ] - intersections = [ - INTERSECT_FORMAT.format(operator=operator, tagset=tagset) - for (operator, tagset) in intersections + clauses = [ + EXIST_FORMAT.format(operator=operator, tagset=tagset) + for (operator, tagset) in clauses ] - return intersections + return clauses def normalize_tagset(photodb, tags, warning_bag=None): if not tags: