-- Named media libraries. audio_files points at a library by id instead of -- repeating the root path in every row. CREATE TABLE libraries ( id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, name TEXT NOT NULL, path TEXT NOT NULL UNIQUE, -- absolute directory created_at BIGINT NOT NULL -- unix seconds ); -- Case-insensitive uniqueness (SQLite uses COLLATE NOCASE for the same effect). CREATE UNIQUE INDEX libraries_name_lower ON libraries (lower(name)); -- Existing data: every distinct root becomes a library, named after its path. -- Names are unique ignoring case, and on Linux /Music and /music are two -- directories, so the second one gets a suffix. Admins can rename them later. INSERT INTO libraries (name, path, created_at) SELECT CASE WHEN n = 1 THEN root ELSE root || ' (' || n || ')' END, root, extract(epoch FROM now())::bigint FROM (SELECT root, ROW_NUMBER() OVER (PARTITION BY lower(root) ORDER BY root) AS n FROM (SELECT DISTINCT root FROM audio_files) AS roots) AS numbered; ALTER TABLE audio_files ADD COLUMN library_id BIGINT REFERENCES libraries(id) ON DELETE CASCADE; UPDATE audio_files f SET library_id = l.id FROM libraries l WHERE l.path = f.root; ALTER TABLE audio_files ALTER COLUMN library_id SET NOT NULL; -- Dropping the column also drops UNIQUE (root, rel_path). ALTER TABLE audio_files DROP COLUMN root; ALTER TABLE audio_files ADD CONSTRAINT audio_files_library_rel_path_key UNIQUE (library_id, rel_path); CREATE INDEX idx_audio_files_library ON audio_files(library_id);