From c57439770bbcd9c8169f606df6e318cdc4ec087e Mon Sep 17 00:00:00 2001 From: Adrian Sampson Date: Sat, 13 Sep 2014 21:35:19 -0700 Subject: [PATCH] Collapse build_sql into _fetch (#953) This was getting so short that it made sense to go back from whence it came. --- beets/dbcore/db.py | 25 ++++++++++++++++++------- beets/dbcore/query.py | 28 ---------------------------- 2 files changed, 18 insertions(+), 35 deletions(-) diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index 5eba083f3..2063cff72 100644 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -24,7 +24,7 @@ import collections import beets from beets.util.functemplate import Template -from .query import MatchQuery, build_sql +from .query import MatchQuery, NullSort from .types import BASE_TYPE @@ -745,19 +745,30 @@ class Database(object): # Querying. - def _fetch(self, model_cls, query, sort_order=None): + def _fetch(self, model_cls, query, sort=None): """Fetch the objects of type `model_cls` matching the given query. The query may be given as a string, string sequence, a - Query object, or None (to fetch everything). If provided, - `sort_order` is either a SQLite ORDER BY clause for sorting or a - Sort object. + Query object, or None (to fetch everything). `sort` is an + optional Sort object. """ - sql, subvals, query, sort = build_sql(model_cls, query, sort_order) + where, subvals = query.clause() + sort = sort or NullSort() + order_by = sort.order_clause() + + sql = ("SELECT * FROM {0} WHERE {1} {2}").format( + model_cls._table, + where or '1', + "ORDER BY {0}".format(order_by) if order_by else '', + ) with self.transaction() as tx: rows = tx.query(sql, subvals) - return Results(model_cls, rows, self, query, sort) + return Results( + model_cls, rows, self, + None if where else query, # Slow query component. + sort if sort.is_slow() else None, # Slow sort component. + ) def _get(self, model_cls, id): """Get a Model object by its id or None if the id does not diff --git a/beets/dbcore/query.py b/beets/dbcore/query.py index b86512538..7197d2564 100644 --- a/beets/dbcore/query.py +++ b/beets/dbcore/query.py @@ -655,31 +655,3 @@ class NullSort(Sort): def __nonzero__(self): return False - - -def build_sql(model_cls, query, sort): - """ Generate a sql statement (and the values that must be injected into it) - from a query, sort and a model class. Query and sort objects are returned - only for slow query and slow sort operation. - """ - where, subvals = query.clause() - if where is not None: - query = None - - if not sort: - sort_order = "" - sort = None - elif isinstance(sort, Sort): - order_clause = sort.order_clause() - sort_order = "ORDER BY {0}".format(order_clause) \ - if order_clause else "" - if not sort.is_slow(): - sort = None - - sql = ("SELECT * FROM {table} WHERE {query_clause} {sort_order}").format( - table=model_cls._table, - query_clause=where or '1', - sort_order=sort_order, - ) - - return sql, subvals, query, sort