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

Last change on this file since 79 was 78, checked in by peter, 10 years ago
  • Separated out the creation of the where clause into a separate function.
  • Revised the where clause to only intersect select statements from the tag table.
File size: 10.4 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 _sql_where_clause {
77    my $self = shift;
78    my $search = shift;
79
80    # build the where clause
81    my @sql;
82    if (@{ $search->tags }) {
83        push @sql, 'where resources.uri in';
84        # subquery to find tagged URIs
85        push @sql, '(';
86        my $intersect = 0;
87        for my $tag (@{ $search->tags }) {
88            push @sql, 'intersect' if $intersect;
89            push @sql, 'select uri from tags where tag =', \$tag;
90            $intersect++;
91        }
92        push @sql, ')';
93    }
94    if ($search->query) {
95        my $fuzzy_match = '%' . $search->query . '%';
96        push @sql, (@{ $search->tags } ? 'and' : 'where'), 'title like', \$fuzzy_match;
97    }
98    return @sql;
99}
100
101sub get_bookmarks {
102    my $self = shift;
103    my $params = shift || {};
104    my $search = Bookmarks::Search->new($params);
105
106    # build the query
107    my @sql;
108
109    push @sql, 'select * from resources join bookmarks on resources.uri = bookmarks.uri';
110    push @sql, $self->_sql_where_clause($search);
111    push @sql, 'order by ctime desc';
112    push @sql, ('limit', \$search->limit) if $search->limit;
113    # an offset is only allowed if we have a limit clause
114    push @sql, ('offset', \$search->offset) if $search->limit && $search->offset;
115
116    my ($sql, @bind) = sql_interp(@sql);
117
118    my $sth_resource = $self->dbh->prepare($sql);
119    $sth_resource->execute(@bind);
120
121    my @resources;
122    while (my $resource = $sth_resource->fetchrow_hashref) {
123        push @resources, Bookmark->new({
124            %$resource,
125            exists     => 1,
126            tags       => [ $self->get_tags({ uri => $resource->{uri} }) ],
127            base_uri   => $self->base_uri,
128            collection => $self,
129        });
130    }
131    return Bookmarks::List->new({
132        bookmarks => $self,
133        search    => $search,
134        results   => \@resources,
135    });
136}
137
138sub get_tags {
139    my $self = shift;
140    my $params = shift;
141    if (my $uri = $params->{uri}) {
142        # get the tags for a particular URI
143        $self->_sth_tags_from_uri->execute($uri);
144        return map { $$_[0] } @{ $self->_sth_tags_from_uri->fetchall_arrayref };
145    } else {
146        # return all tags
147        my $tag = $params->{selected};
148        my $sth_all_tags = $self->dbh->prepare('select tag, count(tag) as count, tag = ? as selected from tags group by tag order by tag');
149        $sth_all_tags->execute($tag);
150        my $all_tags = $sth_all_tags->fetchall_arrayref({});
151        return @{ $all_tags };
152    }
153}
154
155sub get_cotags {
156    my $self = shift;
157    my $params = shift;
158    my $search = $params->{search};
159
160    my @sql;
161
162    push @sql, 'select tag, count(tag) as count from tags';
163    push @sql, 'join resources on tags.uri = resources.uri' if $search->query;
164
165    # build the where clause
166    if (@{ $search->tags }) {
167        push @sql, 'where tags.uri in (';
168        my $intersect = 0;
169        for my $tag (@{ $search->tags }) {
170            push @sql, 'intersect' if $intersect;
171            push @sql, 'select uri from tags where tag = ', \$tag;
172            $intersect++;
173        }
174        push @sql, ') and tag not in ', $search->tags, '';
175    }
176    if ($search->query) {
177        my $fuzzy_match = '%' . $search->query . '%';
178        push @sql, (@{ $search->tags } ? 'and' : 'where'), 'title like', \$fuzzy_match;
179    }
180
181    push @sql, 'group by tag order by tag';
182
183    my ($sql, @bind) = sql_interp(@sql);
184    my $sth = $self->dbh->prepare($sql);
185    $sth->execute(@bind);
186    return @{ $sth->fetchall_arrayref({}) };
187}
188
189sub get_last_modified_time {
190    my $self = shift;
191    my $sth = $self->dbh->prepare('select mtime from bookmarks order by mtime desc limit 1');
192    $sth->execute;
193    my ($mtime) = $sth->fetchrow_array;
194    return $mtime;
195}
196
197sub add {
198    my $self = shift;
199    my $bookmark = shift;
200
201    #TODO: accept a pre-made Bookmark object in addition to a hash
202    my $uri = $bookmark->{uri};
203    my $title = $bookmark->{title};
204    my $ctime = $bookmark->{ctime} || time;
205    my $mtime = $bookmark->{mtime} || $ctime;
206    my $id = $bookmark->{id};
207
208    # create an entry for the resource
209    my $sth_resource = $self->dbh->prepare('insert into resources (uri, title) values (?, ?)');
210    eval {
211        $sth_resource->execute($uri, $title);
212    };
213    if ($@) {
214        if ($@ =~ /column uri is not unique/) {
215            # this is not truly an error condition; the resource is already listed
216            # update the title instead
217            my $sth_update = $self->dbh->prepare('update resources set title = ? where uri = ?');
218            $sth_update->execute($title, $uri);
219        } else {
220            die $@;
221        }
222    }
223
224    # create the bookmark
225    my $bookmark_exists = 0;
226    my ($sql_bookmark, @bind_bookmark) = sql_interp(
227        'insert into bookmarks', { ($id ? (id => $id) : ()), uri => $uri, ctime => $ctime, mtime => $mtime }
228    );
229    my $sth_bookmark = $self->dbh->prepare($sql_bookmark);
230    eval {
231        $sth_bookmark->execute(@bind_bookmark);
232    };
233    if ($@) {
234        if ($@ =~ /column uri is not unique/) {
235            # this is not truly an error condition; the bookmark was already there
236            # set this flag so that later we can update the mtime if tags change
237            $bookmark_exists = 1;
238        } else {
239            die $@;
240        }
241    }
242
243    my $changed_tags = $self->_update_tags($uri, $bookmark->{tags});
244
245    if ($bookmark_exists && $changed_tags) {
246        # update the mtime if the bookmark already existed but the tags were changed
247        my $sth_update = $self->dbh->prepare('update bookmarks set mtime = ? where uri = ?');
248        $sth_update->execute($mtime, $uri);
249    }
250
251    # return the newly created or updated bookmark
252    return $self->get_bookmark({ uri => $uri });
253}
254
255sub update {
256    my $self = shift;
257    my $bookmark = shift;
258
259    my $mtime = time;
260
261    # update the URI, if it has changed
262    my $changed_uri = 0;
263    my $sth_current = $self->dbh->prepare('select uri from bookmarks where id = ?');
264    $sth_current->execute($bookmark->id);
265    my ($stored_uri) = $sth_current->fetchrow_array;
266
267    if ($stored_uri ne $bookmark->uri) {
268        # the URI has changed
269        my $sth_update_uri = $self->dbh->prepare('update resources set uri = ? where uri = ?');
270        $sth_update_uri->execute($bookmark->uri, $stored_uri);
271        $changed_uri++;
272    }
273
274    # update the title, if it has changed
275    my $changed_title = 0;
276    my $sth_current_title = $self->dbh->prepare('select title from resources where uri = ?');
277    $sth_current_title->execute($bookmark->uri);
278    my ($stored_title) = $sth_current_title->fetchrow_array;
279
280    if ($stored_title ne $bookmark->title) {
281        my $sth_update = $self->dbh->prepare('update resources set title = ? where uri = ?');
282        $sth_update->execute($bookmark->title, $bookmark->uri);
283        $changed_title++;
284    }
285
286    # update the tags, if they have changed
287    my $changed_tags = $self->_update_tags($bookmark->uri, $bookmark->tags);
288
289    # update the mtime, if the bookmark has actually been changed
290    if ($changed_uri or $changed_title or $changed_tags) {
291        # update the mtime if the bookmark already existed but the tags were changed
292        my $sth_update = $self->dbh->prepare('update bookmarks set mtime = ? where uri = ?');
293        $sth_update->execute($mtime, $bookmark->uri);
294    }
295
296    # return the bookmark
297    return $bookmark;
298}
299
300sub _update_tags {
301    my $self = shift;
302    my ($uri, $tags) = @_;
303
304    my $changed_tags = 0;
305    my %new_tags = map { $_ => 1 } @{ $tags };
306    my $sth_delete_tag = $self->dbh->prepare('delete from tags where uri = ? and tag = ?');
307    my $sth_insert_tag = $self->dbh->prepare('insert into tags (uri, tag) values (?, ?)');
308    my $sth_current_tags = $self->dbh->prepare('select tag from tags where uri = ?');
309    $sth_current_tags->execute($uri);
310    while (my ($tag) = $sth_current_tags->fetchrow_array) {
311        if (!$new_tags{$tag}) {
312            # if a current tag is not in the new tags, remove it from the database
313            $sth_delete_tag->execute($uri, $tag);
314            $changed_tags++;
315        } else {
316            # if a new tag is already in the database, remove it from the list of tags to add
317            delete $new_tags{$tag};
318        }
319    }
320    for my $tag (keys %new_tags) {
321        $sth_insert_tag->execute($uri, $tag);
322        $changed_tags++;
323    }
324
325    # how many tags have changed?
326    return $changed_tags;
327}
328
329
330# module returns true
3311;
Note: See TracBrowser for help on using the repository browser.