Skip to content
Snippets Groups Projects
Verified Commit f621dca9 authored by Alper Akgun's avatar Alper Akgun :two:
Browse files

Hardened "add" arithmetic for usage data

Deals with  negative numbers and SQL exports
parent ce664d2f
No related branches found
No related tags found
1 merge request!54794Hardened "add" arithmetic for usage data
---
title: Hardened "add" arithmetic for usage data
merge_request: 54794
author:
type: performance
......@@ -32,6 +32,10 @@ def estimate_batch_distinct_count(relation, column = nil, *rest)
raw_sql(relation, column, :distinct)
end
def add(*args)
'SELECT ' + args.map {|arg| "(#{arg})" }.join(' + ')
end
private
def raw_sql(relation, column, distinct = nil)
......
......@@ -86,6 +86,14 @@ def sum(relation, column, batch_size: nil, start: nil, finish: nil)
FALLBACK
end
def add(*args)
return -1 if args.any?(&:negative?)
args.sum
rescue StandardError
FALLBACK
end
def alt_usage_data(value = nil, fallback: FALLBACK, &block)
if block_given?
yield
......
......@@ -38,4 +38,12 @@
expect(described_class.sum(Issue, :weight)).to eq('SELECT SUM("issues"."weight") FROM "issues"')
end
end
describe '.add' do
it 'returns the combined raw SQL with an inner query' do
expect(described_class.add('SELECT COUNT("users"."id") FROM "users"',
'SELECT COUNT("issues"."id") FROM "issues"'))
.to eq('SELECT (SELECT COUNT("users"."id") FROM "users") + (SELECT COUNT("issues"."id") FROM "issues")')
end
end
end
......@@ -183,6 +183,24 @@
end
end
describe '#add' do
it 'adds given values' do
expect(described_class.add(1, 3)).to eq(4)
end
it 'adds given values' do
expect(described_class.add).to eq(0)
end
it 'returns the fallback value when adding fails' do
expect(described_class.add(nil, 3)).to eq(-1)
end
it 'returns the fallback value one of the arguments is negative' do
expect(described_class.add(-1, 1)).to eq(-1)
end
end
describe '#alt_usage_data' do
it 'returns the fallback when it gets an error' do
expect(described_class.alt_usage_data { raise StandardError } ).to eq(-1)
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment