ID3FS: use File::Find to recursively add files
[id3fs.git] / lib / ID3FS / DB.pm
1 package ID3FS::DB;
2
3 use strict;
4 use warnings;
5 use DBI;
6
7 our $SCHEMA_VERSION=1;
8
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     die("$me: $self->{dbpath}: not found. use --init to create.\n") if(!$exists && !$init);
24     die("$me: --init used but $self->{dbpath} exists.\n")           if($exists && $init);
25
26     $self->{dbh}=DBI->connect("dbi:SQLite:dbname=$self->{dbpath}","","",
27                               { AutoCommit=>1 } );
28     unless(defined($self->{dbh}))
29     {
30         die("$me: DB Error: " . $DBI::errstr . "\n");
31     }
32
33     if($init)
34     {
35         $self->create();
36     }
37     else
38     {
39         $self->checkschema();
40     }
41
42     return $self;
43 }
44
45 sub create
46 {
47     my($self,$name)=@_;
48     my @schema=split(/\n\n/,join("", <DATA>));
49     close(DATA);
50     for my $cmd (@schema)
51     {
52         $self->{dbh}->do($cmd);
53     }
54     $self->cmd("INSERT INTO id3fs (schema_version) VALUES (?)", $SCHEMA_VERSION);
55 }
56
57 sub checkschema
58 {
59     my $self=shift;
60     my ($version)=$self->cmd_onerow("SELECT schema_version from id3fs");
61     if(!defined($version) || $version != $SCHEMA_VERSION)
62     {
63         die("$self->{me}: id3fs database version " .
64             defined($version) ? $version : '""' .
65             "not known, current version is $SCHEMA_VERSION.\n");
66     }
67 }
68
69 sub cmd_sth
70 {
71     my($self, $sql, @params)=@_;
72     my $sth=$self->{dbh}->prepare($sql);
73     my $idx=1;
74     for my $param (@params)
75     {
76         $param="" unless(defined($param));
77         $sth->bind_param($idx++, $param);
78     }
79     $sth->execute();
80     return $sth;
81 }
82
83 sub add
84 {
85     my($self,$path)=@_;
86 }
87
88 sub cmd
89 {
90     my ($self, @args)=@_;
91     # don't care about retcode
92     $self->cmd_sth(@args);
93 }
94
95 sub cmd_onerow
96 {
97     my ($self, @args)=@_;
98     my $sth=$self->cmd_sth(@args);
99     return($sth->fetchrow_array());
100 }
101
102 __DATA__
103
104 CREATE TABLE id3fs (
105     schema_version
106 );
107
108 CREATE TABLE files (
109     id INTEGER PRIMARY KEY,
110     path
111 );
112
113 CREATE TABLE tags (
114     id INTEGER PRIMARY KEY,
115     name
116 );
117
118 CREATE TABLE tags_x_files (
119     files_id,
120     tags_id
121 );
122
123 CREATE TABLE v1genres (
124    id,
125    name
126 );