source: bookmarks/trunk/lib/Bookmarks.pm @ 76

Last change on this file since 76 was 76, checked in by peter, 10 years ago
  • only update the title if it has changed
  • update the mtime if the bookmark title has changed
File size: 10.3 KB
Line 
1package Bookmarks;
2
3use Moose;
4
5use SQL::Interp qw{:all};
6use URI;
7
8use Bookmark;
9use Bookmarks::List;
10use Bookmarks::Search;
11
12has dbh      => ( is => 'rw' );
13has base_uri => ( is => 'ro', isa => 'URI' );
14
15has _sth_tags_from_uri => (
16    is       => 'ro',
17    init_arg => undef,
18    lazy     => 1,
19    default  => sub { $_[0]->dbh->prepare('select tag from tags where uri = ? order by tag'); },
20);
21
22sub BUILD {
23    my $self = shift;
24    my $args = shift;
25
26    if (!$self->dbh) {
27        if ($args->{dbname}) {
28            require DBI;
29            $self->dbh(DBI->connect("dbi:SQLite:dbname=$$args{dbname}", "", "", { RaiseError => 1, PrintError => 0 }));
30            # enable foreign key support (requires DBD::SQLite 1.26_05 or above (sqlite 3.6.19 or above))
31            $self->dbh->do('pragma foreign_keys = on;');
32        } else {
33            #TODO: figure out how to make croak play nice with Moose to get the user-visible caller line
34            die "No dbh or dbname specified in the constructor";
35        }
36    }
37}
38
39sub create_tables {
40    my $self = shift;
41    require File::Slurp;
42    my $table_definitions = File::Slurp::read_file('bookmarks.sql');
43    $self->dbh->{sqlite_allow_multiple_statements} = 1;
44    $self->dbh->do($table_definitions);
45    $self->dbh->{sqlite_allow_multiple_statements} = 0;
46    return $self;
47}
48
49sub get_bookmark {
50    my $self = shift;
51    my $params = shift;
52
53    # look for bookmark by id or uri
54    my $sth;
55    if ($params->{id}) {
56        $sth = $self->dbh->prepare('select id,resources.uri,title,ctime,mtime from bookmarks join resources on bookmarks.uri=resources.uri where id=?');
57        $sth->execute($params->{id});
58    } elsif ($params->{uri}) {
59        $sth = $self->dbh->prepare('select id,resources.uri,title,ctime,mtime from bookmarks join resources on bookmarks.uri=resources.uri where resources.uri=?');
60        $sth->execute($params->{uri});
61    } else {
62        die "Must specify either id or uri";
63    }
64    my $bookmark = $sth->fetchrow_hashref;
65    return unless $bookmark;
66
67    return Bookmark->new({
68        %$bookmark,
69        exists     => 1,
70        tags       => [ $self->get_tags({ uri => $bookmark->{uri} }) ],
71        base_uri   => $self->base_uri,
72        collection => $self,
73    });
74}
75
76sub get_bookmarks {
77    my $self = shift;
78    my $params = shift || {};
79    my $search = Bookmarks::Search->new($params);
80
81    # build the query
82    my @sql;
83
84    if (@{ $search->tags }) {
85        my $intersect = 0;
86        for my $tag (@{ $search->tags }) {
87            push @sql, 'intersect' if $intersect;
88            push @sql, 'select resources.*, bookmarks.* from resources join bookmarks on resources.uri = bookmarks.uri';
89            push @sql, 'join tags on resources.uri = tags.uri where tags.tag =', \$tag;
90            $intersect++;
91        }
92    } else {
93        push @sql, 'select * from resources join bookmarks on resources.uri = bookmarks.uri';
94    }
95    if ($search->query) {
96        my $fuzzy_match = '%' . $search->query . '%';
97        push @sql, (@{ $search->tags } ? 'and' : 'where'), 'title like', \$fuzzy_match;
98    }
99    push @sql, 'order by ctime desc';
100    push @sql, ('limit', \$search->limit) if $search->limit;
101    # an offset is only allowed if we have a limit clause
102    push @sql, ('offset', \$search->offset) if $search->limit && $search->offset;
103
104    my ($sql, @bind) = sql_interp(@sql);
105
106    my $sth_resource = $self->dbh->prepare($sql);
107    $sth_resource->execute(@bind);
108
109    my @resources;
110    while (my $resource = $sth_resource->fetchrow_hashref) {
111        push @resources, Bookmark->new({
112            %$resource,
113            exists     => 1,
114            tags       => [ $self->get_tags({ uri => $resource->{uri} }) ],
115            base_uri   => $self->base_uri,
116            collection => $self,
117        });
118    }
119    return Bookmarks::List->new({
120        bookmarks => $self,
121        search    => $search,
122        results   => \@resources,
123    });
124}
125
126sub get_tags {
127    my $self = shift;
128    my $params = shift;
129    if (my $uri = $params->{uri}) {
130        # get the tags for a particular URI
131        $self->_sth_tags_from_uri->execute($uri);
132        return map { $$_[0] } @{ $self->_sth_tags_from_uri->fetchall_arrayref };
133    } else {
134        # return all tags
135        my $tag = $params->{selected};
136        my $sth_all_tags = $self->dbh->prepare('select tag, count(tag) as count, tag = ? as selected from tags group by tag order by tag');
137        $sth_all_tags->execute($tag);
138        my $all_tags = $sth_all_tags->fetchall_arrayref({});
139        return @{ $all_tags };
140    }
141}
142
143sub get_cotags {
144    my $self = shift;
145    my $params = shift;
146    my $search = $params->{search};
147
148    my @sql;
149
150    push @sql, 'select tag, count(tag) as count from tags';
151    push @sql, 'join resources on tags.uri = resources.uri' if $search->query;
152
153    # build the where clause
154    if (@{ $search->tags }) {
155        push @sql, 'where tags.uri in (';
156        my $intersect = 0;
157        for my $tag (@{ $search->tags }) {
158            push @sql, 'intersect' if $intersect;
159            push @sql, 'select uri from tags where tag = ', \$tag;
160            $intersect++;
161        }
162        push @sql, ') and tag not in ', $search->tags, '';
163    }
164    if ($search->query) {
165        my $fuzzy_match = '%' . $search->query . '%';
166        push @sql, (@{ $search->tags } ? 'and' : 'where'), 'title like', \$fuzzy_match;
167    }
168
169    push @sql, 'group by tag order by tag';
170
171    my ($sql, @bind) = sql_interp(@sql);
172    my $sth = $self->dbh->prepare($sql);
173    $sth->execute(@bind);
174    return @{ $sth->fetchall_arrayref({}) };
175}
176
177sub get_last_modified_time {
178    my $self = shift;
179    my $sth = $self->dbh->prepare('select mtime from bookmarks order by mtime desc limit 1');
180    $sth->execute;
181    my ($mtime) = $sth->fetchrow_array;
182    return $mtime;
183}
184
185sub add {
186    my $self = shift;
187    my $bookmark = shift;
188
189    #TODO: accept a pre-made Bookmark object in addition to a hash
190    my $uri = $bookmark->{uri};
191    my $title = $bookmark->{title};
192    my $ctime = $bookmark->{ctime} || time;
193    my $mtime = $bookmark->{mtime} || $ctime;
194    my $id = $bookmark->{id};
195
196    # create an entry for the resource
197    my $sth_resource = $self->dbh->prepare('insert into resources (uri, title) values (?, ?)');
198    eval {
199        $sth_resource->execute($uri, $title);
200    };
201    if ($@) {
202        if ($@ =~ /column uri is not unique/) {
203            # this is not truly an error condition; the resource is already listed
204            # update the title instead
205            my $sth_update = $self->dbh->prepare('update resources set title = ? where uri = ?');
206            $sth_update->execute($title, $uri);
207        } else {
208            die $@;
209        }
210    }
211
212    # create the bookmark
213    my $bookmark_exists = 0;
214    my ($sql_bookmark, @bind_bookmark) = sql_interp(
215        'insert into bookmarks', { ($id ? (id => $id) : ()), uri => $uri, ctime => $ctime, mtime => $mtime }
216    );
217    my $sth_bookmark = $self->dbh->prepare($sql_bookmark);
218    eval {
219        $sth_bookmark->execute(@bind_bookmark);
220    };
221    if ($@) {
222        if ($@ =~ /column uri is not unique/) {
223            # this is not truly an error condition; the bookmark was already there
224            # set this flag so that later we can update the mtime if tags change
225            $bookmark_exists = 1;
226        } else {
227            die $@;
228        }
229    }
230
231    my $changed_tags = $self->_update_tags($uri, $bookmark->{tags});
232
233    if ($bookmark_exists && $changed_tags) {
234        # update the mtime if the bookmark already existed but the tags were changed
235        my $sth_update = $self->dbh->prepare('update bookmarks set mtime = ? where uri = ?');
236        $sth_update->execute($mtime, $uri);
237    }
238
239    # return the newly created or updated bookmark
240    return $self->get_bookmark({ uri => $uri });
241}
242
243sub update {
244    my $self = shift;
245    my $bookmark = shift;
246
247    my $mtime = time;
248
249    # update the URI, if it has changed
250    my $changed_uri = 0;
251    my $sth_current = $self->dbh->prepare('select uri from bookmarks where id = ?');
252    $sth_current->execute($bookmark->id);
253    my ($stored_uri) = $sth_current->fetchrow_array;
254
255    if ($stored_uri ne $bookmark->uri) {
256        # the URI has changed
257        my $sth_update_uri = $self->dbh->prepare('update resources set uri = ? where uri = ?');
258        $sth_update_uri->execute($bookmark->uri, $stored_uri);
259        $changed_uri++;
260    }
261
262    # update the title, if it has changed
263    my $changed_title = 0;
264    my $sth_current_title = $self->dbh->prepare('select title from resources where uri = ?');
265    $sth_current_title->execute($bookmark->uri);
266    my ($stored_title) = $sth_current_title->fetchrow_array;
267
268    if ($stored_title ne $bookmark->title) {
269        my $sth_update = $self->dbh->prepare('update resources set title = ? where uri = ?');
270        $sth_update->execute($bookmark->title, $bookmark->uri);
271        $changed_title++;
272    }
273
274    # update the tags, if they have changed
275    my $changed_tags = $self->_update_tags($bookmark->uri, $bookmark->tags);
276
277    # update the mtime, if the bookmark has actually been changed
278    if ($changed_uri or $changed_title or $changed_tags) {
279        # update the mtime if the bookmark already existed but the tags were changed
280        my $sth_update = $self->dbh->prepare('update bookmarks set mtime = ? where uri = ?');
281        $sth_update->execute($mtime, $bookmark->uri);
282    }
283
284    # return the bookmark
285    return $bookmark;
286}
287
288sub _update_tags {
289    my $self = shift;
290    my ($uri, $tags) = @_;
291
292    my $changed_tags = 0;
293    my %new_tags = map { $_ => 1 } @{ $tags };
294    my $sth_delete_tag = $self->dbh->prepare('delete from tags where uri = ? and tag = ?');
295    my $sth_insert_tag = $self->dbh->prepare('insert into tags (uri, tag) values (?, ?)');
296    my $sth_current_tags = $self->dbh->prepare('select tag from tags where uri = ?');
297    $sth_current_tags->execute($uri);
298    while (my ($tag) = $sth_current_tags->fetchrow_array) {
299        if (!$new_tags{$tag}) {
300            # if a current tag is not in the new tags, remove it from the database
301            $sth_delete_tag->execute($uri, $tag);
302            $changed_tags++;
303        } else {
304            # if a new tag is already in the database, remove it from the list of tags to add
305            delete $new_tags{$tag};
306        }
307    }
308    for my $tag (keys %new_tags) {
309        $sth_insert_tag->execute($uri, $tag);
310        $changed_tags++;
311    }
312
313    # how many tags have changed?
314    return $changed_tags;
315}
316
317
318# module returns true
3191;
Note: See TracBrowser for help on using the repository browser.