Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Sutures

 Sutures

Multi-db tips for ruby on rails

Hunter Madison

February 08, 2016
Tweet

More Decks by Hunter Madison

Other Decks in Programming

Transcript

  1. Why? • The one database only stores a fraction of

    the complete data model. • You need features from a second database. • Your trying to migrate away from one database. • You want to run intensive queries on a reporting mirror.
  2. Secondbase • Gives you the most “Rails like” integration •

    CustomInk uses this • Only works with two databases
  3. Installing Secondbase # in your Gemfile gem 'secondbase' # in

    config/database.yml# development: adapter: sqlite database: myapp_development test: adapter: sqlite database: myapp_test # SecondBase configurations: secondbase: development: adapter: mysql database: myapp_development test: adapter: mysql database: myapp_test
  4. Using Secondbase • Migrations go in db/secondbase/migrate • Models inherit

    from Secondbase::Base • Regular rails rake tasks work as normal
  5. Using Secondbase # somewhere in config/initializers/*.rb Delayed::Backend::ActiveRecord::Job.extend SecondBase::Forced ActiveRecord::SessionStore::Session.extend SecondBase::Forced

    class ApplicationController < ActionController::Base around_filter :cache_other_db_connections private def cache_other_db_connections SecondBase::Base.connection.cache { yield } end end
  6. Sequel • Maintained by Jeremy Evans • Provides a query

    DSL and an active record model • Lightweight • Provides most of its features via plugins
  7. Using Sequel # in your Gemfile gem 'sequel' # somewhere

    in config/initializers/*.rb DB_ONE = Sequel.connect('postgres://user:password@localhost/ db_one') DB_TWO = Sequel.connect('postgres://user:password@localhost/ db_two') # raw db query DB_TWO[:posts].where(:category => 'Ruby Loco') # in your models class Post < Sequel::Model end Post.db = DB_TWO
  8. Migrating Sequel • Write the rake tasks using Sequel::Migrator •

    sequel -m /migrations/dir <connection details>
  9. Sequel’s Caveats • Everything is a plugin • Sequel model

    close, but not exactly ActiveRecord • Does not play nice with spring
  10. Closing Thoughts • Yes, you can do this • Command

    Query Responsibility Segregation really helps • Remember to breathe