source: bookmarks/trunk/Bookmarks.pm @ 41

Last change on this file since 41 was 28, checked in by peter, 11 years ago

only update the mtime of an existing bookmark if its tags change

File size: 7.3 KB
Line 
1package Bookmarks;
2
3use Moose;
4use SQL::Interp qw{:all};
5use URI;
6use Bookmark;
7
8has dbh      => ( is => 'rw' );
9has base_uri => ( is => 'ro', isa => 'URI' );
10
11has _sth_tags_from_uri => (
12    is       => 'ro',
13    init_arg => undef,
14    lazy     => 1,
15    default  => sub { $_[0]->dbh->prepare('select tag from tags where uri = ? order by tag'); },
16);
17
18sub BUILD {
19    my $self = shift;
20    my $args = shift;
21
22    if (!$self->dbh) {
23        if ($args->{dbname}) {
24            require DBI;
25            $self->dbh(DBI->connect("dbi:SQLite:dbname=$$args{dbname}", "", "", { RaiseError => 1, PrintError => 0 }));
26            # enable foreign key support (requires DBD::SQLite 1.26_05 or above (sqlite 3.6.19 or above))
27            $self->dbh->do('pragma foreign_keys = on;');
28        } else {
29            #TODO: figure out how to make croak play nice with Moose to get the user-visible caller line
30            die "No dbh or dbname specified in the constructor";
31        }
32    }
33}
34
35sub get_bookmark {
36    my $self = shift;
37    my $params = shift;
38
39    # look for bookmark by id or uri
40    my $sth;
41    if ($params->{id}) {
42        $sth = $self->dbh->prepare('select id,resources.uri,title,ctime,mtime from bookmarks join resources on bookmarks.uri=resources.uri where id=?');
43        $sth->execute($params->{id});
44    } elsif ($params->{uri}) {
45        $sth = $self->dbh->prepare('select id,resources.uri,title,ctime,mtime from bookmarks join resources on bookmarks.uri=resources.uri where resources.uri=?');
46        $sth->execute($params->{uri});
47    } else {
48        die "Must specify either id or uri";
49    }
50    my $bookmark = $sth->fetchrow_hashref;
51    return unless $bookmark;
52
53    return Bookmark->new({
54        %$bookmark,
55        tags     => [ $self->get_tags({ uri => $bookmark->{uri} }) ],
56        base_uri => $self->base_uri,
57    });
58}
59
60sub get_bookmarks {
61    my $self = shift;
62    my $params = shift;
63    my $tags = $params->{tag} || [];
64    my $limit = $params->{limit};
65    my $offset = $params->{offset};
66
67    # build the query
68    my @sql;
69
70    if (!ref $tags) {
71        $tags = [ $tags ];
72    }
73    if (@$tags) {
74        my $intersect = 0;
75        for my $tag (@{ $tags }) {
76            push @sql, 'intersect' if $intersect;
77            push @sql, 'select resources.*, bookmarks.* from resources join bookmarks on resources.uri = bookmarks.uri';
78            push @sql, 'join tags on resources.uri = tags.uri where tags.tag =', \$tag;
79            $intersect++;
80        }
81    } else {
82        push @sql, 'select * from resources join bookmarks on resources.uri = bookmarks.uri';
83    }
84    push @sql, 'order by ctime desc';
85    push @sql, ('limit', \$limit) if $limit;
86    # an offset is only allowed if we have a limit clause
87    push @sql, ('offset', \$offset) if $limit && $offset;
88
89    my ($sql, @bind) = sql_interp(@sql);
90
91    my $sth_resource = $self->dbh->prepare($sql);
92    $sth_resource->execute(@bind);
93
94    my @resources;
95    while (my $resource = $sth_resource->fetchrow_hashref) {
96        push @resources, Bookmark->new({
97            %$resource,
98            tags     => [ $self->get_tags({ uri => $resource->{uri} }) ],
99            base_uri => $self->base_uri,
100        });
101    }
102    return @resources;
103}
104
105sub get_tags {
106    my $self = shift;
107    my $params = shift;
108    if (my $uri = $params->{uri}) {
109        # get the tags for a particular URI
110        $self->_sth_tags_from_uri->execute($uri);
111        return map { $$_[0] } @{ $self->_sth_tags_from_uri->fetchall_arrayref };
112    } else {
113        # return all tags
114        my $tag = $params->{selected};
115        my $sth_all_tags = $self->dbh->prepare('select tag, count(tag) as count, tag = ? as selected from tags group by tag order by tag');
116        $sth_all_tags->execute($tag);
117        my $all_tags = $sth_all_tags->fetchall_arrayref({});
118        return @{ $all_tags };
119    }
120}
121
122sub get_cotags {
123    my $self = shift;
124    my $params = shift;
125    my $tags = $params->{tag} || [];
126    if (!ref $tags) {
127        $tags = [ $tags ];
128    }
129    my @sql;
130
131    push @sql, 'select tag, count(tag) as count from tags';
132    if (@$tags) {
133        push @sql, 'where uri in (';
134        my $intersect = 0;
135        for my $tag (@{ $tags }) {
136            push @sql, 'intersect' if $intersect;
137            push @sql, 'select uri from tags where tag = ', \$tag;
138            $intersect++;
139        }
140        push @sql, ') and tag not in ', $tags, '';
141    }
142    push @sql, 'group by tag order by tag';
143
144    my ($sql, @bind) = sql_interp(@sql);
145    my $sth = $self->dbh->prepare($sql);
146    $sth->execute(@bind);
147    return @{ $sth->fetchall_arrayref({}) };
148}
149
150sub add {
151    my $self = shift;
152    my $bookmark = shift;
153
154    my $uri = $bookmark->{uri};
155    my $title = $bookmark->{title};
156    my $ctime = $bookmark->{ctime} || time;
157    my $mtime = $bookmark->{mtime} || $ctime;
158    my $id = $bookmark->{id};
159
160    # create an entry for the resource
161    my $sth_resource = $self->dbh->prepare('insert into resources (uri, title) values (?, ?)');
162    eval {
163        $sth_resource->execute($uri, $title);
164    };
165    if ($@) {
166        if ($@ =~ /column uri is not unique/) {
167            # this is not truly an error condition; the resource is already listed
168            # update the title instead
169            my $sth_update = $self->dbh->prepare('update resources set title = ? where uri = ?');
170            $sth_update->execute($title, $uri);
171        } else {
172            die $@;
173        }
174    }
175
176    # create the bookmark
177    my $bookmark_exists = 0;
178    my ($sql_bookmark, @bind_bookmark) = sql_interp(
179        'insert into bookmarks', { ($id ? (id => $id) : ()), uri => $uri, ctime => $ctime, mtime => $mtime }
180    );
181    my $sth_bookmark = $self->dbh->prepare($sql_bookmark);
182    eval {
183        $sth_bookmark->execute(@bind_bookmark);
184    };
185    if ($@) {
186        if ($@ =~ /column uri is not unique/) {
187            # this is not truly an error condition; the bookmark was already there
188            # set this flag so that later we can update the mtime if tags change
189            $bookmark_exists = 1;
190        } else {
191            die $@;
192        }
193    }
194
195    my $changed_tags = 0;
196    my %new_tags = map { $_ => 1 } @{ $bookmark->{tags} };
197    my $sth_delete_tag = $self->dbh->prepare('delete from tags where uri = ? and tag = ?');
198    my $sth_insert_tag = $self->dbh->prepare('insert into tags (uri, tag) values (?, ?)');
199    my $sth_current_tags = $self->dbh->prepare('select tag from tags where uri = ?');
200    $sth_current_tags->execute($uri);
201    while (my ($tag) = $sth_current_tags->fetchrow_array) {
202        if (!$new_tags{$tag}) {
203            # if a current tag is not in the new tags, remove it from the database
204            $sth_delete_tag->execute($uri, $tag);
205            $changed_tags++;
206        } else {
207            # if a new tag is already in the database, remove it from the list of tags to add
208            delete $new_tags{$tag};
209        }
210    }
211    for my $tag (keys %new_tags) {
212        $sth_insert_tag->execute($uri, $tag);
213        $changed_tags++;
214    }
215
216    if ($bookmark_exists && $changed_tags) {
217        # update the mtime if the bookmark already existed but the tags were changed
218        my $sth_update = $self->dbh->prepare('update bookmarks set mtime = ? where uri = ?');
219        $sth_update->execute($mtime, $uri);
220    }
221
222    # return the newly created or updated bookmark
223    return $self->get_bookmark({ uri => $uri });
224}
225
226# module returns true
2271;
Note: See TracBrowser for help on using the repository browser.