Skip to content
Snippets Groups Projects
Commit d36afb9b authored by Andy Yates's avatar Andy Yates
Browse files

Adding a no_error flag to allow for simple single value querying where the...

Adding a no_error flag to allow for simple single value querying where the number of rows returned could be ambigious
parent d3b94415
No related branches found
No related tags found
No related merge requests found
......@@ -471,6 +471,8 @@ sub execute_into_hash {
Arg [USE_HASHREFS] : boolean If set to true will cause HashRefs to be returned
to the callback & not ArrayRefs
Arg [PARAMS] : ArrayRef The binding parameters to the SQL statement
Arg [NO_ERROR] : Boolean Flag to indicate that the code should not
throw an error when row counts are not equal to 1
Returntype : Scalar
Exceptions : If errors occur in the execution of the SQL, if the query
returned more than 1 row and if we found no rows.
......@@ -488,8 +490,8 @@ or less than one row returned
sub execute_single_result {
my ( $self, @args ) = @_;
my ($sql, $callback, $use_hashrefs, $params) = rearrange(
[qw(sql callback use_hashrefs params)], @args);
my ($sql, $callback, $use_hashrefs, $params, $no_error) = rearrange(
[qw(sql callback use_hashrefs params no_error)], @args);
my $results = $self->execute_simple(
-SQL => $sql,
......@@ -499,7 +501,7 @@ sub execute_single_result {
);
my $result_count = scalar(@{$results});
if($result_count != 1) {
if(! $no_error && $result_count != 1) {
$params = [] if ! $params;
my $type = ($result_count == 0) ? 'No' : 'Too many';
my $msg = "${type} results returned. Expected 1 but got $result_count for query '${sql}' with params [";
......@@ -507,7 +509,8 @@ sub execute_single_result {
$msg .= ']';
throw($msg);
}
return $results->[0];
return $results->[0] if defined $results->[0];
return;
}
=pod
......
......@@ -48,9 +48,22 @@ is(
'Checking count of meta key is right with params'
);
throws_ok { $helper->execute_single_result(-SQL => 'select * from meta') } qr/Too many results/, 'More than 1 row causes an error';
throws_ok { $helper->execute_single_result(-SQL => 'select * from meta where species_id =?', -PARAMS => [-1]) } qr/No results/, 'Less than 1 row causes an error';
is(
$helper->execute_single_result(-SQL => 'select meta_id from meta order by meta_id', -NO_ERROR => 1),
1,
'Checking if we have more than row we will not error if we ask to ignore it'
);
is(
$helper->execute_single_result(-SQL => 'select meta_id from meta where species_id =?', -PARAMS => [-1], -NO_ERROR => 1),
undef,
'Checking if we less than row we will not error if we ask to ignore it'
);
is_deeply(
$helper->execute(-SQL => 'select count(*), 3 from meta where meta_key =?', -PARAMS => [$meta_key])->[0],
[1,3],
......
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment