Merge branch 'PierreRust-optimize-model-init'

This commit is contained in:
Adrian Sampson 2014-05-10 14:04:00 -07:00
commit 95b1b2b043
2 changed files with 30 additions and 13 deletions

View file

@ -108,6 +108,21 @@ class Model(object):
self.update(values)
self.clear_dirty()
@classmethod
def _awaken(cls, db=None, fixed_values=None, flex_values=None):
"""Create an object with values drawn from the database.
This is a performance optimization: the checks involved with
ordinary construction are bypassed.
"""
obj = cls(db)
if fixed_values:
for key, value in fixed_values.items():
obj._values_fixed[key] = cls._fields[key].normalize(value)
if flex_values:
obj._values_flex.update(flex_values)
return obj
def __repr__(self):
return '{0}({1})'.format(
type(self).__name__,
@ -492,13 +507,11 @@ class Results(object):
(row['id'],)
)
values = dict(row)
values.update(
dict((row['key'], row['value']) for row in flex_rows)
)
flex_values = dict((row['key'], row['value']) for row in flex_rows)
# Construct the Python object and yield it if it passes the
# predicate.
obj = self.model_class(self.db, **values)
obj = self.model_class._awaken(self.db, values, flex_values)
if not self.query or self.query.match(obj):
yield obj

View file

@ -94,6 +94,19 @@ class PathType(types.Type):
def parse(self, string):
return normpath(bytestring_path(string))
def normalize(self, value):
if isinstance(value, unicode):
# Paths stored internally as encoded bytes.
return bytestring_path(value)
elif isinstance(value, buffer):
# SQLite must store bytestings as buffers to avoid decoding.
# We unwrap buffers to bytes.
return bytes(value)
else:
return value
# Special path format key.
PF_KEY_DEFAULT = 'default'
@ -687,15 +700,6 @@ class Album(LibModel):
getters['path'] = Album.item_dir
return getters
def __setitem__(self, key, value):
"""Set the value of an album attribute."""
if key == 'artpath':
if isinstance(value, unicode):
value = bytestring_path(value)
elif isinstance(value, buffer):
value = bytes(value)
super(Album, self).__setitem__(key, value)
def items(self):
"""Returns an iterable over the items associated with this
album.