diff --git a/README.md b/README.md index e55668a..0789410 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,16 @@ And then execute: ## Usage +The simplest way to get started: + +```rb +require 'sequel_tools' + +namespace :db do + SequelTools.inject_rake_tasks Hash[db_url: 'postgres://username:password@localhost/dbname'], self +end +``` + Here's a sample Rakefile supporting migrate actions: ```ruby @@ -41,7 +51,7 @@ require 'bundler/setup' require 'sequel_tools' base_config = SequelTools.base_config( - project_root: File.expand_path(__dir__), + project_root: __dir__, dbadapter: 'postgres', dbname: 'mydb', username: 'myuser', diff --git a/lib/sequel_tools.rb b/lib/sequel_tools.rb index 5a6e6d2..cd3c972 100644 --- a/lib/sequel_tools.rb +++ b/lib/sequel_tools.rb @@ -1,16 +1,19 @@ # frozen-string-literal: true require 'sequel_tools/version' +require 'sequel/core' +require 'uri' module SequelTools DEFAULT_CONFIG = { - project_root: nil, + project_root: Dir.pwd, pg_dump: 'pg_dump', # command used to run pg_dump psql: 'psql', # command used to run psql maintenancedb: :default, # DB to connect to for creating/dropping databases migrations_location: 'db/migrations', schema_location: 'db/migrations/schema.sql', seeds_location: 'db/seeds.rb', + db_url: nil, dbname: nil, dbhost: 'localhost', dbadapter: 'postgres', @@ -24,13 +27,27 @@ module SequelTools extra_tables_in_dump: nil, } # unfrozen on purpose so that one might want to update the defaults - REQUIRED_KEYS = [ :project_root, :dbadapter, :dbname, :username ] class MissingConfigError < StandardError; end def self.base_config(extra_config = {}) config = DEFAULT_CONFIG.merge extra_config - REQUIRED_KEYS.each do |key| - raise MissingConfigError, "Expected value for #{key} config is missing" if config[key].nil? + unless config[:db_url] || (config[:dbadapter && config[:dbname]]) + raise MissingConfigError, "Must provide either :db_url or :dbadapter and :dbname config options" end + + if config[:db_url] + db = Sequel.connect(config[:db_url], test: false, keep_reference: false) + if RUBY_PLATFORM == 'java' + uri = URI.parse(config[:db_url][/\Ajdbc:(.+)/, 1]) + config[:dbadapter] = uri.scheme + config[:dbname] = uri.path[/\/(.+)/, 1] + else + config[:dbadapter] = db.opts[:adapter] + config[:dbname] = db.opts[:database] + end + config[:username] = db.opts[:user] + config[:password] = db.opts[:password] + end + [:migrations_location, :schema_location, :seeds_location].each do |k| config[k] = File.expand_path config[k], config[:project_root] end @@ -40,7 +57,7 @@ def self.base_config(extra_config = {}) def self.inject_rake_tasks(config = {}, rake_context) require_relative 'sequel_tools/actions_manager' require_relative 'sequel_tools/all_actions' - actions_manager = ActionsManager.new config + actions_manager = ActionsManager.new base_config(config) actions_manager.load_all actions_manager.export_as_rake_tasks rake_context end