Class: ReeDao::BuildConnection

Inherits:
Object
  • Object
show all
Includes:
Ree::FnDSL
Defined in:
lib/ree_lib/packages/ree_dao/package/ree_dao/functions/build_connection.rb

Constant Summary collapse

TIMEZONES =
[:utc, :local].freeze
DEFAULTS =
{
  datetime_class: DateTime,
  database_timezone: :utc,
  application_timezone: :utc,
  typecast_timezone: :utc,
  single_threaded: false,
  timeout: 90
}.freeze

Instance Method Summary collapse

Instance Method Details

#call(conn_opts, **opts) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/ree_lib/packages/ree_dao/package/ree_dao/functions/build_connection.rb', line 43

def call(conn_opts, **opts)
  opts = DEFAULTS.merge(opts.dup)

  database_timezone = opts.delete(:database_timezone)
  application_timezone = opts.delete(:application_timezone)
  typecast_timezone = opts.delete(:typecast_timezone)
  convert_two_digit_years = opts.delete(:convert_two_digit_years)
  single_threaded = opts.delete(:single_threaded)
  datetime_class = opts.delete(:datetime_class)
  extensions = opts.delete(:extensions) || []
  timeout = opts.delete(:timeout)

  Sequel.database_timezone = database_timezone
  Sequel.application_timezone = application_timezone
  Sequel.typecast_timezone = typecast_timezone
  Sequel.single_threaded = single_threaded
  Sequel.convert_two_digit_years = convert_two_digit_years if convert_two_digit_years
  Sequel.datetime_class = datetime_class

  connection = Sequel.connect(conn_opts)

  if opts[:fibered]
    Sequel.extension :fiber_concurrency
  end

  if opts[:logger]
    connection.logger = opts[:logger]
  end

  if opts[:sql_log_level]
    connection.sql_log_level = opts[:sql_log_level]
  end

  Timeout::timeout(timeout) do
    loop do
      begin
        connection.test_connection
        break
      rescue => e
        puts("Unable to establish DB connection: #{conn_opts.inspect}")
        puts(e.inspect)
        sleep(1)
      end
    end
  end

  extensions.each { connection.extension(_1) }
  connections.add(connection)

  dataset_class = connection.dataset_class
  klass = Class.new(dataset_class)
  klass.extend(ReeDao::DatasetExtensions)

  connection.dataset_class = klass

  connection
rescue => e
  connection&.disconnect
  raise e
end