move big chunks of DB into Path
[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     if(!-f $file && !$init)
89     {
90         print "$self->{me}: db not found at $file\n";
91         return undef;
92     }
93     $self->{base}=$base;
94     return $file;
95 }
96
97 sub base_dir { return shift->{base}; }
98
99 sub create
100 {
101     my($self,$name)=@_;
102     my @schema=split(/\n\n/,join("", <DATA>));
103     close(DATA);
104     for my $cmd (@schema)
105     {
106         $self->{dbh}->do($cmd);
107     }
108     if($self->{postgres})
109     {
110         $self->cmd("CREATE SEQUENCE seq");
111     }
112     else
113     {
114         my %indexes=( "idx_files_id"  => "files (id)",
115                       "idx_fxt_both"  => "files_x_tags (files_id, tags_id)",
116                       "idx_fxt_files" => "files_x_tags (files_id)",
117                       "idx_fxt_tags"  => "files_x_tags (tags_id)",
118                       "idx_tags_id"   => "tags (id)",
119                       "idx_tags_name" => "tags (name)");
120         for my $index (keys %indexes)
121         {
122             $self->{dbh}->do("CREATE INDEX $index ON " . $indexes{$index});
123         }
124     }
125     $self->cmd("INSERT INTO id3fs (schema_version, last_update) VALUES (?, ?)",
126                $SCHEMA_VERSION, time());
127 }
128
129 sub checkschema
130 {
131     my $self=shift;
132     my ($version)=$self->cmd_onerow("SELECT schema_version from id3fs");
133     if(!defined($version) || $version != $SCHEMA_VERSION)
134     {
135         die("$self->{me}: id3fs database version " .
136             defined($version) ? $version : '""' .
137             "not known, current version is $SCHEMA_VERSION.\n");
138     }
139 }
140
141 sub analyze
142 {
143     my $self=shift;
144     $self->cmd("ANALYZE");
145 }
146
147 sub enable_foreign_keys
148 {
149     my $self=shift;
150     $self->cmd("PRAGMA foreign_keys = ON");
151 }
152
153 sub last_update
154 {
155     my($self, $newval)=@_;
156     if(defined($newval))
157     {
158         $self->cmd("UPDATE id3fs SET last_update=?", $newval);
159     }
160     else
161     {
162         ($newval)=$self->cmd_onerow("SELECT last_update from id3fs");
163     }
164     return $newval;
165 }
166
167 sub id
168 {
169     my($self, $type, $val)=@_;
170     my $sql="SELECT id FROM $type WHERE name=?";
171     my ($id)=$self->cmd_onerow($sql, $val);
172     return($id);
173 }
174
175 sub tag_has_values
176 {
177     my($self, $id)=@_;
178     my $sql=("SELECT COUNT(*) FROM tags\n\t" .
179              "WHERE tags.parents_id=?\n");
180     my ($rows)=$self->cmd_onerow($sql, $id);
181     return $rows;
182 }
183
184 sub relativise
185 {
186     my($self, $path, $name, $mountpoint, $id3fs_path)=@_;
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=$path;
221     $relpath =~ s/^\Q$self->{base}\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     if($self->ok($year))
263     {
264         $self->add_tag($file_id, "year", $year);
265         if($year=~/^(\d\d\d)\d$/)
266         {
267             $self->add_tag($file_id, "decade", "${1}0s");
268         }
269     }
270
271     if($self->ok($v1genre))
272     {
273         $self->add_tag($file_id, "v1genre", $v1genre);
274     }
275
276     if($haspic)
277     {
278         $self->add_tag($file_id, "haspic", undef);
279     }
280 }
281
282 sub add_tag
283 {
284     my($self, $file_id, $tag, $value)=@_;
285     my $tag_id=$self->add_to_table("tags",  $tag,
286                                    { "parents_id" => undef });
287     $self->add_relation("files_x_tags",
288                         { "files_id" => $file_id,
289                           "tags_id"  => $tag_id });
290     if(defined($value) && length($value))
291     {
292         my $val_id=$self->add_to_table("tags",  $value,
293                                        { "parents_id" => $tag_id });
294         $self->add_relation("files_x_tags",
295                             { "files_id" => $file_id,
296                               "tags_id"  => $val_id });
297     }
298 }
299
300 sub add_to_table
301 {
302     my($self, $table, $name, $extradata)=@_;
303     my $id=$self->lookup_id($table, $name);
304     unless(defined($id))
305     {
306         my $sql="INSERT INTO $table (";
307         $sql .= "id, " if($self->{postgres});
308         my @fields=qw(name);
309         if(defined($extradata))
310         {
311             push(@fields, sort keys(%$extradata));
312         }
313         $sql .= join(", ", @fields);
314         $sql .=") VALUES (";
315         $sql .=") nextval('seq'), " if($self->{postgres});
316         $sql .= join(", ", map { "?"; } @fields);
317         $sql .= ");";
318         $id=$self->cmd_id($sql, $name, map { $extradata->{$_} || ""; } sort keys %$extradata);
319     }
320     return $id;
321 }
322
323 sub add_relation
324 {
325     my ($self, $relname, $fields)=@_;
326     return if($self->relation_exists($relname, $fields));
327     my $sql="INSERT INTO $relname (";
328     $sql .= join(", ", sort keys(%$fields));
329     $sql .= ") VALUES (";
330     $sql .= join(", ", map { "?"; } sort keys(%$fields));
331     $sql .= ");";
332     $self->cmd($sql, map { $fields->{$_}; } sort keys(%$fields));
333 }
334
335 sub files_in
336 {
337     my ($self, $dir)=@_;
338     $dir=~s/^$self->{base}\/?//;
339     my $sql=("SELECT files.name FROM files\n" .
340              "INNER JOIN paths ON files.paths_id=paths.id\n" .
341              "WHERE paths.name=?\n");
342     my $files=$self->cmd_rows($sql, $dir);
343     return(map { $_->[0]; } @$files);
344 }
345
346 sub prune_directories
347 {
348     my($self)=@_;
349     my $sql=("SELECT name, id FROM paths ORDER BY name\n");
350     my $pathsref=$self->cmd_rows($sql);
351     my @ids=();
352     for my $pathpair (@$pathsref)
353     {
354         my($path, $id)=@$pathpair;
355         my $fullpath="$self->{absbase}/$path";
356         unless(-d $fullpath)
357         {
358             push(@ids, $id)
359         }
360     }
361     $self->prune_paths(@ids);
362     return scalar(@ids);
363 }
364
365 sub prune_paths
366 {
367     my($self, @ids)=@_;
368     return unless(@ids);
369     my $sql=("DELETE FROM files WHERE paths_id IN (\n\t" .
370              join(', ', map { "\"$_\""; } @ids). "\n\t)");
371     print "SQL: \n", $sql, "\n";
372     $self->cmd($sql);
373 }
374
375 sub remove_unused
376 {
377     my($self)=@_;
378     my $sql=<<'EOT';
379    DELETE FROM artists WHERE id IN (
380        SELECT artists.id FROM artists
381        LEFT JOIN files ON files.artists_id=artists.id
382        WHERE files.id IS NULL);
383
384    DELETE FROM albums WHERE id IN (
385        SELECT albums.id FROM albums
386        LEFT JOIN files ON files.albums_id=albums.id
387        WHERE files.id IS NULL);
388
389    DELETE FROM paths WHERE id IN (
390        SELECT paths.id FROM paths
391        LEFT JOIN files ON files.paths_id=paths.id
392        WHERE files.id IS NULL);
393
394    DELETE FROM files_x_tags WHERE files_id IN (
395        SELECT files_x_tags.files_id FROM files_x_tags
396        LEFT JOIN files ON files.id=files_x_tags.files_id
397        WHERE files.id IS NULL);
398
399    DELETE FROM tags WHERE id IN (
400        SELECT tags.id FROM tags
401        LEFT JOIN files_x_tags ON files_x_tags.tags_id=tags.id
402        WHERE files_x_tags.files_id IS NULL);
403
404     VACUUM
405 EOT
406     print "SQL: $sql\n";
407     my @sql=split(/\n\n/, $sql);
408     $self->cmd($_) for (@sql);
409 }
410
411 sub relation_exists
412 {
413     my ($self, $relname, $fields)=@_;
414     my $sql="SELECT count(1) FROM $relname WHERE ";
415     my @exprs=();
416     my @vals=();
417     for my $field (keys %$fields)
418     {
419         push(@exprs,$field);
420         push(@vals,$fields->{$field});
421     }
422     $sql .= join(' AND ', map { "$_=?"; } @exprs);
423     my ($ret)=$self->cmd_onerow($sql, @vals);
424     return $ret;
425 }
426
427 sub ok
428 {
429     my($self, $thing)=@_;
430     return(defined($thing) && length($thing) && $thing =~ /\S+/);
431 }
432
433 sub cmd_sth
434 {
435     my($self, $sql, @params)=@_;
436     my $sth=$self->{dbh}->prepare($sql);
437     my $idx=1;
438     for my $param (@params)
439     {
440         $param="" unless(defined($param));
441         $sth->bind_param($idx++, $param);
442     }
443     $sth->execute();
444     return $sth;
445 }
446
447 sub cmd
448 {
449     my ($self, @args)=@_;
450     # don't care about retcode
451     $self->cmd_sth(@args);
452 }
453
454 sub cmd_onerow
455 {
456     my ($self, @args)=@_;
457     my $sth=$self->cmd_sth(@args);
458     return($sth->fetchrow_array());
459 }
460
461 sub cmd_rows
462 {
463     my ($self, @args)=@_;
464     my $sth=$self->cmd_sth(@args);
465     return $sth->fetchall_arrayref();
466 }
467
468 sub cmd_firstcol
469 {
470     my ($self, @args)=@_;
471     return(map { $_->[0] } @{$self->cmd_rows(@args)});
472 }
473
474 sub cmd_id
475 {
476     my ($self, @args)=@_;
477     $self->cmd_sth(@args);
478     return($self->last_insert_id());
479 }
480
481 sub last_insert_id
482 {
483     my $self=shift;
484     if($self->{postgres})
485     {
486         return $self->{dbh}->last_insert_id(undef, undef, undef, undef,
487                                             { sequence => "seq" });
488     }
489     else
490     {
491         return $self->{dbh}->last_insert_id("","","","");
492     }
493 }
494
495 __DATA__
496
497 CREATE TABLE id3fs (
498     schema_version INTEGER,
499     last_update
500 );
501
502 CREATE TABLE paths (
503     id INTEGER PRIMARY KEY,
504     name text
505 );
506
507 CREATE TABLE artists (
508     id INTEGER PRIMARY KEY,
509     name text
510 );
511
512 CREATE TABLE albums (
513     id INTEGER PRIMARY KEY,
514     name text
515 );
516
517 CREATE TABLE files (
518     id INTEGER PRIMARY KEY,
519     name text,
520     artists_id,
521     albums_id,
522     paths_id,
523     FOREIGN KEY(artists_id) REFERENCES artists(id) ON DELETE CASCADE ON UPDATE CASCADE,
524     FOREIGN KEY(albums_id)  REFERENCES albums(id)  ON DELETE CASCADE ON UPDATE CASCADE,
525     FOREIGN KEY(paths_id)   REFERENCES paths(id)   ON DELETE CASCADE ON UPDATE CASCADE
526 );
527
528 CREATE TABLE tags (
529     id INTEGER PRIMARY KEY,
530     parents_id INTEGER,
531     name text
532 );
533
534 CREATE TABLE files_x_tags (
535     files_id INTEGER,
536     tags_id INTEGER,
537     FOREIGN KEY(files_id) REFERENCES files(id) ON DELETE CASCADE ON UPDATE CASCADE,
538     FOREIGN KEY(tags_id)  REFERENCES tags(id)  ON DELETE CASCADE ON UPDATE CASCADE
539 );
540