fix paths on add
[id3fs.git] / lib / ID3FS / DB.pm
1 package ID3FS::DB;
2
3 use strict;
4 use warnings;
5 use DBI;
6 use ID3FS::AudioFile;
7 use Cwd;
8
9 our $SCHEMA_VERSION=1;
10 my $dbfile=".id3fs";
11
12 sub new
13 {
14     my $proto=shift;
15     my $class=ref($proto) || $proto;
16     my $self={};
17     bless($self,$class);
18
19     $self->{me}=shift;
20     $self->{verbose}=shift;
21     my $init=shift;
22     my $dbpath=shift;
23     $self->{base}=shift;
24     my $fallbackdir=shift;
25
26     $dbpath=$self->find_db($init, $dbpath, $fallbackdir);
27     return undef unless($dbpath);
28     $self->{absbase}=Cwd::abs_path($self->{base});
29
30     my $connectstr="dbi:SQLite:dbname=$dbpath";
31     my ($user, $pass)=("", "");
32     if($self->{postgres})
33     {
34         $connectstr="dbi:Pg:dbname=id3fs";
35         $user="ianb";
36         $pass="foo";
37     }
38     my $exists=-f $dbpath;
39     $self->{dbh}=DBI->connect($connectstr, $user, $pass,
40                               { AutoCommit=>1 } );
41     unless(defined($self->{dbh}))
42     {
43         die("$self->{me}: DB Error: " . $DBI::errstr . "\n");
44     }
45
46     if($exists)
47     {
48         $self->checkschema();
49     }
50     else
51     {
52         $self->create();
53     }
54     $self->enable_foreign_keys();
55     return $self;
56 }
57
58 sub find_db
59 {
60     my($self, $init, $dbpath, $fallbackdir)=@_;
61     my $file=undef;
62     my $base=undef;
63     if(defined($dbpath))
64     {
65         $file=$dbpath;
66     }
67     if(defined ($self->{base}))
68     {
69         $file="$self->{base}/$dbfile" unless defined($file);
70         $base=$self->{base};
71     }
72     elsif(defined($fallbackdir) && -d $fallbackdir)
73     {
74         my $path=Cwd::abs_path($fallbackdir);
75         do
76         {
77             $file="$path/$dbfile";
78             $base=$path;
79             $path=~s/(.*)\/.*/$1/;
80         }
81         while(! -f $file && length($path) && -d $path);
82         if(! -f $file)
83         {
84             $file="$fallbackdir/$dbfile";
85             $base=$fallbackdir;
86         }
87     }
88     else
89     {
90         print "$self->{me}: $fallbackdir: not a directory\n";
91         return undef;
92     }
93     if(!-f $file && !$init)
94     {
95         print "$self->{me}: db not found at $file\n";
96         return undef;
97     }
98     $self->{base}=$base;
99     return $file;
100 }
101
102 sub base_dir { return shift->{base}; }
103
104 sub create
105 {
106     my($self,$name)=@_;
107     my @schema=split(/\n\n/,join("", <DATA>));
108     close(DATA);
109     for my $cmd (@schema)
110     {
111         $self->{dbh}->do($cmd);
112     }
113     if($self->{postgres})
114     {
115         $self->cmd("CREATE SEQUENCE seq");
116     }
117     else
118     {
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)
126         {
127             $self->{dbh}->do("CREATE INDEX $index ON " . $indexes{$index});
128         }
129     }
130     $self->cmd("INSERT INTO id3fs (schema_version, last_update) VALUES (?, ?)",
131                $SCHEMA_VERSION, time());
132 }
133
134 sub checkschema
135 {
136     my $self=shift;
137     my ($version)=$self->cmd_onerow("SELECT schema_version from id3fs");
138     if(!defined($version) || $version != $SCHEMA_VERSION)
139     {
140         die("$self->{me}: id3fs database version " .
141             defined($version) ? $version : '""' .
142             "not known, current version is $SCHEMA_VERSION.\n");
143     }
144 }
145
146 sub analyze
147 {
148     my $self=shift;
149     $self->cmd("ANALYZE");
150 }
151
152 sub enable_foreign_keys
153 {
154     my $self=shift;
155     $self->cmd("PRAGMA foreign_keys = ON");
156 }
157
158 sub last_update
159 {
160     my($self, $newval)=@_;
161     if(defined($newval))
162     {
163         $self->cmd("UPDATE id3fs SET last_update=?", $newval);
164     }
165     else
166     {
167         ($newval)=$self->cmd_onerow("SELECT last_update from id3fs");
168     }
169     return $newval;
170 }
171
172 sub id
173 {
174     my($self, $type, $val)=@_;
175     my $sql="SELECT id FROM $type WHERE name=?";
176     my ($id)=$self->cmd_onerow($sql, $val);
177     return($id);
178 }
179
180 sub tag_has_values
181 {
182     my($self, $id)=@_;
183     my $sql=("SELECT COUNT(*) FROM tags\n\t" .
184              "WHERE tags.parents_id=?\n");
185     my ($rows)=$self->cmd_onerow($sql, $id);
186     return $rows;
187 }
188
189 sub relativise
190 {
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])
201     {
202         #no path in common, return absolute
203         print "FAIL: NO PATHS IN COMMON\n";
204         return $name;
205     }
206     # f: /home/foo/bar/baz.mp3
207     # r: /home/ianb/music/albums
208     while(@path && @rel && ($path[0] eq $rel[0]))
209     {
210         shift(@path);
211         shift(@rel);
212 #       print "POP ";
213     }
214 #    print "\n";
215     my $upcount=scalar(@rel);
216     my $result="../" x $upcount;
217     $result .= join("/",@path);
218     $result .= "/$name";
219     return $result;
220 }
221
222 sub add
223 {
224     my($self,$path)=@_;
225     my $relpath=Cwd::abs_path($path);
226     $relpath =~ s/^\Q$self->{absbase}\E\/?//;
227     my($filepart,$pathpart);
228     if($relpath !~ /\//)
229     {
230         $pathpart='';
231         $filepart=$relpath;
232     }
233     else
234     {
235         ($pathpart, $filepart) = ($relpath =~ /(.*)\/(.*)/);
236     }
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();
246
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))
253     {
254         print "$self->{me}: $path: no album tag defined\n";
255     }
256
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 });
262     for my $tag (@tags)
263     {
264         $self->add_tag($file_id, @$tag);
265     }
266
267     $year="UNKNOWN" unless($self->ok($year));
268     $self->add_tag($file_id, "year", $year);
269     if($year=~/^(\d\d\d)\d$/)
270     {
271         $self->add_tag($file_id, "decade", "${1}0s");
272     }
273
274     if($self->ok($v1genre))
275     {
276         $self->add_tag($file_id, "v1genre", $v1genre);
277     }
278
279     if($haspic)
280     {
281         $self->add_tag($file_id, "haspic", undef);
282     }
283 }
284
285 sub add_tag
286 {
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))
294     {
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 });
300     }
301 }
302
303 sub add_to_table
304 {
305     my($self, $table, $name, $extradata)=@_;
306     my $id=$self->lookup_id($table, $name);
307     unless(defined($id))
308     {
309         my $sql="INSERT INTO $table (";
310         $sql .= "id, " if($self->{postgres});
311         my @fields=qw(name);
312         if(defined($extradata))
313         {
314             push(@fields, sort keys(%$extradata));
315         }
316         $sql .= join(", ", @fields);
317         $sql .=") VALUES (";
318         $sql .=") nextval('seq'), " if($self->{postgres});
319         $sql .= join(", ", map { "?"; } @fields);
320         $sql .= ");";
321         $id=$self->cmd_id($sql, $name, map { $extradata->{$_} || ""; } sort keys %$extradata);
322     }
323     return $id;
324 }
325
326 sub add_relation
327 {
328     my ($self, $relname, $fields)=@_;
329     return if($self->relation_exists($relname, $fields));
330     my $sql="INSERT INTO $relname (";
331     $sql .= join(", ", sort keys(%$fields));
332     $sql .= ") VALUES (";
333     $sql .= join(", ", map { "?"; } sort keys(%$fields));
334     $sql .= ");";
335     $self->cmd($sql, map { $fields->{$_}; } sort keys(%$fields));
336 }
337
338 sub files_in
339 {
340     my ($self, $dir)=@_;
341     my $sql=("SELECT files.name FROM files\n" .
342              "INNER JOIN paths ON files.paths_id=paths.id\n" .
343              "WHERE paths.name=?\n");
344 #    print "files_in: SQL: $sql\n";
345     return($self->cmd_firstcol($sql, $dir));
346 }
347
348 sub unindex
349 {
350     my($self, $path, $file)=@_;
351     my $sql=("DELETE FROM files WHERE id IN (" .
352              "\tSELECT files.id FROM files\n" .
353              "\tINNER JOIN paths ON paths.id=files.paths_id\n" .
354              "\tWHERE paths.name=? and files.name=? )\n");
355     $self->cmd_rows($sql, $path, $file);
356 }
357
358
359 sub prune_directories
360 {
361     my($self)=@_;
362     my $sql=("SELECT name, id FROM paths ORDER BY name\n");
363     my $pathsref=$self->cmd_rows($sql);
364     my @ids=();
365     for my $pathpair (@$pathsref)
366     {
367         my($path, $id)=@$pathpair;
368         my $fullpath="$self->{absbase}/$path";
369         unless(-d $fullpath)
370         {
371             push(@ids, $id)
372         }
373     }
374     $self->prune_paths(@ids);
375     return scalar(@ids);
376 }
377
378 sub prune_paths
379 {
380     my($self, @ids)=@_;
381     return unless(@ids);
382     my $sql=("DELETE FROM files WHERE paths_id IN (\n\t" .
383              join(', ', map { "\"$_\""; } @ids). "\n\t)");
384 #    print "SQL: \n", $sql, "\n";
385     $self->cmd($sql);
386 }
387
388 sub remove_unused
389 {
390     my($self)=@_;
391     my $sql=<<'EOT';
392    DELETE FROM artists WHERE id IN (
393        SELECT artists.id FROM artists
394        LEFT JOIN files ON files.artists_id=artists.id
395        WHERE files.id IS NULL);
396
397    DELETE FROM albums WHERE id IN (
398        SELECT albums.id FROM albums
399        LEFT JOIN files ON files.albums_id=albums.id
400        WHERE files.id IS NULL);
401
402    DELETE FROM paths WHERE id IN (
403        SELECT paths.id FROM paths
404        LEFT JOIN files ON files.paths_id=paths.id
405        WHERE files.id IS NULL);
406
407    DELETE FROM files_x_tags WHERE files_id IN (
408        SELECT files_x_tags.files_id FROM files_x_tags
409        LEFT JOIN files ON files.id=files_x_tags.files_id
410        WHERE files.id IS NULL);
411
412    DELETE FROM tags WHERE id IN (
413        SELECT tags.id FROM tags
414        LEFT JOIN files_x_tags ON files_x_tags.tags_id=tags.id
415        WHERE files_x_tags.files_id IS NULL);
416
417     VACUUM
418 EOT
419 #    print "SQL: $sql\n";
420     my @sql=split(/\n\n/, $sql);
421     $self->cmd($_) for (@sql);
422 }
423
424 sub relation_exists
425 {
426     my ($self, $relname, $fields)=@_;
427     my $sql="SELECT count(1) FROM $relname WHERE ";
428     my @exprs=();
429     my @vals=();
430     for my $field (keys %$fields)
431     {
432         push(@exprs,$field);
433         push(@vals,$fields->{$field});
434     }
435     $sql .= join(' AND ', map { "$_=?"; } @exprs);
436     my ($ret)=$self->cmd_onerow($sql, @vals);
437     return $ret;
438 }
439
440 sub ok
441 {
442     my($self, $thing)=@_;
443     return(defined($thing) && length($thing) && $thing =~ /\S+/);
444 }
445
446 sub cmd_sth
447 {
448     my($self, $sql, @params)=@_;
449     my $sth=$self->{dbh}->prepare($sql);
450     my $idx=1;
451     for my $param (@params)
452     {
453         $param="" unless(defined($param));
454         $sth->bind_param($idx++, $param);
455     }
456     $sth->execute();
457     return $sth;
458 }
459
460 sub cmd
461 {
462     my ($self, @args)=@_;
463     # don't care about retcode
464     $self->cmd_sth(@args);
465 }
466
467 sub cmd_onerow
468 {
469     my ($self, @args)=@_;
470     my $sth=$self->cmd_sth(@args);
471     return($sth->fetchrow_array());
472 }
473
474 sub cmd_rows
475 {
476     my ($self, @args)=@_;
477     my $sth=$self->cmd_sth(@args);
478     return $sth->fetchall_arrayref();
479 }
480
481 sub cmd_firstcol
482 {
483     my ($self, @args)=@_;
484     return(map { $_->[0] } @{$self->cmd_rows(@args)});
485 }
486
487 sub cmd_id
488 {
489     my ($self, @args)=@_;
490     $self->cmd_sth(@args);
491     return($self->last_insert_id());
492 }
493
494 sub last_insert_id
495 {
496     my $self=shift;
497     if($self->{postgres})
498     {
499         return $self->{dbh}->last_insert_id(undef, undef, undef, undef,
500                                             { sequence => "seq" });
501     }
502     else
503     {
504         return $self->{dbh}->last_insert_id("","","","");
505     }
506 }
507
508 sub lookup_id
509 {
510     my($self, $table, $name)=@_;
511     my($id)=$self->cmd_onerow("SELECT id FROM $table where name=?", $name);
512     return $id;
513 }
514
515 __DATA__
516
517 CREATE TABLE id3fs (
518     schema_version INTEGER,
519     last_update
520 );
521
522 CREATE TABLE paths (
523     id INTEGER PRIMARY KEY,
524     name text
525 );
526
527 CREATE TABLE artists (
528     id INTEGER PRIMARY KEY,
529     name text
530 );
531
532 CREATE TABLE albums (
533     id INTEGER PRIMARY KEY,
534     name text
535 );
536
537 CREATE TABLE files (
538     id INTEGER PRIMARY KEY,
539     name text,
540     artists_id,
541     albums_id,
542     paths_id,
543     FOREIGN KEY(artists_id) REFERENCES artists(id) ON DELETE CASCADE ON UPDATE CASCADE,
544     FOREIGN KEY(albums_id)  REFERENCES albums(id)  ON DELETE CASCADE ON UPDATE CASCADE,
545     FOREIGN KEY(paths_id)   REFERENCES paths(id)   ON DELETE CASCADE ON UPDATE CASCADE
546 );
547
548 CREATE TABLE tags (
549     id INTEGER PRIMARY KEY,
550     parents_id INTEGER,
551     name text
552 );
553
554 CREATE TABLE files_x_tags (
555     files_id INTEGER,
556     tags_id INTEGER,
557     FOREIGN KEY(files_id) REFERENCES files(id) ON DELETE CASCADE ON UPDATE CASCADE,
558     FOREIGN KEY(tags_id)  REFERENCES tags(id)  ON DELETE CASCADE ON UPDATE CASCADE
559 );
560