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

Last change on this file since 75 was 75, checked in by peter, 11 years ago
  • added a collection attribute to the Bookmark class
  • added an update() method to the Bookmark class that calls the collection->update() method, if the collection is set
  • Bookmarks::Controller::update_and_redirect() calls Bookmark::update()
File size: 9.9 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    my $changed_uri = 0;
250    my $sth_current = $self->dbh->prepare('select uri from bookmarks where id = ?');
251    $sth_current->execute($bookmark->id);
252    my ($stored_uri) = $sth_current->fetchrow_array;
253
254    if ($stored_uri ne $bookmark->uri) {
255        # the URI has changed
256        my $sth_update_uri = $self->dbh->prepare('update resources set uri = ? where uri = ?');
257        $sth_update_uri->execute($bookmark->uri, $stored_uri);
258        $changed_uri++;
259    }
260
261    # update the title
262    # TODO: only do this if the title has changed
263    # TODO: should we update mtime if the title changes?
264    my $sth_update = $self->dbh->prepare('update resources set title = ? where uri = ?');
265    $sth_update->execute($bookmark->title, $bookmark->uri);
266
267    my $changed_tags = $self->_update_tags($bookmark->uri, $bookmark->tags);
268
269    if ($changed_uri or $changed_tags) {
270        # update the mtime if the bookmark already existed but the tags were changed
271        my $sth_update = $self->dbh->prepare('update bookmarks set mtime = ? where uri = ?');
272        $sth_update->execute($mtime, $bookmark->uri);
273    }
274
275    # return the bookmark
276    return $bookmark;
277}
278
279sub _update_tags {
280    my $self = shift;
281    my ($uri, $tags) = @_;
282
283    my $changed_tags = 0;
284    my %new_tags = map { $_ => 1 } @{ $tags };
285    my $sth_delete_tag = $self->dbh->prepare('delete from tags where uri = ? and tag = ?');
286    my $sth_insert_tag = $self->dbh->prepare('insert into tags (uri, tag) values (?, ?)');
287    my $sth_current_tags = $self->dbh->prepare('select tag from tags where uri = ?');
288    $sth_current_tags->execute($uri);
289    while (my ($tag) = $sth_current_tags->fetchrow_array) {
290        if (!$new_tags{$tag}) {
291            # if a current tag is not in the new tags, remove it from the database
292            $sth_delete_tag->execute($uri, $tag);
293            $changed_tags++;
294        } else {
295            # if a new tag is already in the database, remove it from the list of tags to add
296            delete $new_tags{$tag};
297        }
298    }
299    for my $tag (keys %new_tags) {
300        $sth_insert_tag->execute($uri, $tag);
301        $changed_tags++;
302    }
303
304    # how many tags have changed?
305    return $changed_tags;
306}
307
308
309# module returns true
3101;
Note: See TracBrowser for help on using the repository browser.