Skip to content

Commit

Permalink
Merge pull request #88 from Blacksmoke16/lazy-db-url
Browse files Browse the repository at this point in the history
Determine `database_url` when first accessed versus when required
  • Loading branch information
crimson-knight authored Jan 30, 2024
2 parents 6dd42bf + f70d663 commit b8355cf
Showing 1 changed file with 5 additions and 9 deletions.
14 changes: 5 additions & 9 deletions src/micrate/db.cr
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,7 @@ require "./db/*"

module Micrate
module DB
@@connection_url = ENV["DATABASE_URL"]?

def self.connection_url
@@connection_url
end
class_getter connection_url : String? { ENV["DATABASE_URL"]? }

def self.connection_url=(connection_url)
@@dialect = nil
Expand All @@ -16,12 +12,12 @@ module Micrate

def self.connect
validate_connection_url
::DB.connect(@@connection_url.not_nil!)
::DB.connect(self.connection_url.not_nil!)
end

def self.connect(&block)
validate_connection_url
::DB.open @@connection_url.not_nil! do |db|
::DB.open self.connection_url.not_nil! do |db|
yield db
end
end
Expand Down Expand Up @@ -55,11 +51,11 @@ module Micrate

private def self.dialect
validate_connection_url
@@dialect ||= Dialect.from_connection_url(@@connection_url.not_nil!)
@@dialect ||= Dialect.from_connection_url(self.connection_url.not_nil!)
end

private def self.validate_connection_url
if !@@connection_url
if !self.connection_url
raise "No database connection URL is configured. Please set the DATABASE_URL environment variable."
end
end
Expand Down

0 comments on commit b8355cf

Please sign in to comment.