source: bookmarks/trunk/Bookmarks.pm @ 26

Last change on this file since 26 was 26, checked in by peter, 11 years ago

renamed Bookmarks::get_resources() to Bookmarks::get_bookmarks()

File size: 7.8 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    #TODO: accept a ctime or mtime
157    my $ctime = $bookmark->{ctime} || time;
158    my $mtime = $bookmark->{mtime} || $ctime;
159    my $id = $bookmark->{id};
160
161    # create an entry for the resource
162    my $sth_resource = $self->dbh->prepare('insert into resources (uri, title) values (?, ?)');
163    eval {
164        $sth_resource->execute($uri, $title);
165    };
166    if ($@) {
167        if ($@ =~ /column uri is not unique/) {
168            # this is not truly an error condition; the resource is already listed
169            # update the title instead
170            my $sth_update = $self->dbh->prepare('update resources set title = ? where uri = ?');
171            $sth_update->execute($title, $uri);
172        } else {
173            die $@;
174        }
175    }
176
177    # create the bookmark
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            # update the mtime instead
189            # TODO: only update mtime if the tag list is changed?
190            my $sth_update = $self->dbh->prepare('update bookmarks set mtime = ? where uri = ?');
191            $sth_update->execute($mtime, $uri);
192        } else {
193            die $@;
194        }
195    }
196
197    my %new_tags = map { $_ => 1 } @{ $bookmark->{tags} };
198    my $sth_delete_tag = $self->dbh->prepare('delete from tags where uri = ? and tag = ?');
199    my $sth_insert_tag = $self->dbh->prepare('insert into tags (uri, tag) values (?, ?)');
200    my $sth_current_tags = $self->dbh->prepare('select tag from tags where uri = ?');
201    $sth_current_tags->execute($uri);
202    while (my ($tag) = $sth_current_tags->fetchrow_array) {
203        if (!$new_tags{$tag}) {
204            # if a current tag is not in the new tags, remove it from the database
205            $sth_delete_tag->execute($uri, $tag);
206        } else {
207            # if a new tag is already in the database, remove it from the list of tags to add
208            delete $new_tags{$tag};
209        }
210    }
211    for my $tag (keys %new_tags) {
212        $sth_insert_tag->execute($uri, $tag);
213    }
214
215=begin
216
217    # clear all tags
218    my $sth_delete_tag = $self->dbh->prepare('delete from tags where uri = ?');
219    $sth_delete_tag->execute($uri);
220    my $sth_tag = $self->dbh->prepare('insert into tags (uri, tag) values (?, ?)');
221    for my $tag (@{ $bookmark->{tags} }) {
222        #print $tag, "\n";
223        # prevent duplicate (uri,tag) pairs in the database
224        # TODO: should POST with a set of tags ever remove tags?
225        eval {
226            $sth_tag->execute($uri, $tag);
227        };
228        if ($@) {
229            if ($@ =~ /columns uri, tag are not unique/) {
230                # this is not truly an error condition; the tag was already there
231            } else {
232                die $@;
233            }
234        }
235    }
236
237=cut
238
239    # return the newly created or updated bookmark
240    return $self->get_bookmark({ uri => $uri });
241}
242
243# module returns true
2441;
Note: See TracBrowser for help on using the repository browser.