Commit 10343fea authored by Z.J. van de Weg's avatar Z.J. van de Weg
Browse files

Minor refactor for easier extensibility

In the previous version it was harder to extend as you could forget to
include your symbol in the query list. Also, the queries had some
duplication. For extensions this is the easier way forward and the
DRYest.

Also added the first tests for database monitoring.
parent d10e59f4
......@@ -5,17 +5,21 @@ module GitLab
# the row count
# This class works under the assumption you do COUNT(*) queries
class RowCountCollector < Base
QUERIES = [
:soft_deleted_projects,
:soft_deleted_namespaces,
:orphaned_projects
].freeze
QUERIES = {
soft_deleted_projects: { select: :projects, where: "pending_delete=true" },
orphaned_projects: {
select: :projects,
joins: "LEFT JOIN namespaces ON projects.namespace_id = namespaces.id",
where: "namespaces.id IS NULL"
},
soft_deleted_namespaces: { select: :namespaces, where: "deleted_at IS NOT NULL" }
}.freeze
def run
results = Hash.new(0)
QUERIES.each do |query|
results[query] = execute(query)
QUERIES.each do |key, query|
results[key] = execute(query)
end
results
......@@ -24,29 +28,15 @@ module GitLab
private
def execute(query)
connection.exec(send(query))[0]["count"]
connection.exec(construct_query(query))[0]["count"]
end
def soft_deleted_projects
<<-SQL
SELECT COUNT(*) FROM projects
WHERE pending_delete=true;
SQL
end
def soft_deleted_namespaces
<<-SQL
SELECT COUNT(*) FROM namespaces
WHERE deleted_at IS NOT NULL;
SQL
end
def orphaned_projects
<<-SQL
SELECT COUNT(*) FROM projects
LEFT JOIN namespaces ON projects.namespace_id = namespaces.id
WHERE namespaces.id IS NULL;
SQL
# Not private so I can test it without meta programming tricks
def construct_query(query)
query_string = "SELECT COUNT(*) FROM #{query[:select]} "
query_string << "#{query[:joins]} " if query[:joins]
query_string << "WHERE #{query[:where]}" if query[:where]
query_string << ";"
end
end
......
require "spec_helper"
require "gitlab_monitor/database/row_count"
describe GitLab::Monitor::Database::RowCountCollector do
describe "#run" do
let(:query) { { project_1: { select: :projects, where: "id=1" } } }
let(:collector) { described_class.new(connection_string: "host=localhost") }
before do
stub_const("GitLab::Monitor::Database::RowCountCollector::QUERIES", query)
end
it "executes the query" do
allow(collector).to receive(:execute).with(query[:project_1]).and_return(3)
expect(collector.run).to eq(project_1: 3)
end
describe "#construct_query" do
it "accepts a table and where clause" do
expect(collector.send(:construct_query, query[:project_1])).to eq "SELECT COUNT(*) FROM projects WHERE id=1;"
end
end
end
end
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