a3a771fef748eddc0032b84bff0f3769c056bcfb
[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     else
274     {
275         $self->add_tag($file_id, "decade", "UNKNOWN");
276     }
277
278     if($self->ok($v1genre))
279     {
280         $self->add_tag($file_id, "v1genre", $v1genre);
281     }
282
283     if($haspic)
284     {
285         $self->add_tag($file_id, "haspic", undef);
286     }
287 }
288
289 sub add_tag
290 {
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))
298     {
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 });
304     }
305 }
306
307 sub add_to_table
308 {
309     my($self, $table, $name, $extradata)=@_;
310     my $id=$self->lookup_id($table, $name);
311     unless(defined($id))
312     {
313         my $sql="INSERT INTO $table (";
314         $sql .= "id, " if($self->{postgres});
315         my @fields=qw(name);
316         if(defined($extradata))
317         {
318             push(@fields, sort keys(%$extradata));
319         }
320         $sql .= join(", ", @fields);
321         $sql .=") VALUES (";
322         $sql .=") nextval('seq'), " if($self->{postgres});
323         $sql .= join(", ", map { "?"; } @fields);
324         $sql .= ");";
325         $id=$self->cmd_id($sql, $name, map { $extradata->{$_} || ""; } sort keys %$extradata);
326     }
327     return $id;
328 }
329
330 sub add_relation
331 {
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));
338     $sql .= ");";
339     $self->cmd($sql, map { $fields->{$_}; } sort keys(%$fields));
340 }
341
342 sub files_in
343 {
344     my ($self, $dir)=@_;
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));
350 }
351
352 sub unindex
353 {
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);
360 }
361
362
363 sub prune_directories
364 {
365     my($self)=@_;
366     my $sql=("SELECT name, id FROM paths ORDER BY name\n");
367     my $pathsref=$self->cmd_rows($sql);
368     my @ids=();
369     for my $pathpair (@$pathsref)
370     {
371         my($path, $id)=@$pathpair;
372         my $fullpath="$self->{absbase}/$path";
373         unless(-d $fullpath)
374         {
375             push(@ids, $id)
376         }
377     }
378     $self->prune_paths(@ids);
379     return scalar(@ids);
380 }
381
382 sub prune_paths
383 {
384     my($self, @ids)=@_;
385     return unless(@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";
389     $self->cmd($sql);
390 }
391
392 sub remove_unused
393 {
394     my($self)=@_;
395     my $sql=<<'EOT';
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);
400
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);
405
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);
410
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);
415
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);
420
421     VACUUM
422 EOT
423 #    print "SQL: $sql\n";
424     my @sql=split(/\n\n/, $sql);
425     $self->cmd($_) for (@sql);
426 }
427
428 sub relation_exists
429 {
430     my ($self, $relname, $fields)=@_;
431     my $sql="SELECT count(1) FROM $relname WHERE ";
432     my @exprs=();
433     my @vals=();
434     for my $field (keys %$fields)
435     {
436         push(@exprs,$field);
437         push(@vals,$fields->{$field});
438     }
439     $sql .= join(' AND ', map { "$_=?"; } @exprs);
440     my ($ret)=$self->cmd_onerow($sql, @vals);
441     return $ret;
442 }
443
444 sub ok
445 {
446     my($self, $thing)=@_;
447     return(defined($thing) && length($thing) && $thing =~ /\S+/);
448 }
449
450 sub cmd_sth
451 {
452     my($self, $sql, @params)=@_;
453     my $sth=$self->{dbh}->prepare($sql);
454     my $idx=1;
455     for my $param (@params)
456     {
457         $param="" unless(defined($param));
458         $sth->bind_param($idx++, $param);
459     }
460     $sth->execute();
461     return $sth;
462 }
463
464 sub cmd
465 {
466     my ($self, @args)=@_;
467     # don't care about retcode
468     $self->cmd_sth(@args);
469 }
470
471 sub cmd_onerow
472 {
473     my ($self, @args)=@_;
474     my $sth=$self->cmd_sth(@args);
475     return($sth->fetchrow_array());
476 }
477
478 sub cmd_rows
479 {
480     my ($self, @args)=@_;
481     my $sth=$self->cmd_sth(@args);
482     return $sth->fetchall_arrayref();
483 }
484
485 sub cmd_firstcol
486 {
487     my ($self, @args)=@_;
488     return(map { $_->[0] } @{$self->cmd_rows(@args)});
489 }
490
491 sub cmd_id
492 {
493     my ($self, @args)=@_;
494     $self->cmd_sth(@args);
495     return($self->last_insert_id());
496 }
497
498 sub last_insert_id
499 {
500     my $self=shift;
501     if($self->{postgres})
502     {
503         return $self->{dbh}->last_insert_id(undef, undef, undef, undef,
504                                             { sequence => "seq" });
505     }
506     else
507     {
508         return $self->{dbh}->last_insert_id("","","","");
509     }
510 }
511
512 sub lookup_id
513 {
514     my($self, $table, $name)=@_;
515     my($id)=$self->cmd_onerow("SELECT id FROM $table where name=?", $name);
516     return $id;
517 }
518
519 __DATA__
520
521 CREATE TABLE id3fs (
522     schema_version INTEGER,
523     last_update
524 );
525
526 CREATE TABLE paths (
527     id INTEGER PRIMARY KEY,
528     name text
529 );
530
531 CREATE TABLE artists (
532     id INTEGER PRIMARY KEY,
533     name text
534 );
535
536 CREATE TABLE albums (
537     id INTEGER PRIMARY KEY,
538     name text
539 );
540
541 CREATE TABLE files (
542     id INTEGER PRIMARY KEY,
543     name text,
544     artists_id,
545     albums_id,
546     paths_id,
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
550 );
551
552 CREATE TABLE tags (
553     id INTEGER PRIMARY KEY,
554     parents_id INTEGER,
555     name text
556 );
557
558 CREATE TABLE files_x_tags (
559     files_id INTEGER,
560     tags_id INTEGER,
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
563 );
564