implement tags query from http://joinfu.com/presentations/tagging.pdf
[id3fs.git] / lib / ID3FS / DB.pm
1 package ID3FS::DB;
2
3 use strict;
4 use warnings;
5 use DBI;
6 use ID3FS::File;
7
8 our $SCHEMA_VERSION=1;
9 my $dbfile=".id3fs";
10
11 sub new
12 {
13     my $proto=shift;
14     my $class=ref($proto) || $proto;
15     my $self={};
16     bless($self,$class);
17
18     my($dir, $init, $me)=@_;
19     $self->{dbpath}="$dir/$dbfile";
20     $self->{me}=$me;
21
22     my $exists=-f $self->{dbpath};
23
24     $self->{postgres}=0;
25
26     unless($self->{postgres})
27     {
28         die("$me: $self->{dbpath}: not found. use --init to create.\n") if(!$exists && !$init);
29         die("$me: --init used but $self->{dbpath} exists.\n")           if($exists && $init);
30     }
31
32     my $connectstr="dbi:SQLite:dbname=$self->{dbpath}";
33     my ($user, $pass)=("", "");
34     if($self->{postgres})
35     {
36         $connectstr="dbi:Pg:dbname=id3fs";
37         $user="ianb";
38         $pass="foo";
39     }
40     $self->{dbh}=DBI->connect($connectstr, $user, $pass,
41                               { AutoCommit=>1 } );
42     unless(defined($self->{dbh}))
43     {
44         die("$me: DB Error: " . $DBI::errstr . "\n");
45     }
46
47     if($init)
48     {
49         $self->create();
50     }
51     else
52     {
53         $self->checkschema();
54     }
55
56     return $self;
57 }
58
59 sub create
60 {
61     my($self,$name)=@_;
62     my @schema=split(/\n\n/,join("", <DATA>));
63     close(DATA);
64     for my $cmd (@schema)
65     {
66         $self->{dbh}->do($cmd);
67     }
68     if($self->{postgres})
69     {
70         $self->cmd("CREATE SEQUENCE seq");
71     }
72     else
73     {
74         my %indexes=( "idx_files_id"  => "files(id)",
75                       "idx_fxt_both"  => "files_x_tags(files_id, tags_id)",
76                       "idx_fxt_files" => "files_x_tags (files_id)",
77                       "idx_fxt_tags"  => "files_x_tags (tags_id)",
78                       "idx_tags_id"   => "tags (id)",
79                       "idx_tags_name" => "tags(name)" );
80         for my $index (keys %indexes)
81         {
82             $self->{dbh}->do("CREATE INDEX $index ON " . $indexes{$index});
83         }
84     }
85     $self->cmd("INSERT INTO id3fs (schema_version) VALUES (?)", $SCHEMA_VERSION);
86 }
87
88 sub checkschema
89 {
90     my $self=shift;
91     my ($version)=$self->cmd_onerow("SELECT schema_version from id3fs");
92     if(!defined($version) || $version != $SCHEMA_VERSION)
93     {
94         die("$self->{me}: id3fs database version " .
95             defined($version) ? $version : '""' .
96             "not known, current version is $SCHEMA_VERSION.\n");
97     }
98 }
99
100 sub cmd_sth
101 {
102     my($self, $sql, @params)=@_;
103     my $sth=$self->{dbh}->prepare($sql);
104     my $idx=1;
105     for my $param (@params)
106     {
107         $param="" unless(defined($param));
108         $sth->bind_param($idx++, $param);
109     }
110     $sth->execute();
111     return $sth;
112 }
113
114 sub tags
115 {
116     my($self, @constraints)=@_;
117     if(!@constraints) # /
118     {
119         my $sql="SELECT DISTINCT name FROM tags;";
120         my $tags=$self->cmd_rows($sql);
121         return(map { $_->[0]; } @$tags);
122     }
123     my @file_ids=();
124     my @tag_ids=();
125
126     my $main_sql_start=("SELECT t2.name\n" .
127                         "\tFROM (SELECT files_id FROM tags t1\n" .
128                         "\t\tINNER JOIN files_x_tags ON t1.id=files_x_tags.tags_id\n" .
129                         "\t\tWHERE t1.id in \n\t\t\t(");
130     my $main_sql_mid=(")\n\t\t) AS fxt1\n" .
131                       "\tINNER JOIN files_x_tags fxt2 ON fxt1.files_id=fxt2.files_id\n" .
132                       "\tINNER JOIN tags t2 ON fxt2.tags_id=t2.id\n" .
133                       "\tWHERE t2.id NOT IN (");
134     my $main_sql_end=")\n\tGROUP BY t2.name;";
135     while(my $constraint=shift @constraints)
136     {
137         print "CONSTRAINT: $constraint->{name}\n";
138         my $cid=$constraint->{id};
139         push(@tag_ids, $cid);
140     }
141     @tag_ids = map( { "\"$_\""; } @tag_ids) unless($self->{postgres});
142     my $tagstr=join(", ", @tag_ids);
143     my $sql = ($main_sql_start . $tagstr .
144                $main_sql_mid   . $tagstr .
145                $main_sql_end);
146     print "SQL: $sql\n";
147     my $result=$self->cmd_rows($sql);
148     my @tagnames=map { $_->[0]; } @$result;
149     print "SUBNAMES: ", join(', ', @tagnames), "\n";
150     return(@tagnames);
151 }
152
153 sub tag_values
154 {
155     my($self, $tag)=@_;
156     my $sql=("SELECT DISTINCT tagvals.name FROM tags\n" .
157              "INNER JOIN tags_x_tagvals ON tags.id=tags_x_tagvals.tags_id\n" .
158              "INNER JOIN tagvals ON tagvals.id=tags_x_tagvals.tagvals_id\n" .
159              "WHERE tags.name=?");
160     my $tags=$self->cmd_rows($sql, $tag);
161     return(map { $_->[0]; } @$tags);
162 }
163
164 sub tag_id
165 {
166     my($self, $tag)=@_;
167     my $sql='SELECT id FROM tags WHERE name=?';
168     my ($id)=$self->cmd_onerow($sql, $tag);
169     return($id);
170 }
171
172 sub add
173 {
174     my($self,$path)=@_;
175     my $file=ID3FS::File->new($path);
176     return unless(defined($file));
177     my $artist=$file->artist();
178     my $album=$file->album();
179     my $v1genre=$file->v1genre();
180     my $year=$file->year();
181     my $audiotype=$file->album();
182     my $tags=$file->tags();
183     my $haspic=$file->haspic();
184
185     my $file_id=$self->add_to_table("files", $path);
186     my $artists_id=$self->add_to_table("artists",  $artist);
187     my $albums_id=$self->add_to_table("albums",  $album);
188     for my $tag (keys %$tags)
189     {
190         $self->add_tag($file_id, $tag, $tags->{$tag});
191     }
192
193     if($self->ok($year))
194     {
195         $self->add_tag($file_id, "year", $year);
196         if($year=~/^(\d\d\d)\d$/)
197         {
198             $self->add_tag($file_id, "decade", "${1}0s");
199         }
200     }
201     if($self->ok($v1genre))
202     {
203         $self->add_tag($file_id, "v1genre", $v1genre);
204     }
205
206     if($haspic)
207     {
208         $self->add_tag($file_id, "haspic", undef);
209     }
210
211     $self->add_relation("files_x_artists",
212                         { "files_id" => $file_id,
213                           "artists_id" => $artists_id });
214
215     $self->add_relation("artists_x_albums",
216                       { "artists_id" => $artists_id,
217                         "albums_id" => $albums_id});
218 }
219
220 sub add_tag
221 {
222     my($self, $file_id, $tag, $val)=@_;
223     my $tag_id=$self->add_to_table("tags",  $tag);
224     $self->add_relation("files_x_tags",
225                         { "files_id" => $file_id,
226                           "tags_id"  => $tag_id });
227     if(defined($val))
228     {
229         my $val_id=$self->add_to_table("tagvals", $val);
230         $self->add_relation("tags_x_tagvals",
231                             { "tags_id"     => $tag_id,
232                               "tagvals_id"  => $val_id });
233     }
234 }
235
236 sub add_to_table
237 {
238     my($self, $table, $name, $extradata)=@_;
239     my $id=$self->lookup_id($table, $name);
240     unless(defined($id))
241     {
242         my $sql="INSERT INTO $table (";
243         $sql .= "id, " if($self->{postgres});
244         my @fields=qw(name);
245         if(defined($extradata))
246         {
247             push(@fields, sort keys(%$extradata));
248         }
249         $sql .= join(", ", @fields);
250         $sql .=") VALUES (";
251         $sql .=") nextval('seq'), " if($self->{postgres});
252         $sql .= join(", ", map { "?"; } @fields);
253         $sql .= ");";
254         $id=$self->cmd_id($sql, $name, map { $extradata->{$_} || ""; } sort keys %$extradata);
255     }
256     return $id;
257 }
258
259 sub add_relation
260 {
261     my ($self, $relname, $fields)=@_;
262     return if($self->relation_exists($relname, $fields));
263     my $sql="INSERT INTO $relname (";
264     $sql .= join(", ", sort keys(%$fields));
265     $sql .= ") VALUES (";
266     $sql .= join(", ", map { "?"; } sort keys(%$fields));
267     $sql .= ");";
268     $self->cmd($sql, map { $fields->{$_}; } sort keys(%$fields));
269 }
270
271 sub lookup_id
272 {
273     my($self, $table, $name)=@_;
274     my($id)=$self->cmd_onerow("SELECT id FROM $table where name=?", $name);
275     return $id;
276 }
277
278 sub relation_exists
279 {
280     my ($self, $relname, $fields)=@_;
281     my $sql="SELECT count(1) FROM $relname WHERE ";
282     my @exprs=();
283     my @vals=();
284     for my $field (keys %$fields)
285     {
286         push(@exprs,$field);
287         push(@vals,$fields->{$field});
288     }
289     $sql .= join(' AND ', map { "$_=?"; } @exprs);
290     my ($ret)=$self->cmd_onerow($sql, @vals);
291     return $ret;
292 }
293
294 sub ok
295 {
296     my($self, $thing)=@_;
297     return(defined($thing) && length($thing));
298 }
299
300 sub cmd
301 {
302     my ($self, @args)=@_;
303     # don't care about retcode
304     $self->cmd_sth(@args);
305 }
306
307 sub cmd_onerow
308 {
309     my ($self, @args)=@_;
310     my $sth=$self->cmd_sth(@args);
311     return($sth->fetchrow_array());
312 }
313
314 sub cmd_rows
315 {
316     my ($self, @args)=@_;
317     my $sth=$self->cmd_sth(@args);
318     return $sth->fetchall_arrayref();
319 }
320
321 sub cmd_id
322 {
323     my ($self, @args)=@_;
324     $self->cmd_sth(@args);
325     return($self->last_insert_id());
326 }
327
328 sub last_insert_id
329 {
330     my $self=shift;
331     if($self->{postgres})
332     {
333         return $self->{dbh}->last_insert_id(undef, undef, undef, undef,
334                                             { sequence => "seq" });
335     }
336     else
337     {
338         return $self->{dbh}->last_insert_id("","","","");
339     }
340 }
341
342 __DATA__
343
344 CREATE TABLE id3fs (
345     schema_version INTEGER
346 );
347
348 CREATE TABLE files (
349     id INTEGER PRIMARY KEY,
350     name text
351 );
352
353 CREATE TABLE artists (
354     id INTEGER PRIMARY KEY,
355     name text
356 );
357
358 CREATE TABLE albums (
359     id INTEGER PRIMARY KEY,
360     name text
361 );
362
363 CREATE TABLE tags (
364     id INTEGER PRIMARY KEY,
365     name text
366 );
367
368 CREATE TABLE tagvals (
369     id INTEGER PRIMARY KEY,
370     name text
371 );
372
373 CREATE TABLE files_x_tags (
374     files_id INTEGER,
375     tags_id INTEGER
376 );
377
378 CREATE TABLE tags_x_tagvals (
379     tags_id INTEGER,
380     tagvals_id INTEGER
381 );
382
383 CREATE TABLE files_x_artists (
384     files_id INTEGER,
385     artists_id INTEGER
386 );
387
388 CREATE TABLE artists_x_albums (
389     artists_id INTEGER,
390     albums_id INTEGER
391 );