15 my $class=ref($proto) || $proto;
20 $self->{verbose}=shift;
24 my $fallbackdir=shift;
26 $self->{dbpath}=$self->find_db($init, $dbpath, $fallbackdir);
27 return undef unless($self->{dbpath});
28 $self->{absbase}=Cwd::abs_path($self->{base});
30 my $connectstr="dbi:SQLite:dbname=$self->{dbpath}";
31 my $exists=-f $self->{dbpath};
32 $self->{dbh}=DBI->connect($connectstr, undef, undef,
34 unless(defined($self->{dbh}))
36 die("$self->{me}: DB Error: " . $DBI::errstr . "\n");
47 $self->enable_foreign_keys();
53 my($self, $init, $dbpath, $fallbackdir)=@_;
60 if(defined ($self->{base}))
62 $file="$self->{base}/$dbfile" unless defined($file);
65 elsif(defined($fallbackdir) && -d $fallbackdir)
67 my $path=Cwd::abs_path($fallbackdir);
70 $file="$path/$dbfile";
72 $path=~s/(.*)\/.*/$1/;
74 while(! -f $file && length($path) && -d $path);
77 $file="$fallbackdir/$dbfile";
83 print "$self->{me}: $fallbackdir: not a directory\n";
86 if(!-f $file && !$init)
88 print "$self->{me}: db not found at $file\n";
95 sub base_dir { return shift->{base}; }
100 my @schema=split(/\n\n/,join("", <DATA>));
102 for my $cmd (@schema)
104 $self->{dbh}->do($cmd);
106 $self->cmd("INSERT INTO id3fs (schema_version, last_update) VALUES (?, ?)",
107 $SCHEMA_VERSION, time());
113 my ($version)=$self->cmd_onerow("SELECT schema_version from id3fs");
114 if(!defined($version) || $version != $SCHEMA_VERSION)
116 die("$self->{me}: id3fs database version " .
117 defined($version) ? $version : '""' .
118 "not known, current version is $SCHEMA_VERSION.\n");
125 $self->cmd("ANALYZE");
128 sub enable_foreign_keys
131 $self->cmd("PRAGMA foreign_keys = ON");
136 my($self, $newval)=@_;
139 $self->cmd("UPDATE id3fs SET last_update=?", $newval);
143 ($newval)=$self->cmd_onerow("SELECT last_update from id3fs");
151 my $sql=("SELECT tags.name FROM tags\n" .
152 "WHERE tags.parents_id=''\n" .
153 "GROUP BY tags.name\n");
154 my @names=$self->cmd_firstcol($sql);
161 my $sql=("SELECT p.name, t.name FROM tags t\n" .
162 "INNER JOIN tags p ON t.parents_id=p.id\n" .
163 "GROUP BY p.name, t.name\n");
164 # print "SQL: $sql\n";
165 my $result=$self->cmd_rows($sql);
167 for my $pair (@$result)
169 push(@{$tags->{$pair->[0]}}, $pair->[1]);
177 my $sql=("SELECT COUNT(*) FROM tags\n\t" .
178 "WHERE tags.parents_id=?\n");
179 my ($rows)=$self->cmd_onerow($sql, $id);
185 my($self, $path, $name, $mountpoint)=@_;
186 my $id3fs_path=$self->{dbpath};
187 $id3fs_path=~s/(.*)\/.*/$1/;
188 my $rpath="$self->{absbase}/$path";
189 my $vpath="$mountpoint/$id3fs_path";
190 my @path=split(/\//,$rpath);
191 my @rel=split(/\//,$vpath);
192 #absolute paths have empty first element due to leading /
193 shift(@path) if($path[0] eq "");
194 shift(@rel) if($rel[0] eq "");
195 if($path[0] ne $rel[0])
197 #no path in common, return absolute
198 print "FAIL: NO PATHS IN COMMON\n";
201 # f: /home/foo/bar/baz.mp3
202 # r: /home/ianb/music/albums
203 while(@path && @rel && ($path[0] eq $rel[0]))
210 my $upcount=scalar(@rel);
211 my $result="../" x $upcount;
212 $result .= join("/",@path);
220 my $relpath=Cwd::abs_path($path);
221 $relpath =~ s/^\Q$self->{absbase}\E\/?//;
222 my($filepart,$pathpart);
230 ($pathpart, $filepart) = ($relpath =~ /(.*)\/(.*)/);
232 my $file=ID3FS::AudioFile->new($path, $self->{me});
233 return unless(defined($file));
234 my $artist=$file->artist();
235 my $album=$file->album();
236 my $v1genre=$file->v1genre();
237 my $year=$file->year();
238 my $audiotype=$file->audiotype();
239 my @tags=$file->tags();
240 my $haspic=$file->haspic();
242 $artist=undef unless($self->ok($artist));
243 print "$self->{me}: $path: no artist tag defined\n" unless(defined($artist));
244 my $artist_id=$self->add_to_table("artists", $artist);
245 my $path_id=$self->add_to_table("paths", $pathpart);
246 $album=undef unless($self->ok($album));
247 if($self->{verbose} && !defined($album))
249 print "$self->{me}: $path: no album tag defined\n";
252 my $albums_id=$self->add_to_table("albums", $album);
253 my $file_id=$self->add_to_table("files", $filepart,
254 { "artists_id" => $artist_id,
255 "albums_id" => $albums_id,
256 "paths_id" => $path_id });
259 $self->add_tag($file_id, @$tag);
262 $year="UNKNOWN" unless($self->ok($year));
263 $self->add_tag($file_id, "year", $year);
264 if($year=~/^(\d\d\d)\d$/)
266 $self->add_tag($file_id, "decade", "${1}0s");
270 $self->add_tag($file_id, "decade", "UNKNOWN");
273 if($self->ok($v1genre))
275 $self->add_tag($file_id, "v1genre", $v1genre);
280 $self->add_tag($file_id, "haspic", undef);
286 my($self, $file_id, $tag, $value)=@_;
287 my $tag_id=$self->add_to_table("tags", $tag,
288 { "parents_id" => undef });
289 $self->add_relation("files_x_tags",
290 { "files_id" => $file_id,
291 "tags_id" => $tag_id });
292 if(defined($value) && length($value))
294 my $val_id=$self->add_to_table("tags", $value,
295 { "parents_id" => $tag_id });
296 $self->add_relation("files_x_tags",
297 { "files_id" => $file_id,
298 "tags_id" => $val_id });
304 my($self, $table, $name, $extradata)=@_;
306 if($extradata && $extradata->{parents_id})
308 $parent=$extradata->{parents_id};
310 my $id=$self->lookup_id($table, $name, $parent);
313 my $sql="INSERT INTO $table (";
315 if(defined($extradata))
317 push(@fields, sort keys(%$extradata));
319 $sql .= join(", ", @fields);
321 $sql .= join(", ", map { "?"; } @fields);
323 $id=$self->cmd_id($sql, $name, map { $extradata->{$_} || ""; } sort keys %$extradata);
330 my ($self, $relname, $fields)=@_;
331 return if($self->relation_exists($relname, $fields));
332 my $sql="INSERT INTO $relname (";
333 $sql .= join(", ", sort keys(%$fields));
334 $sql .= ") VALUES (";
335 $sql .= join(", ", map { "?"; } sort keys(%$fields));
337 $self->cmd($sql, map { $fields->{$_}; } sort keys(%$fields));
343 my $sql=("SELECT files.name FROM files\n" .
344 "INNER JOIN paths ON files.paths_id=paths.id\n" .
345 "WHERE paths.name=?\n");
346 # print "files_in: SQL: $sql\n";
347 return($self->cmd_firstcol($sql, $dir));
352 my($self, $path, $file)=@_;
353 my $sql=("DELETE FROM files WHERE id IN (" .
354 "\tSELECT files.id FROM files\n" .
355 "\tINNER JOIN paths ON paths.id=files.paths_id\n" .
356 "\tWHERE paths.name=? and files.name=? )\n");
357 $self->cmd_rows($sql, $path, $file);
361 sub prune_directories
364 my $sql=("SELECT name, id FROM paths\n");
365 my $pathsref=$self->cmd_rows($sql);
367 for my $pathpair (@$pathsref)
369 my($path, $id)=@$pathpair;
370 my $fullpath="$self->{absbase}/$path";
376 $self->prune_paths(@ids);
384 my $sql=("DELETE FROM files WHERE paths_id IN (\n\t" .
385 join(', ', map { "\"$_\""; } @ids). "\n\t)");
386 # print "SQL: \n", $sql, "\n";
394 DELETE FROM artists WHERE id IN (
395 SELECT artists.id FROM artists
396 LEFT JOIN files ON files.artists_id=artists.id
397 WHERE files.id IS NULL);
399 DELETE FROM albums WHERE id IN (
400 SELECT albums.id FROM albums
401 LEFT JOIN files ON files.albums_id=albums.id
402 WHERE files.id IS NULL);
404 DELETE FROM paths WHERE id IN (
405 SELECT paths.id FROM paths
406 LEFT JOIN files ON files.paths_id=paths.id
407 WHERE files.id IS NULL);
409 DELETE FROM files_x_tags WHERE files_id IN (
410 SELECT files_x_tags.files_id FROM files_x_tags
411 LEFT JOIN files ON files.id=files_x_tags.files_id
412 WHERE files.id IS NULL);
414 DELETE FROM tags WHERE id IN (
415 SELECT tags.id FROM tags
416 LEFT JOIN files_x_tags ON files_x_tags.tags_id=tags.id
417 WHERE files_x_tags.files_id IS NULL);
421 # print "SQL: $sql\n";
422 my @sql=split(/\n\n/, $sql);
423 $self->cmd($_) for (@sql);
428 my ($self, $relname, $fields)=@_;
429 my $sql="SELECT count(1) FROM $relname WHERE ";
432 for my $field (keys %$fields)
435 push(@vals,$fields->{$field});
437 $sql .= join(' AND ', map { "$_=?"; } @exprs);
438 my ($ret)=$self->cmd_onerow($sql, @vals);
444 my($self, $thing)=@_;
445 return(defined($thing) && length($thing) && $thing =~ /\S+/);
450 my($self, $sql, @params)=@_;
451 my $sth=$self->{dbh}->prepare($sql);
453 for my $param (@params)
455 $param="" unless(defined($param));
456 $sth->bind_param($idx++, $param);
464 my ($self, @args)=@_;
465 # don't care about retcode
466 $self->cmd_sth(@args);
471 my ($self, @args)=@_;
472 my $sth=$self->cmd_sth(@args);
473 return($sth->fetchrow_array());
478 my ($self, @args)=@_;
479 my $sth=$self->cmd_sth(@args);
480 return $sth->fetchall_arrayref();
485 my ($self, @args)=@_;
486 return(map { $_->[0] } @{$self->cmd_rows(@args)});
491 my ($self, @args)=@_;
492 $self->cmd_sth(@args);
493 return($self->last_insert_id());
499 return $self->{dbh}->last_insert_id("","","","");
504 my($self, $table, $name, $parent)=@_;
505 my $sql="SELECT id FROM $table where name=?";
509 $sql .= " AND parents_id=?";
510 push(@args, $parent);
512 my($id)=$self->cmd_onerow($sql, @args);
519 schema_version INTEGER,
529 CREATE TABLE artists (
535 CREATE TABLE albums (
547 PRIMARY KEY(id DESC),
548 FOREIGN KEY(artists_id) REFERENCES artists(id) ON DELETE CASCADE ON UPDATE CASCADE,
549 FOREIGN KEY(albums_id) REFERENCES albums(id) ON DELETE CASCADE ON UPDATE CASCADE,
550 FOREIGN KEY(paths_id) REFERENCES paths(id) ON DELETE CASCADE ON UPDATE CASCADE
560 CREATE TABLE files_x_tags (
563 FOREIGN KEY(files_id) REFERENCES files(id) ON DELETE CASCADE ON UPDATE CASCADE,
564 FOREIGN KEY(tags_id) REFERENCES tags(id) ON DELETE CASCADE ON UPDATE CASCADE
567 CREATE INDEX idx_fxt_both ON files_x_tags (files_id, tags_id)
569 CREATE INDEX idx_fxt_tags ON files_x_tags (tags_id)
571 CREATE INDEX idx_files_id_name ON files (id, name)
573 CREATE INDEX idx_files_name_id ON files (name, id)
575 CREATE INDEX idx_tags_id_parent_name ON tags (id, parents_id, name)
577 CREATE INDEX idx_tags_parent_id_name ON tags (parents_id, id, name)
579 CREATE INDEX idx_tags_name ON tags (name)