or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

configuration.mdimport-autotag.mdindex.mdlibrary-management.mdplugin-system.mdquery-system.mduser-interface.mdutilities-templates.md

library-management.mddocs/

0

# Library Management

1

2

Core database operations for managing music collections including item and album CRUD operations, query execution, and metadata management. The library system provides the foundation for all beets functionality.

3

4

## Capabilities

5

6

### Library Class

7

8

The central database interface that manages Items and Albums with an SQLite backend, providing query functionality and transaction management.

9

10

```python { .api }

11

class Library:

12

def __init__(self, path: str, directory: str, path_formats=None, replacements=None):

13

"""

14

Initialize a music library.

15

16

Parameters:

17

- path: Path to SQLite database file

18

- directory: Root directory for music files

19

- path_formats: List of (query, template) tuples for path formatting

20

- replacements: List of (regex, replacement) tuples for filename sanitization

21

"""

22

23

def items(self, query: str = None) -> Results:

24

"""

25

Query for items (tracks) in the library.

26

27

Parameters:

28

- query: Query string for filtering (optional)

29

30

Returns:

31

Results iterator over matching Item objects

32

"""

33

34

def albums(self, query: str = None) -> Results:

35

"""

36

Query for albums in the library.

37

38

Parameters:

39

- query: Query string for filtering (optional)

40

41

Returns:

42

Results iterator over matching Album objects

43

"""

44

45

def add(self, obj: Union[Item, Album]) -> None:

46

"""

47

Add an Item or Album to the library database.

48

49

Parameters:

50

- obj: Item or Album object to add

51

"""

52

53

def add_album(self, items: List[Item]) -> Album:

54

"""

55

Create an album from a list of items.

56

57

Parameters:

58

- items: List of Item objects to group into an album

59

60

Returns:

61

Album object containing the items

62

"""

63

64

def get_item(self, id: int) -> Item:

65

"""

66

Get an item by database ID.

67

68

Parameters:

69

- id: Database ID of the item

70

71

Returns:

72

Item object or None if not found

73

"""

74

75

def get_album(self, id: int) -> Album:

76

"""

77

Get an album by database ID.

78

79

Parameters:

80

- id: Database ID of the album

81

82

Returns:

83

Album object or None if not found

84

"""

85

86

def parse_query_string(self, query_string: str, model_cls: Type) -> Query:

87

"""

88

Parse a query string into a Query object.

89

90

Parameters:

91

- query_string: String representation of query

92

- model_cls: Item or Album class

93

94

Returns:

95

Query object for database operations

96

"""

97

```

98

99

#### Usage Examples

100

101

```python

102

from beets.library import Library

103

104

# Create a new library

105

lib = Library('/home/user/.config/beets/musiclibrary.db', '/home/user/Music')

106

107

# Query all items

108

all_items = lib.items()

109

print(f"Total tracks: {len(all_items)}")

110

111

# Query with filters

112

recent_items = lib.items('added:2024..')

113

beatles_albums = lib.albums('artist:Beatles')

114

115

# Add items to library

116

from beets.library import Item

117

item = Item.from_path('/path/to/song.mp3')

118

lib.add(item)

119

```

120

121

### Item Class

122

123

Represents a single music track/file with comprehensive metadata fields and file operations.

124

125

```python { .api }

126

class Item(Model):

127

# Core metadata fields

128

title: str

129

artist: str

130

album: str

131

albumartist: str

132

track: int

133

disc: int

134

year: int

135

month: int

136

day: int

137

genre: str

138

length: float # Duration in seconds

139

bitrate: int

140

samplerate: int

141

channels: int

142

path: bytes # Filesystem path

143

mtime: float # Modification time

144

added: float # Time added to library

145

146

@classmethod

147

def from_path(cls, path: str) -> 'Item':

148

"""

149

Create an Item from a file path, reading metadata from file.

150

151

Parameters:

152

- path: Filesystem path to audio file

153

154

Returns:

155

Item object with metadata loaded from file

156

"""

157

158

def add(self, library: Library) -> None:

159

"""

160

Add this item to a library database.

161

162

Parameters:

163

- library: Library instance to add to

164

"""

165

166

def store(self) -> None:

167

"""

168

Save changes to the database.

169

"""

170

171

def load(self) -> None:

172

"""

173

Load metadata from the audio file, updating item fields.

174

"""

175

176

def write(self) -> None:

177

"""

178

Write current metadata to the audio file tags.

179

"""

180

181

def move(self, library: Library, operation: str, basedir: str = None) -> None:

182

"""

183

Move or copy the item's file according to library path formats.

184

185

Parameters:

186

- library: Library instance for path formatting

187

- operation: 'move', 'copy', 'link', or 'reflink'

188

- basedir: Base directory for relative paths (optional)

189

"""

190

191

def remove(self, delete: bool = False, with_album: bool = True) -> None:

192

"""

193

Remove item from database and optionally delete file.

194

195

Parameters:

196

- delete: Whether to delete the physical file

197

- with_album: Whether to remove album if it becomes empty

198

"""

199

200

def formatted(self) -> Dict[str, str]:

201

"""

202

Get dictionary of formatted field values for display.

203

204

Returns:

205

Dictionary mapping field names to formatted string values

206

"""

207

```

