Commit 48e8c06d authored by Dmytro Zaporozhets (DZ)'s avatar Dmytro Zaporozhets (DZ)

Merge branch '322099-sql-definition-for-template_repositories' into 'master'

Hardened "add" arithmetic for usage data

See merge request gitlab-org/gitlab!54794
parents 1be5430d f621dca9
---
title: Hardened "add" arithmetic for usage data
merge_request: 54794
author:
type: performance
...@@ -32,6 +32,10 @@ module Gitlab ...@@ -32,6 +32,10 @@ module Gitlab
raw_sql(relation, column, :distinct) raw_sql(relation, column, :distinct)
end end
def add(*args)
'SELECT ' + args.map {|arg| "(#{arg})" }.join(' + ')
end
private private
def raw_sql(relation, column, distinct = nil) def raw_sql(relation, column, distinct = nil)
......
...@@ -87,6 +87,14 @@ module Gitlab ...@@ -87,6 +87,14 @@ module Gitlab
FALLBACK FALLBACK
end 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) def alt_usage_data(value = nil, fallback: FALLBACK, &block)
if block_given? if block_given?
yield yield
......
...@@ -38,4 +38,12 @@ RSpec.describe Gitlab::UsageDataQueries do ...@@ -38,4 +38,12 @@ RSpec.describe Gitlab::UsageDataQueries do
expect(described_class.sum(Issue, :weight)).to eq('SELECT SUM("issues"."weight") FROM "issues"') expect(described_class.sum(Issue, :weight)).to eq('SELECT SUM("issues"."weight") FROM "issues"')
end end
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 end
...@@ -183,6 +183,24 @@ RSpec.describe Gitlab::Utils::UsageData do ...@@ -183,6 +183,24 @@ RSpec.describe Gitlab::Utils::UsageData do
end end
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 describe '#alt_usage_data' do
it 'returns the fallback when it gets an error' do it 'returns the fallback when it gets an error' do
expect(described_class.alt_usage_data { raise StandardError } ).to eq(-1) expect(described_class.alt_usage_data { raise StandardError } ).to eq(-1)
......
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