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");
174 my($self, $type, $val)=@_;
175 my $sql="SELECT id FROM $type WHERE name=?";
176 my ($id)=$self->cmd_onerow($sql, $val);
183 my $sql=("SELECT COUNT(*) FROM tags\n\t" .
184 "WHERE tags.parents_id=?\n");
185 my ($rows)=$self->cmd_onerow($sql, $id);
191 my($self, $path, $name, $mountpoint, $id3fs_path)=@_;
192 $id3fs_path=~s/(.*)\/.*/$1/;
193 my $rpath="$self->{absbase}/$path";
194 my $vpath="$mountpoint/$id3fs_path";
195 my @path=split(/\//,$rpath);
196 my @rel=split(/\//,$vpath);
197 #absolute paths have empty first element due to leading /
198 shift(@path) if($path[0] eq "");
199 shift(@rel) if($rel[0] eq "");
200 if($path[0] ne $rel[0])
202 #no path in common, return absolute
203 print "FAIL: NO PATHS IN COMMON\n";
206 # f: /home/foo/bar/baz.mp3
207 # r: /home/ianb/music/albums
208 while(@path && @rel && ($path[0] eq $rel[0]))
215 my $upcount=scalar(@rel);
216 my $result="../" x $upcount;
217 $result .= join("/",@path);
225 my $relpath=Cwd::abs_path($path);
226 $relpath =~ s/^\Q$self->{absbase}\E\/?//;
227 my($filepart,$pathpart);
235 ($pathpart, $filepart) = ($relpath =~ /(.*)\/(.*)/);
237 my $file=ID3FS::AudioFile->new($path, $self->{me});
238 return unless(defined($file));
239 my $artist=$file->artist();
240 my $album=$file->album();
241 my $v1genre=$file->v1genre();
242 my $year=$file->year();
243 my $audiotype=$file->audiotype();
244 my @tags=$file->tags();
245 my $haspic=$file->haspic();
247 $artist=undef unless($self->ok($artist));
248 print "$self->{me}: $path: no artist tag defined\n" unless(defined($artist));
249 my $artist_id=$self->add_to_table("artists", $artist);
250 my $path_id=$self->add_to_table("paths", $pathpart);
251 $album=undef unless($self->ok($album));
252 if($self->{verbose} && !defined($album))
254 print "$self->{me}: $path: no album tag defined\n";
257 my $albums_id=$self->add_to_table("albums", $album);
258 my $file_id=$self->add_to_table("files", $filepart,
259 { "artists_id" => $artist_id,
260 "albums_id" => $albums_id,
261 "paths_id" => $path_id });
264 $self->add_tag($file_id, @$tag);
267 $year="UNKNOWN" unless($self->ok($year));
268 $self->add_tag($file_id, "year", $year);
269 if($year=~/^(\d\d\d)\d$/)
271 $self->add_tag($file_id, "decade", "${1}0s");
275 $self->add_tag($file_id, "decade", "UNKNOWN");
278 if($self->ok($v1genre))
280 $self->add_tag($file_id, "v1genre", $v1genre);
285 $self->add_tag($file_id, "haspic", undef);
291 my($self, $file_id, $tag, $value)=@_;
292 my $tag_id=$self->add_to_table("tags", $tag,
293 { "parents_id" => undef });
294 $self->add_relation("files_x_tags",
295 { "files_id" => $file_id,
296 "tags_id" => $tag_id });
297 if(defined($value) && length($value))
299 my $val_id=$self->add_to_table("tags", $value,
300 { "parents_id" => $tag_id });
301 $self->add_relation("files_x_tags",
302 { "files_id" => $file_id,
303 "tags_id" => $val_id });
309 my($self, $table, $name, $extradata)=@_;
310 my $id=$self->lookup_id($table, $name);
313 my $sql="INSERT INTO $table (";
314 $sql .= "id, " if($self->{postgres});
316 if(defined($extradata))
318 push(@fields, sort keys(%$extradata));
320 $sql .= join(", ", @fields);
322 $sql .=") nextval('seq'), " if($self->{postgres});
323 $sql .= join(", ", map { "?"; } @fields);
325 $id=$self->cmd_id($sql, $name, map { $extradata->{$_} || ""; } sort keys %$extradata);
332 my ($self, $relname, $fields)=@_;
333 return if($self->relation_exists($relname, $fields));
334 my $sql="INSERT INTO $relname (";
335 $sql .= join(", ", sort keys(%$fields));
336 $sql .= ") VALUES (";
337 $sql .= join(", ", map { "?"; } sort keys(%$fields));
339 $self->cmd($sql, map { $fields->{$_}; } sort keys(%$fields));
345 my $sql=("SELECT files.name FROM files\n" .
346 "INNER JOIN paths ON files.paths_id=paths.id\n" .
347 "WHERE paths.name=?\n");
348 # print "files_in: SQL: $sql\n";
349 return($self->cmd_firstcol($sql, $dir));
354 my($self, $path, $file)=@_;
355 my $sql=("DELETE FROM files WHERE id IN (" .
356 "\tSELECT files.id FROM files\n" .
357 "\tINNER JOIN paths ON paths.id=files.paths_id\n" .
358 "\tWHERE paths.name=? and files.name=? )\n");
359 $self->cmd_rows($sql, $path, $file);
363 sub prune_directories
366 my $sql=("SELECT name, id FROM paths ORDER BY name\n");
367 my $pathsref=$self->cmd_rows($sql);
369 for my $pathpair (@$pathsref)
371 my($path, $id)=@$pathpair;
372 my $fullpath="$self->{absbase}/$path";
378 $self->prune_paths(@ids);
386 my $sql=("DELETE FROM files WHERE paths_id IN (\n\t" .
387 join(', ', map { "\"$_\""; } @ids). "\n\t)");
388 # print "SQL: \n", $sql, "\n";
396 DELETE FROM artists WHERE id IN (
397 SELECT artists.id FROM artists
398 LEFT JOIN files ON files.artists_id=artists.id
399 WHERE files.id IS NULL);
401 DELETE FROM albums WHERE id IN (
402 SELECT albums.id FROM albums
403 LEFT JOIN files ON files.albums_id=albums.id
404 WHERE files.id IS NULL);
406 DELETE FROM paths WHERE id IN (
407 SELECT paths.id FROM paths
408 LEFT JOIN files ON files.paths_id=paths.id
409 WHERE files.id IS NULL);
411 DELETE FROM files_x_tags WHERE files_id IN (
412 SELECT files_x_tags.files_id FROM files_x_tags
413 LEFT JOIN files ON files.id=files_x_tags.files_id
414 WHERE files.id IS NULL);
416 DELETE FROM tags WHERE id IN (
417 SELECT tags.id FROM tags
418 LEFT JOIN files_x_tags ON files_x_tags.tags_id=tags.id
419 WHERE files_x_tags.files_id IS NULL);
423 # print "SQL: $sql\n";
424 my @sql=split(/\n\n/, $sql);
425 $self->cmd($_) for (@sql);
430 my ($self, $relname, $fields)=@_;
431 my $sql="SELECT count(1) FROM $relname WHERE ";
434 for my $field (keys %$fields)
437 push(@vals,$fields->{$field});
439 $sql .= join(' AND ', map { "$_=?"; } @exprs);
440 my ($ret)=$self->cmd_onerow($sql, @vals);
446 my($self, $thing)=@_;
447 return(defined($thing) && length($thing) && $thing =~ /\S+/);
452 my($self, $sql, @params)=@_;
453 my $sth=$self->{dbh}->prepare($sql);
455 for my $param (@params)
457 $param="" unless(defined($param));
458 $sth->bind_param($idx++, $param);
466 my ($self, @args)=@_;
467 # don't care about retcode
468 $self->cmd_sth(@args);
473 my ($self, @args)=@_;
474 my $sth=$self->cmd_sth(@args);
475 return($sth->fetchrow_array());
480 my ($self, @args)=@_;
481 my $sth=$self->cmd_sth(@args);
482 return $sth->fetchall_arrayref();
487 my ($self, @args)=@_;
488 return(map { $_->[0] } @{$self->cmd_rows(@args)});
493 my ($self, @args)=@_;
494 $self->cmd_sth(@args);
495 return($self->last_insert_id());
501 if($self->{postgres})
503 return $self->{dbh}->last_insert_id(undef, undef, undef, undef,
504 { sequence => "seq" });
508 return $self->{dbh}->last_insert_id("","","","");
514 my($self, $table, $name)=@_;
515 my($id)=$self->cmd_onerow("SELECT id FROM $table where name=?", $name);
522 schema_version INTEGER,
527 id INTEGER PRIMARY KEY,
531 CREATE TABLE artists (
532 id INTEGER PRIMARY KEY,
536 CREATE TABLE albums (
537 id INTEGER PRIMARY KEY,
542 id INTEGER PRIMARY KEY,
547 FOREIGN KEY(artists_id) REFERENCES artists(id) ON DELETE CASCADE ON UPDATE CASCADE,
548 FOREIGN KEY(albums_id) REFERENCES albums(id) ON DELETE CASCADE ON UPDATE CASCADE,
549 FOREIGN KEY(paths_id) REFERENCES paths(id) ON DELETE CASCADE ON UPDATE CASCADE
553 id INTEGER PRIMARY KEY,
558 CREATE TABLE files_x_tags (
561 FOREIGN KEY(files_id) REFERENCES files(id) ON DELETE CASCADE ON UPDATE CASCADE,
562 FOREIGN KEY(tags_id) REFERENCES tags(id) ON DELETE CASCADE ON UPDATE CASCADE