3 # Copyright ByWater Solutions 2014
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
23 use List::MoreUtils qw( none );
27 use Koha::Exceptions::Object;
28 use Koha::DateUtils qw( dt_from_string );
32 Koha::Objects - Koha Object set base class
37 my $objects = Koha::Objects->search({ borrowernumber => $borrowernumber});
41 This class must be subclassed.
49 =head3 Koha::Objects->new();
51 my $object = Koha::Objects->new();
59 bless( $self, $class );
62 =head3 Koha::Objects->_new_from_dbic();
64 my $object = Koha::Objects->_new_from_dbic( $resultset );
69 my ( $class, $resultset ) = @_;
70 my $self = { _resultset => $resultset };
72 bless( $self, $class );
75 =head3 Koha::Objects->find();
77 Similar to DBIx::Class::ResultSet->find this method accepts:
78 \%columns_values | @pk_values, { key => $unique_constraint, %attrs }?
79 Strictly speaking, columns_values should only refer to columns under an
82 It returns undef if no results were found
84 my $object = Koha::Objects->find( { col1 => $val1, col2 => $val2 } );
85 my $object = Koha::Objects->find( $id );
86 my $object = Koha::Objects->find( $idpart1, $idpart2, $attrs ); # composite PK
91 my ( $self, @pars ) = @_;
95 unless (!@pars || none { defined($_) } @pars) {
96 my $result = $self->_resultset()->find(@pars);
98 $object = $self->object_class()->_new_from_dbic($result);
105 =head3 Koha::Objects->find_or_create();
107 my $object = Koha::Objects->find_or_create( $attrs );
112 my ( $self, $params ) = @_;
114 my $result = $self->_resultset->find_or_create($params);
116 return unless $result;
118 my $object = $self->object_class->_new_from_dbic($result);
126 my $objects = Koha::Objects->search([$params, $attributes]);
127 while (my $object = $objects->next) {
131 This B<instantiates> the I<Koha::Objects> class, and generates a resultset
132 based on the query I<$params> and I<$attributes> that are passed (like in DBIC).
137 my ( $self, $params, $attributes ) = @_;
139 my $class = ref($self) ? ref($self) : $self;
140 my $rs = $self->_resultset()->search($params, $attributes);
142 return $class->_new_from_dbic($rs);
145 =head3 search_related
147 my $objects = Koha::Objects->search_related( $rel_name, $cond?, \%attrs? );
149 Searches the specified relationship, optionally specifying a condition and attributes for matching records.
154 my ( $self, $rel_name, @params ) = @_;
156 return if !$rel_name;
158 my $rs = $self->_resultset()->search_related($rel_name, @params);
160 my $object_class = _get_objects_class( $rs->result_class );
162 eval "require $object_class";
163 return _new_from_dbic( $object_class, $rs );
173 if ( Class::Inspector->function_exists( $self->object_class, 'delete' ) ) {
175 $self->_resultset->result_source->schema->txn_do( sub {
176 $self->reset; # If we iterated already over the set
177 while ( my $o = $self->next ) {
182 return $objects_deleted;
185 return $self->_resultset->delete;
190 my $objects = Koha::Objects->new; # or Koha::Objects->search
191 $objects->update( $fields, [ { no_triggers => 0/1 } ] );
193 This method overloads the DBIC inherited one so if code-level triggers exist
194 (through the use of an overloaded I<update> or I<store> method in the Koha::Object
195 based class) those are called in a loop on the resultset.
197 If B<no_triggers> is passed and I<true>, then the DBIC update method is called
198 directly. This feature is important for performance, in cases where no code-level
199 triggers should be triggered. The developer will explicitly ask for this and QA should
200 catch wrong uses as well.
205 my ($self, $fields, $options) = @_;
207 Koha::Exceptions::Object::NotInstantiated->throw(
212 my $no_triggers = $options->{no_triggers};
216 && ( Class::Inspector->function_exists( $self->object_class, 'update' )
217 or Class::Inspector->function_exists( $self->object_class, 'store' ) )
221 $self->_resultset->result_source->schema->txn_do( sub {
222 while ( my $o = $self->next ) {
227 return $objects_updated;
230 return $self->_resultset->update($fields);
233 =head3 filter_by_last_update
235 my $filtered_objects = $objects->filter_by_last_update({
236 from => $date1, to => $date2,
237 days|older_than => $days, min_days => $days, younger_than => $days,
240 You should pass at least one of the parameters: from, to, days|older_than,
241 min_days or younger_than. Make sure that they do not conflict with each other
242 to get meaningful results.
243 Note: from, to and min_days are inclusive! And by nature days|older_than
244 and younger_than are exclusive.
246 The from and to parameters can be DateTime objects or date strings.
250 sub filter_by_last_update {
251 my ( $self, $params ) = @_;
252 my $timestamp_column_name = $params->{timestamp_column_name} || 'timestamp';
254 Koha::Exceptions::MissingParameter->throw("Please pass: days|from|to|older_than|younger_than")
255 unless grep { exists $params->{$_} } qw/days from to older_than younger_than min_days/;
257 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
258 foreach my $p ( qw/days older_than younger_than min_days/ ) {
259 next if !exists $params->{$p};
260 my $dt = Koha::DateUtils::dt_from_string();
261 my $operator = { days => '<', older_than => '<', min_days => '<=' }->{$p} // '>';
262 $dt->subtract( days => $params->{$p} )->truncate( to => 'day' );
263 $conditions->{$operator} = $dtf->format_datetime( $dt );
265 if ( exists $params->{from} ) {
266 my $from = ref($params->{from}) ? $params->{from} : dt_from_string($params->{from});
267 $conditions->{'>='} = $dtf->format_datetime( $from );
269 if ( exists $params->{to} ) {
270 my $to = ref($params->{to}) ? $params->{to} : dt_from_string($params->{to});
271 $conditions->{'<='} = $dtf->format_datetime( $to );
274 return $self->search(
276 $timestamp_column_name => $conditions
283 my $object = Koha::Objects->search({}, { rows => 1 })->single
285 Returns one and only one object that is part of this set.
286 Returns undef if there are no objects found.
288 This is optimal as it will grab the first returned result without instantiating
292 http://search.cpan.org/dist/DBIx-Class/lib/DBIx/Class/Manual/Cookbook.pod#Retrieve_one_and_only_one_row_from_a_resultset
299 my $single = $self->_resultset()->single;
300 return unless $single;
302 return $self->object_class()->_new_from_dbic($single);
305 =head3 Koha::Objects->next();
307 my $object = Koha::Objects->next();
309 Returns the next object that is part of this set.
310 Returns undef if there are no more objects to return.
317 my $result = $self->_resultset()->next();
318 return unless $result;
320 my $object = $self->object_class()->_new_from_dbic( $result );
325 =head3 Koha::Objects->last;
327 my $object = Koha::Objects->last;
329 Returns the last object that is part of this set.
330 Returns undef if there are no object to return.
337 my $count = $self->_resultset->count;
338 return unless $count;
340 my ( $result ) = $self->_resultset->slice($count - 1, $count - 1);
342 my $object = $self->object_class()->_new_from_dbic( $result );
349 my $empty_rs = Koha::Objects->new->empty;
351 Sets the resultset empty. This is handy for consistency on method returns
352 (e.g. if we know in advance we won't have results but want to keep returning
360 Koha::Exceptions::Object::NotInstantiated->throw(
365 $self = $self->search(\'0 = 1');
366 $self->_resultset()->set_cache([]);
371 =head3 Koha::Objects->reset();
373 Koha::Objects->reset();
375 resets iteration so the next call to next() will start agein
376 with the first object in a set.
383 $self->_resultset()->reset();
388 =head3 Koha::Objects->as_list();
390 Koha::Objects->as_list();
392 Returns an arrayref of the objects in this set.
399 my @dbic_rows = $self->_resultset()->all();
401 my @objects = $self->_wrap(@dbic_rows);
403 return wantarray ? @objects : \@objects;
406 =head3 Koha::Objects->unblessed
408 Returns an unblessed representation of objects.
415 return [ map { $_->unblessed } $self->as_list ];
418 =head3 Koha::Objects->get_column
420 Return all the values of this set for a given column
425 my ($self, $column_name) = @_;
426 return $self->_resultset->get_column( $column_name )->all;
429 =head3 Koha::Objects->TO_JSON
431 Returns an unblessed representation of objects, suitable for JSON output.
438 return [ map { $_->TO_JSON } $self->as_list ];
441 =head3 Koha::Objects->to_api
443 Returns a representation of the objects, suitable for API output .
448 my ($self, $params) = @_;
450 return [ map { $_->to_api($params) } $self->as_list ];
453 =head3 attributes_from_api
455 my $attributes = $objects->attributes_from_api( $api_attributes );
457 Translates attributes from the API to DBIC
461 sub attributes_from_api {
462 my ( $self, $attributes ) = @_;
464 $self->{_singular_object} ||= $self->object_class->new();
465 return $self->{_singular_object}->attributes_from_api( $attributes );
468 =head3 from_api_mapping
470 my $mapped_attributes_hash = $objects->from_api_mapping;
472 Attributes map from the API to DBIC
476 sub from_api_mapping {
479 $self->{_singular_object} ||= $self->object_class->new();
480 return $self->{_singular_object}->from_api_mapping;
483 =head3 prefetch_whitelist
485 my $whitelist = $object->prefetch_whitelist()
487 Returns a hash of prefetchable subs and the type it returns
491 sub prefetch_whitelist {
494 $self->{_singular_object} ||= $self->object_class->new();
496 $self->{_singular_object}->prefetch_whitelist;
499 =head3 Koha::Objects->_wrap
501 wraps the DBIC object in a corresponding Koha object
506 my ( $self, @dbic_rows ) = @_;
508 my @objects = map { $self->object_class->_new_from_dbic( $_ ) } @dbic_rows;
513 =head3 Koha::Objects->_resultset
515 Returns the internal resultset or creates it if undefined
523 $self->{_resultset} ||=
524 Koha::Database->new()->schema()->resultset( $self->_type() );
526 return $self->{_resultset};
529 return Koha::Database->new()->schema()->resultset( $self->_type() );
533 sub _get_objects_class {
537 if( $type->can('koha_objects_class') ) {
538 return $type->koha_objects_class;
540 $type =~ s|Schema::Result::||;
546 my @columns = Koha::Objects->columns
548 Return the table columns
554 return Koha::Database->new->schema->resultset( $class->_type )->result_source->columns;
559 The autoload method is used call DBIx::Class method on a resultset.
561 Important: If you plan to use one of the DBIx::Class methods you must provide
562 relevant tests in t/db_dependent/Koha/Objects.t
563 Currently count, is_paged, pager, result_class, single and slice are covered.
568 my ( $self, @params ) = @_;
570 my @known_methods = qw( count is_paged pager result_class single slice );
571 my $method = our $AUTOLOAD;
575 unless ( grep { $_ eq $method } @known_methods ) {
576 my $class = ref($self) ? ref($self) : $self;
577 Koha::Exceptions::Object::MethodNotCoveredByTests->throw(
578 error => sprintf("The method %s->%s is not covered by tests!", $class, $method),
583 my $r = eval { $self->_resultset->$method(@params) };
585 carp "No method $method found for " . ref($self) . " " . $@;
593 The _type method must be set for all child classes.
594 The value returned by it should be the DBIC resultset name.
595 For example, for holds, _type should return 'Reserve'.
603 This method must be set for all child classes.
604 The value returned by it should be the name of the Koha
605 object class that is returned by this class.
606 For example, for holds, object_class should return 'Koha::Hold'.
616 Kyle M Hall <kyle@bywatersolutions.com>