| 1 | package KiokuX::CouchDB::Role::View; | ||
| 2 | |||
| 3 | use Moose::Role; | ||
| 4 | use Data::Dmap 'cut', 'dmap'; | ||
| 5 | use Carp 'croak'; | ||
| 6 | use Scalar::Util 'blessed'; | ||
| 7 | |||
| 8 | use namespace::clean -except => 'meta'; | ||
| 9 | |||
| 10 | # TODO Merge into KiokuDB::Backend::CouchDB and change to comply with KiokuDB::Backend::Role::Query | ||
| 11 | |||
| 12 | # view() is a non-compliant method that can be called directly to query | ||
| 13 | # couchdb views and have all KiokuDB objects instantiated when needed | ||
| 14 | # $name is a name of a CouchDB view that can contain complete KiokuDB | ||
| 15 | # entries or references (in serialized form, of course). | ||
| 16 | sub view { | ||
| 17 | my($self, $name, $options) = @_; | ||
| 18 | |||
| 19 | # Backend data fix hack | ||
| 20 | # The real solution to this ugly way of recovering backend data is to | ||
| 21 | # replace the JSPON expander/collapser with a version that doesn't throw | ||
| 22 | # away revision numbers. | ||
| 23 | my $backend_data; | ||
| 24 | my($response) = $self->backend->db->view($name, $options)->recv; | ||
| 25 | dmap { | ||
| 26 | if(ref eq 'HASH' and exists $_->{_id}) { | ||
| 27 | my $id = $_->{_id}; | ||
| 28 | $backend_data->{$id} ||= { _id => $id }; | ||
| 29 | $backend_data->{$id}{_rev} ||= $_->{_rev}; | ||
| 30 | $backend_data->{$id}{_attachments} ||= $_->{_attachments}; | ||
| 31 | } | ||
| 32 | return $_; | ||
| 33 | } $response; | ||
| 34 | # End hack | ||
| 35 | |||
| 36 | my($result) = dmap { | ||
| 37 | if(ref eq 'HASH') { | ||
| 38 | if($_->{key} and $_->{value} and blessed $_->{value}) { | ||
| 39 | if($_->{value}->isa('KiokuDB::Entry')) { | ||
| 40 | my $entry = $_->{value}; | ||
| 41 | # Patch backend data for later use | ||
| 42 | $entry->backend_data($backend_data->{$entry->id}) if $backend_data->{$entry->id}; | ||
| 43 | my $object; | ||
| 44 | if(not $object = $self->live_objects->id_to_object($entry->id)) { | ||
| 45 | $object = $self->linker->expand_object($entry); | ||
| 46 | } | ||
| 47 | cut $object; | ||
| 48 | } | ||
| 49 | } | ||
| 50 | } elsif(blessed $_ and $_->isa('KiokuDB::Reference')) { | ||
| 51 | my $object = $self->live_objects->id_to_object($_->id); | ||
| 52 | if(not $object) { | ||
| 53 | my $ref_obj = $_; | ||
| 54 | $_ = ['Unlinked KiokuDB::Reference']; | ||
| 55 | $self->linker->queue_ref($ref_obj, \$_); | ||
| 56 | } else { | ||
| 57 | cut $object; | ||
| 58 | } | ||
| 59 | } elsif(blessed $_) { | ||
| 60 | cut $_; | ||
| 61 | } | ||
| 62 | $_ | ||
| 63 | } $self->backend->deserialize($response); | ||
| 64 | |||
| 65 | $self->linker->load_queue; | ||
| 66 | |||
| 67 | return $result; | ||
| 68 | } | ||
| 69 | |||
| 70 | 1; | ||
| 71 | |||
| 72 | __END__ |