source: bookmarks/trunk/Bookmarks.pm @ 46

Last change on this file since 46 was 46, checked in by peter, 11 years ago
  • moved the update method from Bookmark to Bookmarks
  • added a utility helper method _update_tags that is called by add and update in the Bookmarks class
File size: 8.7 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 = $self->_update_tags($uri, $bookmark->{tags});
196
197    if ($bookmark_exists && $changed_tags) {
198        # update the mtime if the bookmark already existed but the tags were changed
199        my $sth_update = $self->dbh->prepare('update bookmarks set mtime = ? where uri = ?');
200        $sth_update->execute($mtime, $uri);
201    }
202
203    # return the newly created or updated bookmark
204    return $self->get_bookmark({ uri => $uri });
205}
206
207sub update {
208    my $self = shift;
209    my $bookmark = shift;
210
211    my $mtime = time;
212
213    my $changed_uri = 0;
214    my $sth_current = $self->dbh->prepare('select uri from bookmarks where id = ?');
215    $sth_current->execute($bookmark->id);
216    my ($stored_uri) = $sth_current->fetchrow_array;
217
218    if ($stored_uri ne $bookmark->uri) {
219        # the URI has changed
220        my $sth_update_uri = $self->dbh->prepare('update resources set uri = ? where uri = ?');
221        $sth_update_uri->execute($bookmark->uri, $stored_uri);
222        $changed_uri++;
223    }
224
225    # update the title
226    # TODO: only do this if the title has changed
227    # TODO: should we update mtime if the title changes?
228    my $sth_update = $self->dbh->prepare('update resources set title = ? where uri = ?');
229    $sth_update->execute($bookmark->title, $bookmark->uri);
230
231    my $changed_tags = $self->_update_tags($bookmark->uri, $bookmark->tags);
232
233    if ($changed_uri or $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, $bookmark->uri);
237    }
238
239    # return the bookmark
240    return $bookmark;
241}
242
243sub _update_tags {
244    my $self = shift;
245    my ($uri, $tags) = @_;
246
247    my $changed_tags = 0;
248    my %new_tags = map { $_ => 1 } @{ $tags };
249    my $sth_delete_tag = $self->dbh->prepare('delete from tags where uri = ? and tag = ?');
250    my $sth_insert_tag = $self->dbh->prepare('insert into tags (uri, tag) values (?, ?)');
251    my $sth_current_tags = $self->dbh->prepare('select tag from tags where uri = ?');
252    $sth_current_tags->execute($uri);
253    while (my ($tag) = $sth_current_tags->fetchrow_array) {
254        if (!$new_tags{$tag}) {
255            # if a current tag is not in the new tags, remove it from the database
256            $sth_delete_tag->execute($uri, $tag);
257            $changed_tags++;
258        } else {
259            # if a new tag is already in the database, remove it from the list of tags to add
260            delete $new_tags{$tag};
261        }
262    }
263    for my $tag (keys %new_tags) {
264        $sth_insert_tag->execute($uri, $tag);
265        $changed_tags++;
266    }
267
268    # how many tags have changed?
269    return $changed_tags;
270}
271
272
273# module returns true
2741;
Note: See TracBrowser for help on using the repository browser.