Bug 23982: (bug 23624 follow-up) Handle SQL error caused by derived table

Caused by
  commit bca4453c50
  Bug 23624: (QA follow-up) Optimize even more

A report like:
SELECT * FROM issues JOIN borrowers USING (borrowernumber)

will have two borrowernumber columns - SQL will give us there rsults,
but if we try to wrap them in a SELECT COUNT(*) FROM (report) it throws
a duplicated column error.

This patch suggests to execute the query the old way if the derived
table optimization failed.

Signed-off-by: Martin Renvoize <martin.renvoize@ptfs-europe.com>
Signed-off-by: Nick Clemens <nick@bywatersolutions.com>
Signed-off-by: Martin Renvoize <martin.renvoize@ptfs-europe.com>
This commit is contained in:
Jonathan Druart 2019-11-18 11:20:46 +01:00 committed by Martin Renvoize
parent 468513a5de
commit 24f780e22f
Signed by: martin.renvoize
GPG key ID: 422B469130441A0F

View file

@ -425,19 +425,37 @@ sub nb_rows {
$derived_name .= 'x';
}
my $sth = C4::Context->dbh->prepare(qq{
SELECT COUNT(*) FROM
( $sql ) $derived_name
});
$sth->execute();
my $dbh = C4::Context->dbh;
my ( $sth, $n );
if ( $sth->errstr ) {
return 0;
}
else {
return $sth->fetch->[0];
my $RaiseError = $dbh->{RaiseError};
my $PrintError = $dbh->{PrintError};
$dbh->{RaiseError} = 1;
$dbh->{PrintError} = 0;
eval {
$sth = $dbh->prepare(qq{
SELECT COUNT(*) FROM
( $sql ) $derived_name
});
$sth->execute();
};
$dbh->{RaiseError} = $RaiseError;
$dbh->{PrintError} = $PrintError;
if ($@) { # To catch "Duplicate column name" caused by the derived table, or any other syntax error
$sth = $dbh->prepare($sql);
$sth->execute;
# Loop through the complete results, fetching 1,000 rows at a time. This
# lowers memory requirements but increases execution time.
while (my $rows = $sth->fetchall_arrayref(undef, 1000)) {
$n += @$rows;
}
return $n;
}
my $results = $sth->fetch;
return $results ? $results->[0] : 0;
}
=head2 execute_query