| 1 |
Library Database API |
| 2 |
==================== |
| 3 |
|
| 4 |
.. currentmodule:: beets.library |
| 5 |
|
| 6 |
This page describes the internal API of beets' core database features. It |
| 7 |
doesn't exhaustively document the API, but is aimed at giving an overview of the |
| 8 |
architecture to orient anyone who wants to dive into the code. |
| 9 |
|
| 10 |
The |Library| object is the central repository for data in beets. It represents |
| 11 |
a database containing songs, which are |Item| instances, and groups of items, |
| 12 |
which are |Album| instances. |
| 13 |
|
| 14 |
The Library Class |
| 15 |
----------------- |
| 16 |
|
| 17 |
The |Library| is typically instantiated as a singleton. A single invocation of |
| 18 |
beets usually has only one |Library|. It's powered by :class:`dbcore.Database` |
| 19 |
under the hood, which handles the SQLite_ abstraction, something like a very |
| 20 |
minimal ORM_. The library is also responsible for handling queries to retrieve |
| 21 |
stored objects. |
| 22 |
|
| 23 |
Overview |
| 24 |
~~~~~~~~ |
| 25 |
|
| 26 |
You can add new items or albums to the library via the :py:meth:`Library.add` |
| 27 |
and :py:meth:`Library.add_album` methods. |
| 28 |
|
| 29 |
You may also query the library for items and albums using the |
| 30 |
:py:meth:`Library.items`, :py:meth:`Library.albums`, :py:meth:`Library.get_item` |
| 31 |
and :py:meth:`Library.get_album` methods. |
| 32 |
|
| 33 |
Any modifications to the library must go through a :class:`Transaction` object, |
| 34 |
which you can get using the :py:meth:`Library.transaction` context manager. |
| 35 |
|
| 36 |
.. _orm: https://en.wikipedia.org/wiki/Object-relational_mapping |
| 37 |
|
| 38 |
.. _sqlite: https://sqlite.org/index.html |
| 39 |
|
| 40 |
Model Classes |
| 41 |
------------- |
| 42 |
|
| 43 |
The two model entities in beets libraries, |Item| and |Album|, share a base |
| 44 |
class, :class:`LibModel`, that provides common functionality. That class itself |
| 45 |
specialises :class:`beets.dbcore.Model` which provides an ORM-like abstraction. |
| 46 |
|
| 47 |
To get or change the metadata of a model (an item or album), either access its |
| 48 |
attributes (e.g., ``print(album.year)`` or ``album.year = 2012``) or use the |
| 49 |
``dict``-like interface (e.g. ``item['artist']``). |
| 50 |
|
| 51 |
Model base |
| 52 |
~~~~~~~~~~ |
| 53 |
|
| 54 |
Models use dirty-flags to track when the object's metadata goes out of sync with |
| 55 |
the database. The dirty dictionary maps field names to booleans indicating |
| 56 |
whether the field has been written since the object was last synchronized (via |
| 57 |
load or store) with the database. This logic is implemented in the model base |
| 58 |
class :class:`LibModel` and is inherited by both |Item| and |Album|. |
| 59 |
|
| 60 |
We provide CRUD-like methods for interacting with the database: |
| 61 |
|
| 62 |
- :py:meth:`LibModel.store` |
| 63 |
- :py:meth:`LibModel.load` |
| 64 |
- :py:meth:`LibModel.remove` |
| 65 |
- :py:meth:`LibModel.add` |
| 66 |
|
| 67 |
The base class :class:`beets.dbcore.Model` has a ``dict``-like interface, so |
| 68 |
normal the normal mapping API is supported: |
| 69 |
|
| 70 |
- :py:meth:`LibModel.keys` |
| 71 |
- :py:meth:`LibModel.update` |
| 72 |
- :py:meth:`LibModel.items` |
| 73 |
- :py:meth:`LibModel.get` |
| 74 |
|
| 75 |
Item |
| 76 |
~~~~ |
| 77 |
|
| 78 |
Each |Item| object represents a song or track. (We use the more generic term |
| 79 |
item because, one day, beets might support non-music media.) An item can either |
| 80 |
be purely abstract, in which case it's just a bag of metadata fields, or it can |
| 81 |
have an associated file (indicated by ``item.path``). |
| 82 |
|
| 83 |
In terms of the underlying SQLite database, items are backed by a single table |
| 84 |
called items with one column per metadata fields. The metadata fields currently |
| 85 |
in use are listed in ``library.py`` in ``Item._fields``. |
| 86 |
|
| 87 |
To read and write a file's tags, we use the MediaFile_ library. To make changes |
| 88 |
to either the database or the tags on a file, you update an item's fields (e.g., |
| 89 |
``item.title = "Let It Be"``) and then call ``item.write()``. |
| 90 |
|
| 91 |
.. _mediafile: https://mediafile.readthedocs.io/en/latest/ |
| 92 |
|
| 93 |
Items also track their modification times (mtimes) to help detect when they |
| 94 |
become out of sync with on-disk metadata, mainly to speed up the |
| 95 |
:ref:`update-cmd` (which needs to check whether the database is in sync with the |
| 96 |
filesystem). This feature turns out to be sort of complicated. |
| 97 |
|
| 98 |
For any |Item|, there are two mtimes: the on-disk mtime (maintained by the OS) |
| 99 |
and the database mtime (maintained by beets). Correspondingly, there is on-disk |
| 100 |
metadata (ID3 tags, for example) and DB metadata. The goal with the mtime is to |
| 101 |
ensure that the on-disk and DB mtimes match when the on-disk and DB metadata are |
| 102 |
in sync; this lets beets do a quick mtime check and avoid rereading files in |
| 103 |
some circumstances. |
| 104 |
|
| 105 |
Specifically, beets attempts to maintain the following invariant: |
| 106 |
|
| 107 |
If the on-disk metadata differs from the DB metadata, then the on-disk mtime |
| 108 |
must be greater than the DB mtime. |
| 109 |
|
| 110 |
As a result, it is always valid for the DB mtime to be zero (assuming that real |
| 111 |
disk mtimes are always positive). However, whenever possible, beets tries to set |
| 112 |
``db_mtime = disk_mtime`` at points where it knows the metadata is synchronized. |
| 113 |
When it is possible that the metadata is out of sync, beets can then just set |
| 114 |
``db_mtime = 0`` to return to a consistent state. |
| 115 |
|
| 116 |
This leads to the following implementation policy: |
| 117 |
|
| 118 |
- On every write of disk metadata (``Item.write()``), the DB mtime is |
| 119 |
updated to match the post-write disk mtime. |
| 120 |
- Same for metadata reads (``Item.read()``). |
| 121 |
- On every modification to DB metadata (``item.field = ...``), the DB mtime |
| 122 |
is reset to zero. |
| 123 |
|
| 124 |
Album |
| 125 |
~~~~~ |
| 126 |
|
| 127 |
An |Album| is a collection of Items in the database. Every item in the database |
| 128 |
has either zero or one associated albums (accessible via ``item.album_id``). An |
| 129 |
item that has no associated album is called a singleton. Changing fields on an |
| 130 |
album (e.g. ``album.year = 2012``) updates the album itself and also changes the |
| 131 |
same field in all associated items. |
| 132 |
|
| 133 |
An |Album| object keeps track of album-level metadata, which is (mostly) a |
| 134 |
subset of the track-level metadata. The album-level metadata fields are listed |
| 135 |
in ``Album._fields``. For those fields that are both item-level and album-level |
| 136 |
(e.g., ``year`` or ``albumartist``), every item in an album should share the |
| 137 |
same value. Albums use an SQLite table called ``albums``, in which each column |
| 138 |
is an album metadata field. |
| 139 |
|
| 140 |
.. note:: |
| 141 |
|
| 142 |
The :py:meth:`Album.items` method is not inherited from |
| 143 |
:py:meth:`LibModel.items` for historical reasons. |
| 144 |
|
| 145 |
Transactions |
| 146 |
~~~~~~~~~~~~ |
| 147 |
|
| 148 |
The |Library| class provides the basic methods necessary to access and |
| 149 |
manipulate its contents. To perform more complicated operations atomically, or |
| 150 |
to interact directly with the underlying SQLite database, you must use a |
| 151 |
*transaction* (see this `blog post`_ for motivation). For example |
| 152 |
|
| 153 |
.. code-block:: python |
| 154 |
|
| 155 |
lib = Library() |
| 156 |
with lib.transaction() as tx: |
| 157 |
items = lib.items(query) |
| 158 |
lib.add_album(list(items)) |
| 159 |
|
| 160 |
.. currentmodule:: beets.dbcore.db |
| 161 |
|
| 162 |
The :class:`Transaction` class is a context manager that provides a |
| 163 |
transactional interface to the underlying SQLite database. It is responsible for |
| 164 |
managing the transaction's lifecycle, including beginning, committing, and |
| 165 |
rolling back the transaction if an error occurs. |
| 166 |
|
| 167 |
.. _blog post: https://beets.io/blog/sqlite-nightmare.html |
| 168 |
|
| 169 |
Migrations |
| 170 |
~~~~~~~~~~ |
| 171 |
|
| 172 |
The database layer includes a first-class migration system for data changes that |
| 173 |
must happen alongside schema evolution. This keeps compatibility work explicit, |
| 174 |
testable, and isolated from normal query and model code. |
| 175 |
|
| 176 |
Each database subclass declares its migrations in ``_migrations`` as pairs of a |
| 177 |
migration class and the model classes it applies to. During startup, the |
| 178 |
database creates required tables and columns first, then executes configured |
| 179 |
migrations. |
| 180 |
|
| 181 |
Migration completion is tracked in a dedicated ``migrations`` table keyed by |
| 182 |
migration name and table name. This means each migration runs at most once per |
| 183 |
table, so large one-time data rewrites can be safely coordinated across |
| 184 |
restarts. |
| 185 |
|
| 186 |
The migration name is derived from the migration class name. Because that name |
| 187 |
is the persisted identity in the ``migrations`` table, renaming a released |
| 188 |
migration class changes its identity and can cause the migration to run again. |
| 189 |
Treat migration class names as stable once shipped. |
| 190 |
|
| 191 |
For example, ``MultiGenreFieldMigration`` becomes ``multi_genre_field``. After |
| 192 |
it runs for the ``items`` table, beets records a row equivalent to: |
| 193 |
|
| 194 |
.. code-block:: text |
| 195 |
|
| 196 |
name = "multi_genre_field", table_name = "items" |
| 197 |
|
| 198 |
Common use cases include: |
| 199 |
|
| 200 |
1. Backfilling a newly introduced canonical field from older data. |
| 201 |
2. Normalizing legacy free-form values into a structured representation. |
| 202 |
3. Splitting mixed-content legacy fields into cleaned primary content plus |
| 203 |
auxiliary metadata stored as flexible attributes. |
| 204 |
|
| 205 |
To add a migration: |
| 206 |
|
| 207 |
1. Create a :class:`beets.dbcore.db.Migration` subclass. |
| 208 |
2. Implement the table-specific data rewrite logic in ``_migrate_data``. |
| 209 |
3. Register the migration in the database subclass ``_migrations`` list for the |
| 210 |
target models. |
| 211 |
|
| 212 |
In practice, migrations should be idempotent and conservative: gate behavior on |
| 213 |
the current schema when needed, keep writes transactional, and batch large |
| 214 |
updates so startup remains predictable for real libraries. |
| 215 |
|
| 216 |
Queries |
| 217 |
------- |
| 218 |
|
| 219 |
.. currentmodule:: beets.dbcore.query |
| 220 |
|
| 221 |
To access albums and items in a library, we use :doc:`/reference/query`. In |
| 222 |
beets, the :class:`Query` abstract base class represents a criterion that |
| 223 |
matches items or albums in the database. Every subclass of :class:`Query` must |
| 224 |
implement two methods, which implement two different ways of identifying |
| 225 |
matching items/albums. |
| 226 |
|
| 227 |
The ``clause()`` method should return an SQLite ``WHERE`` clause that matches |
| 228 |
appropriate albums/items. This allows for efficient batch queries. |
| 229 |
Correspondingly, the ``match(item)`` method should take an |Item| object and |
| 230 |
return a boolean, indicating whether or not a specific item matches the |
| 231 |
criterion. This alternate implementation allows clients to determine whether |
| 232 |
items that have already been fetched from the database match the query. |
| 233 |
|
| 234 |
There are many different types of queries. Just as an example, |
| 235 |
:class:`FieldQuery` determines whether a certain field matches a certain value |
| 236 |
(an equality query). :class:`AndQuery` (like its abstract superclass, |
| 237 |
:class:`CollectionQuery`) takes a set of other query objects and bundles them |
| 238 |
together, matching only albums/items that match all constituent queries. |
| 239 |
|
| 240 |
Beets has a human-writable plain-text query syntax that can be parsed into |
| 241 |
:class:`Query` objects. Calling ``AndQuery.from_strings`` parses a list of query |
| 242 |
parts into a query object that can then be used with |Library| objects. |