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

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