desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Run the edit command, with mocked stdin and yaml writing, and
passing `args` to `run_command`.'
| def run_mocked_command(self, modify_file_args={}, stdin=[], args=[]):
| m = ModifyFileMocker(**modify_file_args)
with patch('beetsplug.edit.edit', side_effect=m.action):
with control_stdin('\n'.join(stdin)):
self.run_command('edit', *args)
|
'Several common assertions on Album, Track and call counts.'
| def assertCounts(self, mock_write, album_count=ALBUM_COUNT, track_count=TRACK_COUNT, write_call_count=TRACK_COUNT, title_starts_with=''):
| self.assertEqual(len(self.lib.albums()), album_count)
self.assertEqual(len(self.lib.items()), track_count)
self.assertEqual(mock_write.call_count, write_call_count)
self.assertTrue(all((i.title.startswith(title_starts_with) for i in self.lib.items())))
|
'Edit title for all items in the library, then discard changes.'
| def test_title_edit_discard(self, mock_write):
| self.run_mocked_command({'replacements': {u't\xeftle': u'modified t\xeftle'}}, ['c'])
self.assertCounts(mock_write, write_call_count=0, title_starts_with=u't\xeftle')
self.assertItemFieldsModified(self.album.items(), self.items_orig, [])
|
'Edit title for all items in the library, then apply changes.'
| def test_title_edit_apply(self, mock_write):
| self.run_mocked_command({'replacements': {u't\xeftle': u'modified t\xeftle'}}, ['a'])
self.assertCounts(mock_write, write_call_count=self.TRACK_COUNT, title_starts_with=u'modified t\xeftle')
self.assertItemFieldsModified(self.album.items(), self.items_orig, ['title'])
|
'Edit title for one item in the library, then apply changes.'
| def test_single_title_edit_apply(self, mock_write):
| self.run_mocked_command({'replacements': {u't\xeftle 9': u'modified t\xeftle 9'}}, ['a'])
self.assertCounts(mock_write, write_call_count=1)
self.assertItemFieldsModified(list(self.album.items())[:(-1)], self.items_orig[:(-1)], [])
self.assertEqual(list(self.album.items())[(-1)].title, u'modifie... |
'Do not edit anything.'
| def test_noedit(self, mock_write):
| self.run_mocked_command({'contents': None}, [])
self.assertCounts(mock_write, write_call_count=0, title_starts_with=u't\xeftle')
self.assertItemFieldsModified(self.album.items(), self.items_orig, [])
|
'Edit the album field for all items in the library, apply changes.
By design, the album should not be updated.""'
| def test_album_edit_apply(self, mock_write):
| self.run_mocked_command({'replacements': {u'\xe4lbum': u'modified \xe4lbum'}}, ['a'])
self.assertCounts(mock_write, write_call_count=self.TRACK_COUNT)
self.assertItemFieldsModified(self.album.items(), self.items_orig, ['album'])
self.album.load()
self.assertEqual(self.album.album, u'\xe4lbum')
|
'Edit the yaml file appending an extra field to the first item, then
apply changes.'
| def test_single_edit_add_field(self, mock_write):
| self.run_mocked_command({'replacements': {u'id: 1': u'id: 1\nfoo: bar'}}, ['a'])
self.assertEqual(self.lib.items(u'id:1')[0].foo, 'bar')
self.assertCounts(mock_write, write_call_count=1, title_starts_with=u't\xeftle')
|
'Album query (-a), edit album field, apply changes.'
| def test_a_album_edit_apply(self, mock_write):
| self.run_mocked_command({'replacements': {u'\xe4lbum': u'modified \xe4lbum'}}, ['a'], args=['-a'])
self.album.load()
self.assertCounts(mock_write, write_call_count=self.TRACK_COUNT)
self.assertEqual(self.album.album, u'modified \xe4lbum')
self.assertItemFieldsModified(self.album.items(), self.... |
'Album query (-a), edit albumartist field, apply changes.'
| def test_a_albumartist_edit_apply(self, mock_write):
| self.run_mocked_command({'replacements': {u'album artist': u'modified album artist'}}, ['a'], args=['-a'])
self.album.load()
self.assertCounts(mock_write, write_call_count=self.TRACK_COUNT)
self.assertEqual(self.album.albumartist, u'the modified album artist')
self.assertItemFields... |
'Edit the yaml file incorrectly (resulting in a malformed yaml
document).'
| def test_malformed_yaml(self, mock_write):
| self.run_mocked_command({'contents': '!MALFORMED'}, ['n'])
self.assertCounts(mock_write, write_call_count=0, title_starts_with=u't\xeftle')
|
'Edit the yaml file incorrectly (resulting in a well-formed but
invalid yaml document).'
| def test_invalid_yaml(self, mock_write):
| self.run_mocked_command({'contents': u'wellformed: yes, but invalid'}, [])
self.assertCounts(mock_write, write_call_count=0, title_starts_with=u't\xeftle')
|
'Edit the album field for all items in the library, apply changes,
using the original item tags.'
| def test_edit_apply_asis(self):
| self._setup_import_session()
self.run_mocked_interpreter({'replacements': {u'Tag Title': u'Edited Title'}}, ['d', 'a'])
self.assertItemFieldsModified(self.lib.items(), self.items_orig, ['title'], (self.IGNORED + ['albumartist', 'mb_albumartistid']))
self.assertTrue(all((('Edited Title' in i.tit... |
'Edit the album field for all items in the library, discard changes,
using the original item tags.'
| def test_edit_discard_asis(self):
| self._setup_import_session()
self.run_mocked_interpreter({'replacements': {u'Tag Title': u'Edited Title'}}, ['d', 'c', 'u'])
self.assertItemFieldsModified(self.lib.items(), self.items_orig, [], (self.IGNORED + ['albumartist', 'mb_albumartistid']))
self.assertTrue(all((('Tag Title' in i.title) f... |
'Edit the album field for all items in the library, apply changes,
using a candidate.'
| def test_edit_apply_candidate(self):
| self._setup_import_session()
self.run_mocked_interpreter({'replacements': {u'Applied Title': u'Edited Title'}}, ['c', '1', 'a'])
self.assertTrue(all((('Edited Title ' in i.title) for i in self.lib.items())))
self.assertTrue(all((('match ' in i.mb_trackid) for i in self.lib.items())))
... |
'Edit the album field for all items in the library, discard changes,
using a candidate.'
| def test_edit_discard_candidate(self):
| self._setup_import_session()
self.run_mocked_interpreter({'replacements': {u'Applied Title': u'Edited Title'}}, ['c', '1', 'a'])
self.assertTrue(all((('Edited Title ' in i.title) for i in self.lib.items())))
self.assertTrue(all((('match ' in i.mb_trackid) for i in self.lib.items())))
... |
'Edit the album field for all items in the library, apply changes,
using the original item tags and singleton mode.'
| def test_edit_apply_asis_singleton(self):
| self._setup_import_session(singletons=True)
self.run_mocked_interpreter({'replacements': {u'Tag Title': u'Edited Title'}}, ['d', 'a', 'b'])
self.assertItemFieldsModified(self.lib.items(), self.items_orig, ['title'], (self.IGNORED + ['albumartist', 'mb_albumartistid']))
self.assertTrue(all((('Edite... |
'Edit the album field for all items in the library, apply changes,
using a candidate and singleton mode.'
| def test_edit_apply_candidate_singleton(self):
| self._setup_import_session()
self.run_mocked_interpreter({'replacements': {u'Applied Title': u'Edited Title'}}, ['c', '1', 'a', 'b'])
self.assertTrue(all((('Edited Title ' in i.title) for i in self.lib.items())))
self.assertTrue(all((('match ' in i.mb_trackid) for i in self.lib.items())))... |
'Test ordering by a field not present on all items.'
| def test_field_present_in_some_items(self):
| items = self.lib.items(u'id+')
ids = [i.id for i in items]
items[1].foo = u'bar1'
items[2].foo = u'bar2'
items[1].store()
items[2].store()
results_asc = list(self.lib.items(u'foo+ id+'))
self.assertEqual([i.id for i in results_asc], [ids[0], ids[3], ids[1], ids[2]])
results_desc =... |
'Test the handling of negation and sorting together.
If a string ends with a sorting suffix, it takes precedence over the
NotQuery parsing.'
| def test_negation_interaction(self):
| (query, sort) = beets.library.parse_query_string(u'-bar+', beets.library.Item)
self.assertEqual(len(query.subqueries), 1)
self.assertTrue(isinstance(query.subqueries[0], dbcore.query.TrueQuery))
self.assertTrue(isinstance(sort, dbcore.query.SlowFieldSort))
self.assertEqual(sort.field, u'-bar')
|
'Creates a directory with media files to import.
Sets ``self.import_dir`` to the path of the directory. Also sets
``self.import_media`` to a list :class:`MediaFile` for all the files in
the directory.
The directory has following layout
the_album/
track_1.mp3
track_2.mp3
track_3.mp3
:param count: Number of files to cre... | def _create_import_dir(self, count=3):
| self.import_dir = os.path.join(self.temp_dir, 'testsrcdir')
if os.path.isdir(self.import_dir):
shutil.rmtree(self.import_dir)
album_path = os.path.join(self.import_dir, 'the_album')
os.makedirs(album_path)
resource_path = os.path.join(_common.RSRC, 'full.mp3')
metadata = {'artist': u'Tag... |
'Join the ``segments`` and assert that this path exists in the library
directory'
| def assert_file_in_lib(self, *segments):
| self.assertExists(os.path.join(self.libdir, *segments))
|
'Join the ``segments`` and assert that this path exists in the library
directory'
| def assert_file_not_in_lib(self, *segments):
| self.assertNotExists(os.path.join(self.libdir, *segments))
|
'Create some music in multiple album directories.
`files` indicates whether to create the files (otherwise, only
directories are made). `ascii` indicates ACII-only filenames;
otherwise, we use Unicode names.'
| def create_music(self, files=True, ascii=True):
| self.base = os.path.abspath(os.path.join(self.temp_dir, 'tempdir'))
os.mkdir(self.base)
name = ('CAT' if ascii else util.bytestring_path(u'C\xc1T'))
name_alt_case = ('CAt' if ascii else util.bytestring_path(u'C\xc1t'))
self.dirs = [os.path.join(self.base, 'ABCD1234'), os.path.join(self.base, 'ABCD12... |
'Normalize a path\'s Unicode combining form according to the
platform.'
| def _normalize_path(self, path):
| path = path.decode('utf-8')
norm_form = ('NFD' if (sys.platform == 'darwin') else 'NFC')
path = unicodedata.normalize(norm_form, path)
return path.encode('utf-8')
|
'Test directly ImportTask.lookup_candidates().'
| def test_candidates_album(self):
| task = importer.ImportTask(paths=self.import_dir, toppath='top path', items=[_common.item()])
task.search_ids = [(self.MB_RELEASE_PREFIX + self.ID_RELEASE_0), (self.MB_RELEASE_PREFIX + self.ID_RELEASE_1), 'an invalid and discarded id']
task.lookup_candidates()
self.assertEqual(set(['VALID... |
'Test directly SingletonImportTask.lookup_candidates().'
| def test_candidates_singleton(self):
| task = importer.SingletonImportTask(toppath='top path', item=_common.item())
task.search_ids = [(self.MB_RECORDING_PREFIX + self.ID_RECORDING_0), (self.MB_RECORDING_PREFIX + self.ID_RECORDING_1), 'an invalid and discarded id']
task.lookup_candidates()
self.assertEqual(set(['VALID_RECORDIN... |
'Changing a non-"tag" field like `bitrate` and writing should
have no effect.'
| def test_non_metadata_field_unchanged(self):
| item = self.add_item_fixture()
item.read()
item.bitrate = 123
item.store()
output = self.write_cmd()
self.assertEqual(output, '')
|
'Return an unicode string representing the changes'
| def _show_change(self, items=None, info=None, cur_artist=u'the artist', cur_album=u'the album', dist=0.1):
| items = (items or self.items)
info = (info or self.info)
mapping = dict(zip(items, info.tracks))
config['ui']['color'] = False
album_dist = distance(items, info, mapping)
album_dist._penalties = {'album': [dist]}
commands.show_change(cur_artist, cur_album, autotag.AlbumMatch(album_dist, info... |
'Return a mapping from field names to getter functions.'
| @classmethod
def _getters(cls):
| raise NotImplementedError()
|
'Return a mapping from function names to text-transformer
functions.'
| def _template_funcs(self):
| raise NotImplementedError()
|
'Create a new object with an optional Database association and
initial field values.'
| def __init__(self, db=None, **values):
| self._db = db
self._dirty = set()
self._values_fixed = {}
self._values_flex = {}
self.update(values)
self.clear_dirty()
|
'Create an object with values drawn from the database.
This is a performance optimization: the checks involved with
ordinary construction are bypassed.'
| @classmethod
def _awaken(cls, db=None, fixed_values={}, flex_values={}):
| obj = cls(db)
for (key, value) in fixed_values.items():
obj._values_fixed[key] = cls._type(key).from_sql(value)
for (key, value) in flex_values.items():
obj._values_flex[key] = cls._type(key).from_sql(value)
return obj
|
'Mark all fields as *clean* (i.e., not needing to be stored to
the database).'
| def clear_dirty(self):
| self._dirty = set()
|
'Ensure that this object is associated with a database row: it
has a reference to a database (`_db`) and an id. A ValueError
exception is raised otherwise.'
| def _check_db(self, need_id=True):
| if (not self._db):
raise ValueError(u'{0} has no database'.format(type(self).__name__))
if (need_id and (not self.id)):
raise ValueError(u'{0} has no id'.format(type(self).__name__))
|
'Get the type of a field, a `Type` instance.
If the field has no explicit type, it is given the base `Type`,
which does no conversion.'
| @classmethod
def _type(cls, key):
| return (cls._fields.get(key) or cls._types.get(key) or types.DEFAULT)
|
'Get the value for a field. Raise a KeyError if the field is
not available.'
| def __getitem__(self, key):
| getters = self._getters()
if (key in getters):
return getters[key](self)
elif (key in self._fields):
return self._values_fixed.get(key, self._type(key).null)
elif (key in self._values_flex):
return self._values_flex[key]
else:
raise KeyError(key)
|
'Assign the value for a field.'
| def __setitem__(self, key, value):
| if (key in self._fields):
source = self._values_fixed
else:
source = self._values_flex
value = self._type(key).normalize(value)
old_value = source.get(key)
source[key] = value
if (self._always_dirty or (old_value != value)):
self._dirty.add(key)
|
'Remove a flexible attribute from the model.'
| def __delitem__(self, key):
| if (key in self._values_flex):
del self._values_flex[key]
self._dirty.add(key)
elif (key in self._getters()):
raise KeyError(u'computed field {0} cannot be deleted'.format(key))
elif (key in self._fields):
raise KeyError(u'fixed field {0} cannot be ... |
'Get a list of available field names for this object. The
`computed` parameter controls whether computed (plugin-provided)
fields are included in the key list.'
| def keys(self, computed=False):
| base_keys = (list(self._fields) + list(self._values_flex.keys()))
if computed:
return (base_keys + list(self._getters().keys()))
else:
return base_keys
|
'Get a list of available keys for objects of this type.
Includes fixed and computed fields.'
| @classmethod
def all_keys(cls):
| return (list(cls._fields) + list(cls._getters().keys()))
|
'Assign all values in the given dict.'
| def update(self, values):
| for (key, value) in values.items():
self[key] = value
|
'Iterate over (key, value) pairs that this object contains.
Computed fields are not included.'
| def items(self):
| for key in self:
(yield (key, self[key]))
|
'Get the value for a given key or `default` if it does not
exist.'
| def get(self, key, default=None):
| if (key in self):
return self[key]
else:
return default
|
'Determine whether `key` is an attribute on this object.'
| def __contains__(self, key):
| return (key in self.keys(True))
|
'Iterate over the available field names (excluding computed
fields).'
| def __iter__(self):
| return iter(self.keys())
|
'Save the object\'s metadata into the library database.
:param fields: the fields to be stored. If not specified, all fields
will be.'
| def store(self, fields=None):
| if (fields is None):
fields = self._fields
self._check_db()
assignments = []
subvars = []
for key in fields:
if ((key != 'id') and (key in self._dirty)):
self._dirty.remove(key)
assignments.append((key + '=?'))
value = self._type(key).to_sql(self[k... |
'Refresh the object\'s metadata from the library database.'
| def load(self):
| self._check_db()
stored_obj = self._db._get(type(self), self.id)
assert (stored_obj is not None), u'object {0} not in DB'.format(self.id)
self._values_fixed = {}
self._values_flex = {}
self.update(dict(stored_obj))
self.clear_dirty()
|
'Remove the object\'s associated rows from the database.'
| def remove(self):
| self._check_db()
with self._db.transaction() as tx:
tx.mutate('DELETE FROM {0} WHERE id=?'.format(self._table), (self.id,))
tx.mutate('DELETE FROM {0} WHERE entity_id=?'.format(self._flex_table), (self.id,))
|
'Add the object to the library database. This object must be
associated with a database; you can provide one via the `db`
parameter or use the currently associated database.
The object\'s `id` and `added` fields are set along with any
current field values.'
| def add(self, db=None):
| if db:
self._db = db
self._check_db(False)
with self._db.transaction() as tx:
new_id = tx.mutate('INSERT INTO {0} DEFAULT VALUES'.format(self._table))
self.id = new_id
self.added = time.time()
for key in self:
if (self[key] is not None):
... |
'Get a mapping containing all values on this object formatted
as human-readable unicode strings.'
| def formatted(self, for_path=False):
| return self._formatter(self, for_path)
|
'Evaluate a template (a string or a `Template` object) using
the object\'s fields. If `for_path` is true, then no new path
separators will be added to the template.'
| def evaluate_template(self, template, for_path=False):
| if isinstance(template, six.string_types):
template = Template(template)
return template.substitute(self.formatted(for_path), self._template_funcs())
|
'Parse a string as a value for the given key.'
| @classmethod
def _parse(cls, key, string):
| if (not isinstance(string, six.string_types)):
raise TypeError(u'_parse() argument must be a string')
return cls._type(key).parse(string)
|
'Set the object\'s key to a value represented by a string.'
| def set_parse(self, key, string):
| self[key] = self._parse(key, string)
|
'Create a result set that will construct objects of type
`model_class`.
`model_class` is a subclass of `LibModel` that will be
constructed. `rows` is a query result: a list of mappings. The
new objects will be associated with the database `db`.
If `query` is provided, it is used as a predicate to filter the
results for... | def __init__(self, model_class, rows, db, query=None, sort=None):
| self.model_class = model_class
self.rows = rows
self.db = db
self.query = query
self.sort = sort
self._rows = rows
self._row_count = len(rows)
self._objects = []
|
'Construct and generate Model objects for they query. The
objects are returned in the order emitted from the database; no
slow sort is applied.
For performance, this generator caches materialized objects to
avoid constructing them more than once. This way, iterating over
a `Results` object a second time should be much ... | def _get_objects(self):
| index = 0
while ((index < len(self._objects)) or self._rows):
if (index < len(self._objects)):
(yield self._objects[index])
index += 1
else:
while self._rows:
row = self._rows.pop(0)
obj = self._make_model(row)
i... |
'Construct and generate Model objects for all matching
objects, in sorted order.'
| def __iter__(self):
| if self.sort:
objects = self.sort.sort(list(self._get_objects()))
return iter(objects)
else:
return self._get_objects()
|
'Get the number of matching objects.'
| def __len__(self):
| if (not self._rows):
return len(self._objects)
elif self.query:
count = 0
for obj in self:
count += 1
return count
else:
return self._row_count
|
'Does this result contain any objects?'
| def __nonzero__(self):
| return self.__bool__()
|
'Does this result contain any objects?'
| def __bool__(self):
| return bool(len(self))
|
'Get the nth item in this result set. This is inefficient: all
items up to n are materialized and thrown away.'
| def __getitem__(self, n):
| if ((not self._rows) and (not self.sort)):
return self._objects[n]
it = iter(self)
try:
for i in range(n):
next(it)
return next(it)
except StopIteration:
raise IndexError(u'result index {0} out of range'.format(n))
|
'Return the first matching object, or None if no objects
match.'
| def get(self):
| it = iter(self)
try:
return next(it)
except StopIteration:
return None
|
'Begin a transaction. This transaction may be created while
another is active in a different thread.'
| def __enter__(self):
| with self.db._tx_stack() as stack:
first = (not stack)
stack.append(self)
if first:
self.db._db_lock.acquire()
return self
|
'Complete a transaction. This must be the most recently
entered but not yet exited transaction. If it is the last active
transaction, the database updates are committed.'
| def __exit__(self, exc_type, exc_value, traceback):
| with self.db._tx_stack() as stack:
assert (stack.pop() is self)
empty = (not stack)
if empty:
self.db._connection().commit()
self.db._db_lock.release()
|
'Execute an SQL statement with substitution values and return
a list of rows from the database.'
| def query(self, statement, subvals=()):
| cursor = self.db._connection().execute(statement, subvals)
return cursor.fetchall()
|
'Execute an SQL statement with substitution values and return
the row ID of the last affected row.'
| def mutate(self, statement, subvals=()):
| try:
cursor = self.db._connection().execute(statement, subvals)
return cursor.lastrowid
except sqlite3.OperationalError as e:
if (e.args[0] in ('attempt to write a readonly database', 'unable to open database file')):
raise DBAccessError(e.args[0])
... |
'Execute a string containing multiple SQL statements.'
| def script(self, statements):
| self.db._connection().executescript(statements)
|
'Get a SQLite connection object to the underlying database.
One connection object is created per thread.'
| def _connection(self):
| thread_id = threading.current_thread().ident
with self._shared_map_lock:
if (thread_id in self._connections):
return self._connections[thread_id]
else:
conn = self._create_connection()
self._connections[thread_id] = conn
return conn
|
'Create a SQLite connection to the underlying database.
Makes a new connection every time. If you need to configure the
connection settings (e.g., add custom functions), override this
method.'
| def _create_connection(self):
| conn = sqlite3.connect(py3_path(self.path), timeout=self.timeout)
conn.row_factory = sqlite3.Row
return conn
|
'Close the all connections to the underlying SQLite database
from all threads. This does not render the database object
unusable; new connections can still be opened on demand.'
| def _close(self):
| with self._shared_map_lock:
self._connections.clear()
|
'A context manager providing access to the current thread\'s
transaction stack. The context manager synchronizes access to
the stack map. Transactions should never migrate across threads.'
| @contextlib.contextmanager
def _tx_stack(self):
| thread_id = threading.current_thread().ident
with self._shared_map_lock:
(yield self._tx_stacks[thread_id])
|
'Get a :class:`Transaction` object for interacting directly
with the underlying SQLite database.'
| def transaction(self):
| return Transaction(self)
|
'Set up the schema of the database. `fields` is a mapping
from field names to `Type`s. Columns are added if necessary.'
| def _make_table(self, table, fields):
| with self.transaction() as tx:
rows = tx.query(('PRAGMA table_info(%s)' % table))
current_fields = set([row[1] for row in rows])
field_names = set(fields.keys())
if current_fields.issuperset(field_names):
return
if (not current_fields):
columns = []
for (name, typ)... |
'Create a table and associated index for flexible attributes
for the given entity (if they don\'t exist).'
| def _make_attribute_table(self, flex_table):
| with self.transaction() as tx:
tx.script('\n CREATE TABLE IF NOT EXISTS {0} (\n id INTEGER PRIMARY KEY,\n ... |
'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). `sort` is an
`Sort` object.'
| def _fetch(self, model_cls, query=None, sort=None):
| query = (query or TrueQuery())
sort = (sort or NullSort())
(where, subvals) = query.clause()
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.tr... |
'Get a Model object by its id or None if the id does not
exist.'
| def _get(self, model_cls, id):
| return self._fetch(model_cls, MatchQuery('id', id)).get()
|
'Generate an SQLite expression implementing the query.
Return (clause, subvals) where clause is a valid sqlite
WHERE clause implementing the query and subvals is a list of
items to be substituted for ?s in the clause.'
| def clause(self):
| return (None, ())
|
'Check whether this query matches a given Item. Can be used to
perform queries on arbitrary sets of Items.'
| def match(self, item):
| raise NotImplementedError
|
'Determine whether the value matches the pattern. Both
arguments are strings.'
| @classmethod
def value_match(cls, pattern, value):
| raise NotImplementedError()
|
'Determine whether the value matches the pattern. The value
may have any type.'
| @classmethod
def value_match(cls, pattern, value):
| return cls.string_match(pattern, util.as_string(value))
|
'Determine whether the value matches the pattern. Both
arguments are strings. Subclasses implement this method.'
| @classmethod
def string_match(cls, pattern, value):
| raise NotImplementedError()
|
'Normalize a Unicode string\'s representation (used on both
patterns and matched values).'
| @staticmethod
def _normalize(s):
| return unicodedata.normalize('NFC', s)
|
'Convert a string to a numeric type (float or int).
Return None if `s` is empty.
Raise an InvalidQueryError if the string cannot be converted.'
| def _convert(self, s):
| if (not s):
return None
try:
return int(s)
except ValueError:
try:
return float(s)
except ValueError:
raise InvalidQueryArgumentValueError(s, u'an int or a float')
|
'Return a clause created by joining together the clauses of
all subqueries with the string joiner (padded by spaces).'
| def clause_with_joiner(self, joiner):
| clause_parts = []
subvals = []
for subq in self.subqueries:
(subq_clause, subq_subvals) = subq.clause()
if (not subq_clause):
return (None, ())
clause_parts.append((('(' + subq_clause) + ')'))
subvals += subq_subvals
clause = ((' ' + joiner) + ' ').join(... |
'Since subqueries are mutable, this object should not be hashable.
However and for conveniences purposes, it can be hashed.'
| def __hash__(self):
| return reduce(mul, map(hash, self.subqueries), 1)
|
'Create a period with the given date (a `datetime` object) and
precision (a string, one of "year", "month", "day", "hour", "minute",
or "second").'
| def __init__(self, date, precision):
| if (precision not in Period.precisions):
raise ValueError(u'Invalid precision {0}'.format(precision))
self.date = date
self.precision = precision
|
'Parse a date and return a `Period` object or `None` if the
string is empty, or raise an InvalidQueryArgumentValueError if
the string cannot be parsed to a date.
The date may be absolute or relative. Absolute dates look like
`YYYY`, or `YYYY-MM-DD`, or `YYYY-MM-DD HH:MM:SS`, etc. Relative
dates have three parts:
- Opti... | @classmethod
def parse(cls, string):
| def find_date_and_format(string):
for (ord, format) in enumerate(cls.date_formats):
for format_option in format:
try:
date = datetime.strptime(string, format_option)
return (date, ord)
except ValueError:
... |
'Based on the precision, convert the period to a precise
`datetime` for use as a right endpoint in a right-open interval.'
| def open_right_endpoint(self):
| precision = self.precision
date = self.date
if ('year' == self.precision):
return date.replace(year=(date.year + 1), month=1)
elif ('month' == precision):
if (date.month < 12):
return date.replace(month=(date.month + 1))
else:
return date.replace(year=(dat... |
'Create an interval with two Periods as the endpoints.'
| @classmethod
def from_periods(cls, start, end):
| end_date = (end.open_right_endpoint() if (end is not None) else None)
start_date = (start.date if (start is not None) else None)
return cls(start_date, end_date)
|
'Convert a M:SS or numeric string to a float.
Return None if `s` is empty.
Raise an InvalidQueryError if the string cannot be converted.'
| def _convert(self, s):
| if (not s):
return None
try:
return util.raw_seconds_short(s)
except ValueError:
try:
return float(s)
except ValueError:
raise InvalidQueryArgumentValueError(s, u'a M:SS string or a float')
|
'Generates a SQL fragment to be used in a ORDER BY clause, or
None if no fragment is used (i.e., this is a slow sort).'
| def order_clause(self):
| return None
|
'Sort the list of objects and return a list.'
| def sort(self, items):
| return sorted(items)
|
'Indicate whether this query is *slow*, meaning that it cannot
be executed in SQL and must be executed in Python.'
| def is_slow(self):
| return False
|
'Return the list of sub-sorts for which we can be (at least
partially) fast.
A contiguous suffix of fast (SQL-capable) sub-sorts are
executable in SQL. The remaining, even if they are fast
independently, must be executed slowly.'
| def _sql_sorts(self):
| sql_sorts = []
for sort in reversed(self.sorts):
if (not (sort.order_clause() is None)):
sql_sorts.append(sort)
else:
break
sql_sorts.reverse()
return sql_sorts
|
'The value to be exposed when the underlying value is None.'
| @property
def null(self):
| return self.model_type()
|
'Given a value of this type, produce a Unicode string
representing the value. This is used in template evaluation.'
| def format(self, value):
| if (value is None):
value = self.null
if (value is None):
value = u''
if isinstance(value, bytes):
value = value.decode('utf-8', 'ignore')
return six.text_type(value)
|
'Parse a (possibly human-written) string and return the
indicated value of this type.'
| def parse(self, string):
| try:
return self.model_type(string)
except ValueError:
return self.null
|
'Given a value that will be assigned into a field of this
type, normalize the value to have the appropriate type. This
base implementation only reinterprets `None`.'
| def normalize(self, value):
| if (value is None):
return self.null
else:
return value
|
'Receives the value stored in the SQL backend and return the
value to be stored in the model.
For fixed fields the type of `value` is determined by the column
type affinity given in the `sql` property and the SQL to Python
mapping of the database adapter. For more information see:
http://www.sqlite.org/datatype3.html
h... | def from_sql(self, sql_value):
| if isinstance(sql_value, buffer):
sql_value = bytes(sql_value).decode('utf-8', 'ignore')
if isinstance(sql_value, six.text_type):
return self.parse(sql_value)
else:
return self.normalize(sql_value)
|
'Convert a value as stored in the model object to a value used
by the database adapter.'
| def to_sql(self, model_value):
| return model_value
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.