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);
160 # FIXME: only shows one level of tag depth
162 my $sql=("SELECT p.name, t.name FROM tags t\n" .
163 "INNER JOIN tags p ON t.parents_id=p.id\n" .
164 "GROUP BY p.name, t.name\n");
165 # print "SQL: $sql\n";
166 my $result=$self->cmd_rows($sql);
168 for my $pair (@$result)
170 push(@{$tags->{$pair->[0]}}, $pair->[1]);
178 my $sql=("SELECT COUNT(*) FROM tags\n\t" .
179 "WHERE tags.parents_id=?\n");
180 my ($rows)=$self->cmd_onerow($sql, $id);
186 my($self, $path, $name, $mountpoint)=@_;
187 my $id3fs_path=$self->{dbpath};
188 $id3fs_path=~s/(.*)\/.*/$1/;
189 my $rpath="$self->{absbase}/$path";
190 my $vpath="$mountpoint/$id3fs_path";
191 my @path=split(/\//,$rpath);
192 my @rel=split(/\//,$vpath);
193 #absolute paths have empty first element due to leading /
194 shift(@path) if($path[0] eq "");
195 shift(@rel) if($rel[0] eq "");
196 if($path[0] ne $rel[0])
198 #no path in common, return absolute
199 print "FAIL: NO PATHS IN COMMON\n";
202 # f: /home/foo/bar/baz.mp3
203 # r: /home/ianb/music/albums
204 while(@path && @rel && ($path[0] eq $rel[0]))
211 my $upcount=scalar(@rel);
212 my $result="../" x $upcount;
213 $result .= join("/",@path);
221 my $relpath=Cwd::abs_path($path);
222 $relpath =~ s/^\Q$self->{absbase}\E\/?//;
223 my($filepart,$pathpart);
231 ($pathpart, $filepart) = ($relpath =~ /(.*)\/(.*)/);
233 my $file=ID3FS::AudioFile->new($path, $self->{me});
234 return unless(defined($file));
235 my $artist=$file->artist();
236 my $album=$file->album();
237 my $v1genre=$file->v1genre();
238 my $year=$file->year();
239 my $audiotype=$file->audiotype();
240 my @tags=$file->tags();
241 my $haspic=$file->haspic();
243 $artist=undef unless($self->ok($artist));
244 print "$self->{me}: $path: no artist tag defined\n" unless(defined($artist));
245 my $artist_id=$self->add_to_table("artists", $artist);
246 my $path_id=$self->add_to_table("paths", $pathpart);
247 $album=undef unless($self->ok($album));
248 if($self->{verbose} && !defined($album))
250 print "$self->{me}: $path: no album tag defined\n";
253 my $albums_id=$self->add_to_table("albums", $album);
254 my $file_id=$self->add_to_table("files", $filepart,
255 { "artists_id" => $artist_id,
256 "albums_id" => $albums_id,
257 "paths_id" => $path_id });
260 $self->add_tag($file_id, @$tag);
263 $year="UNKNOWN" unless($self->ok($year));
264 $self->add_tag($file_id, "year", $year);
265 if($year=~/^(\d\d\d)\d$/)
267 $self->add_tag($file_id, "decade", "${1}0s");
271 $self->add_tag($file_id, "decade", "UNKNOWN");
274 if($self->ok($v1genre))
276 $self->add_tag($file_id, "v1genre", $v1genre);
281 $self->add_tag($file_id, "haspic", undef);
287 my($self, $file_id, $tag, $value)=@_;
288 my $tag_id=$self->add_to_table("tags", $tag,
289 { "parents_id" => undef });
290 $self->add_relation("files_x_tags",
291 { "files_id" => $file_id,
292 "tags_id" => $tag_id });
293 if(defined($value) && length($value))
295 my $val_id=$self->add_to_table("tags", $value,
296 { "parents_id" => $tag_id });
297 $self->add_relation("files_x_tags",
298 { "files_id" => $file_id,
299 "tags_id" => $val_id });
305 my($self, $table, $name, $extradata)=@_;
307 if($extradata && $extradata->{parents_id})
309 $parent=$extradata->{parents_id};
311 my $id=$self->lookup_id($table, $name, $parent);
314 my $sql="INSERT INTO $table (";
316 if(defined($extradata))
318 push(@fields, sort keys(%$extradata));
320 $sql .= join(", ", @fields);
322 $sql .= join(", ", map { "?"; } @fields);
324 $id=$self->cmd_id($sql, $name, map { $extradata->{$_} || ""; } sort keys %$extradata);
331 my ($self, $relname, $fields)=@_;
332 return if($self->relation_exists($relname, $fields));
333 my $sql="INSERT INTO $relname (";
334 $sql .= join(", ", sort keys(%$fields));
335 $sql .= ") VALUES (";
336 $sql .= join(", ", map { "?"; } sort keys(%$fields));
338 $self->cmd($sql, map { $fields->{$_}; } sort keys(%$fields));
344 my $sql=("SELECT files.name FROM files\n" .
345 "INNER JOIN paths ON files.paths_id=paths.id\n" .
346 "WHERE paths.name=?\n");
347 # print "files_in: SQL: $sql\n";
348 return($self->cmd_firstcol($sql, $dir));
353 my($self, $path, $file)=@_;
354 my $sql=("DELETE FROM files WHERE id IN (" .
355 "\tSELECT files.id FROM files\n" .
356 "\tINNER JOIN paths ON paths.id=files.paths_id\n" .
357 "\tWHERE paths.name=? and files.name=? )\n");
358 $self->cmd_rows($sql, $path, $file);
362 sub prune_directories
365 my $sql=("SELECT name, id FROM paths\n");
366 my $pathsref=$self->cmd_rows($sql);
368 for my $pathpair (@$pathsref)
370 my($path, $id)=@$pathpair;
371 my $fullpath="$self->{absbase}/$path";
377 $self->prune_paths(@ids);
385 my $sql=("DELETE FROM files WHERE paths_id IN (\n\t" .
386 join(', ', map { "\"$_\""; } @ids). "\n\t)");
387 # print "SQL: \n", $sql, "\n";
395 DELETE FROM artists WHERE id IN (
396 SELECT artists.id FROM artists
397 LEFT JOIN files ON files.artists_id=artists.id
398 WHERE files.id IS NULL);
400 DELETE FROM albums WHERE id IN (
401 SELECT albums.id FROM albums
402 LEFT JOIN files ON files.albums_id=albums.id
403 WHERE files.id IS NULL);
405 DELETE FROM paths WHERE id IN (
406 SELECT paths.id FROM paths
407 LEFT JOIN files ON files.paths_id=paths.id
408 WHERE files.id IS NULL);
410 DELETE FROM files_x_tags WHERE files_id IN (
411 SELECT files_x_tags.files_id FROM files_x_tags
412 LEFT JOIN files ON files.id=files_x_tags.files_id
413 WHERE files.id IS NULL);
415 DELETE FROM tags WHERE id IN (
416 SELECT tags.id FROM tags
417 LEFT JOIN files_x_tags ON files_x_tags.tags_id=tags.id
418 WHERE files_x_tags.files_id IS NULL);
422 # print "SQL: $sql\n";
423 my @sql=split(/\n\n/, $sql);
424 $self->cmd($_) for (@sql);
429 my ($self, $relname, $fields)=@_;
430 my $sql="SELECT count(1) FROM $relname WHERE ";
433 for my $field (keys %$fields)
436 push(@vals,$fields->{$field});
438 $sql .= join(' AND ', map { "$_=?"; } @exprs);
439 my ($ret)=$self->cmd_onerow($sql, @vals);
445 my($self, $thing)=@_;
446 return(defined($thing) && length($thing) && $thing =~ /\S+/);
451 my($self, $sql, @params)=@_;
452 my $sth=$self->{dbh}->prepare($sql);
454 for my $param (@params)
456 $param="" unless(defined($param));
457 $sth->bind_param($idx++, $param);
465 my ($self, @args)=@_;
466 # don't care about retcode
467 $self->cmd_sth(@args);
472 my ($self, @args)=@_;
473 my $sth=$self->cmd_sth(@args);
474 return($sth->fetchrow_array());
479 my ($self, @args)=@_;
480 my $sth=$self->cmd_sth(@args);
481 return $sth->fetchall_arrayref();
486 my ($self, @args)=@_;
487 return(map { $_->[0] } @{$self->cmd_rows(@args)});
492 my ($self, @args)=@_;
493 $self->cmd_sth(@args);
494 return($self->last_insert_id());
500 return $self->{dbh}->last_insert_id("","","","");
505 my($self, $table, $name, $parent)=@_;
506 my $sql="SELECT id FROM $table where name=?";
510 $sql .= " AND parents_id=?";
511 push(@args, $parent);
513 my($id)=$self->cmd_onerow($sql, @args);
520 schema_version INTEGER,
530 CREATE TABLE artists (
536 CREATE TABLE albums (
548 PRIMARY KEY(id DESC),
549 FOREIGN KEY(artists_id) REFERENCES artists(id) ON DELETE CASCADE ON UPDATE CASCADE,
550 FOREIGN KEY(albums_id) REFERENCES albums(id) ON DELETE CASCADE ON UPDATE CASCADE,
551 FOREIGN KEY(paths_id) REFERENCES paths(id) ON DELETE CASCADE ON UPDATE CASCADE
561 CREATE TABLE files_x_tags (
564 FOREIGN KEY(files_id) REFERENCES files(id) ON DELETE CASCADE ON UPDATE CASCADE,
565 FOREIGN KEY(tags_id) REFERENCES tags(id) ON DELETE CASCADE ON UPDATE CASCADE
568 CREATE INDEX idx_fxt_both ON files_x_tags (files_id, tags_id)
570 CREATE INDEX idx_fxt_tags ON files_x_tags (tags_id)
572 CREATE INDEX idx_files_id_name ON files (id, name)
574 CREATE INDEX idx_files_name_id ON files (name, id)
576 CREATE INDEX idx_tags_id_parent_name ON tags (id, parents_id, name)
578 CREATE INDEX idx_tags_parent_id_name ON tags (parents_id, id, name)
580 CREATE INDEX idx_tags_name ON tags (name)