| 1 | use v5.10; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | |||
| 5 | package Meerkat::Collection; | ||
| 6 | # ABSTRACT: Associate a class, database and MongoDB collection | ||
| 7 | |||
| 8 | our $VERSION = '0.016'; | ||
| 9 | |||
| 10 | use Moose 2; | ||
| 11 | use MooseX::AttributeShortcuts; | ||
| 12 | |||
| 13 | use Carp qw/croak/; | ||
| 14 | use Meerkat::Cursor; | ||
| 15 | use Module::Runtime qw/require_module/; | ||
| 16 | use Tie::IxHash; | ||
| 17 | use Try::Tiny::Retry 0.002 qw/:all/; | ||
| 18 | use Type::Params qw/compile/; | ||
| 19 | use Types::Standard qw/slurpy :types/; | ||
| 20 | |||
| 21 | use namespace::autoclean; | ||
| 22 | |||
| 23 | our @CARP_NOT = qw/Meerkat::Role::Document Try::Tiny/; | ||
| 24 | |||
| 25 | #--------------------------------------------------------------------------# | ||
| 26 | # Public attributes | ||
| 27 | #--------------------------------------------------------------------------# | ||
| 28 | |||
| 29 | #pod =attr meerkat (required) | ||
| 30 | #pod | ||
| 31 | #pod The Meerkat object that constructed the object. It holds the MongoDB | ||
| 32 | #pod collections used to access the database. | ||
| 33 | #pod | ||
| 34 | #pod =cut | ||
| 35 | |||
| 36 | has meerkat => ( | ||
| 37 | is => 'ro', | ||
| 38 | isa => 'Meerkat', | ||
| 39 | required => 1, | ||
| 40 | ); | ||
| 41 | |||
| 42 | #pod =attr class (required) | ||
| 43 | #pod | ||
| 44 | #pod The class name to associate with documents. The class is loaded | ||
| 45 | #pod for you if needed. | ||
| 46 | #pod | ||
| 47 | #pod =cut | ||
| 48 | |||
| 49 | has class => ( | ||
| 50 | is => 'ro', | ||
| 51 | isa => 'Str', # XXX should check that the class does the role | ||
| 52 | required => 1, | ||
| 53 | ); | ||
| 54 | |||
| 55 | #pod =attr collection_name | ||
| 56 | #pod | ||
| 57 | #pod The collection name to associate with the class. Defaults to the | ||
| 58 | #pod name of the class with "::" replaced with "_". | ||
| 59 | #pod | ||
| 60 | #pod =cut | ||
| 61 | |||
| 62 | has collection_name => ( | ||
| 63 | is => 'lazy', | ||
| 64 | isa => 'Str', | ||
| 65 | ); | ||
| 66 | |||
| 67 | sub _build_collection_name { | ||
| 68 | my ($self) = @_; | ||
| 69 | ( my $name = $self->class ) =~ s{::}{_}g; | ||
| 70 | return $name; | ||
| 71 | } | ||
| 72 | |||
| 73 | has _class_loaded => ( | ||
| 74 | is => 'rw', | ||
| 75 | isa => 'Bool', | ||
| 76 | ); | ||
| 77 | |||
| 78 | #--------------------------------------------------------------------------# | ||
| 79 | # Constructor | ||
| 80 | #--------------------------------------------------------------------------# | ||
| 81 | |||
| 82 | sub BUILD { | ||
| 83 | my ($self) = @_; | ||
| 84 | return if $self->_class_loaded; | ||
| 85 | require_module( $self->class ) and $self->_class_loaded(1); | ||
| 86 | } | ||
| 87 | |||
| 88 | #--------------------------------------------------------------------------# | ||
| 89 | # Public methods on collection as a whole | ||
| 90 | #--------------------------------------------------------------------------# | ||
| 91 | |||
| 92 | #pod =method create | ||
| 93 | #pod | ||
| 94 | #pod my $obj = $person->create( name => 'John' ); | ||
| 95 | #pod | ||
| 96 | #pod Creates an object of the class associated with the Meerkat::Collection and | ||
| 97 | #pod inserts it into the associated collection in the database. Returns the object on | ||
| 98 | #pod success or throws an error on failure. | ||
| 99 | #pod | ||
| 100 | #pod Any arguments given are passed directly to the associated class constructor. | ||
| 101 | #pod Arguments may be given either as a list or as a hash reference. | ||
| 102 | #pod | ||
| 103 | #pod =cut | ||
| 104 | |||
| 105 | sub create { | ||
| 106 | state $check = compile( Object, slurpy ArrayRef ); | ||
| 107 | my ( $self, $args ) = $check->(@_); | ||
| 108 | my @args = ( ref $args->[0] eq 'HASH' ? %{ $args->[0] } : @$args ); | ||
| 109 | my $obj = $self->class->new( @args, _collection => $self ); | ||
| 110 | $self->_save($obj); | ||
| 111 | return $obj; | ||
| 112 | } | ||
| 113 | |||
| 114 | #pod =method count | ||
| 115 | #pod | ||
| 116 | #pod my $count = $person->count; | ||
| 117 | #pod my $count = $person->count( $query ); | ||
| 118 | #pod | ||
| 119 | #pod Returns the number of documents in the associated collection or throws an error on | ||
| 120 | #pod failure. If a hash reference is provided, it is passed as a query parameter to | ||
| 121 | #pod the MongoDB L<count_documents|MongoDB::Collection/count_documents> method. | ||
| 122 | #pod Otherwise, the MongoDB | ||
| 123 | #pod L<estimated_document_count|MongoDB::Collection/estimated_document_count> method | ||
| 124 | #pod is used instead. | ||
| 125 | #pod | ||
| 126 | #pod =cut | ||
| 127 | |||
| 128 | sub count { | ||
| 129 | state $check = compile( Object, Optional [HashRef] ); | ||
| 130 | my ( $self, $query ) = $check->(@_); | ||
| 131 | if ( defined $query ) { | ||
| 132 | return $self->_try_mongo_op( | ||
| 133 | count => sub { $self->_mongo_collection->count_documents($query) } ); | ||
| 134 | } | ||
| 135 | return $self->_try_mongo_op( | ||
| 136 | count => sub { $self->_mongo_collection->estimated_document_count() } ); | ||
| 137 | } | ||
| 138 | |||
| 139 | #pod =method find_id | ||
| 140 | #pod | ||
| 141 | #pod my $obj = $person->find_id( $id ); | ||
| 142 | #pod | ||
| 143 | #pod Finds a document with the given C<_id> and returns it as an object of the | ||
| 144 | #pod associated class. Returns undef if the C<_id> is not found or throws an error | ||
| 145 | #pod if one occurs. This is a shorthand for the same query via C<find_one>: | ||
| 146 | #pod | ||
| 147 | #pod $person->find_one( { _id => $id } ); | ||
| 148 | #pod | ||
| 149 | #pod However, C<find_id> can take either a scalar C<_id> or a L<BSON::OID> object | ||
| 150 | #pod as an argument. | ||
| 151 | #pod | ||
| 152 | #pod =cut | ||
| 153 | |||
| 154 | sub find_id { | ||
| 155 | state $check = compile( Object, Defined ); | ||
| 156 | my ( $self, $id ) = $check->(@_); | ||
| 157 | my $data = | ||
| 158 | $self->_try_mongo_op( | ||
| 159 | find_id => sub { $self->_mongo_collection->find_one( { _id => $id } ) } ); | ||
| 160 | return unless $data; | ||
| 161 | return $self->thaw_object($data); | ||
| 162 | } | ||
| 163 | |||
| 164 | #pod =method find_one | ||
| 165 | #pod | ||
| 166 | #pod my $obj = $person->find_one( { name => "Larry Wall" } ); | ||
| 167 | #pod | ||
| 168 | #pod Finds the first document matching a query parameter hash reference and returns | ||
| 169 | #pod it as an object of the associated class. Returns undef if the C<_id> is not | ||
| 170 | #pod found or throws an error if one occurs. | ||
| 171 | #pod | ||
| 172 | #pod =cut | ||
| 173 | |||
| 174 | sub find_one { | ||
| 175 | state $check = compile( Object, HashRef ); | ||
| 176 | my ( $self, $query ) = $check->(@_); | ||
| 177 | return | ||
| 178 | unless my $data = | ||
| 179 | $self->_try_mongo_op( | ||
| 180 | find_one => sub { $self->_mongo_collection->find_one($query) } ); | ||
| 181 | return $self->thaw_object($data); | ||
| 182 | } | ||
| 183 | |||
| 184 | #pod =method find | ||
| 185 | #pod | ||
| 186 | #pod my $cursor = $person->find( { tag => "trendy" } ); | ||
| 187 | #pod my @objs = $cursor->all; | ||
| 188 | #pod | ||
| 189 | #pod Executes a query against C<collection_name>. It returns a L<Meerkat::Cursor> | ||
| 190 | #pod or throws an error on failure. If a hash reference is provided, it is passed | ||
| 191 | #pod as a query parameter to the MongoDB L<find|MongoDB::Collection/find> method, | ||
| 192 | #pod otherwise all documents are returned. You may include and optional options | ||
| 193 | #pod hash reference after the query hash reference. Iterating the cursor will return | ||
| 194 | #pod objects of the associated class. | ||
| 195 | #pod | ||
| 196 | #pod =cut | ||
| 197 | |||
| 198 | sub find { | ||
| 199 | state $check = compile( Object, Optional [HashRef], Optional [HashRef] ); | ||
| 200 | my ( $self, $query, $options ) = $check->(@_); | ||
| 201 | my $cursor = | ||
| 202 | $self->_try_mongo_op( | ||
| 203 | find => sub { $self->_mongo_collection->find( $query, $options ) } ); | ||
| 204 | return Meerkat::Cursor->new( cursor => $cursor, collection => $self ); | ||
| 205 | } | ||
| 206 | |||
| 207 | #pod =method ensure_indexes | ||
| 208 | #pod | ||
| 209 | #pod $person->ensure_indexes; | ||
| 210 | #pod | ||
| 211 | #pod Ensures an index is constructed for index returned by the C<_index> method | ||
| 212 | #pod of the associated class. Returns true on success or throws an error if one | ||
| 213 | #pod occurs. See L<Meerkat::Role::Document> for more. | ||
| 214 | #pod | ||
| 215 | #pod =cut | ||
| 216 | |||
| 217 | sub ensure_indexes { | ||
| 218 | state $check = compile(Object); | ||
| 219 | my ($self) = $check->(@_); | ||
| 220 | state $aoa_check = compile( slurpy ArrayRef [ArrayRef] ); | ||
| 221 | my ($aoa) = $aoa_check->( $self->class->_indexes ); | ||
| 222 | my $index_view = $self->_mongo_collection->indexes; | ||
| 223 | my @indexes; | ||
| 224 | for my $index (@$aoa) { | ||
| 225 | my @copy = @$index; | ||
| 226 | my $options = ref $copy[0] eq 'HASH' ? shift @copy : undef; | ||
| 227 | if ( @copy % 2 != 0 ) { | ||
| 228 | $self->_croak( | ||
| 229 | "_indexes must provide a list of key/value pairs, with an optional leading hashref"); | ||
| 230 | } | ||
| 231 | my $spec = Tie::IxHash->new(@copy); | ||
| 232 | push @indexes, { keys => $spec, ( $options ? ( options => $options ) : () ) }; | ||
| 233 | } | ||
| 234 | $self->_try_mongo_op( ensure_indexes => sub { $index_view->create_many(@indexes) } ); | ||
| 235 | return 1; | ||
| 236 | } | ||
| 237 | |||
| 238 | #--------------------------------------------------------------------------# | ||
| 239 | # Semi-private methods on individual objects; typically called by object to | ||
| 240 | # modify itself and synchronize with the database | ||
| 241 | #--------------------------------------------------------------------------# | ||
| 242 | |||
| 243 | sub remove { | ||
| 244 | state $check = compile( Object, Object ); | ||
| 245 | my ( $self, $obj ) = $check->(@_); | ||
| 246 | $self->_try_mongo_op( | ||
| 247 | remove => sub { $self->_mongo_collection->delete_one( { _id => $obj->_id } ) } ); | ||
| 248 | $obj->_set_removed(1); | ||
| 249 | return 1; | ||
| 250 | } | ||
| 251 | |||
| 252 | sub reinsert { | ||
| 253 | state $check = compile( Object, Object ); | ||
| 254 | my ( $self, $obj ) = $check->(@_); | ||
| 255 | $self->_save($obj); | ||
| 256 | $obj->_set_removed(0); | ||
| 257 | return 1; | ||
| 258 | } | ||
| 259 | |||
| 260 | sub sync { | ||
| 261 | state $check = compile( Object, Object ); | ||
| 262 | my ( $self, $obj ) = $check->(@_); | ||
| 263 | my $data = $self->_try_mongo_op( | ||
| 264 | sync => sub { $self->_mongo_collection->find_one( { _id => $obj->_id } ) } ); | ||
| 265 | if ($data) { | ||
| 266 | $self->_sync( $data => $obj ); | ||
| 267 | $obj->_set_removed(0); | ||
| 268 | return 1; | ||
| 269 | } | ||
| 270 | else { | ||
| 271 | $obj->_set_removed(1); | ||
| 272 | return; # false means removed | ||
| 273 | } | ||
| 274 | } | ||
| 275 | |||
| 276 | sub update { | ||
| 277 | state $check = compile( Object, Object, HashRef ); | ||
| 278 | my ( $self, $obj, $update ) = $check->(@_); | ||
| 279 | my $data = $self->_try_mongo_op( | ||
| 280 | update => sub { | ||
| 281 | $self->_mongo_collection->find_one_and_update( { _id => $obj->_id }, | ||
| 282 | $update, { returnDocument => "after" } ); | ||
| 283 | }, | ||
| 284 | ); | ||
| 285 | |||
| 286 | if ( ref $data ) { | ||
| 287 | $self->_sync( $data => $obj ); | ||
| 288 | return 1; | ||
| 289 | } | ||
| 290 | else { | ||
| 291 | $obj->_set_removed(1); | ||
| 292 | return; # false means removed | ||
| 293 | } | ||
| 294 | } | ||
| 295 | |||
| 296 | sub thaw_object { | ||
| 297 | state $check = compile( Object, HashRef ); | ||
| 298 | my ( $self, $data ) = $check->(@_); | ||
| 299 | $data->{__CLASS__} = $self->class; | ||
| 300 | $data->{_collection} = $self; | ||
| 301 | return $self->class->unpack($data); | ||
| 302 | } | ||
| 303 | |||
| 304 | #--------------------------------------------------------------------------# | ||
| 305 | # Private methods | ||
| 306 | #--------------------------------------------------------------------------# | ||
| 307 | |||
| 308 | sub _mongo_collection { | ||
| 309 | state $check = compile(Object); | ||
| 310 | my ($self) = $check->(@_); | ||
| 311 | return $self->meerkat->mongo_collection( $self->collection_name ); | ||
| 312 | } | ||
| 313 | |||
| 314 | sub _try_mongo_op { | ||
| 315 | state $check = compile( Object, Str, CodeRef ); | ||
| 316 | my ( $self, $action, $code, $rest ) = $check->(@_); | ||
| 317 | # call &retry to bypass prototype | ||
| 318 | return &retry( | ||
| 319 | $code, @$rest, | ||
| 320 | retry_if { /not connected/ }, | ||
| 321 | delay_exp { 5, 1e6 }, | ||
| 322 | on_retry { $self->mongo_clear_caches }, | ||
| 323 | catch { croak "$action error: $_" } | ||
| 324 | ); | ||
| 325 | } | ||
| 326 | |||
| 327 | sub _save { | ||
| 328 | state $check = compile( Object, Object ); | ||
| 329 | my ( $self, $obj ) = $check->(@_); | ||
| 330 | my $pack = $obj->pack; | ||
| 331 | delete $pack->{$_} for qw/__CLASS__ _collection _removed/; | ||
| 332 | return $self->_try_mongo_op( | ||
| 333 | sync => sub { | ||
| 334 | !!$self->_mongo_collection->replace_one( { _id => $pack->{_id} }, | ||
| 335 | $pack, { upsert => 1 } ); | ||
| 336 | } | ||
| 337 | ); | ||
| 338 | } | ||
| 339 | |||
| 340 | sub _sync { | ||
| 341 | state $check = compile( Object, HashRef, Object ); | ||
| 342 | my ( $self, $data, $tgt ) = $check->(@_); | ||
| 343 | my $src = try { | ||
| 344 | $self->thaw_object($data); | ||
| 345 | } | ||
| 346 | catch { | ||
| 347 | $self->_croak( | ||
| 348 | "Could not inflate updated document with _id=$data->{_id} because: $_"); | ||
| 349 | }; | ||
| 350 | for my $tgt_attr ( $tgt->meta->get_all_attributes ) { | ||
| 351 | my $src_attr = $src->meta->find_attribute_by_name( $tgt_attr->name ); | ||
| 352 | $tgt_attr->set_value( $tgt, $src_attr->get_value($src) ); | ||
| 353 | } | ||
| 354 | return 1; | ||
| 355 | } | ||
| 356 | |||
| 357 | sub _croak { | ||
| 358 | my ( $self, $msg ) = @_; | ||
| 359 | $msg =~ s/ at \S+ line \d+.*//ms; | ||
| 360 | croak $msg; | ||
| 361 | } | ||
| 362 | |||
| 363 | __PACKAGE__->meta->make_immutable; | ||
| 364 | |||
| 365 | 1; | ||
| 366 | |||
| 367 | |||
| 368 | # vim: ts=4 sts=4 sw=4 et: | ||
| 369 | |||
| 370 | __END__ |