Collapse build_sql into _fetch (#953)

This was getting so short that it made sense to go back from whence it came.
This commit is contained in:
Adrian Sampson 2014-09-13 21:35:19 -07:00
parent 85de214399
commit c57439770b
2 changed files with 18 additions and 35 deletions

View file

@ -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

View file

@ -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