29c50e3881ba23e016089afbf11d8fe4b039f9c4
[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 tag_has_values
173 {
174     my($self, $id)=@_;
175     my $sql=("SELECT COUNT(*) FROM tags\n\t" .
176              "WHERE tags.parents_id=?\n");
177     my ($rows)=$self->cmd_onerow($sql, $id);
178     return $rows;
179 }
180
181 sub relativise
182 {
183     my($self, $path, $name, $mountpoint, $id3fs_path)=@_;
184     $id3fs_path=~s/(.*)\/.*/$1/;
185     my $rpath="$self->{absbase}/$path";
186     my $vpath="$mountpoint/$id3fs_path";
187     my @path=split(/\//,$rpath);
188     my @rel=split(/\//,$vpath);
189     #absolute paths have empty first element due to leading /
190     shift(@path) if($path[0] eq "");
191     shift(@rel)  if($rel[0]  eq "");
192     if($path[0] ne $rel[0])
193     {
194         #no path in common, return absolute
195         print "FAIL: NO PATHS IN COMMON\n";
196         return $name;
197     }
198     # f: /home/foo/bar/baz.mp3
199     # r: /home/ianb/music/albums
200     while(@path && @rel && ($path[0] eq $rel[0]))
201     {
202         shift(@path);
203         shift(@rel);
204 #       print "POP ";
205     }
206 #    print "\n";
207     my $upcount=scalar(@rel);
208     my $result="../" x $upcount;
209     $result .= join("/",@path);
210     $result .= "/$name";
211     return $result;
212 }
213
214 sub add
215 {
216     my($self,$path)=@_;
217     my $relpath=Cwd::abs_path($path);
218     $relpath =~ s/^\Q$self->{absbase}\E\/?//;
219     my($filepart,$pathpart);
220     if($relpath !~ /\//)
221     {
222         $pathpart='';
223         $filepart=$relpath;
224     }
225     else
226     {
227         ($pathpart, $filepart) = ($relpath =~ /(.*)\/(.*)/);
228     }
229     my $file=ID3FS::AudioFile->new($path, $self->{me});
230     return unless(defined($file));
231     my $artist=$file->artist();
232     my $album=$file->album();
233     my $v1genre=$file->v1genre();
234     my $year=$file->year();
235     my $audiotype=$file->audiotype();
236     my @tags=$file->tags();
237     my $haspic=$file->haspic();
238
239     $artist=undef unless($self->ok($artist));
240     print "$self->{me}: $path: no artist tag defined\n" unless(defined($artist));
241     my $artist_id=$self->add_to_table("artists",  $artist);
242     my $path_id=$self->add_to_table("paths", $pathpart);
243     $album=undef unless($self->ok($album));
244     if($self->{verbose} && !defined($album))
245     {
246         print "$self->{me}: $path: no album tag defined\n";
247     }
248
249     my $albums_id=$self->add_to_table("albums", $album);
250     my $file_id=$self->add_to_table("files", $filepart,
251                                     { "artists_id" => $artist_id,
252                                       "albums_id"  => $albums_id,
253                                       "paths_id"   => $path_id });
254     for my $tag (@tags)
255     {
256         $self->add_tag($file_id, @$tag);
257     }
258
259     $year="UNKNOWN" unless($self->ok($year));
260     $self->add_tag($file_id, "year", $year);
261     if($year=~/^(\d\d\d)\d$/)
262     {
263         $self->add_tag($file_id, "decade", "${1}0s");
264     }
265     else
266     {
267         $self->add_tag($file_id, "decade", "UNKNOWN");
268     }
269
270     if($self->ok($v1genre))
271     {
272         $self->add_tag($file_id, "v1genre", $v1genre);
273     }
274
275     if($haspic)
276     {
277         $self->add_tag($file_id, "haspic", undef);
278     }
279 }
280
281 sub add_tag
282 {
283     my($self, $file_id, $tag, $value)=@_;
284     my $tag_id=$self->add_to_table("tags",  $tag,
285                                    { "parents_id" => undef });
286     $self->add_relation("files_x_tags",
287                         { "files_id" => $file_id,
288                           "tags_id"  => $tag_id });
289     if(defined($value) && length($value))
290     {
291         my $val_id=$self->add_to_table("tags",  $value,
292                                        { "parents_id" => $tag_id });
293         $self->add_relation("files_x_tags",
294                             { "files_id" => $file_id,
295                               "tags_id"  => $val_id });
296     }
297 }
298
299 sub add_to_table
300 {
301     my($self, $table, $name, $extradata)=@_;
302     my $parent=undef;
303     if($extradata && $extradata->{parents_id})
304     {
305         $parent=$extradata->{parents_id};
306     }
307     my $id=$self->lookup_id($table, $name, $parent);
308     unless(defined($id))
309     {
310         my $sql="INSERT INTO $table (";
311         $sql .= "id, " if($self->{postgres});
312         my @fields=qw(name);
313         if(defined($extradata))
314         {
315             push(@fields, sort keys(%$extradata));
316         }
317         $sql .= join(", ", @fields);
318         $sql .=") VALUES (";
319         $sql .=") nextval('seq'), " if($self->{postgres});
320         $sql .= join(", ", map { "?"; } @fields);
321         $sql .= ");";
322         $id=$self->cmd_id($sql, $name, map { $extradata->{$_} || ""; } sort keys %$extradata);
323     }
324     return $id;
325 }
326
327 sub add_relation
328 {
329     my ($self, $relname, $fields)=@_;
330     return if($self->relation_exists($relname, $fields));
331     my $sql="INSERT INTO $relname (";
332     $sql .= join(", ", sort keys(%$fields));
333     $sql .= ") VALUES (";
334     $sql .= join(", ", map { "?"; } sort keys(%$fields));
335     $sql .= ");";
336     $self->cmd($sql, map { $fields->{$_}; } sort keys(%$fields));
337 }
338
339 sub files_in
340 {
341     my ($self, $dir)=@_;
342     my $sql=("SELECT files.name FROM files\n" .
343              "INNER JOIN paths ON files.paths_id=paths.id\n" .
344              "WHERE paths.name=?\n");
345 #    print "files_in: SQL: $sql\n";
346     return($self->cmd_firstcol($sql, $dir));
347 }
348
349 sub unindex
350 {
351     my($self, $path, $file)=@_;
352     my $sql=("DELETE FROM files WHERE id IN (" .
353              "\tSELECT files.id FROM files\n" .
354              "\tINNER JOIN paths ON paths.id=files.paths_id\n" .
355              "\tWHERE paths.name=? and files.name=? )\n");
356     $self->cmd_rows($sql, $path, $file);
357 }
358
359
360 sub prune_directories
361 {
362     my($self)=@_;
363     my $sql=("SELECT name, id FROM paths ORDER BY name\n");
364     my $pathsref=$self->cmd_rows($sql);
365     my @ids=();
366     for my $pathpair (@$pathsref)
367     {
368         my($path, $id)=@$pathpair;
369         my $fullpath="$self->{absbase}/$path";
370         unless(-d $fullpath)
371         {
372             push(@ids, $id)
373         }
374     }
375     $self->prune_paths(@ids);
376     return scalar(@ids);
377 }
378
379 sub prune_paths
380 {
381     my($self, @ids)=@_;
382     return unless(@ids);
383     my $sql=("DELETE FROM files WHERE paths_id IN (\n\t" .
384              join(', ', map { "\"$_\""; } @ids). "\n\t)");
385 #    print "SQL: \n", $sql, "\n";
386     $self->cmd($sql);
387 }
388
389 sub remove_unused
390 {
391     my($self)=@_;
392     my $sql=<<'EOT';
393    DELETE FROM artists WHERE id IN (
394        SELECT artists.id FROM artists
395        LEFT JOIN files ON files.artists_id=artists.id
396        WHERE files.id IS NULL);
397
398    DELETE FROM albums WHERE id IN (
399        SELECT albums.id FROM albums
400        LEFT JOIN files ON files.albums_id=albums.id
401        WHERE files.id IS NULL);
402
403    DELETE FROM paths WHERE id IN (
404        SELECT paths.id FROM paths
405        LEFT JOIN files ON files.paths_id=paths.id
406        WHERE files.id IS NULL);
407
408    DELETE FROM files_x_tags WHERE files_id IN (
409        SELECT files_x_tags.files_id FROM files_x_tags
410        LEFT JOIN files ON files.id=files_x_tags.files_id
411        WHERE files.id IS NULL);
412
413    DELETE FROM tags WHERE id IN (
414        SELECT tags.id FROM tags
415        LEFT JOIN files_x_tags ON files_x_tags.tags_id=tags.id
416        WHERE files_x_tags.files_id IS NULL);
417
418     VACUUM
419 EOT
420 #    print "SQL: $sql\n";
421     my @sql=split(/\n\n/, $sql);
422     $self->cmd($_) for (@sql);
423 }
424
425 sub relation_exists
426 {
427     my ($self, $relname, $fields)=@_;
428     my $sql="SELECT count(1) FROM $relname WHERE ";
429     my @exprs=();
430     my @vals=();
431     for my $field (keys %$fields)
432     {
433         push(@exprs,$field);
434         push(@vals,$fields->{$field});
435     }
436     $sql .= join(' AND ', map { "$_=?"; } @exprs);
437     my ($ret)=$self->cmd_onerow($sql, @vals);
438     return $ret;
439 }
440
441 sub ok
442 {
443     my($self, $thing)=@_;
444     return(defined($thing) && length($thing) && $thing =~ /\S+/);
445 }
446
447 sub cmd_sth
448 {
449     my($self, $sql, @params)=@_;
450     my $sth=$self->{dbh}->prepare($sql);
451     my $idx=1;
452     for my $param (@params)
453     {
454         $param="" unless(defined($param));
455         $sth->bind_param($idx++, $param);
456     }
457     $sth->execute();
458     return $sth;
459 }
460
461 sub cmd
462 {
463     my ($self, @args)=@_;
464     # don't care about retcode
465     $self->cmd_sth(@args);
466 }
467
468 sub cmd_onerow
469 {
470     my ($self, @args)=@_;
471     my $sth=$self->cmd_sth(@args);
472     return($sth->fetchrow_array());
473 }
474
475 sub cmd_rows
476 {
477     my ($self, @args)=@_;
478     my $sth=$self->cmd_sth(@args);
479     return $sth->fetchall_arrayref();
480 }
481
482 sub cmd_firstcol
483 {
484     my ($self, @args)=@_;
485     return(map { $_->[0] } @{$self->cmd_rows(@args)});
486 }
487
488 sub cmd_id
489 {
490     my ($self, @args)=@_;
491     $self->cmd_sth(@args);
492     return($self->last_insert_id());
493 }
494
495 sub last_insert_id
496 {
497     my $self=shift;
498     if($self->{postgres})
499     {
500         return $self->{dbh}->last_insert_id(undef, undef, undef, undef,
501                                             { sequence => "seq" });
502     }
503     else
504     {
505         return $self->{dbh}->last_insert_id("","","","");
506     }
507 }
508
509 sub lookup_id
510 {
511     my($self, $table, $name, $parent)=@_;
512     my $sql="SELECT id FROM $table where name=?";
513     my @args=($name);
514     if($parent)
515     {
516         $sql .= " AND parents_id=?";
517         push(@args, $parent);
518     }
519     my($id)=$self->cmd_onerow($sql, @args);
520     return $id;
521 }
522
523 __DATA__
524
525 CREATE TABLE id3fs (
526     schema_version INTEGER,
527     last_update
528 );
529
530 CREATE TABLE paths (
531     id INTEGER,
532     name text,
533     PRIMARY KEY(id DESC)
534 );
535
536 CREATE TABLE artists (
537     id INTEGER,
538     name text,
539     PRIMARY KEY(id DESC)
540 );
541
542 CREATE TABLE albums (
543     id INTEGER,
544     name text,
545     PRIMARY KEY(id DESC)
546 );
547
548 CREATE TABLE files (
549     id INTEGER,
550     name text,
551     artists_id,
552     albums_id,
553     paths_id,
554     PRIMARY KEY(id DESC),
555     FOREIGN KEY(artists_id) REFERENCES artists(id) ON DELETE CASCADE ON UPDATE CASCADE,
556     FOREIGN KEY(albums_id)  REFERENCES albums(id)  ON DELETE CASCADE ON UPDATE CASCADE,
557     FOREIGN KEY(paths_id)   REFERENCES paths(id)   ON DELETE CASCADE ON UPDATE CASCADE
558 );
559
560 CREATE TABLE tags (
561     id INTEGER,
562     parents_id INTEGER,
563     name text,
564     PRIMARY KEY(id DESC)
565 );
566
567 CREATE TABLE files_x_tags (
568     files_id INTEGER,
569     tags_id INTEGER,
570     FOREIGN KEY(files_id) REFERENCES files(id) ON DELETE CASCADE ON UPDATE CASCADE,
571     FOREIGN KEY(tags_id)  REFERENCES tags(id)  ON DELETE CASCADE ON UPDATE CASCADE
572 );
573