lib/legion/data/connection.rb in legion-data-0.1.1 vs lib/legion/data/connection.rb in legion-data-0.2.0

- old
+ new

@@ -1,30 +1,63 @@ require 'sequel' module Legion module Data - class Connection - attr_accessor :database - def initialize(options = {}) - options.merge!(default_options) { |_key, v1, _v2| v1 } - return unless options[:auto_connect] + module Connection + class << self + attr_reader :sequel + if RUBY_ENGINE == 'jruby' + require_relative 'connections/jdbc' + include Legion::Data::Connections::JDBC + else + require_relative 'connections/mysql2' + include Legion::Data::Connections::MySQL2 + end - jruby(options) if RUBY_ENGINE == 'jruby' - mri(options) unless RUBY_ENGINE == 'jruby' - end + def setup + @sequel = ::Sequel.connect(adapter: adapter, **creds_builder) + Legion::Settings[:data][:connected] = true + return unless Legion::Settings[:data][:connection][:log] - def default_options - { auto_connect: true } - end + @sequel.logger = Legion::Logging::Logger.new(level: 'debug') + @sequel.sql_log_level = Legion::Settings[:data][:connection][:sql_log_level] + @sequel.log_warn_duration = Legion::Settings[:data][:connection][:log_warn_duration] + end - def jruby(_options = {}) - require 'legion/data/connections/jdbc' - @database = Legion::Data::Connections::JDBC.new - end + def shutdown + @sequel.disconnect + end - def mri(_options = {}) - require 'legion/data/connections/mysql2' - @database = Legion::Data::Connections::MySQL2.new + def creds_builder # rubocop:disable Metrics/AbcSize + final_creds = {} + final_creds.merge! default_creds + final_creds.merge! Legion::Settings[:data][:creds] + return final_creds if Legion::Settings[:vault].nil? + + if Legion::Settings[:vault][:connected] && ::Vault.sys.mounts.key?(:database) + temp_vault_creds = Legion::Crypt.read('database/creds/legion') + final_creds[:user] = temp_vault_creds[:username] + final_creds[:password] = temp_vault_creds[:password] + end + + final_creds + end + + def default_creds + { + host: '127.0.0.1', + port: 3306, + username: 'legion', + password: 'legion', + database: 'legion', + max_connections: 32, + preconnect: 'concurrently' + } + end + + def adapter + 'mysql2' + end end end end end