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);
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");
269 if($self->ok($v1genre))
271 $self->add_tag($file_id, "v1genre", $v1genre);
276 $self->add_tag($file_id, "haspic", undef);
282 my($self, $file_id, $tag, $value)=@_;
283 my $tag_id=$self->add_to_table("tags", $tag,
284 { "parents_id" => undef });
285 $self->add_relation("files_x_tags",
286 { "files_id" => $file_id,
287 "tags_id" => $tag_id });
288 if(defined($value) && length($value))
290 my $val_id=$self->add_to_table("tags", $value,
291 { "parents_id" => $tag_id });
292 $self->add_relation("files_x_tags",
293 { "files_id" => $file_id,
294 "tags_id" => $val_id });
300 my($self, $table, $name, $extradata)=@_;
301 my $id=$self->lookup_id($table, $name);
304 my $sql="INSERT INTO $table (";
305 $sql .= "id, " if($self->{postgres});
307 if(defined($extradata))
309 push(@fields, sort keys(%$extradata));
311 $sql .= join(", ", @fields);
313 $sql .=") nextval('seq'), " if($self->{postgres});
314 $sql .= join(", ", map { "?"; } @fields);
316 $id=$self->cmd_id($sql, $name, map { $extradata->{$_} || ""; } sort keys %$extradata);
323 my ($self, $relname, $fields)=@_;
324 return if($self->relation_exists($relname, $fields));
325 my $sql="INSERT INTO $relname (";
326 $sql .= join(", ", sort keys(%$fields));
327 $sql .= ") VALUES (";
328 $sql .= join(", ", map { "?"; } sort keys(%$fields));
330 $self->cmd($sql, map { $fields->{$_}; } sort keys(%$fields));
336 $dir=~s/^$self->{base}\/?//;
337 my $sql=("SELECT files.name FROM files\n" .
338 "INNER JOIN paths ON files.paths_id=paths.id\n" .
339 "WHERE paths.name=?\n");
340 my $files=$self->cmd_rows($sql, $dir);
341 return(map { $_->[0]; } @$files);
344 sub prune_directories
347 my $sql=("SELECT name, id FROM paths ORDER BY name\n");
348 my $pathsref=$self->cmd_rows($sql);
350 for my $pathpair (@$pathsref)
352 my($path, $id)=@$pathpair;
353 my $fullpath="$self->{absbase}/$path";
359 $self->prune_paths(@ids);
367 my $sql=("DELETE FROM files WHERE paths_id IN (\n\t" .
368 join(', ', map { "\"$_\""; } @ids). "\n\t)");
369 print "SQL: \n", $sql, "\n";
377 DELETE FROM artists WHERE id IN (
378 SELECT artists.id FROM artists
379 LEFT JOIN files ON files.artists_id=artists.id
380 WHERE files.id IS NULL);
382 DELETE FROM albums WHERE id IN (
383 SELECT albums.id FROM albums
384 LEFT JOIN files ON files.albums_id=albums.id
385 WHERE files.id IS NULL);
387 DELETE FROM paths WHERE id IN (
388 SELECT paths.id FROM paths
389 LEFT JOIN files ON files.paths_id=paths.id
390 WHERE files.id IS NULL);
392 DELETE FROM files_x_tags WHERE files_id IN (
393 SELECT files_x_tags.files_id FROM files_x_tags
394 LEFT JOIN files ON files.id=files_x_tags.files_id
395 WHERE files.id IS NULL);
397 DELETE FROM tags WHERE id IN (
398 SELECT tags.id FROM tags
399 LEFT JOIN files_x_tags ON files_x_tags.tags_id=tags.id
400 WHERE files_x_tags.files_id IS NULL);
405 my @sql=split(/\n\n/, $sql);
406 $self->cmd($_) for (@sql);
411 my ($self, $relname, $fields)=@_;
412 my $sql="SELECT count(1) FROM $relname WHERE ";
415 for my $field (keys %$fields)
418 push(@vals,$fields->{$field});
420 $sql .= join(' AND ', map { "$_=?"; } @exprs);
421 my ($ret)=$self->cmd_onerow($sql, @vals);
427 my($self, $thing)=@_;
428 return(defined($thing) && length($thing) && $thing =~ /\S+/);
433 my($self, $sql, @params)=@_;
434 my $sth=$self->{dbh}->prepare($sql);
436 for my $param (@params)
438 $param="" unless(defined($param));
439 $sth->bind_param($idx++, $param);
447 my ($self, @args)=@_;
448 # don't care about retcode
449 $self->cmd_sth(@args);
454 my ($self, @args)=@_;
455 my $sth=$self->cmd_sth(@args);
456 return($sth->fetchrow_array());
461 my ($self, @args)=@_;
462 my $sth=$self->cmd_sth(@args);
463 return $sth->fetchall_arrayref();
468 my ($self, @args)=@_;
469 return(map { $_->[0] } @{$self->cmd_rows(@args)});
474 my ($self, @args)=@_;
475 $self->cmd_sth(@args);
476 return($self->last_insert_id());
482 if($self->{postgres})
484 return $self->{dbh}->last_insert_id(undef, undef, undef, undef,
485 { sequence => "seq" });
489 return $self->{dbh}->last_insert_id("","","","");
495 my($self, $table, $name)=@_;
496 my($id)=$self->cmd_onerow("SELECT id FROM $table where name=?", $name);
503 schema_version INTEGER,
508 id INTEGER PRIMARY KEY,
512 CREATE TABLE artists (
513 id INTEGER PRIMARY KEY,
517 CREATE TABLE albums (
518 id INTEGER PRIMARY KEY,
523 id INTEGER PRIMARY KEY,
528 FOREIGN KEY(artists_id) REFERENCES artists(id) ON DELETE CASCADE ON UPDATE CASCADE,
529 FOREIGN KEY(albums_id) REFERENCES albums(id) ON DELETE CASCADE ON UPDATE CASCADE,
530 FOREIGN KEY(paths_id) REFERENCES paths(id) ON DELETE CASCADE ON UPDATE CASCADE
534 id INTEGER PRIMARY KEY,
539 CREATE TABLE files_x_tags (
542 FOREIGN KEY(files_id) REFERENCES files(id) ON DELETE CASCADE ON UPDATE CASCADE,
543 FOREIGN KEY(tags_id) REFERENCES tags(id) ON DELETE CASCADE ON UPDATE CASCADE