Skip to content

Commit

Permalink
Check for a connection before running db.create task (#397)
Browse files Browse the repository at this point in the history
* Updated db.create task to check for a connection first before running the create.

* clean up code with already built in Process runner

* rename alias for clarity. Moved connection to private method
  • Loading branch information
jwoertink committed Jun 25, 2020
1 parent 629e89d commit af99911
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 4 deletions.
11 changes: 11 additions & 0 deletions spec/tasks/db_create_spec.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
require "../spec_helper"

describe Db::Create do
it "raises a connection error when unable to connect" do
Avram.temp_config(database_to_migrate: DatabaseWithIncorrectSettings) do
expect_raises(Avram::ConnectionError, /Failed to connect to database/) do
Db::Create.new(quiet: true).call
end
end
end
end
4 changes: 2 additions & 2 deletions src/avram/migrator/runner.cr
Original file line number Diff line number Diff line change
Expand Up @@ -144,12 +144,12 @@ class Avram::Migrator::Runner
"sudo apt-get update && sudo apt-get install postgresql postgresql-contrib".colorize(:green)
end

def self.run(command : String)
def self.run(command : String, output : IO = STDOUT)
error_messages = IO::Memory.new
ENV["PGPASSWORD"] = self.db_password if self.db_password
result = Process.run command,
shell: true,
output: STDOUT,
output: output,
error: error_messages
ENV.delete("PGPASSWORD") if self.db_password
unless result.success?
Expand Down
23 changes: 21 additions & 2 deletions src/avram/tasks/db/create.cr
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
class Db::Create < LuckyCli::Task
alias Migrator = Avram::Migrator
summary "Create the database"

def initialize(@quiet : Bool = false)
Expand All @@ -19,8 +20,26 @@ class Db::Create < LuckyCli::Task
end

def call
Avram::Migrator.run do
Avram::Migrator::Runner.create_db(@quiet)
attempt_to_connect
Migrator.run do
Migrator::Runner.create_db(@quiet)
end
rescue
uri = URI.parse(connection_url)
raise Avram::ConnectionError.new(uri, Avram.settings.database_to_migrate)
end

private def connection_url : String
Avram::PostgresURL.build(
database: "",
hostname: Migrator::Runner.db_host.to_s,
username: Migrator::Runner.db_user.to_s,
password: Migrator::Runner.db_password.to_s,
port: Migrator::Runner.db_port.to_s
)
end

private def attempt_to_connect
Migrator::Runner.run("psql -q -l #{connection_url}", output: IO::Memory.new)
end
end

0 comments on commit af99911

Please sign in to comment.