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