Module: Dorm::Database

Extended by:
Database
Included in:
Database
Defined in:
lib/dorm/database.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#adapterObject (readonly)

Returns the value of attribute adapter.



9
10
11
# File 'lib/dorm/database.rb', line 9

def adapter
  @adapter
end

#poolObject (readonly)

Returns the value of attribute pool.



9
10
11
# File 'lib/dorm/database.rb', line 9

def pool
  @pool
end

Instance Method Details

#configure(adapter:, pool_size: 5, pool_timeout: 5, **options) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/dorm/database.rb', line 11

def configure(adapter:, pool_size: 5, pool_timeout: 5, **options)
  @adapter = adapter.to_sym
  @connection_options = options
  @pool_size = pool_size
  @pool_timeout = pool_timeout

  # Disconnect existing pool if any
  @pool&.disconnect!

  # Create new pool
  @pool = ConnectionPool.new(
    size: pool_size,
    timeout: pool_timeout,
    max_age: options[:max_connection_age] || 3600,
    max_idle: options[:max_idle_time] || 300,
    reap_frequency: options[:reap_frequency] || 60
  )

  # Configure the connection factory
  @pool.configure_factory { establish_connection }
end

#disconnect!Object

Disconnect all connections (useful for testing or shutdown)



66
67
68
# File 'lib/dorm/database.rb', line 66

def disconnect!
  @pool&.disconnect!
end

#pool_statsObject

Pool statistics for monitoring



54
55
56
57
58
59
60
61
62
63
# File 'lib/dorm/database.rb', line 54

def pool_stats
  return {} unless @pool

  {
    size: @pool.size,
    available: @pool.available_count,
    checked_out: @pool.checked_out_count,
    adapter: @adapter
  }
end

#query(sql, params = []) ⇒ Object



33
34
35
36
37
38
39
40
41
# File 'lib/dorm/database.rb', line 33

def query(sql, params = [])
  ensure_configured!

  @pool.with_connection do |connection|
    execute_query(connection, sql, params)
  end
rescue StandardError => e
  raise Error, "Database query failed: #{e.message}"
end

#transaction(&block) ⇒ Object



43
44
45
46
47
48
49
50
51
# File 'lib/dorm/database.rb', line 43

def transaction(&block)
  ensure_configured!

  @pool.with_connection do |connection|
    execute_transaction(connection, &block)
  end
rescue StandardError => e
  raise Error, "Transaction failed: #{e.message}"
end