Commit 462b1c47 authored by Aaron Wells's avatar Aaron Wells
Browse files

Refactoring SQL query in View::shared_to_user() (Bug 1476495)

The old one unnecessarily used two separate queries for Postgres
& MySQL. And it had a bug in how it used MySQL's extended
"GROUP BY" functionality. While MySQL does let you return
non-aggregated columns, it uses an arbitrary record for these of
them, NOT the first record according to ORDER BY.

Also restructured the query a bit for optimization purposes.

behatnotneeded (Test in subsequent patch)

Change-Id: I3d49292025dcf7ac510a84d7e800476defec0525
parent c2a427e2
......@@ -4381,38 +4381,39 @@ class View {
return $result;
if (is_postgres()) {
$lastcomments = '
SELECT DISTINCT ON (l.onview) l.onview, a.mtime,, a.authorname,, a.description
FROM {artefact_comment_comment} l
JOIN {artefact} a ON (l.artefact = AND l.deletedby IS NULL AND l.private = 0)
ORDER BY l.onview, a.mtime DESC';
else if (is_mysql()) {
$lastcomments = '
SELECT onview, mtime, author, authorname, id, description
SELECT l.onview, a.mtime,, a.authorname,, a.description
FROM {artefact_comment_comment} l
JOIN {artefact} a ON (l.artefact = AND l.deletedby IS NULL AND l.private = 0)
) temp1
GROUP BY onview';
// Get additional data: number of comments, last commenter
$commentdata = get_records_sql_assoc('
SELECT, last.mtime AS lastcommenttime, AS commentauthor, last.authorname AS commentauthorname,
last.description AS commenttext, AS commentid,
COUNT(c.artefact) AS commentcount
FROM {view} v
LEFT JOIN {artefact_comment_comment} c ON (c.onview = AND c.deletedby IS NULL AND c.private = 0)
LEFT JOIN (' . $lastcomments . '
) last ON last.onview =
WHERE IN (' . join(',', array_fill(0, count($result->data), '?')) . ')
GROUP BY, last.mtime,, last.authorname, last.description,',
$commentdata = get_records_sql_assoc(
acc.onview AS id,
a.mtime AS lastcommenttime, AS commentauthor,
a.authorname AS commentauthorname, AS commentid,
a.description AS commenttext,
(SELECT COUNT(*) FROM {artefact_comment_comment} c WHERE c.onview = acc.onview AND c.deletedby IS NULL AND c.private=0) AS commentcount
{artefact_comment_comment} acc
inner join {artefact} a
on acc.artefact =
acc.artefact = (
-- Get ID of most recently updated comment on this view
-- (NOTE: This will not work in Oracle)
SELECT acc2.artefact
{artefact_comment_comment} acc2
INNER JOIN {artefact} a3
ON acc2.artefact =
acc2.onview = acc.onview
AND acc2.deletedby IS NULL
AND acc2.private = 0
ORDER BY a3.mtime DESC, acc2.artefact ASC
AND acc.onview IN (' . join(',', array_fill(0, count($result->data), '?')) . ')
Markdown is supported
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