From 0f377371683a8dd2147deb4e0d3101ea2dd18bbf Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Mon, 15 Sep 2014 17:52:52 -0700 Subject: [PATCH] dbcore: parse_sorted_query (#953) --- beets/dbcore/__init__.py | 1 + beets/dbcore/queryparse.py | 25 +++++++++++++++++++++++++ beets/library.py | 10 ++-------- 3 files changed, 28 insertions(+), 8 deletions(-) diff --git a/beets/dbcore/__init__.py b/beets/dbcore/__init__.py index fdf6b4695..c364fdfc3 100644 --- a/beets/dbcore/__init__.py +++ b/beets/dbcore/__init__.py @@ -20,5 +20,6 @@ from .query import Query, FieldQuery, MatchQuery, AndQuery, OrQuery from .types import Type from .queryparse import query_from_strings from .queryparse import sort_from_strings +from .queryparse import parse_sorted_query # flake8: noqa diff --git a/beets/dbcore/queryparse.py b/beets/dbcore/queryparse.py index 8a50e04d5..bcd864e01 100644 --- a/beets/dbcore/queryparse.py +++ b/beets/dbcore/queryparse.py @@ -157,3 +157,28 @@ def sort_from_strings(model_cls, sort_parts): for part in sort_parts: sort.add_sort(construct_sort_part(model_cls, part)) return sort + + +def parse_sorted_query(model_cls, parts, prefixes={}, + query_cls=query.AndQuery): + """Given a list of strings, create the `Query` and `Sort` that they + represent. + + Return a `SortedQuery` namedtuple, which is a pair of a `Query` and + `Sort`. + """ + # Separate query token and sort token. + query_parts = [] + sort_parts = [] + for part in parts: + if part.endswith((u'+', u'-')) and u':' not in part: + sort_parts.append(part) + else: + query_parts.append(part) + + # Parse each. + q = query_from_strings( + query_cls, model_cls, prefixes, query_parts + ) + s = sort_from_strings(model_cls, sort_parts) + return query.SortedQuery(q, s) diff --git a/beets/library.py b/beets/library.py index f5fb30b54..7ab83f111 100644 --- a/beets/library.py +++ b/beets/library.py @@ -959,15 +959,9 @@ def get_query_sort(val, model_cls): path_parts = () non_path_parts = val - # separate query token and sort token - query_val = [s for s in non_path_parts if not s.endswith(('+', '-'))] - sort_val = [s for s in non_path_parts if s.endswith(('+', '-'))] - - # Parse remaining parts and construct an AndQuery. - query = dbcore.query_from_strings( - dbcore.AndQuery, model_cls, prefixes, query_val + query, sort = dbcore.parse_sorted_query( + model_cls, non_path_parts, prefixes ) - sort = dbcore.sort_from_strings(model_cls, sort_val) # Add path queries to aggregate query. if path_parts: