15 my $class=ref($proto) || $proto;
20 $self->{verbose}=shift;
24 my $fallbackdir=shift;
26 $dbpath=$self->find_db($init, $dbpath, $fallbackdir);
27 return undef unless($dbpath);
28 $self->{absbase}=Cwd::abs_path($self->{base});
30 my $connectstr="dbi:SQLite:dbname=$dbpath";
31 my ($user, $pass)=("", "");
34 $connectstr="dbi:Pg:dbname=id3fs";
38 my $exists=-f $dbpath;
39 $self->{dbh}=DBI->connect($connectstr, $user, $pass,
41 unless(defined($self->{dbh}))
43 die("$self->{me}: DB Error: " . $DBI::errstr . "\n");
54 $self->enable_foreign_keys();
60 my($self, $init, $dbpath, $fallbackdir)=@_;
67 if(defined ($self->{base}))
69 $file="$self->{base}/$dbfile" unless defined($file);
72 elsif(defined($fallbackdir) && -d $fallbackdir)
74 my $path=Cwd::abs_path($fallbackdir);
77 $file="$path/$dbfile";
79 $path=~s/(.*)\/.*/$1/;
81 while(! -f $file && length($path) && -d $path);
84 $file="$fallbackdir/$dbfile";
90 print "$self->{me}: $fallbackdir: not a directory\n";
93 if(!-f $file && !$init)
95 print "$self->{me}: db not found at $file\n";
102 sub base_dir { return shift->{base}; }
107 my @schema=split(/\n\n/,join("", <DATA>));
109 for my $cmd (@schema)
111 $self->{dbh}->do($cmd);
113 if($self->{postgres})
115 $self->cmd("CREATE SEQUENCE seq");
119 my %indexes=( "idx_files_id" => "files (id)",
120 "idx_fxt_both" => "files_x_tags (files_id, tags_id)",
121 "idx_fxt_files" => "files_x_tags (files_id)",
122 "idx_fxt_tags" => "files_x_tags (tags_id)",
123 "idx_tags_id" => "tags (id)",
124 "idx_tags_name" => "tags (name)");
125 for my $index (keys %indexes)
127 $self->{dbh}->do("CREATE INDEX $index ON " . $indexes{$index});
130 $self->cmd("INSERT INTO id3fs (schema_version, last_update) VALUES (?, ?)",
131 $SCHEMA_VERSION, time());
137 my ($version)=$self->cmd_onerow("SELECT schema_version from id3fs");
138 if(!defined($version) || $version != $SCHEMA_VERSION)
140 die("$self->{me}: id3fs database version " .
141 defined($version) ? $version : '""' .
142 "not known, current version is $SCHEMA_VERSION.\n");
149 $self->cmd("ANALYZE");
152 sub enable_foreign_keys
155 $self->cmd("PRAGMA foreign_keys = ON");
160 my($self, $newval)=@_;
163 $self->cmd("UPDATE id3fs SET last_update=?", $newval);
167 ($newval)=$self->cmd_onerow("SELECT last_update from id3fs");
175 my $sql=("SELECT tags.name FROM tags\n" .
176 "WHERE tags.parents_id=''\n" .
177 "GROUP BY tags.name\n");
178 my @names=$self->cmd_firstcol($sql);
184 # FIXME: only shows one level of tag depth
186 my $sql=("SELECT p.name, t.name FROM tags t\n" .
187 "INNER JOIN tags p ON t.parents_id=p.id\n" .
188 "GROUP BY p.name, t.name\n");
189 # print "SQL: $sql\n";
190 my $result=$self->cmd_rows($sql);
192 for my $pair (@$result)
194 push(@{$tags->{$pair->[0]}}, $pair->[1]);
202 my $sql=("SELECT COUNT(*) FROM tags\n\t" .
203 "WHERE tags.parents_id=?\n");
204 my ($rows)=$self->cmd_onerow($sql, $id);
210 my($self, $path, $name, $mountpoint, $id3fs_path)=@_;
211 $id3fs_path=~s/(.*)\/.*/$1/;
212 my $rpath="$self->{absbase}/$path";
213 my $vpath="$mountpoint/$id3fs_path";
214 my @path=split(/\//,$rpath);
215 my @rel=split(/\//,$vpath);
216 #absolute paths have empty first element due to leading /
217 shift(@path) if($path[0] eq "");
218 shift(@rel) if($rel[0] eq "");
219 if($path[0] ne $rel[0])
221 #no path in common, return absolute
222 print "FAIL: NO PATHS IN COMMON\n";
225 # f: /home/foo/bar/baz.mp3
226 # r: /home/ianb/music/albums
227 while(@path && @rel && ($path[0] eq $rel[0]))
234 my $upcount=scalar(@rel);
235 my $result="../" x $upcount;
236 $result .= join("/",@path);
244 my $relpath=Cwd::abs_path($path);
245 $relpath =~ s/^\Q$self->{absbase}\E\/?//;
246 my($filepart,$pathpart);
254 ($pathpart, $filepart) = ($relpath =~ /(.*)\/(.*)/);
256 my $file=ID3FS::AudioFile->new($path, $self->{me});
257 return unless(defined($file));
258 my $artist=$file->artist();
259 my $album=$file->album();
260 my $v1genre=$file->v1genre();
261 my $year=$file->year();
262 my $audiotype=$file->audiotype();
263 my @tags=$file->tags();
264 my $haspic=$file->haspic();
266 $artist=undef unless($self->ok($artist));
267 print "$self->{me}: $path: no artist tag defined\n" unless(defined($artist));
268 my $artist_id=$self->add_to_table("artists", $artist);
269 my $path_id=$self->add_to_table("paths", $pathpart);
270 $album=undef unless($self->ok($album));
271 if($self->{verbose} && !defined($album))
273 print "$self->{me}: $path: no album tag defined\n";
276 my $albums_id=$self->add_to_table("albums", $album);
277 my $file_id=$self->add_to_table("files", $filepart,
278 { "artists_id" => $artist_id,
279 "albums_id" => $albums_id,
280 "paths_id" => $path_id });
283 $self->add_tag($file_id, @$tag);
286 $year="UNKNOWN" unless($self->ok($year));
287 $self->add_tag($file_id, "year", $year);
288 if($year=~/^(\d\d\d)\d$/)
290 $self->add_tag($file_id, "decade", "${1}0s");
294 $self->add_tag($file_id, "decade", "UNKNOWN");
297 if($self->ok($v1genre))
299 $self->add_tag($file_id, "v1genre", $v1genre);
304 $self->add_tag($file_id, "haspic", undef);
310 my($self, $file_id, $tag, $value)=@_;
311 my $tag_id=$self->add_to_table("tags", $tag,
312 { "parents_id" => undef });
313 $self->add_relation("files_x_tags",
314 { "files_id" => $file_id,
315 "tags_id" => $tag_id });
316 if(defined($value) && length($value))
318 my $val_id=$self->add_to_table("tags", $value,
319 { "parents_id" => $tag_id });
320 $self->add_relation("files_x_tags",
321 { "files_id" => $file_id,
322 "tags_id" => $val_id });
328 my($self, $table, $name, $extradata)=@_;
330 if($extradata && $extradata->{parents_id})
332 $parent=$extradata->{parents_id};
334 my $id=$self->lookup_id($table, $name, $parent);
337 my $sql="INSERT INTO $table (";
338 $sql .= "id, " if($self->{postgres});
340 if(defined($extradata))
342 push(@fields, sort keys(%$extradata));
344 $sql .= join(", ", @fields);
346 $sql .=") nextval('seq'), " if($self->{postgres});
347 $sql .= join(", ", map { "?"; } @fields);
349 $id=$self->cmd_id($sql, $name, map { $extradata->{$_} || ""; } sort keys %$extradata);
356 my ($self, $relname, $fields)=@_;
357 return if($self->relation_exists($relname, $fields));
358 my $sql="INSERT INTO $relname (";
359 $sql .= join(", ", sort keys(%$fields));
360 $sql .= ") VALUES (";
361 $sql .= join(", ", map { "?"; } sort keys(%$fields));
363 $self->cmd($sql, map { $fields->{$_}; } sort keys(%$fields));
369 my $sql=("SELECT files.name FROM files\n" .
370 "INNER JOIN paths ON files.paths_id=paths.id\n" .
371 "WHERE paths.name=?\n");
372 # print "files_in: SQL: $sql\n";
373 return($self->cmd_firstcol($sql, $dir));
378 my($self, $path, $file)=@_;
379 my $sql=("DELETE FROM files WHERE id IN (" .
380 "\tSELECT files.id FROM files\n" .
381 "\tINNER JOIN paths ON paths.id=files.paths_id\n" .
382 "\tWHERE paths.name=? and files.name=? )\n");
383 $self->cmd_rows($sql, $path, $file);
387 sub prune_directories
390 my $sql=("SELECT name, id FROM paths ORDER BY name\n");
391 my $pathsref=$self->cmd_rows($sql);
393 for my $pathpair (@$pathsref)
395 my($path, $id)=@$pathpair;
396 my $fullpath="$self->{absbase}/$path";
402 $self->prune_paths(@ids);
410 my $sql=("DELETE FROM files WHERE paths_id IN (\n\t" .
411 join(', ', map { "\"$_\""; } @ids). "\n\t)");
412 # print "SQL: \n", $sql, "\n";
420 DELETE FROM artists WHERE id IN (
421 SELECT artists.id FROM artists
422 LEFT JOIN files ON files.artists_id=artists.id
423 WHERE files.id IS NULL);
425 DELETE FROM albums WHERE id IN (
426 SELECT albums.id FROM albums
427 LEFT JOIN files ON files.albums_id=albums.id
428 WHERE files.id IS NULL);
430 DELETE FROM paths WHERE id IN (
431 SELECT paths.id FROM paths
432 LEFT JOIN files ON files.paths_id=paths.id
433 WHERE files.id IS NULL);
435 DELETE FROM files_x_tags WHERE files_id IN (
436 SELECT files_x_tags.files_id FROM files_x_tags
437 LEFT JOIN files ON files.id=files_x_tags.files_id
438 WHERE files.id IS NULL);
440 DELETE FROM tags WHERE id IN (
441 SELECT tags.id FROM tags
442 LEFT JOIN files_x_tags ON files_x_tags.tags_id=tags.id
443 WHERE files_x_tags.files_id IS NULL);
447 # print "SQL: $sql\n";
448 my @sql=split(/\n\n/, $sql);
449 $self->cmd($_) for (@sql);
454 my ($self, $relname, $fields)=@_;
455 my $sql="SELECT count(1) FROM $relname WHERE ";
458 for my $field (keys %$fields)
461 push(@vals,$fields->{$field});
463 $sql .= join(' AND ', map { "$_=?"; } @exprs);
464 my ($ret)=$self->cmd_onerow($sql, @vals);
470 my($self, $thing)=@_;
471 return(defined($thing) && length($thing) && $thing =~ /\S+/);
476 my($self, $sql, @params)=@_;
477 my $sth=$self->{dbh}->prepare($sql);
479 for my $param (@params)
481 $param="" unless(defined($param));
482 $sth->bind_param($idx++, $param);
490 my ($self, @args)=@_;
491 # don't care about retcode
492 $self->cmd_sth(@args);
497 my ($self, @args)=@_;
498 my $sth=$self->cmd_sth(@args);
499 return($sth->fetchrow_array());
504 my ($self, @args)=@_;
505 my $sth=$self->cmd_sth(@args);
506 return $sth->fetchall_arrayref();
511 my ($self, @args)=@_;
512 return(map { $_->[0] } @{$self->cmd_rows(@args)});
517 my ($self, @args)=@_;
518 $self->cmd_sth(@args);
519 return($self->last_insert_id());
525 if($self->{postgres})
527 return $self->{dbh}->last_insert_id(undef, undef, undef, undef,
528 { sequence => "seq" });
532 return $self->{dbh}->last_insert_id("","","","");
538 my($self, $table, $name, $parent)=@_;
539 my $sql="SELECT id FROM $table where name=?";
543 $sql .= " AND parents_id=?";
544 push(@args, $parent);
546 my($id)=$self->cmd_onerow($sql, @args);
553 schema_version INTEGER,
563 CREATE TABLE artists (
569 CREATE TABLE albums (
581 PRIMARY KEY(id DESC),
582 FOREIGN KEY(artists_id) REFERENCES artists(id) ON DELETE CASCADE ON UPDATE CASCADE,
583 FOREIGN KEY(albums_id) REFERENCES albums(id) ON DELETE CASCADE ON UPDATE CASCADE,
584 FOREIGN KEY(paths_id) REFERENCES paths(id) ON DELETE CASCADE ON UPDATE CASCADE
594 CREATE TABLE files_x_tags (
597 FOREIGN KEY(files_id) REFERENCES files(id) ON DELETE CASCADE ON UPDATE CASCADE,
598 FOREIGN KEY(tags_id) REFERENCES tags(id) ON DELETE CASCADE ON UPDATE CASCADE