Bug 17783: Add Koha::Objects->single
authorLari Taskula <lari.taskula@jns.fi>
Thu, 15 Dec 2016 17:28:38 +0000 (19:28 +0200)
committerKyle M Hall <kyle@bywatersolutions.com>
Fri, 23 Dec 2016 12:01:56 +0000 (12:01 +0000)
Returns one and only one object that is part of this set.
Returns undef if there are no objects found.

->single is faster than ->search->next

This is optimal as it will grab the first returned result without instantiating
a cursor.

It is useful for this Bug as we only want to select the top row of found issuing
rules.

To test:
1. Run t/db_dependent/Koha/Objects.t

Signed-off-by: Josef Moravec <josef.moravec@gmail.com>
Signed-off-by: Jonathan Druart <jonathan.druart@biblibre.com>
Signed-off-by: Kyle M Hall <kyle@bywatersolutions.com>
Koha/Objects.pm
t/db_dependent/Koha/Objects.t

index 56f165c..9231206 100644 (file)
@@ -161,6 +161,30 @@ sub search_related {
     }
 }
 
+=head3 single
+
+my $object = Koha::Objects->search({}, { rows => 1 })->single
+
+Returns one and only one object that is part of this set.
+Returns undef if there are no objects found.
+
+This is optimal as it will grab the first returned result without instantiating
+a cursor.
+
+See:
+http://search.cpan.org/dist/DBIx-Class/lib/DBIx/Class/Manual/Cookbook.pod#Retrieve_one_and_only_one_row_from_a_resultset
+
+=cut
+
+sub single {
+    my ($self) = @_;
+
+    my $single = $self->_resultset()->single;
+    return unless $single;
+
+    return $self->object_class()->_new_from_dbic($single);
+}
+
 =head3 Koha::Objects->next();
 
 my $object = Koha::Objects->next();
@@ -299,7 +323,7 @@ Currently count, pager, update and delete are covered.
 sub AUTOLOAD {
     my ( $self, @params ) = @_;
 
-    my @known_methods = qw( count pager update delete result_class );
+    my @known_methods = qw( count pager update delete result_class single );
     my $method = our $AUTOLOAD;
     $method =~ s/.*:://;
 
index 84b1a86..29dea67 100644 (file)
@@ -19,7 +19,7 @@
 
 use Modern::Perl;
 
-use Test::More tests => 10;
+use Test::More tests => 11;
 use Test::Warn;
 
 use Koha::Authority::Types;
@@ -116,6 +116,17 @@ subtest 'search_related' => sub {
     is( $libraries[1]->branchcode, $patron_2->{branchcode}, 'Koha::Objects->search_related should work as expected' );
 };
 
+subtest 'single' => sub {
+    plan tests => 2;
+    my $builder   = t::lib::TestBuilder->new;
+    my $patron_1  = $builder->build( { source => 'Borrower' } );
+    my $patron_2  = $builder->build( { source => 'Borrower' } );
+    my $patron = Koha::Patrons->search({}, { rows => 1 })->single;
+    is(ref($patron), 'Koha::Patron', 'Koha::Objects->single returns a single Koha::Patron object.');
+    warning_like { Koha::Patrons->search->single } qr/SQL that returns multiple rows/,
+    "Warning is presented if single is used for a result with multiple rows.";
+};
+
 subtest 'Exceptions' => sub {
     plan tests => 2;