source: bookmarks/trunk/Bookmarks.pm @ 52

Last change on this file since 52 was 52, checked in by peter, 11 years ago
  • Bookmarks::get_bookmarks() and Bookmarks::get_cotags() support a query argument that limits the results to the bookmarks whose titles contain the query (implemented using SQL LIKE)
  • the bookmark application takes a q query parameter and uses it as the bookmark text query
  • added a text input to enter a text query
File size: 9.3 KB
RevLine 
[2]1package Bookmarks;
2
[15]3use Moose;
[9]4use SQL::Interp qw{:all};
[24]5use URI;
[2]6use Bookmark;
7
[15]8has dbh      => ( is => 'rw' );
[24]9has base_uri => ( is => 'ro', isa => 'URI' );
[2]10
[25]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
[15]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
[47]35sub create_tables {
36    my $self = shift;
37    require File::Slurp;
38    my $table_definitions = File::Slurp::read_file('bookmarks.sql');
39    $self->dbh->{sqlite_allow_multiple_statements} = 1;
40    $self->dbh->do($table_definitions);
41    $self->dbh->{sqlite_allow_multiple_statements} = 0;
42    return $self;
43}
44
[2]45sub get_bookmark {
46    my $self = shift;
47    my $params = shift;
[25]48
49    # look for bookmark by id or uri
[2]50    my $sth;
51    if ($params->{id}) {
52        $sth = $self->dbh->prepare('select id,resources.uri,title,ctime,mtime from bookmarks join resources on bookmarks.uri=resources.uri where id=?');
53        $sth->execute($params->{id});
54    } elsif ($params->{uri}) {
55        $sth = $self->dbh->prepare('select id,resources.uri,title,ctime,mtime from bookmarks join resources on bookmarks.uri=resources.uri where resources.uri=?');
56        $sth->execute($params->{uri});
57    } else {
58        die "Must specify either id or uri";
59    }
60    my $bookmark = $sth->fetchrow_hashref;
[25]61    return unless $bookmark;
62
63    return Bookmark->new({
64        %$bookmark,
65        tags     => [ $self->get_tags({ uri => $bookmark->{uri} }) ],
66        base_uri => $self->base_uri,
67    });
[2]68}
69
[26]70sub get_bookmarks {
[2]71    my $self = shift;
72    my $params = shift;
[52]73    my $query = $params->{query};
[20]74    my $tags = $params->{tag} || [];
[9]75    my $limit = $params->{limit};
[13]76    my $offset = $params->{offset};
[2]77
[20]78    # build the query
79    my @sql;
[9]80
[20]81    if (!ref $tags) {
82        $tags = [ $tags ];
83    }
84    if (@$tags) {
85        my $intersect = 0;
86        for my $tag (@{ $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    }
[52]95    if ($query) {
96        push @sql, (@$tags ? 'and' : 'where'), 'title like', \"%$query%";
97    }
[20]98    push @sql, 'order by ctime desc';
99    push @sql, ('limit', \$limit) if $limit;
100    # an offset is only allowed if we have a limit clause
101    push @sql, ('offset', \$offset) if $limit && $offset;
102
103    my ($sql, @bind) = sql_interp(@sql);
[52]104    #die $sql;
[20]105
[9]106    my $sth_resource = $self->dbh->prepare($sql);
107    $sth_resource->execute(@bind);
108
[2]109    my @resources;
110    while (my $resource = $sth_resource->fetchrow_hashref) {
[25]111        push @resources, Bookmark->new({
112            %$resource,
113            tags     => [ $self->get_tags({ uri => $resource->{uri} }) ],
114            base_uri => $self->base_uri,
115        });
[2]116    }
117    return @resources;
118}
119
120sub get_tags {
121    my $self = shift;
122    my $params = shift;
[25]123    if (my $uri = $params->{uri}) {
124        # get the tags for a particular URI
125        $self->_sth_tags_from_uri->execute($uri);
126        return map { $$_[0] } @{ $self->_sth_tags_from_uri->fetchall_arrayref };
127    } else {
128        # return all tags
129        my $tag = $params->{selected};
130        my $sth_all_tags = $self->dbh->prepare('select tag, count(tag) as count, tag = ? as selected from tags group by tag order by tag');
131        $sth_all_tags->execute($tag);
132        my $all_tags = $sth_all_tags->fetchall_arrayref({});
133        return @{ $all_tags };
134    }
[2]135}
136
137sub get_cotags {
138    my $self = shift;
139    my $params = shift;
[52]140    my $query = $params->{query};
[20]141    my $tags = $params->{tag} || [];
142    if (!ref $tags) {
143        $tags = [ $tags ];
144    }
145    my @sql;
146
147    push @sql, 'select tag, count(tag) as count from tags';
[52]148    push @sql, 'join resources on tags.uri = resources.uri' if $query;
149
150    # build the where clause
[20]151    if (@$tags) {
[52]152        push @sql, 'where tags.uri in (';
[20]153        my $intersect = 0;
154        for my $tag (@{ $tags }) {
155            push @sql, 'intersect' if $intersect;
156            push @sql, 'select uri from tags where tag = ', \$tag;
157            $intersect++;
158        }
159        push @sql, ') and tag not in ', $tags, '';
160    }
[52]161    if ($query) {
162        push @sql, (@$tags ? 'and' : 'where'), 'title like', \"%$query%";
163    }
164
[20]165    push @sql, 'group by tag order by tag';
166
167    my ($sql, @bind) = sql_interp(@sql);
168    my $sth = $self->dbh->prepare($sql);
169    $sth->execute(@bind);
[2]170    return @{ $sth->fetchall_arrayref({}) };
171}
172
173sub add {
174    my $self = shift;
175    my $bookmark = shift;
176
177    my $uri = $bookmark->{uri};
178    my $title = $bookmark->{title};
[15]179    my $ctime = $bookmark->{ctime} || time;
180    my $mtime = $bookmark->{mtime} || $ctime;
181    my $id = $bookmark->{id};
[2]182
183    # create an entry for the resource
184    my $sth_resource = $self->dbh->prepare('insert into resources (uri, title) values (?, ?)');
185    eval {
186        $sth_resource->execute($uri, $title);
187    };
188    if ($@) {
189        if ($@ =~ /column uri is not unique/) {
190            # this is not truly an error condition; the resource is already listed
191            # update the title instead
192            my $sth_update = $self->dbh->prepare('update resources set title = ? where uri = ?');
193            $sth_update->execute($title, $uri);
194        } else {
195            die $@;
196        }
197    }
198
199    # create the bookmark
[28]200    my $bookmark_exists = 0;
[15]201    my ($sql_bookmark, @bind_bookmark) = sql_interp(
202        'insert into bookmarks', { ($id ? (id => $id) : ()), uri => $uri, ctime => $ctime, mtime => $mtime }
203    );
204    my $sth_bookmark = $self->dbh->prepare($sql_bookmark);
[2]205    eval {
[15]206        $sth_bookmark->execute(@bind_bookmark);
[2]207    };
208    if ($@) {
209        if ($@ =~ /column uri is not unique/) {
210            # this is not truly an error condition; the bookmark was already there
[28]211            # set this flag so that later we can update the mtime if tags change
212            $bookmark_exists = 1;
[2]213        } else {
214            die $@;
215        }
216    }
217
[46]218    my $changed_tags = $self->_update_tags($uri, $bookmark->{tags});
219
220    if ($bookmark_exists && $changed_tags) {
221        # update the mtime if the bookmark already existed but the tags were changed
222        my $sth_update = $self->dbh->prepare('update bookmarks set mtime = ? where uri = ?');
223        $sth_update->execute($mtime, $uri);
224    }
225
226    # return the newly created or updated bookmark
227    return $self->get_bookmark({ uri => $uri });
228}
229
230sub update {
231    my $self = shift;
232    my $bookmark = shift;
233
234    my $mtime = time;
235
236    my $changed_uri = 0;
237    my $sth_current = $self->dbh->prepare('select uri from bookmarks where id = ?');
238    $sth_current->execute($bookmark->id);
239    my ($stored_uri) = $sth_current->fetchrow_array;
240
241    if ($stored_uri ne $bookmark->uri) {
242        # the URI has changed
243        my $sth_update_uri = $self->dbh->prepare('update resources set uri = ? where uri = ?');
244        $sth_update_uri->execute($bookmark->uri, $stored_uri);
245        $changed_uri++;
246    }
247
248    # update the title
249    # TODO: only do this if the title has changed
250    # TODO: should we update mtime if the title changes?
251    my $sth_update = $self->dbh->prepare('update resources set title = ? where uri = ?');
252    $sth_update->execute($bookmark->title, $bookmark->uri);
253
254    my $changed_tags = $self->_update_tags($bookmark->uri, $bookmark->tags);
255
256    if ($changed_uri or $changed_tags) {
257        # update the mtime if the bookmark already existed but the tags were changed
258        my $sth_update = $self->dbh->prepare('update bookmarks set mtime = ? where uri = ?');
259        $sth_update->execute($mtime, $bookmark->uri);
260    }
261
262    # return the bookmark
263    return $bookmark;
264}
265
266sub _update_tags {
267    my $self = shift;
268    my ($uri, $tags) = @_;
269
[28]270    my $changed_tags = 0;
[46]271    my %new_tags = map { $_ => 1 } @{ $tags };
[2]272    my $sth_delete_tag = $self->dbh->prepare('delete from tags where uri = ? and tag = ?');
273    my $sth_insert_tag = $self->dbh->prepare('insert into tags (uri, tag) values (?, ?)');
274    my $sth_current_tags = $self->dbh->prepare('select tag from tags where uri = ?');
275    $sth_current_tags->execute($uri);
276    while (my ($tag) = $sth_current_tags->fetchrow_array) {
277        if (!$new_tags{$tag}) {
278            # if a current tag is not in the new tags, remove it from the database
279            $sth_delete_tag->execute($uri, $tag);
[28]280            $changed_tags++;
[2]281        } else {
282            # if a new tag is already in the database, remove it from the list of tags to add
283            delete $new_tags{$tag};
284        }
285    }
286    for my $tag (keys %new_tags) {
287        $sth_insert_tag->execute($uri, $tag);
[28]288        $changed_tags++;
[2]289    }
290
[46]291    # how many tags have changed?
292    return $changed_tags;
[2]293}
294
[46]295
[2]296# module returns true
2971;
Note: See TracBrowser for help on using the repository browser.