martenframework / marten

The pragmatic web framework.
https://martenframework.com
MIT License
407 stars 23 forks source link

Make it possible to configure databases through connection strings #257

Open ellmetha opened 1 month ago

ellmetha commented 1 month ago

Description

Let's make it possible to easily configure databases through connection strings.

Context

Right now, Marten allows to explicitly configure databases by providing each of the database attributes (such as the database name, host, port user, password, etc). For example:

config.database do |db|
  db.backend = :postgresql
  db.host = "localhost"
  db.name = "my_db"
  db.user = "my_user"
  db.password = "my_passport"
end

That said, some cloud providers only provide a connection string in order to connect to a specific database (usually in a DATABASE_URL environment variable). The only way to connect to such databases with Marten presently involves parsing the connection string and assigning the right database attributes to the right database settings manually.

Proposition

Let's make this process easier by making it possible to provide a connection string to the #database config method. For example:

# Default database
config.database ENV.fetch("DATABASE_URL")

# Other database
config.database :other, ENV.fetch("OTHER_DATABASE_URL")

It is worth noting that it should still be possible to provide a block to this alternative #database method in order to access the Marten::Conf::GlobalSettings::Database object and set additional database settings manually:

config.database ENV.fetch("DATABASE_URL") do |db|
  db.initial_pool_size = 2
end