source: bookmarks/trunk/Bookmarks.pm @ 66

Last change on this file since 66 was 66, checked in by peter, 10 years ago
  • the bookmark.tt template takes a hash or object named bookmark as its only variable
  • moved the calculation of a human-readable timestamp and the ISO timestamps for the WayBack machine from the BookmarkController class into the Bookmark class as methods (created, updated, created_iso, and updated_iso
  • moved the exists flag into the Bookmark class as an attribute
File size: 9.6 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 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
45sub get_bookmark {
46    my $self = shift;
47    my $params = shift;
48
49    # look for bookmark by id or uri
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;
61    return unless $bookmark;
62
63    return Bookmark->new({
64        %$bookmark,
65        exists   => 1,
66        tags     => [ $self->get_tags({ uri => $bookmark->{uri} }) ],
67        base_uri => $self->base_uri,
68    });
69}
70
71sub get_bookmarks {
72    my $self = shift;
73    my $params = shift;
74    my $query = $params->{query};
75    my $tags = $params->{tag} || [];
76    my $limit = $params->{limit};
77    my $offset = $params->{offset};
78
79    # build the query
80    my @sql;
81
82    if (!ref $tags) {
83        $tags = [ $tags ];
84    }
85    if (@$tags) {
86        my $intersect = 0;
87        for my $tag (@{ $tags }) {
88            push @sql, 'intersect' if $intersect;
89            push @sql, 'select resources.*, bookmarks.* from resources join bookmarks on resources.uri = bookmarks.uri';
90            push @sql, 'join tags on resources.uri = tags.uri where tags.tag =', \$tag;
91            $intersect++;
92        }
93    } else {
94        push @sql, 'select * from resources join bookmarks on resources.uri = bookmarks.uri';
95    }
96    if ($query) {
97        push @sql, (@$tags ? 'and' : 'where'), 'title like', \"%$query%";
98    }
99    push @sql, 'order by ctime desc';
100    push @sql, ('limit', \$limit) if $limit;
101    # an offset is only allowed if we have a limit clause
102    push @sql, ('offset', \$offset) if $limit && $offset;
103
104    my ($sql, @bind) = sql_interp(@sql);
105    #die $sql;
106
107    my $sth_resource = $self->dbh->prepare($sql);
108    $sth_resource->execute(@bind);
109
110    my @resources;
111    while (my $resource = $sth_resource->fetchrow_hashref) {
112        push @resources, Bookmark->new({
113            %$resource,
114            tags     => [ $self->get_tags({ uri => $resource->{uri} }) ],
115            base_uri => $self->base_uri,
116        });
117    }
118    return @resources;
119}
120
121sub get_tags {
122    my $self = shift;
123    my $params = shift;
124    if (my $uri = $params->{uri}) {
125        # get the tags for a particular URI
126        $self->_sth_tags_from_uri->execute($uri);
127        return map { $$_[0] } @{ $self->_sth_tags_from_uri->fetchall_arrayref };
128    } else {
129        # return all tags
130        my $tag = $params->{selected};
131        my $sth_all_tags = $self->dbh->prepare('select tag, count(tag) as count, tag = ? as selected from tags group by tag order by tag');
132        $sth_all_tags->execute($tag);
133        my $all_tags = $sth_all_tags->fetchall_arrayref({});
134        return @{ $all_tags };
135    }
136}
137
138sub get_cotags {
139    my $self = shift;
140    my $params = shift;
141    my $query = $params->{query};
142    my $tags = $params->{tag} || [];
143    if (!ref $tags) {
144        $tags = [ $tags ];
145    }
146    my @sql;
147
148    push @sql, 'select tag, count(tag) as count from tags';
149    push @sql, 'join resources on tags.uri = resources.uri' if $query;
150
151    # build the where clause
152    if (@$tags) {
153        push @sql, 'where tags.uri in (';
154        my $intersect = 0;
155        for my $tag (@{ $tags }) {
156            push @sql, 'intersect' if $intersect;
157            push @sql, 'select uri from tags where tag = ', \$tag;
158            $intersect++;
159        }
160        push @sql, ') and tag not in ', $tags, '';
161    }
162    if ($query) {
163        push @sql, (@$tags ? 'and' : 'where'), 'title like', \"%$query%";
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.