Skip to content

Commit 1015d9e

Browse files
authored
FEATURE: Tweak postgres_highest_sequence only for int columns (#98)
Tweak `postgres_highest_sequence` metric to export the highest sequence only for integer columns. These are the most probable columns to run out of values. There are some exceptions to this rule to include `bigint` columns that may be referenced in `integer` columns. For example, `reviewables.id` is a `bigint` column, but `reviewable_scores.reviewable_id` is an integer.
1 parent f77c9a0 commit 1015d9e

File tree

2 files changed

+20
-5
lines changed

2 files changed

+20
-5
lines changed

‎lib/internal_metric/global.rb

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -368,10 +368,25 @@ def calc_postgres_highest_sequence
368368

369369
RailsMultisite::ConnectionManagement.each_connection do |db|
370370
result[{ db: db }] = DB.query_single(<<~SQL)[0]
371-
SELECT last_value
372-
FROM pg_sequences
373-
ORDER BY last_value DESC NULLS LAST
374-
LIMIT 1
371+
WITH columns_and_sequences AS (
372+
SELECT table_name,
373+
column_name,
374+
information_schema.columns.data_type column_type,
375+
pg_sequences.data_type::text sequence_type,
376+
COALESCE(last_value, 0) last_value
377+
FROM information_schema.columns
378+
JOIN pg_sequences ON sequencename = REPLACE(REPLACE(column_default, 'nextval(''', ''), '''::regclass)', '')
379+
WHERE information_schema.columns.table_schema = 'public'
380+
)
381+
SELECT MAX(last_value)
382+
FROM columns_and_sequences
383+
WHERE column_type = 'integer' OR
384+
-- The column and sequence types should match, but this is just an extra check.
385+
sequence_type = 'integer' OR
386+
-- The `id` column of these tables is a `bigint`, but the foreign key columns are usually integers.
387+
-- These columns will be migrated in the future.
388+
-- See https://github.com/discourse/discourse/blob/6e1aeb1f504f469ceed189c24d43a7a99b8970c7/spec/rails_helper.rb#L480-L490
389+
table_name IN ('reviewables', 'flags', 'sidebar_sections')
375390
SQL
376391
end
377392

‎spec/lib/internal_metric/global_spec.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@
110110
expect(metric.postgres_highest_sequence).to be_a_kind_of(Hash)
111111
expect(metric.postgres_highest_sequence[{ db: "default" }]).to be_present
112112

113-
expect do metric.collect end.not_to change {
113+
expect { metric.collect }.not_to change {
114114
metric.class.class_variable_get(:@@postgres_highest_sequence_last_check)
115115
}
116116
end

0 commit comments

Comments
 (0)