208

209

#### Item Field Types

210

211

```python { .api }

212

# Core metadata fields with types

213

title: str # Track title

214

artist: str # Track artist

215

album: str # Album name

216

albumartist: str # Album artist (may differ from track artist)

217

track: int # Track number within album

218

disc: int # Disc number for multi-disc albums

219

year: int # Release year

220

month: int # Release month (1-12)

221

day: int # Release day (1-31)

222

genre: str # Musical genre

223

length: float # Duration in seconds

224

bitrate: int # Audio bitrate in kbps

225

samplerate: int # Sample rate in Hz

226

channels: int # Number of audio channels

227

format: str # Audio format (MP3, FLAC, etc.)

228

path: bytes # Filesystem path to file

229

mtime: float # File modification time (Unix timestamp)

230

added: float # Time added to library (Unix timestamp)

231

```

232

233

#### Usage Examples

234

235

```python

236

from beets.library import Item, Library

237

238

# Create item from file

239

item = Item.from_path('/path/to/song.mp3')

240

print(f"Title: {item.title}, Artist: {item.artist}")

241

print(f"Duration: {item.length} seconds")

242

243

# Modify metadata

244

item.year = 2024

245

item.genre = 'Rock'

246

item.store() # Save to database

247

248

# Write metadata to file

249

item.write()

250

251

# Move file according to library path format

252

lib = Library('/path/to/library.db', '/music')

253

item.move(lib, 'move') # Move file to organized location

254

255

# Access formatted values for display

256

formatted = item.formatted()

257

print(f"Formatted: {formatted['artist']} - {formatted['title']}")

258

```

259

260

### Album Class

261

262

Represents a collection of tracks as an album with album-level metadata and operations.

263

264

```python { .api }

265

class Album(Model):

266

# Album metadata fields

267

album: str

268

albumartist: str

269

year: int

270

month: int

271

day: int

272

genre: str

273

albumtotal: int # Total number of tracks

274

disctotal: int # Total number of discs

275

artpath: bytes # Path to album art file

276

277

def items(self) -> Results:

278

"""

279

Get all items (tracks) in this album.

280

281

Returns:

282

Results iterator over Item objects in album

283

"""

284

285

def add(self, library: Library) -> None:

286

"""

287

Add this album to a library database.

288

289

Parameters:

290

- library: Library instance to add to

291

"""

292

293

def store(self) -> None:

294

"""

295

Save album changes to the database.

296

"""

297

298

def remove(self, delete_items: bool = False) -> None:

299

"""

300

Remove album from database.

301

302

Parameters:

303

- delete_items: Whether to also remove all items in the album

304

"""

305

306

def art_destination(self, item: Item) -> str:

307

"""

308

Get the destination path for album art based on an item.

309

310

Parameters:

311

- item: Item in the album to base path on

312

313

Returns:

314

Filesystem path for album art file

315

"""

316

```

317

318

#### Usage Examples

319

320

```python

321

from beets.library import Album, Library

322

323

lib = Library('/path/to/library.db', '/music')

324

325

# Get albums

326

beatles_albums = lib.albums('artist:Beatles')

327

for album in beatles_albums:

328

print(f"Album: {album.album} ({album.year})")

329

330

# Get tracks in album

331

tracks = album.items()

332

print(f" {len(tracks)} tracks")

333

334

for item in tracks:

335

print(f" {item.track}. {item.title}")

336

337

# Create album from items

338

items = lib.items('album:"Abbey Road" artist:Beatles')

339

abbey_road = lib.add_album(list(items))

340

```

341

342

## Database Model Base

343

344

```python { .api }

345

class Model:

346

"""Base class for database models (Item and Album inherit from this)."""

347

348

def store(self) -> None:

349

"""Save object to database."""

350

351

def load(self) -> None:

352

"""Load object from database."""

353

354

def remove(self) -> None:

355

"""Remove object from database."""

356

357

def __getitem__(self, key: str) -> Any:

358

"""Get field value by name."""

359

360

def __setitem__(self, key: str, value: Any) -> None:

361

"""Set field value by name."""

362

363

def get(self, key: str, default: Any = None) -> Any:

364

"""Get field value with default fallback."""

365

```

366

367

## Results Iterator

368

369

```python { .api }

370

class Results:

371

"""Iterator over query results with additional functionality."""

372

373

def __len__(self) -> int:

374

"""Get count of results."""

375

376

def __iter__(self) -> Iterator:

377

"""Iterate over result objects."""

378

379

def get(self) -> Union[Item, Album, None]:

380

"""Get single result or None if no matches."""

381

```

382

383

## Error Handling

384

385

```python { .api }

386

class FileOperationError(Exception):

387

"""Raised when file operations fail."""

388

389

class DBAccessError(Exception):

390

"""Raised when database access fails."""

391

```

392

393

Common error scenarios:

394

- Database file permissions issues

395

- Corrupt audio files during metadata reading

396

- File system errors during move/copy operations

397

- Missing files when attempting operations