Skip to content
This repository was archived by the owner on Apr 17, 2023. It is now read-only.

Commit cb7e8ae

Browse files
authored
Merge pull request #1358 from mssola/check-db
Added a way to check the DB's status
2 parents c305979 + 564c3cb commit cb7e8ae

File tree

3 files changed

+72
-0
lines changed

3 files changed

+72
-0
lines changed

bin/check_db.rb

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# This is a rails runner that will print the status of Portus' database.
2+
# Possible outcomes:
3+
#
4+
# * `DB_READY`: the database has been created and initialized.
5+
# * `DB_EMPTY`: the database has been created but has not been initialized.
6+
# * `DB_MISSING`: the database has not been created.
7+
# * `DB_DOWN`: cannot connect to the database.
8+
# * `DB_UNKNOWN`: unknown error.
9+
#
10+
# Originally included in the https://github.com/openSUSE/docker-containers
11+
# repository under the same license.
12+
13+
require "portus/db"
14+
15+
puts case Portus::DB.ping
16+
when :ready
17+
"DB_READY"
18+
when :empty
19+
"DB_EMPTY"
20+
when :missing
21+
"DB_MISSING"
22+
when :down
23+
"DB_DOWN"
24+
else
25+
"DB_UNKNOWN"
26+
end

lib/portus/db.rb

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
module Portus
2+
# The DB module has useful methods for DB purposes.
3+
module DB
4+
# Pings the DB and returns a proper symbol depending on the situation:
5+
# * ready: the database has been created and initialized.
6+
# * empty: the database has been created but has not been initialized.
7+
# * missing: the database has not been created.
8+
# * down: cannot connect to the database.
9+
def self.ping
10+
::Portus::DB.migrations? ? :ready : :empty
11+
rescue ActiveRecord::NoDatabaseError
12+
:missing
13+
rescue Mysql2::Error
14+
:down
15+
end
16+
17+
# Returns true if the migrations have been run. The implementation is pretty
18+
# trivial, but this gives us a nice way to test this module.
19+
def self.migrations?
20+
ActiveRecord::Base.connection
21+
ActiveRecord::Base.connection.table_exists? "schema_migrations"
22+
end
23+
end
24+
end

spec/lib/portus/db_spec.rb

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
require "rails_helper"
2+
3+
describe Portus::DB do
4+
it "returns :ready on the usual case" do
5+
expect(Portus::DB.ping).to eq :ready
6+
end
7+
8+
it "returns :empty if the DB is still initializing" do
9+
allow(::Portus::DB).to receive(:migrations?).and_return(false)
10+
expect(Portus::DB.ping).to eq :empty
11+
end
12+
13+
it "returns :missing if the DB is missing" do
14+
allow(::Portus::DB).to receive(:migrations?).and_raise(ActiveRecord::NoDatabaseError, "a")
15+
expect(Portus::DB.ping).to eq :missing
16+
end
17+
18+
it "returns :down if the DB is down" do
19+
allow(::Portus::DB).to receive(:migrations?).and_raise(Mysql2::Error, "a")
20+
expect(Portus::DB.ping).to eq :down
21+
end
22+
end

0 commit comments

Comments
 (0)