From 4cfb59bfba27ff2f1ac7aff44a963167dbe51ebf Mon Sep 17 00:00:00 2001 From: Thomas Scholtes Date: Sun, 14 Sep 2014 15:11:59 +0200 Subject: [PATCH] Add Type.to_sql() and simplify model code Instead of encoding the conversion behaviour in the model class (via the `_bytes_keys` attribute) we define it on the type. This gives us a more extensible interface and separates logic. This should not change any behaviour (as one can see by closely staring at the code). --- beets/dbcore/db.py | 11 +---------- beets/dbcore/types.py | 6 ++++++ beets/library.py | 6 +++++- 3 files changed, 12 insertions(+), 11 deletions(-) diff --git a/beets/dbcore/db.py b/beets/dbcore/db.py index fc5820173..070f7104d 100644 --- a/beets/dbcore/db.py +++ b/beets/dbcore/db.py @@ -115,11 +115,6 @@ class Model(object): keys are field names and the values are `Type` objects. """ - _bytes_keys = () - """Keys whose values should be stored as raw bytes blobs rather than - strings. - """ - _search_fields = () """The fields that should be queried by default by unqualified query terms. @@ -338,11 +333,7 @@ class Model(object): if key != 'id' and key in self._dirty: self._dirty.remove(key) assignments += key + '=?,' - value = self[key] - # Wrap path strings in buffers so they get stored - # "in the raw". - if key in self._bytes_keys and isinstance(value, str): - value = buffer(value) + value = self._type(key).to_sql(self[key]) subvars.append(value) assignments = assignments[:-1] # Knock off last , diff --git a/beets/dbcore/types.py b/beets/dbcore/types.py index 28e28f596..2738f3425 100644 --- a/beets/dbcore/types.py +++ b/beets/dbcore/types.py @@ -75,6 +75,12 @@ class Type(object): """ return self.normalize(sql_value) + def to_sql(self, model_value): + """Convert a value as stored in the model object to a value used + by the database adapter. + """ + return model_value + # Reusable types. diff --git a/beets/library.py b/beets/library.py index 3a6829176..595eaa833 100644 --- a/beets/library.py +++ b/beets/library.py @@ -109,6 +109,11 @@ class PathType(types.Type): else: return value + def to_sql(self, value): + if isinstance(value, str): + value = buffer(value) + return value + class MusicalKey(types.String): """String representing the musical key of a song. @@ -188,7 +193,6 @@ class WriteError(FileOperationError): class LibModel(dbcore.Model): """Shared concrete functionality for Items and Albums. """ - _bytes_keys = ('path', 'artpath') def _template_funcs(self): funcs = DefaultTemplateFunctions(self, self._db).functions()