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";
88 if(!-f $file && !$init)
90 print "$self->{me}: db not found at $file\n";
97 sub base_dir { return shift->{base}; }
102 my @schema=split(/\n\n/,join("", <DATA>));
104 for my $cmd (@schema)
106 $self->{dbh}->do($cmd);
108 if($self->{postgres})
110 $self->cmd("CREATE SEQUENCE seq");
114 my %indexes=( "idx_files_id" => "files (id)",
115 "idx_fxt_both" => "files_x_tags (files_id, tags_id)",
116 "idx_fxt_files" => "files_x_tags (files_id)",
117 "idx_fxt_tags" => "files_x_tags (tags_id)",
118 "idx_tags_id" => "tags (id)",
119 "idx_tags_name" => "tags (name)");
120 for my $index (keys %indexes)
122 $self->{dbh}->do("CREATE INDEX $index ON " . $indexes{$index});
125 $self->cmd("INSERT INTO id3fs (schema_version, last_update) VALUES (?, ?)",
126 $SCHEMA_VERSION, time());
132 my ($version)=$self->cmd_onerow("SELECT schema_version from id3fs");
133 if(!defined($version) || $version != $SCHEMA_VERSION)
135 die("$self->{me}: id3fs database version " .
136 defined($version) ? $version : '""' .
137 "not known, current version is $SCHEMA_VERSION.\n");
144 $self->cmd("ANALYZE");
147 sub enable_foreign_keys
150 $self->cmd("PRAGMA foreign_keys = ON");
155 my($self, $newval)=@_;
158 $self->cmd("UPDATE id3fs SET last_update=?", $newval);
162 ($newval)=$self->cmd_onerow("SELECT last_update from id3fs");
169 my($self, $type, $val)=@_;
170 my $sql="SELECT id FROM $type WHERE name=?";
171 my ($id)=$self->cmd_onerow($sql, $val);
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, $id3fs_path)=@_;
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);
221 $relpath =~ s/^\Q$self->{base}\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);
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 if($self->ok($v1genre))
273 $self->add_tag($file_id, "v1genre", $v1genre);
278 $self->add_tag($file_id, "haspic", undef);
284 my($self, $file_id, $tag, $value)=@_;
285 my $tag_id=$self->add_to_table("tags", $tag,
286 { "parents_id" => undef });
287 $self->add_relation("files_x_tags",
288 { "files_id" => $file_id,
289 "tags_id" => $tag_id });
290 if(defined($value) && length($value))
292 my $val_id=$self->add_to_table("tags", $value,
293 { "parents_id" => $tag_id });
294 $self->add_relation("files_x_tags",
295 { "files_id" => $file_id,
296 "tags_id" => $val_id });
302 my($self, $table, $name, $extradata)=@_;
303 my $id=$self->lookup_id($table, $name);
306 my $sql="INSERT INTO $table (";
307 $sql .= "id, " if($self->{postgres});
309 if(defined($extradata))
311 push(@fields, sort keys(%$extradata));
313 $sql .= join(", ", @fields);
315 $sql .=") nextval('seq'), " if($self->{postgres});
316 $sql .= join(", ", map { "?"; } @fields);
318 $id=$self->cmd_id($sql, $name, map { $extradata->{$_} || ""; } sort keys %$extradata);
325 my ($self, $relname, $fields)=@_;
326 return if($self->relation_exists($relname, $fields));
327 my $sql="INSERT INTO $relname (";
328 $sql .= join(", ", sort keys(%$fields));
329 $sql .= ") VALUES (";
330 $sql .= join(", ", map { "?"; } sort keys(%$fields));
332 $self->cmd($sql, map { $fields->{$_}; } sort keys(%$fields));
338 $dir=~s/^$self->{base}\/?//;
339 my $sql=("SELECT files.name FROM files\n" .
340 "INNER JOIN paths ON files.paths_id=paths.id\n" .
341 "WHERE paths.name=?\n");
342 my $files=$self->cmd_rows($sql, $dir);
343 return(map { $_->[0]; } @$files);
346 sub prune_directories
349 my $sql=("SELECT name, id FROM paths ORDER BY name\n");
350 my $pathsref=$self->cmd_rows($sql);
352 for my $pathpair (@$pathsref)
354 my($path, $id)=@$pathpair;
355 my $fullpath="$self->{absbase}/$path";
361 $self->prune_paths(@ids);
369 my $sql=("DELETE FROM files WHERE paths_id IN (\n\t" .
370 join(', ', map { "\"$_\""; } @ids). "\n\t)");
371 print "SQL: \n", $sql, "\n";
379 DELETE FROM artists WHERE id IN (
380 SELECT artists.id FROM artists
381 LEFT JOIN files ON files.artists_id=artists.id
382 WHERE files.id IS NULL);
384 DELETE FROM albums WHERE id IN (
385 SELECT albums.id FROM albums
386 LEFT JOIN files ON files.albums_id=albums.id
387 WHERE files.id IS NULL);
389 DELETE FROM paths WHERE id IN (
390 SELECT paths.id FROM paths
391 LEFT JOIN files ON files.paths_id=paths.id
392 WHERE files.id IS NULL);
394 DELETE FROM files_x_tags WHERE files_id IN (
395 SELECT files_x_tags.files_id FROM files_x_tags
396 LEFT JOIN files ON files.id=files_x_tags.files_id
397 WHERE files.id IS NULL);
399 DELETE FROM tags WHERE id IN (
400 SELECT tags.id FROM tags
401 LEFT JOIN files_x_tags ON files_x_tags.tags_id=tags.id
402 WHERE files_x_tags.files_id IS NULL);
407 my @sql=split(/\n\n/, $sql);
408 $self->cmd($_) for (@sql);
413 my ($self, $relname, $fields)=@_;
414 my $sql="SELECT count(1) FROM $relname WHERE ";
417 for my $field (keys %$fields)
420 push(@vals,$fields->{$field});
422 $sql .= join(' AND ', map { "$_=?"; } @exprs);
423 my ($ret)=$self->cmd_onerow($sql, @vals);
429 my($self, $thing)=@_;
430 return(defined($thing) && length($thing) && $thing =~ /\S+/);
435 my($self, $sql, @params)=@_;
436 my $sth=$self->{dbh}->prepare($sql);
438 for my $param (@params)
440 $param="" unless(defined($param));
441 $sth->bind_param($idx++, $param);
449 my ($self, @args)=@_;
450 # don't care about retcode
451 $self->cmd_sth(@args);
456 my ($self, @args)=@_;
457 my $sth=$self->cmd_sth(@args);
458 return($sth->fetchrow_array());
463 my ($self, @args)=@_;
464 my $sth=$self->cmd_sth(@args);
465 return $sth->fetchall_arrayref();
470 my ($self, @args)=@_;
471 return(map { $_->[0] } @{$self->cmd_rows(@args)});
476 my ($self, @args)=@_;
477 $self->cmd_sth(@args);
478 return($self->last_insert_id());
484 if($self->{postgres})
486 return $self->{dbh}->last_insert_id(undef, undef, undef, undef,
487 { sequence => "seq" });
491 return $self->{dbh}->last_insert_id("","","","");
498 schema_version INTEGER,
503 id INTEGER PRIMARY KEY,
507 CREATE TABLE artists (
508 id INTEGER PRIMARY KEY,
512 CREATE TABLE albums (
513 id INTEGER PRIMARY KEY,
518 id INTEGER PRIMARY KEY,
523 FOREIGN KEY(artists_id) REFERENCES artists(id) ON DELETE CASCADE ON UPDATE CASCADE,
524 FOREIGN KEY(albums_id) REFERENCES albums(id) ON DELETE CASCADE ON UPDATE CASCADE,
525 FOREIGN KEY(paths_id) REFERENCES paths(id) ON DELETE CASCADE ON UPDATE CASCADE
529 id INTEGER PRIMARY KEY,
534 CREATE TABLE files_x_tags (
537 FOREIGN KEY(files_id) REFERENCES files(id) ON DELETE CASCADE ON UPDATE CASCADE,
538 FOREIGN KEY(tags_id) REFERENCES tags(id) ON DELETE CASCADE ON UPDATE CASCADE