diff --git a/spec/marten/conf/global_settings/database_spec.cr b/spec/marten/conf/global_settings/database_spec.cr index 28d030081..d89db6022 100644 --- a/spec/marten/conf/global_settings/database_spec.cr +++ b/spec/marten/conf/global_settings/database_spec.cr @@ -536,6 +536,13 @@ describe Marten::Conf::GlobalSettings::Database do db_config_1.name.should eq ":memory:" end + it "parses sqlite3://:memory:" do + db_config_1 = Marten::Conf::GlobalSettings::Database.new("default") + db_config_1.from_url "sqlite3://:memory:" + db_config_1.backend.should eq "sqlite" + db_config_1.name.should eq ":memory:" + end + it "parses sqlite url" do db_config_1 = Marten::Conf::GlobalSettings::Database.new("default") db_config_1.from_url "sqlite://marten.db" diff --git a/src/marten/conf/global_settings.cr b/src/marten/conf/global_settings.cr index 842a676ff..ee17ea961 100644 --- a/src/marten/conf/global_settings.cr +++ b/src/marten/conf/global_settings.cr @@ -258,7 +258,7 @@ module Marten # Allows to configure a specific database connection for the application using a connection URL. def database(id = DB::Connection::DEFAULT_CONNECTION_NAME, url : String | Nil = nil) - self.database id, url do |_| + self.database(id, url) do |_| end end diff --git a/src/marten/conf/global_settings/database.cr b/src/marten/conf/global_settings/database.cr index 97e77fff9..b7acaef12 100644 --- a/src/marten/conf/global_settings/database.cr +++ b/src/marten/conf/global_settings/database.cr @@ -92,17 +92,23 @@ module Marten def initialize(@id : String) end + # Allows to set the connection backend of the database. + def backend=(val : Nil | String | Symbol) + @backend = val.try(&.to_s) + end + + # Allows to set the database configuration from a connection URL. def from_url(url : String) - # URI.parse cant parse 'sqlite://:memory:' - if url.starts_with? "sqlite://:memory:" + # URI.parse can't parse 'sqlite://:memory:' or 'sqlite3://:memory:' + if SQLITE_SCHEMES.any? { |scheme| url.starts_with?("#{scheme}://#{SQLITE_MEMORY_ID}") } self.backend = DB::Connection::SQLITE_ID - self.name = ":memory:" + self.name = SQLITE_MEMORY_ID return end - uri = URI.parse url + uri = URI.parse(url) - self.backend = uri.scheme == "sqlite3" ? DB::Connection::SQLITE_ID : uri.scheme + self.backend = SQLITE_SCHEMES.includes?(uri.scheme) ? DB::Connection::SQLITE_ID : uri.scheme self.host = uri.host self.port = uri.port self.user = uri.user @@ -138,11 +144,6 @@ module Marten self.options = params_map end - # Allows to set the connection backend of the database. - def backend=(val : Nil | String | Symbol) - @backend = val.try(&.to_s) - end - # Allows to set the database host. def host=(val : Nil | String | Symbol) @host = val.try(&.to_s) @@ -195,6 +196,9 @@ module Marten @target_env = current_target_env end + private SQLITE_MEMORY_ID = ":memory:" + private SQLITE_SCHEMES = ["sqlite", "sqlite3"] + private def driver_installed? case backend when DB::Connection::MYSQL_ID