Fix stage index migration failing in PostgreSQL 10

As discussed in
https://www.postgresql.org/message-id/9922.1353433645%40sss.pgh.pa.us,
the PostgreSQL window function last_value may not consider the
right rows:

Note that first_value, last_value, and nth_value consider only the rows
within the "window frame", which by default contains the rows from the
start of the partition through the last peer of the current row. This is
likely to give unhelpful results for last_value and sometimes also
nth_value. You can redefine the frame by adding a suitable frame
specification (RANGE or ROWS) to the OVER clause. See Section 4.2.8 for
more information about frame specifications.

This query could be fixed by adding `RANGE BETWEEN UNBOUNDED PRECEDING
AND UNBOUNDED FOLLOWING`, but that's quite verbose. It's simpler just to
use the first_value function.

Closes https://gitlab.com/gitlab-org/gitlab-ce/issues/59985
This commit is contained in:
Stan Hu 2019-04-03 22:00:29 -07:00
parent 74ace2a445
commit 0f5b735685
2 changed files with 3 additions and 3 deletions

View File

@ -21,8 +21,8 @@ module Gitlab
AND stage_idx IS NOT NULL
GROUP BY stage_id, stage_idx
), indexes AS (
SELECT DISTINCT stage_id, last_value(stage_idx)
OVER (PARTITION BY stage_id ORDER BY freq ASC) AS index
SELECT DISTINCT stage_id, first_value(stage_idx)
OVER (PARTITION BY stage_id ORDER BY freq DESC) AS index
FROM freqs
)

View File

@ -30,6 +30,6 @@ describe Gitlab::BackgroundMigration::MigrateStageIndex, :migration, schema: 201
described_class.new.perform(100, 101)
expect(stages.all.pluck(:position)).to eq [2, 3]
expect(stages.all.order(:id).pluck(:position)).to eq [2, 3]
end
end