Search code examples
rubyhanamihanami-model

How can I access more than one database with Hanami/Repository


I have a application that has to generate reports from a data warehouse.
I don't want to save the app specific data (user, permissions, report defintions, ...) in the same database where the warehouse lives. Also, in the future it is very likely that I have to get access to other databases as well (maybe even Oracle).
I have configured my database connection in the .env files but I don't know if or where I can define a new connection and also how to instanciate a repository for this explicit connection.
Since this is the 2nd container from my app, I was wondering if it is possible to change the orm for one container, when hanami-model isn't suited for my needs...


Solution

  • This is an example how to connect to two databases using hanami:

    require 'pg'
    require 'hanami/model'
    require 'hanami/model/adapters/sql_adapter'
    
    mapper = Hanami::Model::Mapper.new do
      # ...
    end
    
    adapter1 = Hanami::Model::Adapters::SqlAdapter.new(mapper, 'postgres://host:port/database1')
    
    adapter2 = Hanami::Model::Adapters::SqlAdapter.new(mapper, 'postgres://host:port/database2')
    
    
    DataRepository.adapter  = adapter1
    UserRepository.adapter = adapter2